1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26pub mod hover_popover;
27mod indent_guides;
28mod inlay_hint_cache;
29pub mod items;
30mod jsx_tag_auto_close;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod 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, Subscription, Task, TextStyle, TextStyleRefinement,
92 UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
93 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
94};
95use highlight_matching_bracket::refresh_matching_bracket_highlights;
96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
97pub use hover_popover::hover_markdown_style;
98use hover_popover::{HoverState, hide_hover};
99use indent_guides::ActiveIndentGuidesState;
100use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
101pub use inline_completion::Direction;
102use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
103pub use items::MAX_TAB_TITLE_LEN;
104use itertools::Itertools;
105use language::{
106 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
107 CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
108 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
109 TransactionId, TreeSitterOptions, WordsQuery,
110 language_settings::{
111 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
112 all_language_settings, language_settings,
113 },
114 point_from_lsp, text_diff_with_options,
115};
116use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
117use linked_editing_ranges::refresh_linked_ranges;
118use mouse_context_menu::MouseContextMenu;
119use persistence::DB;
120use project::{
121 ProjectPath,
122 debugger::breakpoint_store::{
123 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
124 },
125};
126
127pub use git::blame::BlameRenderer;
128pub use proposed_changes_editor::{
129 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
130};
131use smallvec::smallvec;
132use std::{cell::OnceCell, iter::Peekable};
133use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
134
135pub use lsp::CompletionContext;
136use lsp::{
137 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
138 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
139};
140
141use language::BufferSnapshot;
142pub use lsp_ext::lsp_tasks;
143use movement::TextLayoutDetails;
144pub use multi_buffer::{
145 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
146 RowInfo, ToOffset, ToPoint,
147};
148use multi_buffer::{
149 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
150 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
151};
152use parking_lot::Mutex;
153use project::{
154 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
155 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
156 TaskSourceKind,
157 debugger::breakpoint_store::Breakpoint,
158 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
159 project_settings::{GitGutterSetting, ProjectSettings},
160};
161use rand::prelude::*;
162use rpc::{ErrorExt, proto::*};
163use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
164use selections_collection::{
165 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
166};
167use serde::{Deserialize, Serialize};
168use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
169use smallvec::SmallVec;
170use snippet::Snippet;
171use std::sync::Arc;
172use std::{
173 any::TypeId,
174 borrow::Cow,
175 cell::RefCell,
176 cmp::{self, Ordering, Reverse},
177 mem,
178 num::NonZeroU32,
179 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
180 path::{Path, PathBuf},
181 rc::Rc,
182 time::{Duration, Instant},
183};
184pub use sum_tree::Bias;
185use sum_tree::TreeMap;
186use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
187use theme::{
188 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
189 observe_buffer_font_size_adjustment,
190};
191use ui::{
192 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
193 IconSize, Key, Tooltip, h_flex, prelude::*,
194};
195use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
196use workspace::{
197 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
198 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
199 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
200 item::{ItemHandle, PreviewTabsSettings},
201 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
202 searchable::SearchEvent,
203};
204
205use crate::hover_links::{find_url, find_url_from_range};
206use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
207
208pub const FILE_HEADER_HEIGHT: u32 = 2;
209pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
210pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
211const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
212const MAX_LINE_LEN: usize = 1024;
213const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
214const MAX_SELECTION_HISTORY_LEN: usize = 1024;
215pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
216#[doc(hidden)]
217pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
218
219pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
220pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
221pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
222
223pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
224pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
225pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
226
227pub type RenderDiffHunkControlsFn = Arc<
228 dyn Fn(
229 u32,
230 &DiffHunkStatus,
231 Range<Anchor>,
232 bool,
233 Pixels,
234 &Entity<Editor>,
235 &mut Window,
236 &mut App,
237 ) -> AnyElement,
238>;
239
240const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
241 alt: true,
242 shift: true,
243 control: false,
244 platform: false,
245 function: false,
246};
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
249pub enum InlayId {
250 InlineCompletion(usize),
251 Hint(usize),
252}
253
254impl InlayId {
255 fn id(&self) -> usize {
256 match self {
257 Self::InlineCompletion(id) => *id,
258 Self::Hint(id) => *id,
259 }
260 }
261}
262
263pub enum DebugCurrentRowHighlight {}
264enum DocumentHighlightRead {}
265enum DocumentHighlightWrite {}
266enum InputComposition {}
267enum SelectedTextHighlight {}
268
269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
270pub enum Navigated {
271 Yes,
272 No,
273}
274
275impl Navigated {
276 pub fn from_bool(yes: bool) -> Navigated {
277 if yes { Navigated::Yes } else { Navigated::No }
278 }
279}
280
281#[derive(Debug, Clone, PartialEq, Eq)]
282enum DisplayDiffHunk {
283 Folded {
284 display_row: DisplayRow,
285 },
286 Unfolded {
287 is_created_file: bool,
288 diff_base_byte_range: Range<usize>,
289 display_row_range: Range<DisplayRow>,
290 multi_buffer_range: Range<Anchor>,
291 status: DiffHunkStatus,
292 },
293}
294
295pub enum HideMouseCursorOrigin {
296 TypingAction,
297 MovementAction,
298}
299
300pub fn init_settings(cx: &mut App) {
301 EditorSettings::register(cx);
302}
303
304pub fn init(cx: &mut App) {
305 init_settings(cx);
306
307 cx.set_global(GlobalBlameRenderer(Arc::new(())));
308
309 workspace::register_project_item::<Editor>(cx);
310 workspace::FollowableViewRegistry::register::<Editor>(cx);
311 workspace::register_serializable_item::<Editor>(cx);
312
313 cx.observe_new(
314 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
315 workspace.register_action(Editor::new_file);
316 workspace.register_action(Editor::new_file_vertical);
317 workspace.register_action(Editor::new_file_horizontal);
318 workspace.register_action(Editor::cancel_language_server_work);
319 },
320 )
321 .detach();
322
323 cx.on_action(move |_: &workspace::NewFile, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(
327 Default::default(),
328 app_state,
329 cx,
330 |workspace, window, cx| {
331 Editor::new_file(workspace, &Default::default(), window, cx)
332 },
333 )
334 .detach();
335 }
336 });
337 cx.on_action(move |_: &workspace::NewWindow, cx| {
338 let app_state = workspace::AppState::global(cx);
339 if let Some(app_state) = app_state.upgrade() {
340 workspace::open_new(
341 Default::default(),
342 app_state,
343 cx,
344 |workspace, window, cx| {
345 cx.activate(true);
346 Editor::new_file(workspace, &Default::default(), window, cx)
347 },
348 )
349 .detach();
350 }
351 });
352}
353
354pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
355 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
356}
357
358pub trait DiagnosticRenderer {
359 fn render_group(
360 &self,
361 diagnostic_group: Vec<DiagnosticEntry<Point>>,
362 buffer_id: BufferId,
363 snapshot: EditorSnapshot,
364 editor: WeakEntity<Editor>,
365 cx: &mut App,
366 ) -> Vec<BlockProperties<Anchor>>;
367}
368
369pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
370
371impl gpui::Global for GlobalDiagnosticRenderer {}
372pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
373 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
374}
375
376pub struct SearchWithinRange;
377
378trait InvalidationRegion {
379 fn ranges(&self) -> &[Range<Anchor>];
380}
381
382#[derive(Clone, Debug, PartialEq)]
383pub enum SelectPhase {
384 Begin {
385 position: DisplayPoint,
386 add: bool,
387 click_count: usize,
388 },
389 BeginColumnar {
390 position: DisplayPoint,
391 reset: bool,
392 goal_column: u32,
393 },
394 Extend {
395 position: DisplayPoint,
396 click_count: usize,
397 },
398 Update {
399 position: DisplayPoint,
400 goal_column: u32,
401 scroll_delta: gpui::Point<f32>,
402 },
403 End,
404}
405
406#[derive(Clone, Debug)]
407pub enum SelectMode {
408 Character,
409 Word(Range<Anchor>),
410 Line(Range<Anchor>),
411 All,
412}
413
414#[derive(Copy, Clone, PartialEq, Eq, Debug)]
415pub enum EditorMode {
416 SingleLine {
417 auto_width: bool,
418 },
419 AutoHeight {
420 max_lines: usize,
421 },
422 Full {
423 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
424 scale_ui_elements_with_buffer_font_size: bool,
425 /// When set to `true`, the editor will render a background for the active line.
426 show_active_line_background: bool,
427 },
428}
429
430impl EditorMode {
431 pub fn full() -> Self {
432 Self::Full {
433 scale_ui_elements_with_buffer_font_size: true,
434 show_active_line_background: true,
435 }
436 }
437
438 pub fn is_full(&self) -> bool {
439 matches!(self, Self::Full { .. })
440 }
441}
442
443#[derive(Copy, Clone, Debug)]
444pub enum SoftWrap {
445 /// Prefer not to wrap at all.
446 ///
447 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
448 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
449 GitDiff,
450 /// Prefer a single line generally, unless an overly long line is encountered.
451 None,
452 /// Soft wrap lines that exceed the editor width.
453 EditorWidth,
454 /// Soft wrap lines at the preferred line length.
455 Column(u32),
456 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
457 Bounded(u32),
458}
459
460#[derive(Clone)]
461pub struct EditorStyle {
462 pub background: Hsla,
463 pub local_player: PlayerColor,
464 pub text: TextStyle,
465 pub scrollbar_width: Pixels,
466 pub syntax: Arc<SyntaxTheme>,
467 pub status: StatusColors,
468 pub inlay_hints_style: HighlightStyle,
469 pub inline_completion_styles: InlineCompletionStyles,
470 pub unnecessary_code_fade: f32,
471}
472
473impl Default for EditorStyle {
474 fn default() -> Self {
475 Self {
476 background: Hsla::default(),
477 local_player: PlayerColor::default(),
478 text: TextStyle::default(),
479 scrollbar_width: Pixels::default(),
480 syntax: Default::default(),
481 // HACK: Status colors don't have a real default.
482 // We should look into removing the status colors from the editor
483 // style and retrieve them directly from the theme.
484 status: StatusColors::dark(),
485 inlay_hints_style: HighlightStyle::default(),
486 inline_completion_styles: InlineCompletionStyles {
487 insertion: HighlightStyle::default(),
488 whitespace: HighlightStyle::default(),
489 },
490 unnecessary_code_fade: Default::default(),
491 }
492 }
493}
494
495pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
496 let show_background = language_settings::language_settings(None, None, cx)
497 .inlay_hints
498 .show_background;
499
500 HighlightStyle {
501 color: Some(cx.theme().status().hint),
502 background_color: show_background.then(|| cx.theme().status().hint_background),
503 ..HighlightStyle::default()
504 }
505}
506
507pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
508 InlineCompletionStyles {
509 insertion: HighlightStyle {
510 color: Some(cx.theme().status().predictive),
511 ..HighlightStyle::default()
512 },
513 whitespace: HighlightStyle {
514 background_color: Some(cx.theme().status().created_background),
515 ..HighlightStyle::default()
516 },
517 }
518}
519
520type CompletionId = usize;
521
522pub(crate) enum EditDisplayMode {
523 TabAccept,
524 DiffPopover,
525 Inline,
526}
527
528enum InlineCompletion {
529 Edit {
530 edits: Vec<(Range<Anchor>, String)>,
531 edit_preview: Option<EditPreview>,
532 display_mode: EditDisplayMode,
533 snapshot: BufferSnapshot,
534 },
535 Move {
536 target: Anchor,
537 snapshot: BufferSnapshot,
538 },
539}
540
541struct InlineCompletionState {
542 inlay_ids: Vec<InlayId>,
543 completion: InlineCompletion,
544 completion_id: Option<SharedString>,
545 invalidation_range: Range<Anchor>,
546}
547
548enum EditPredictionSettings {
549 Disabled,
550 Enabled {
551 show_in_menu: bool,
552 preview_requires_modifier: bool,
553 },
554}
555
556enum InlineCompletionHighlight {}
557
558#[derive(Debug, Clone)]
559struct InlineDiagnostic {
560 message: SharedString,
561 group_id: usize,
562 is_primary: bool,
563 start: Point,
564 severity: DiagnosticSeverity,
565}
566
567pub enum MenuInlineCompletionsPolicy {
568 Never,
569 ByProvider,
570}
571
572pub enum EditPredictionPreview {
573 /// Modifier is not pressed
574 Inactive { released_too_fast: bool },
575 /// Modifier pressed
576 Active {
577 since: Instant,
578 previous_scroll_position: Option<ScrollAnchor>,
579 },
580}
581
582impl EditPredictionPreview {
583 pub fn released_too_fast(&self) -> bool {
584 match self {
585 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
586 EditPredictionPreview::Active { .. } => false,
587 }
588 }
589
590 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
591 if let EditPredictionPreview::Active {
592 previous_scroll_position,
593 ..
594 } = self
595 {
596 *previous_scroll_position = scroll_position;
597 }
598 }
599}
600
601pub struct ContextMenuOptions {
602 pub min_entries_visible: usize,
603 pub max_entries_visible: usize,
604 pub placement: Option<ContextMenuPlacement>,
605}
606
607#[derive(Debug, Clone, PartialEq, Eq)]
608pub enum ContextMenuPlacement {
609 Above,
610 Below,
611}
612
613#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
614struct EditorActionId(usize);
615
616impl EditorActionId {
617 pub fn post_inc(&mut self) -> Self {
618 let answer = self.0;
619
620 *self = Self(answer + 1);
621
622 Self(answer)
623 }
624}
625
626// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
627// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
628
629type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
630type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
631
632#[derive(Default)]
633struct ScrollbarMarkerState {
634 scrollbar_size: Size<Pixels>,
635 dirty: bool,
636 markers: Arc<[PaintQuad]>,
637 pending_refresh: Option<Task<Result<()>>>,
638}
639
640impl ScrollbarMarkerState {
641 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
642 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
643 }
644}
645
646#[derive(Clone, Debug)]
647struct RunnableTasks {
648 templates: Vec<(TaskSourceKind, TaskTemplate)>,
649 offset: multi_buffer::Anchor,
650 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
651 column: u32,
652 // Values of all named captures, including those starting with '_'
653 extra_variables: HashMap<String, String>,
654 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
655 context_range: Range<BufferOffset>,
656}
657
658impl RunnableTasks {
659 fn resolve<'a>(
660 &'a self,
661 cx: &'a task::TaskContext,
662 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
663 self.templates.iter().filter_map(|(kind, template)| {
664 template
665 .resolve_task(&kind.to_id_base(), cx)
666 .map(|task| (kind.clone(), task))
667 })
668 }
669}
670
671#[derive(Clone)]
672struct ResolvedTasks {
673 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
674 position: Anchor,
675}
676
677#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
678struct BufferOffset(usize);
679
680// Addons allow storing per-editor state in other crates (e.g. Vim)
681pub trait Addon: 'static {
682 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
683
684 fn render_buffer_header_controls(
685 &self,
686 _: &ExcerptInfo,
687 _: &Window,
688 _: &App,
689 ) -> Option<AnyElement> {
690 None
691 }
692
693 fn to_any(&self) -> &dyn std::any::Any;
694}
695
696/// A set of caret positions, registered when the editor was edited.
697pub struct ChangeList {
698 changes: Vec<Vec<Anchor>>,
699 /// Currently "selected" change.
700 position: Option<usize>,
701}
702
703impl ChangeList {
704 pub fn new() -> Self {
705 Self {
706 changes: Vec::new(),
707 position: None,
708 }
709 }
710
711 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
712 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
713 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
714 if self.changes.is_empty() {
715 return None;
716 }
717
718 let prev = self.position.unwrap_or(self.changes.len());
719 let next = if direction == Direction::Prev {
720 prev.saturating_sub(count)
721 } else {
722 (prev + count).min(self.changes.len() - 1)
723 };
724 self.position = Some(next);
725 self.changes.get(next).map(|anchors| anchors.as_slice())
726 }
727
728 /// Adds a new change to the list, resetting the change list position.
729 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
730 self.position.take();
731 if pop_state {
732 self.changes.pop();
733 }
734 self.changes.push(new_positions.clone());
735 }
736
737 pub fn last(&self) -> Option<&[Anchor]> {
738 self.changes.last().map(|anchors| anchors.as_slice())
739 }
740}
741
742/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
743///
744/// See the [module level documentation](self) for more information.
745pub struct Editor {
746 focus_handle: FocusHandle,
747 last_focused_descendant: Option<WeakFocusHandle>,
748 /// The text buffer being edited
749 buffer: Entity<MultiBuffer>,
750 /// Map of how text in the buffer should be displayed.
751 /// Handles soft wraps, folds, fake inlay text insertions, etc.
752 pub display_map: Entity<DisplayMap>,
753 pub selections: SelectionsCollection,
754 pub scroll_manager: ScrollManager,
755 /// When inline assist editors are linked, they all render cursors because
756 /// typing enters text into each of them, even the ones that aren't focused.
757 pub(crate) show_cursor_when_unfocused: bool,
758 columnar_selection_tail: Option<Anchor>,
759 add_selections_state: Option<AddSelectionsState>,
760 select_next_state: Option<SelectNextState>,
761 select_prev_state: Option<SelectNextState>,
762 selection_history: SelectionHistory,
763 autoclose_regions: Vec<AutocloseRegion>,
764 snippet_stack: InvalidationStack<SnippetState>,
765 select_syntax_node_history: SelectSyntaxNodeHistory,
766 ime_transaction: Option<TransactionId>,
767 active_diagnostics: ActiveDiagnostic,
768 show_inline_diagnostics: bool,
769 inline_diagnostics_update: Task<()>,
770 inline_diagnostics_enabled: bool,
771 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
772 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
773 hard_wrap: Option<usize>,
774
775 // TODO: make this a access method
776 pub project: Option<Entity<Project>>,
777 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
778 completion_provider: Option<Box<dyn CompletionProvider>>,
779 collaboration_hub: Option<Box<dyn CollaborationHub>>,
780 blink_manager: Entity<BlinkManager>,
781 show_cursor_names: bool,
782 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
783 pub show_local_selections: bool,
784 mode: EditorMode,
785 show_breadcrumbs: bool,
786 show_gutter: bool,
787 show_scrollbars: bool,
788 show_line_numbers: Option<bool>,
789 use_relative_line_numbers: Option<bool>,
790 show_git_diff_gutter: Option<bool>,
791 show_code_actions: Option<bool>,
792 show_runnables: Option<bool>,
793 show_breakpoints: Option<bool>,
794 show_wrap_guides: Option<bool>,
795 show_indent_guides: Option<bool>,
796 placeholder_text: Option<Arc<str>>,
797 highlight_order: usize,
798 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
799 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
800 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
801 scrollbar_marker_state: ScrollbarMarkerState,
802 active_indent_guides_state: ActiveIndentGuidesState,
803 nav_history: Option<ItemNavHistory>,
804 context_menu: RefCell<Option<CodeContextMenu>>,
805 context_menu_options: Option<ContextMenuOptions>,
806 mouse_context_menu: Option<MouseContextMenu>,
807 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
808 signature_help_state: SignatureHelpState,
809 auto_signature_help: Option<bool>,
810 find_all_references_task_sources: Vec<Anchor>,
811 next_completion_id: CompletionId,
812 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
813 code_actions_task: Option<Task<Result<()>>>,
814 selection_highlight_task: Option<Task<()>>,
815 document_highlights_task: Option<Task<()>>,
816 linked_editing_range_task: Option<Task<Option<()>>>,
817 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
818 pending_rename: Option<RenameState>,
819 searchable: bool,
820 cursor_shape: CursorShape,
821 current_line_highlight: Option<CurrentLineHighlight>,
822 collapse_matches: bool,
823 autoindent_mode: Option<AutoindentMode>,
824 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
825 input_enabled: bool,
826 use_modal_editing: bool,
827 read_only: bool,
828 leader_peer_id: Option<PeerId>,
829 remote_id: Option<ViewId>,
830 hover_state: HoverState,
831 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
832 gutter_hovered: bool,
833 hovered_link_state: Option<HoveredLinkState>,
834 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
835 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
836 active_inline_completion: Option<InlineCompletionState>,
837 /// Used to prevent flickering as the user types while the menu is open
838 stale_inline_completion_in_menu: Option<InlineCompletionState>,
839 edit_prediction_settings: EditPredictionSettings,
840 inline_completions_hidden_for_vim_mode: bool,
841 show_inline_completions_override: Option<bool>,
842 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
843 edit_prediction_preview: EditPredictionPreview,
844 edit_prediction_indent_conflict: bool,
845 edit_prediction_requires_modifier_in_indent_conflict: bool,
846 inlay_hint_cache: InlayHintCache,
847 next_inlay_id: usize,
848 _subscriptions: Vec<Subscription>,
849 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
850 gutter_dimensions: GutterDimensions,
851 style: Option<EditorStyle>,
852 text_style_refinement: Option<TextStyleRefinement>,
853 next_editor_action_id: EditorActionId,
854 editor_actions:
855 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
856 use_autoclose: bool,
857 use_auto_surround: bool,
858 auto_replace_emoji_shortcode: bool,
859 jsx_tag_auto_close_enabled_in_any_buffer: bool,
860 show_git_blame_gutter: bool,
861 show_git_blame_inline: bool,
862 show_git_blame_inline_delay_task: Option<Task<()>>,
863 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
864 git_blame_inline_enabled: bool,
865 render_diff_hunk_controls: RenderDiffHunkControlsFn,
866 serialize_dirty_buffers: bool,
867 show_selection_menu: Option<bool>,
868 blame: Option<Entity<GitBlame>>,
869 blame_subscription: Option<Subscription>,
870 custom_context_menu: Option<
871 Box<
872 dyn 'static
873 + Fn(
874 &mut Self,
875 DisplayPoint,
876 &mut Window,
877 &mut Context<Self>,
878 ) -> Option<Entity<ui::ContextMenu>>,
879 >,
880 >,
881 last_bounds: Option<Bounds<Pixels>>,
882 last_position_map: Option<Rc<PositionMap>>,
883 expect_bounds_change: Option<Bounds<Pixels>>,
884 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
885 tasks_update_task: Option<Task<()>>,
886 breakpoint_store: Option<Entity<BreakpointStore>>,
887 /// Allow's a user to create a breakpoint by selecting this indicator
888 /// It should be None while a user is not hovering over the gutter
889 /// Otherwise it represents the point that the breakpoint will be shown
890 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
891 in_project_search: bool,
892 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
893 breadcrumb_header: Option<String>,
894 focused_block: Option<FocusedBlock>,
895 next_scroll_position: NextScrollCursorCenterTopBottom,
896 addons: HashMap<TypeId, Box<dyn Addon>>,
897 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
898 load_diff_task: Option<Shared<Task<()>>>,
899 selection_mark_mode: bool,
900 toggle_fold_multiple_buffers: Task<()>,
901 _scroll_cursor_center_top_bottom_task: Task<()>,
902 serialize_selections: Task<()>,
903 serialize_folds: Task<()>,
904 mouse_cursor_hidden: bool,
905 hide_mouse_mode: HideMouseMode,
906 pub change_list: ChangeList,
907}
908
909#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
910enum NextScrollCursorCenterTopBottom {
911 #[default]
912 Center,
913 Top,
914 Bottom,
915}
916
917impl NextScrollCursorCenterTopBottom {
918 fn next(&self) -> Self {
919 match self {
920 Self::Center => Self::Top,
921 Self::Top => Self::Bottom,
922 Self::Bottom => Self::Center,
923 }
924 }
925}
926
927#[derive(Clone)]
928pub struct EditorSnapshot {
929 pub mode: EditorMode,
930 show_gutter: bool,
931 show_line_numbers: Option<bool>,
932 show_git_diff_gutter: Option<bool>,
933 show_code_actions: Option<bool>,
934 show_runnables: Option<bool>,
935 show_breakpoints: Option<bool>,
936 git_blame_gutter_max_author_length: Option<usize>,
937 pub display_snapshot: DisplaySnapshot,
938 pub placeholder_text: Option<Arc<str>>,
939 is_focused: bool,
940 scroll_anchor: ScrollAnchor,
941 ongoing_scroll: OngoingScroll,
942 current_line_highlight: CurrentLineHighlight,
943 gutter_hovered: bool,
944}
945
946#[derive(Default, Debug, Clone, Copy)]
947pub struct GutterDimensions {
948 pub left_padding: Pixels,
949 pub right_padding: Pixels,
950 pub width: Pixels,
951 pub margin: Pixels,
952 pub git_blame_entries_width: Option<Pixels>,
953}
954
955impl GutterDimensions {
956 /// The full width of the space taken up by the gutter.
957 pub fn full_width(&self) -> Pixels {
958 self.margin + self.width
959 }
960
961 /// The width of the space reserved for the fold indicators,
962 /// use alongside 'justify_end' and `gutter_width` to
963 /// right align content with the line numbers
964 pub fn fold_area_width(&self) -> Pixels {
965 self.margin + self.right_padding
966 }
967}
968
969#[derive(Debug)]
970pub struct RemoteSelection {
971 pub replica_id: ReplicaId,
972 pub selection: Selection<Anchor>,
973 pub cursor_shape: CursorShape,
974 pub peer_id: PeerId,
975 pub line_mode: bool,
976 pub participant_index: Option<ParticipantIndex>,
977 pub user_name: Option<SharedString>,
978}
979
980#[derive(Clone, Debug)]
981struct SelectionHistoryEntry {
982 selections: Arc<[Selection<Anchor>]>,
983 select_next_state: Option<SelectNextState>,
984 select_prev_state: Option<SelectNextState>,
985 add_selections_state: Option<AddSelectionsState>,
986}
987
988enum SelectionHistoryMode {
989 Normal,
990 Undoing,
991 Redoing,
992}
993
994#[derive(Clone, PartialEq, Eq, Hash)]
995struct HoveredCursor {
996 replica_id: u16,
997 selection_id: usize,
998}
999
1000impl Default for SelectionHistoryMode {
1001 fn default() -> Self {
1002 Self::Normal
1003 }
1004}
1005
1006#[derive(Default)]
1007struct SelectionHistory {
1008 #[allow(clippy::type_complexity)]
1009 selections_by_transaction:
1010 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1011 mode: SelectionHistoryMode,
1012 undo_stack: VecDeque<SelectionHistoryEntry>,
1013 redo_stack: VecDeque<SelectionHistoryEntry>,
1014}
1015
1016impl SelectionHistory {
1017 fn insert_transaction(
1018 &mut self,
1019 transaction_id: TransactionId,
1020 selections: Arc<[Selection<Anchor>]>,
1021 ) {
1022 self.selections_by_transaction
1023 .insert(transaction_id, (selections, None));
1024 }
1025
1026 #[allow(clippy::type_complexity)]
1027 fn transaction(
1028 &self,
1029 transaction_id: TransactionId,
1030 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1031 self.selections_by_transaction.get(&transaction_id)
1032 }
1033
1034 #[allow(clippy::type_complexity)]
1035 fn transaction_mut(
1036 &mut self,
1037 transaction_id: TransactionId,
1038 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1039 self.selections_by_transaction.get_mut(&transaction_id)
1040 }
1041
1042 fn push(&mut self, entry: SelectionHistoryEntry) {
1043 if !entry.selections.is_empty() {
1044 match self.mode {
1045 SelectionHistoryMode::Normal => {
1046 self.push_undo(entry);
1047 self.redo_stack.clear();
1048 }
1049 SelectionHistoryMode::Undoing => self.push_redo(entry),
1050 SelectionHistoryMode::Redoing => self.push_undo(entry),
1051 }
1052 }
1053 }
1054
1055 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1056 if self
1057 .undo_stack
1058 .back()
1059 .map_or(true, |e| e.selections != entry.selections)
1060 {
1061 self.undo_stack.push_back(entry);
1062 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1063 self.undo_stack.pop_front();
1064 }
1065 }
1066 }
1067
1068 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1069 if self
1070 .redo_stack
1071 .back()
1072 .map_or(true, |e| e.selections != entry.selections)
1073 {
1074 self.redo_stack.push_back(entry);
1075 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1076 self.redo_stack.pop_front();
1077 }
1078 }
1079 }
1080}
1081
1082struct RowHighlight {
1083 index: usize,
1084 range: Range<Anchor>,
1085 color: Hsla,
1086 should_autoscroll: bool,
1087}
1088
1089#[derive(Clone, Debug)]
1090struct AddSelectionsState {
1091 above: bool,
1092 stack: Vec<usize>,
1093}
1094
1095#[derive(Clone)]
1096struct SelectNextState {
1097 query: AhoCorasick,
1098 wordwise: bool,
1099 done: bool,
1100}
1101
1102impl std::fmt::Debug for SelectNextState {
1103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1104 f.debug_struct(std::any::type_name::<Self>())
1105 .field("wordwise", &self.wordwise)
1106 .field("done", &self.done)
1107 .finish()
1108 }
1109}
1110
1111#[derive(Debug)]
1112struct AutocloseRegion {
1113 selection_id: usize,
1114 range: Range<Anchor>,
1115 pair: BracketPair,
1116}
1117
1118#[derive(Debug)]
1119struct SnippetState {
1120 ranges: Vec<Vec<Range<Anchor>>>,
1121 active_index: usize,
1122 choices: Vec<Option<Vec<String>>>,
1123}
1124
1125#[doc(hidden)]
1126pub struct RenameState {
1127 pub range: Range<Anchor>,
1128 pub old_name: Arc<str>,
1129 pub editor: Entity<Editor>,
1130 block_id: CustomBlockId,
1131}
1132
1133struct InvalidationStack<T>(Vec<T>);
1134
1135struct RegisteredInlineCompletionProvider {
1136 provider: Arc<dyn InlineCompletionProviderHandle>,
1137 _subscription: Subscription,
1138}
1139
1140#[derive(Debug, PartialEq, Eq)]
1141pub struct ActiveDiagnosticGroup {
1142 pub active_range: Range<Anchor>,
1143 pub active_message: String,
1144 pub group_id: usize,
1145 pub blocks: HashSet<CustomBlockId>,
1146}
1147
1148#[derive(Debug, PartialEq, Eq)]
1149#[allow(clippy::large_enum_variant)]
1150pub(crate) enum ActiveDiagnostic {
1151 None,
1152 All,
1153 Group(ActiveDiagnosticGroup),
1154}
1155
1156#[derive(Serialize, Deserialize, Clone, Debug)]
1157pub struct ClipboardSelection {
1158 /// The number of bytes in this selection.
1159 pub len: usize,
1160 /// Whether this was a full-line selection.
1161 pub is_entire_line: bool,
1162 /// The indentation of the first line when this content was originally copied.
1163 pub first_line_indent: u32,
1164}
1165
1166// selections, scroll behavior, was newest selection reversed
1167type SelectSyntaxNodeHistoryState = (
1168 Box<[Selection<usize>]>,
1169 SelectSyntaxNodeScrollBehavior,
1170 bool,
1171);
1172
1173#[derive(Default)]
1174struct SelectSyntaxNodeHistory {
1175 stack: Vec<SelectSyntaxNodeHistoryState>,
1176 // disable temporarily to allow changing selections without losing the stack
1177 pub disable_clearing: bool,
1178}
1179
1180impl SelectSyntaxNodeHistory {
1181 pub fn try_clear(&mut self) {
1182 if !self.disable_clearing {
1183 self.stack.clear();
1184 }
1185 }
1186
1187 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1188 self.stack.push(selection);
1189 }
1190
1191 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1192 self.stack.pop()
1193 }
1194}
1195
1196enum SelectSyntaxNodeScrollBehavior {
1197 CursorTop,
1198 FitSelection,
1199 CursorBottom,
1200}
1201
1202#[derive(Debug)]
1203pub(crate) struct NavigationData {
1204 cursor_anchor: Anchor,
1205 cursor_position: Point,
1206 scroll_anchor: ScrollAnchor,
1207 scroll_top_row: u32,
1208}
1209
1210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1211pub enum GotoDefinitionKind {
1212 Symbol,
1213 Declaration,
1214 Type,
1215 Implementation,
1216}
1217
1218#[derive(Debug, Clone)]
1219enum InlayHintRefreshReason {
1220 ModifiersChanged(bool),
1221 Toggle(bool),
1222 SettingsChange(InlayHintSettings),
1223 NewLinesShown,
1224 BufferEdited(HashSet<Arc<Language>>),
1225 RefreshRequested,
1226 ExcerptsRemoved(Vec<ExcerptId>),
1227}
1228
1229impl InlayHintRefreshReason {
1230 fn description(&self) -> &'static str {
1231 match self {
1232 Self::ModifiersChanged(_) => "modifiers changed",
1233 Self::Toggle(_) => "toggle",
1234 Self::SettingsChange(_) => "settings change",
1235 Self::NewLinesShown => "new lines shown",
1236 Self::BufferEdited(_) => "buffer edited",
1237 Self::RefreshRequested => "refresh requested",
1238 Self::ExcerptsRemoved(_) => "excerpts removed",
1239 }
1240 }
1241}
1242
1243pub enum FormatTarget {
1244 Buffers,
1245 Ranges(Vec<Range<MultiBufferPoint>>),
1246}
1247
1248pub(crate) struct FocusedBlock {
1249 id: BlockId,
1250 focus_handle: WeakFocusHandle,
1251}
1252
1253#[derive(Clone)]
1254enum JumpData {
1255 MultiBufferRow {
1256 row: MultiBufferRow,
1257 line_offset_from_top: u32,
1258 },
1259 MultiBufferPoint {
1260 excerpt_id: ExcerptId,
1261 position: Point,
1262 anchor: text::Anchor,
1263 line_offset_from_top: u32,
1264 },
1265}
1266
1267pub enum MultibufferSelectionMode {
1268 First,
1269 All,
1270}
1271
1272#[derive(Clone, Copy, Debug, Default)]
1273pub struct RewrapOptions {
1274 pub override_language_settings: bool,
1275 pub preserve_existing_whitespace: bool,
1276}
1277
1278impl Editor {
1279 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1280 let buffer = cx.new(|cx| Buffer::local("", cx));
1281 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1282 Self::new(
1283 EditorMode::SingleLine { auto_width: false },
1284 buffer,
1285 None,
1286 window,
1287 cx,
1288 )
1289 }
1290
1291 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1292 let buffer = cx.new(|cx| Buffer::local("", cx));
1293 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1294 Self::new(EditorMode::full(), buffer, None, window, cx)
1295 }
1296
1297 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1298 let buffer = cx.new(|cx| Buffer::local("", cx));
1299 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1300 Self::new(
1301 EditorMode::SingleLine { auto_width: true },
1302 buffer,
1303 None,
1304 window,
1305 cx,
1306 )
1307 }
1308
1309 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1310 let buffer = cx.new(|cx| Buffer::local("", cx));
1311 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1312 Self::new(
1313 EditorMode::AutoHeight { max_lines },
1314 buffer,
1315 None,
1316 window,
1317 cx,
1318 )
1319 }
1320
1321 pub fn for_buffer(
1322 buffer: Entity<Buffer>,
1323 project: Option<Entity<Project>>,
1324 window: &mut Window,
1325 cx: &mut Context<Self>,
1326 ) -> Self {
1327 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1328 Self::new(EditorMode::full(), buffer, project, window, cx)
1329 }
1330
1331 pub fn for_multibuffer(
1332 buffer: Entity<MultiBuffer>,
1333 project: Option<Entity<Project>>,
1334 window: &mut Window,
1335 cx: &mut Context<Self>,
1336 ) -> Self {
1337 Self::new(EditorMode::full(), buffer, project, window, cx)
1338 }
1339
1340 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1341 let mut clone = Self::new(
1342 self.mode,
1343 self.buffer.clone(),
1344 self.project.clone(),
1345 window,
1346 cx,
1347 );
1348 self.display_map.update(cx, |display_map, cx| {
1349 let snapshot = display_map.snapshot(cx);
1350 clone.display_map.update(cx, |display_map, cx| {
1351 display_map.set_state(&snapshot, cx);
1352 });
1353 });
1354 clone.folds_did_change(cx);
1355 clone.selections.clone_state(&self.selections);
1356 clone.scroll_manager.clone_state(&self.scroll_manager);
1357 clone.searchable = self.searchable;
1358 clone.read_only = self.read_only;
1359 clone
1360 }
1361
1362 pub fn new(
1363 mode: EditorMode,
1364 buffer: Entity<MultiBuffer>,
1365 project: Option<Entity<Project>>,
1366 window: &mut Window,
1367 cx: &mut Context<Self>,
1368 ) -> Self {
1369 let style = window.text_style();
1370 let font_size = style.font_size.to_pixels(window.rem_size());
1371 let editor = cx.entity().downgrade();
1372 let fold_placeholder = FoldPlaceholder {
1373 constrain_width: true,
1374 render: Arc::new(move |fold_id, fold_range, cx| {
1375 let editor = editor.clone();
1376 div()
1377 .id(fold_id)
1378 .bg(cx.theme().colors().ghost_element_background)
1379 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1380 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1381 .rounded_xs()
1382 .size_full()
1383 .cursor_pointer()
1384 .child("⋯")
1385 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1386 .on_click(move |_, _window, cx| {
1387 editor
1388 .update(cx, |editor, cx| {
1389 editor.unfold_ranges(
1390 &[fold_range.start..fold_range.end],
1391 true,
1392 false,
1393 cx,
1394 );
1395 cx.stop_propagation();
1396 })
1397 .ok();
1398 })
1399 .into_any()
1400 }),
1401 merge_adjacent: true,
1402 ..Default::default()
1403 };
1404 let display_map = cx.new(|cx| {
1405 DisplayMap::new(
1406 buffer.clone(),
1407 style.font(),
1408 font_size,
1409 None,
1410 FILE_HEADER_HEIGHT,
1411 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1412 fold_placeholder,
1413 cx,
1414 )
1415 });
1416
1417 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1418
1419 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1420
1421 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1422 .then(|| language_settings::SoftWrap::None);
1423
1424 let mut project_subscriptions = Vec::new();
1425 if mode.is_full() {
1426 if let Some(project) = project.as_ref() {
1427 project_subscriptions.push(cx.subscribe_in(
1428 project,
1429 window,
1430 |editor, _, event, window, cx| match event {
1431 project::Event::RefreshCodeLens => {
1432 // we always query lens with actions, without storing them, always refreshing them
1433 }
1434 project::Event::RefreshInlayHints => {
1435 editor
1436 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1437 }
1438 project::Event::SnippetEdit(id, snippet_edits) => {
1439 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1440 let focus_handle = editor.focus_handle(cx);
1441 if focus_handle.is_focused(window) {
1442 let snapshot = buffer.read(cx).snapshot();
1443 for (range, snippet) in snippet_edits {
1444 let editor_range =
1445 language::range_from_lsp(*range).to_offset(&snapshot);
1446 editor
1447 .insert_snippet(
1448 &[editor_range],
1449 snippet.clone(),
1450 window,
1451 cx,
1452 )
1453 .ok();
1454 }
1455 }
1456 }
1457 }
1458 _ => {}
1459 },
1460 ));
1461 if let Some(task_inventory) = project
1462 .read(cx)
1463 .task_store()
1464 .read(cx)
1465 .task_inventory()
1466 .cloned()
1467 {
1468 project_subscriptions.push(cx.observe_in(
1469 &task_inventory,
1470 window,
1471 |editor, _, window, cx| {
1472 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1473 },
1474 ));
1475 };
1476
1477 project_subscriptions.push(cx.subscribe_in(
1478 &project.read(cx).breakpoint_store(),
1479 window,
1480 |editor, _, event, window, cx| match event {
1481 BreakpointStoreEvent::ActiveDebugLineChanged => {
1482 if editor.go_to_active_debug_line(window, cx) {
1483 cx.stop_propagation();
1484 }
1485 }
1486 _ => {}
1487 },
1488 ));
1489 }
1490 }
1491
1492 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1493
1494 let inlay_hint_settings =
1495 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1496 let focus_handle = cx.focus_handle();
1497 cx.on_focus(&focus_handle, window, Self::handle_focus)
1498 .detach();
1499 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1500 .detach();
1501 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1502 .detach();
1503 cx.on_blur(&focus_handle, window, Self::handle_blur)
1504 .detach();
1505
1506 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1507 Some(false)
1508 } else {
1509 None
1510 };
1511
1512 let breakpoint_store = match (mode, project.as_ref()) {
1513 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1514 _ => None,
1515 };
1516
1517 let mut code_action_providers = Vec::new();
1518 let mut load_uncommitted_diff = None;
1519 if let Some(project) = project.clone() {
1520 load_uncommitted_diff = Some(
1521 get_uncommitted_diff_for_buffer(
1522 &project,
1523 buffer.read(cx).all_buffers(),
1524 buffer.clone(),
1525 cx,
1526 )
1527 .shared(),
1528 );
1529 code_action_providers.push(Rc::new(project) as Rc<_>);
1530 }
1531
1532 let mut this = Self {
1533 focus_handle,
1534 show_cursor_when_unfocused: false,
1535 last_focused_descendant: None,
1536 buffer: buffer.clone(),
1537 display_map: display_map.clone(),
1538 selections,
1539 scroll_manager: ScrollManager::new(cx),
1540 columnar_selection_tail: None,
1541 add_selections_state: None,
1542 select_next_state: None,
1543 select_prev_state: None,
1544 selection_history: Default::default(),
1545 autoclose_regions: Default::default(),
1546 snippet_stack: Default::default(),
1547 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1548 ime_transaction: Default::default(),
1549 active_diagnostics: ActiveDiagnostic::None,
1550 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1551 inline_diagnostics_update: Task::ready(()),
1552 inline_diagnostics: Vec::new(),
1553 soft_wrap_mode_override,
1554 hard_wrap: None,
1555 completion_provider: project.clone().map(|project| Box::new(project) as _),
1556 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1557 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1558 project,
1559 blink_manager: blink_manager.clone(),
1560 show_local_selections: true,
1561 show_scrollbars: true,
1562 mode,
1563 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1564 show_gutter: mode.is_full(),
1565 show_line_numbers: None,
1566 use_relative_line_numbers: None,
1567 show_git_diff_gutter: None,
1568 show_code_actions: None,
1569 show_runnables: None,
1570 show_breakpoints: None,
1571 show_wrap_guides: None,
1572 show_indent_guides,
1573 placeholder_text: None,
1574 highlight_order: 0,
1575 highlighted_rows: HashMap::default(),
1576 background_highlights: Default::default(),
1577 gutter_highlights: TreeMap::default(),
1578 scrollbar_marker_state: ScrollbarMarkerState::default(),
1579 active_indent_guides_state: ActiveIndentGuidesState::default(),
1580 nav_history: None,
1581 context_menu: RefCell::new(None),
1582 context_menu_options: None,
1583 mouse_context_menu: None,
1584 completion_tasks: Default::default(),
1585 signature_help_state: SignatureHelpState::default(),
1586 auto_signature_help: None,
1587 find_all_references_task_sources: Vec::new(),
1588 next_completion_id: 0,
1589 next_inlay_id: 0,
1590 code_action_providers,
1591 available_code_actions: Default::default(),
1592 code_actions_task: Default::default(),
1593 selection_highlight_task: Default::default(),
1594 document_highlights_task: Default::default(),
1595 linked_editing_range_task: Default::default(),
1596 pending_rename: Default::default(),
1597 searchable: true,
1598 cursor_shape: EditorSettings::get_global(cx)
1599 .cursor_shape
1600 .unwrap_or_default(),
1601 current_line_highlight: None,
1602 autoindent_mode: Some(AutoindentMode::EachLine),
1603 collapse_matches: false,
1604 workspace: None,
1605 input_enabled: true,
1606 use_modal_editing: mode.is_full(),
1607 read_only: false,
1608 use_autoclose: true,
1609 use_auto_surround: true,
1610 auto_replace_emoji_shortcode: false,
1611 jsx_tag_auto_close_enabled_in_any_buffer: false,
1612 leader_peer_id: None,
1613 remote_id: None,
1614 hover_state: Default::default(),
1615 pending_mouse_down: None,
1616 hovered_link_state: Default::default(),
1617 edit_prediction_provider: None,
1618 active_inline_completion: None,
1619 stale_inline_completion_in_menu: None,
1620 edit_prediction_preview: EditPredictionPreview::Inactive {
1621 released_too_fast: false,
1622 },
1623 inline_diagnostics_enabled: mode.is_full(),
1624 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1625
1626 gutter_hovered: false,
1627 pixel_position_of_newest_cursor: None,
1628 last_bounds: None,
1629 last_position_map: None,
1630 expect_bounds_change: None,
1631 gutter_dimensions: GutterDimensions::default(),
1632 style: None,
1633 show_cursor_names: false,
1634 hovered_cursors: Default::default(),
1635 next_editor_action_id: EditorActionId::default(),
1636 editor_actions: Rc::default(),
1637 inline_completions_hidden_for_vim_mode: false,
1638 show_inline_completions_override: None,
1639 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1640 edit_prediction_settings: EditPredictionSettings::Disabled,
1641 edit_prediction_indent_conflict: false,
1642 edit_prediction_requires_modifier_in_indent_conflict: true,
1643 custom_context_menu: None,
1644 show_git_blame_gutter: false,
1645 show_git_blame_inline: false,
1646 show_selection_menu: None,
1647 show_git_blame_inline_delay_task: None,
1648 git_blame_inline_tooltip: None,
1649 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1650 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1651 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1652 .session
1653 .restore_unsaved_buffers,
1654 blame: None,
1655 blame_subscription: None,
1656 tasks: Default::default(),
1657
1658 breakpoint_store,
1659 gutter_breakpoint_indicator: (None, None),
1660 _subscriptions: vec![
1661 cx.observe(&buffer, Self::on_buffer_changed),
1662 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1663 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1664 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1665 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1666 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1667 cx.observe_window_activation(window, |editor, window, cx| {
1668 let active = window.is_window_active();
1669 editor.blink_manager.update(cx, |blink_manager, cx| {
1670 if active {
1671 blink_manager.enable(cx);
1672 } else {
1673 blink_manager.disable(cx);
1674 }
1675 });
1676 }),
1677 ],
1678 tasks_update_task: None,
1679 linked_edit_ranges: Default::default(),
1680 in_project_search: false,
1681 previous_search_ranges: None,
1682 breadcrumb_header: None,
1683 focused_block: None,
1684 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1685 addons: HashMap::default(),
1686 registered_buffers: HashMap::default(),
1687 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1688 selection_mark_mode: false,
1689 toggle_fold_multiple_buffers: Task::ready(()),
1690 serialize_selections: Task::ready(()),
1691 serialize_folds: Task::ready(()),
1692 text_style_refinement: None,
1693 load_diff_task: load_uncommitted_diff,
1694 mouse_cursor_hidden: false,
1695 hide_mouse_mode: EditorSettings::get_global(cx)
1696 .hide_mouse
1697 .unwrap_or_default(),
1698 change_list: ChangeList::new(),
1699 };
1700 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1701 this._subscriptions
1702 .push(cx.observe(breakpoints, |_, _, cx| {
1703 cx.notify();
1704 }));
1705 }
1706 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1707 this._subscriptions.extend(project_subscriptions);
1708
1709 this._subscriptions.push(cx.subscribe_in(
1710 &cx.entity(),
1711 window,
1712 |editor, _, e: &EditorEvent, window, cx| match e {
1713 EditorEvent::ScrollPositionChanged { local, .. } => {
1714 if *local {
1715 let new_anchor = editor.scroll_manager.anchor();
1716 let snapshot = editor.snapshot(window, cx);
1717 editor.update_restoration_data(cx, move |data| {
1718 data.scroll_position = (
1719 new_anchor.top_row(&snapshot.buffer_snapshot),
1720 new_anchor.offset,
1721 );
1722 });
1723 }
1724 }
1725 EditorEvent::Edited { .. } => {
1726 if !vim_enabled(cx) {
1727 let (map, selections) = editor.selections.all_adjusted_display(cx);
1728 let pop_state = editor
1729 .change_list
1730 .last()
1731 .map(|previous| {
1732 previous.len() == selections.len()
1733 && previous.iter().enumerate().all(|(ix, p)| {
1734 p.to_display_point(&map).row()
1735 == selections[ix].head().row()
1736 })
1737 })
1738 .unwrap_or(false);
1739 let new_positions = selections
1740 .into_iter()
1741 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1742 .collect();
1743 editor
1744 .change_list
1745 .push_to_change_list(pop_state, new_positions);
1746 }
1747 }
1748 _ => (),
1749 },
1750 ));
1751
1752 this.end_selection(window, cx);
1753 this.scroll_manager.show_scrollbars(window, cx);
1754 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1755
1756 if mode.is_full() {
1757 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1758 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1759
1760 if this.git_blame_inline_enabled {
1761 this.git_blame_inline_enabled = true;
1762 this.start_git_blame_inline(false, window, cx);
1763 }
1764
1765 this.go_to_active_debug_line(window, cx);
1766
1767 if let Some(buffer) = buffer.read(cx).as_singleton() {
1768 if let Some(project) = this.project.as_ref() {
1769 let handle = project.update(cx, |project, cx| {
1770 project.register_buffer_with_language_servers(&buffer, cx)
1771 });
1772 this.registered_buffers
1773 .insert(buffer.read(cx).remote_id(), handle);
1774 }
1775 }
1776 }
1777
1778 this.report_editor_event("Editor Opened", None, cx);
1779 this
1780 }
1781
1782 pub fn deploy_mouse_context_menu(
1783 &mut self,
1784 position: gpui::Point<Pixels>,
1785 context_menu: Entity<ContextMenu>,
1786 window: &mut Window,
1787 cx: &mut Context<Self>,
1788 ) {
1789 self.mouse_context_menu = Some(MouseContextMenu::new(
1790 self,
1791 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1792 context_menu,
1793 window,
1794 cx,
1795 ));
1796 }
1797
1798 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1799 self.mouse_context_menu
1800 .as_ref()
1801 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1802 }
1803
1804 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1805 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1806 }
1807
1808 fn key_context_internal(
1809 &self,
1810 has_active_edit_prediction: bool,
1811 window: &Window,
1812 cx: &App,
1813 ) -> KeyContext {
1814 let mut key_context = KeyContext::new_with_defaults();
1815 key_context.add("Editor");
1816 let mode = match self.mode {
1817 EditorMode::SingleLine { .. } => "single_line",
1818 EditorMode::AutoHeight { .. } => "auto_height",
1819 EditorMode::Full { .. } => "full",
1820 };
1821
1822 if EditorSettings::jupyter_enabled(cx) {
1823 key_context.add("jupyter");
1824 }
1825
1826 key_context.set("mode", mode);
1827 if self.pending_rename.is_some() {
1828 key_context.add("renaming");
1829 }
1830
1831 match self.context_menu.borrow().as_ref() {
1832 Some(CodeContextMenu::Completions(_)) => {
1833 key_context.add("menu");
1834 key_context.add("showing_completions");
1835 }
1836 Some(CodeContextMenu::CodeActions(_)) => {
1837 key_context.add("menu");
1838 key_context.add("showing_code_actions")
1839 }
1840 None => {}
1841 }
1842
1843 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1844 if !self.focus_handle(cx).contains_focused(window, cx)
1845 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1846 {
1847 for addon in self.addons.values() {
1848 addon.extend_key_context(&mut key_context, cx)
1849 }
1850 }
1851
1852 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1853 if let Some(extension) = singleton_buffer
1854 .read(cx)
1855 .file()
1856 .and_then(|file| file.path().extension()?.to_str())
1857 {
1858 key_context.set("extension", extension.to_string());
1859 }
1860 } else {
1861 key_context.add("multibuffer");
1862 }
1863
1864 if has_active_edit_prediction {
1865 if self.edit_prediction_in_conflict() {
1866 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1867 } else {
1868 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1869 key_context.add("copilot_suggestion");
1870 }
1871 }
1872
1873 if self.selection_mark_mode {
1874 key_context.add("selection_mode");
1875 }
1876
1877 key_context
1878 }
1879
1880 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1881 self.mouse_cursor_hidden = match origin {
1882 HideMouseCursorOrigin::TypingAction => {
1883 matches!(
1884 self.hide_mouse_mode,
1885 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1886 )
1887 }
1888 HideMouseCursorOrigin::MovementAction => {
1889 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1890 }
1891 };
1892 }
1893
1894 pub fn edit_prediction_in_conflict(&self) -> bool {
1895 if !self.show_edit_predictions_in_menu() {
1896 return false;
1897 }
1898
1899 let showing_completions = self
1900 .context_menu
1901 .borrow()
1902 .as_ref()
1903 .map_or(false, |context| {
1904 matches!(context, CodeContextMenu::Completions(_))
1905 });
1906
1907 showing_completions
1908 || self.edit_prediction_requires_modifier()
1909 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1910 // bindings to insert tab characters.
1911 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1912 }
1913
1914 pub fn accept_edit_prediction_keybind(
1915 &self,
1916 window: &Window,
1917 cx: &App,
1918 ) -> AcceptEditPredictionBinding {
1919 let key_context = self.key_context_internal(true, window, cx);
1920 let in_conflict = self.edit_prediction_in_conflict();
1921
1922 AcceptEditPredictionBinding(
1923 window
1924 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1925 .into_iter()
1926 .filter(|binding| {
1927 !in_conflict
1928 || binding
1929 .keystrokes()
1930 .first()
1931 .map_or(false, |keystroke| keystroke.modifiers.modified())
1932 })
1933 .rev()
1934 .min_by_key(|binding| {
1935 binding
1936 .keystrokes()
1937 .first()
1938 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1939 }),
1940 )
1941 }
1942
1943 pub fn new_file(
1944 workspace: &mut Workspace,
1945 _: &workspace::NewFile,
1946 window: &mut Window,
1947 cx: &mut Context<Workspace>,
1948 ) {
1949 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1950 "Failed to create buffer",
1951 window,
1952 cx,
1953 |e, _, _| match e.error_code() {
1954 ErrorCode::RemoteUpgradeRequired => Some(format!(
1955 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1956 e.error_tag("required").unwrap_or("the latest version")
1957 )),
1958 _ => None,
1959 },
1960 );
1961 }
1962
1963 pub fn new_in_workspace(
1964 workspace: &mut Workspace,
1965 window: &mut Window,
1966 cx: &mut Context<Workspace>,
1967 ) -> Task<Result<Entity<Editor>>> {
1968 let project = workspace.project().clone();
1969 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1970
1971 cx.spawn_in(window, async move |workspace, cx| {
1972 let buffer = create.await?;
1973 workspace.update_in(cx, |workspace, window, cx| {
1974 let editor =
1975 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1976 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1977 editor
1978 })
1979 })
1980 }
1981
1982 fn new_file_vertical(
1983 workspace: &mut Workspace,
1984 _: &workspace::NewFileSplitVertical,
1985 window: &mut Window,
1986 cx: &mut Context<Workspace>,
1987 ) {
1988 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1989 }
1990
1991 fn new_file_horizontal(
1992 workspace: &mut Workspace,
1993 _: &workspace::NewFileSplitHorizontal,
1994 window: &mut Window,
1995 cx: &mut Context<Workspace>,
1996 ) {
1997 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1998 }
1999
2000 fn new_file_in_direction(
2001 workspace: &mut Workspace,
2002 direction: SplitDirection,
2003 window: &mut Window,
2004 cx: &mut Context<Workspace>,
2005 ) {
2006 let project = workspace.project().clone();
2007 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2008
2009 cx.spawn_in(window, async move |workspace, cx| {
2010 let buffer = create.await?;
2011 workspace.update_in(cx, move |workspace, window, cx| {
2012 workspace.split_item(
2013 direction,
2014 Box::new(
2015 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2016 ),
2017 window,
2018 cx,
2019 )
2020 })?;
2021 anyhow::Ok(())
2022 })
2023 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2024 match e.error_code() {
2025 ErrorCode::RemoteUpgradeRequired => Some(format!(
2026 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2027 e.error_tag("required").unwrap_or("the latest version")
2028 )),
2029 _ => None,
2030 }
2031 });
2032 }
2033
2034 pub fn leader_peer_id(&self) -> Option<PeerId> {
2035 self.leader_peer_id
2036 }
2037
2038 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2039 &self.buffer
2040 }
2041
2042 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2043 self.workspace.as_ref()?.0.upgrade()
2044 }
2045
2046 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2047 self.buffer().read(cx).title(cx)
2048 }
2049
2050 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2051 let git_blame_gutter_max_author_length = self
2052 .render_git_blame_gutter(cx)
2053 .then(|| {
2054 if let Some(blame) = self.blame.as_ref() {
2055 let max_author_length =
2056 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2057 Some(max_author_length)
2058 } else {
2059 None
2060 }
2061 })
2062 .flatten();
2063
2064 EditorSnapshot {
2065 mode: self.mode,
2066 show_gutter: self.show_gutter,
2067 show_line_numbers: self.show_line_numbers,
2068 show_git_diff_gutter: self.show_git_diff_gutter,
2069 show_code_actions: self.show_code_actions,
2070 show_runnables: self.show_runnables,
2071 show_breakpoints: self.show_breakpoints,
2072 git_blame_gutter_max_author_length,
2073 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2074 scroll_anchor: self.scroll_manager.anchor(),
2075 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2076 placeholder_text: self.placeholder_text.clone(),
2077 is_focused: self.focus_handle.is_focused(window),
2078 current_line_highlight: self
2079 .current_line_highlight
2080 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2081 gutter_hovered: self.gutter_hovered,
2082 }
2083 }
2084
2085 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2086 self.buffer.read(cx).language_at(point, cx)
2087 }
2088
2089 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2090 self.buffer.read(cx).read(cx).file_at(point).cloned()
2091 }
2092
2093 pub fn active_excerpt(
2094 &self,
2095 cx: &App,
2096 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2097 self.buffer
2098 .read(cx)
2099 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2100 }
2101
2102 pub fn mode(&self) -> EditorMode {
2103 self.mode
2104 }
2105
2106 pub fn set_mode(&mut self, mode: EditorMode) {
2107 self.mode = mode;
2108 }
2109
2110 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2111 self.collaboration_hub.as_deref()
2112 }
2113
2114 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2115 self.collaboration_hub = Some(hub);
2116 }
2117
2118 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2119 self.in_project_search = in_project_search;
2120 }
2121
2122 pub fn set_custom_context_menu(
2123 &mut self,
2124 f: impl 'static
2125 + Fn(
2126 &mut Self,
2127 DisplayPoint,
2128 &mut Window,
2129 &mut Context<Self>,
2130 ) -> Option<Entity<ui::ContextMenu>>,
2131 ) {
2132 self.custom_context_menu = Some(Box::new(f))
2133 }
2134
2135 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2136 self.completion_provider = provider;
2137 }
2138
2139 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2140 self.semantics_provider.clone()
2141 }
2142
2143 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2144 self.semantics_provider = provider;
2145 }
2146
2147 pub fn set_edit_prediction_provider<T>(
2148 &mut self,
2149 provider: Option<Entity<T>>,
2150 window: &mut Window,
2151 cx: &mut Context<Self>,
2152 ) where
2153 T: EditPredictionProvider,
2154 {
2155 self.edit_prediction_provider =
2156 provider.map(|provider| RegisteredInlineCompletionProvider {
2157 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2158 if this.focus_handle.is_focused(window) {
2159 this.update_visible_inline_completion(window, cx);
2160 }
2161 }),
2162 provider: Arc::new(provider),
2163 });
2164 self.update_edit_prediction_settings(cx);
2165 self.refresh_inline_completion(false, false, window, cx);
2166 }
2167
2168 pub fn placeholder_text(&self) -> Option<&str> {
2169 self.placeholder_text.as_deref()
2170 }
2171
2172 pub fn set_placeholder_text(
2173 &mut self,
2174 placeholder_text: impl Into<Arc<str>>,
2175 cx: &mut Context<Self>,
2176 ) {
2177 let placeholder_text = Some(placeholder_text.into());
2178 if self.placeholder_text != placeholder_text {
2179 self.placeholder_text = placeholder_text;
2180 cx.notify();
2181 }
2182 }
2183
2184 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2185 self.cursor_shape = cursor_shape;
2186
2187 // Disrupt blink for immediate user feedback that the cursor shape has changed
2188 self.blink_manager.update(cx, BlinkManager::show_cursor);
2189
2190 cx.notify();
2191 }
2192
2193 pub fn set_current_line_highlight(
2194 &mut self,
2195 current_line_highlight: Option<CurrentLineHighlight>,
2196 ) {
2197 self.current_line_highlight = current_line_highlight;
2198 }
2199
2200 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2201 self.collapse_matches = collapse_matches;
2202 }
2203
2204 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2205 let buffers = self.buffer.read(cx).all_buffers();
2206 let Some(project) = self.project.as_ref() else {
2207 return;
2208 };
2209 project.update(cx, |project, cx| {
2210 for buffer in buffers {
2211 self.registered_buffers
2212 .entry(buffer.read(cx).remote_id())
2213 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2214 }
2215 })
2216 }
2217
2218 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2219 if self.collapse_matches {
2220 return range.start..range.start;
2221 }
2222 range.clone()
2223 }
2224
2225 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2226 if self.display_map.read(cx).clip_at_line_ends != clip {
2227 self.display_map
2228 .update(cx, |map, _| map.clip_at_line_ends = clip);
2229 }
2230 }
2231
2232 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2233 self.input_enabled = input_enabled;
2234 }
2235
2236 pub fn set_inline_completions_hidden_for_vim_mode(
2237 &mut self,
2238 hidden: bool,
2239 window: &mut Window,
2240 cx: &mut Context<Self>,
2241 ) {
2242 if hidden != self.inline_completions_hidden_for_vim_mode {
2243 self.inline_completions_hidden_for_vim_mode = hidden;
2244 if hidden {
2245 self.update_visible_inline_completion(window, cx);
2246 } else {
2247 self.refresh_inline_completion(true, false, window, cx);
2248 }
2249 }
2250 }
2251
2252 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2253 self.menu_inline_completions_policy = value;
2254 }
2255
2256 pub fn set_autoindent(&mut self, autoindent: bool) {
2257 if autoindent {
2258 self.autoindent_mode = Some(AutoindentMode::EachLine);
2259 } else {
2260 self.autoindent_mode = None;
2261 }
2262 }
2263
2264 pub fn read_only(&self, cx: &App) -> bool {
2265 self.read_only || self.buffer.read(cx).read_only()
2266 }
2267
2268 pub fn set_read_only(&mut self, read_only: bool) {
2269 self.read_only = read_only;
2270 }
2271
2272 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2273 self.use_autoclose = autoclose;
2274 }
2275
2276 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2277 self.use_auto_surround = auto_surround;
2278 }
2279
2280 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2281 self.auto_replace_emoji_shortcode = auto_replace;
2282 }
2283
2284 pub fn toggle_edit_predictions(
2285 &mut self,
2286 _: &ToggleEditPrediction,
2287 window: &mut Window,
2288 cx: &mut Context<Self>,
2289 ) {
2290 if self.show_inline_completions_override.is_some() {
2291 self.set_show_edit_predictions(None, window, cx);
2292 } else {
2293 let show_edit_predictions = !self.edit_predictions_enabled();
2294 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2295 }
2296 }
2297
2298 pub fn set_show_edit_predictions(
2299 &mut self,
2300 show_edit_predictions: Option<bool>,
2301 window: &mut Window,
2302 cx: &mut Context<Self>,
2303 ) {
2304 self.show_inline_completions_override = show_edit_predictions;
2305 self.update_edit_prediction_settings(cx);
2306
2307 if let Some(false) = show_edit_predictions {
2308 self.discard_inline_completion(false, cx);
2309 } else {
2310 self.refresh_inline_completion(false, true, window, cx);
2311 }
2312 }
2313
2314 fn inline_completions_disabled_in_scope(
2315 &self,
2316 buffer: &Entity<Buffer>,
2317 buffer_position: language::Anchor,
2318 cx: &App,
2319 ) -> bool {
2320 let snapshot = buffer.read(cx).snapshot();
2321 let settings = snapshot.settings_at(buffer_position, cx);
2322
2323 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2324 return false;
2325 };
2326
2327 scope.override_name().map_or(false, |scope_name| {
2328 settings
2329 .edit_predictions_disabled_in
2330 .iter()
2331 .any(|s| s == scope_name)
2332 })
2333 }
2334
2335 pub fn set_use_modal_editing(&mut self, to: bool) {
2336 self.use_modal_editing = to;
2337 }
2338
2339 pub fn use_modal_editing(&self) -> bool {
2340 self.use_modal_editing
2341 }
2342
2343 fn selections_did_change(
2344 &mut self,
2345 local: bool,
2346 old_cursor_position: &Anchor,
2347 show_completions: bool,
2348 window: &mut Window,
2349 cx: &mut Context<Self>,
2350 ) {
2351 window.invalidate_character_coordinates();
2352
2353 // Copy selections to primary selection buffer
2354 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2355 if local {
2356 let selections = self.selections.all::<usize>(cx);
2357 let buffer_handle = self.buffer.read(cx).read(cx);
2358
2359 let mut text = String::new();
2360 for (index, selection) in selections.iter().enumerate() {
2361 let text_for_selection = buffer_handle
2362 .text_for_range(selection.start..selection.end)
2363 .collect::<String>();
2364
2365 text.push_str(&text_for_selection);
2366 if index != selections.len() - 1 {
2367 text.push('\n');
2368 }
2369 }
2370
2371 if !text.is_empty() {
2372 cx.write_to_primary(ClipboardItem::new_string(text));
2373 }
2374 }
2375
2376 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2377 self.buffer.update(cx, |buffer, cx| {
2378 buffer.set_active_selections(
2379 &self.selections.disjoint_anchors(),
2380 self.selections.line_mode,
2381 self.cursor_shape,
2382 cx,
2383 )
2384 });
2385 }
2386 let display_map = self
2387 .display_map
2388 .update(cx, |display_map, cx| display_map.snapshot(cx));
2389 let buffer = &display_map.buffer_snapshot;
2390 self.add_selections_state = None;
2391 self.select_next_state = None;
2392 self.select_prev_state = None;
2393 self.select_syntax_node_history.try_clear();
2394 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2395 self.snippet_stack
2396 .invalidate(&self.selections.disjoint_anchors(), buffer);
2397 self.take_rename(false, window, cx);
2398
2399 let new_cursor_position = self.selections.newest_anchor().head();
2400
2401 self.push_to_nav_history(
2402 *old_cursor_position,
2403 Some(new_cursor_position.to_point(buffer)),
2404 false,
2405 cx,
2406 );
2407
2408 if local {
2409 let new_cursor_position = self.selections.newest_anchor().head();
2410 let mut context_menu = self.context_menu.borrow_mut();
2411 let completion_menu = match context_menu.as_ref() {
2412 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2413 _ => {
2414 *context_menu = None;
2415 None
2416 }
2417 };
2418 if let Some(buffer_id) = new_cursor_position.buffer_id {
2419 if !self.registered_buffers.contains_key(&buffer_id) {
2420 if let Some(project) = self.project.as_ref() {
2421 project.update(cx, |project, cx| {
2422 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2423 return;
2424 };
2425 self.registered_buffers.insert(
2426 buffer_id,
2427 project.register_buffer_with_language_servers(&buffer, cx),
2428 );
2429 })
2430 }
2431 }
2432 }
2433
2434 if let Some(completion_menu) = completion_menu {
2435 let cursor_position = new_cursor_position.to_offset(buffer);
2436 let (word_range, kind) =
2437 buffer.surrounding_word(completion_menu.initial_position, true);
2438 if kind == Some(CharKind::Word)
2439 && word_range.to_inclusive().contains(&cursor_position)
2440 {
2441 let mut completion_menu = completion_menu.clone();
2442 drop(context_menu);
2443
2444 let query = Self::completion_query(buffer, cursor_position);
2445 cx.spawn(async move |this, cx| {
2446 completion_menu
2447 .filter(query.as_deref(), cx.background_executor().clone())
2448 .await;
2449
2450 this.update(cx, |this, cx| {
2451 let mut context_menu = this.context_menu.borrow_mut();
2452 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2453 else {
2454 return;
2455 };
2456
2457 if menu.id > completion_menu.id {
2458 return;
2459 }
2460
2461 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2462 drop(context_menu);
2463 cx.notify();
2464 })
2465 })
2466 .detach();
2467
2468 if show_completions {
2469 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2470 }
2471 } else {
2472 drop(context_menu);
2473 self.hide_context_menu(window, cx);
2474 }
2475 } else {
2476 drop(context_menu);
2477 }
2478
2479 hide_hover(self, cx);
2480
2481 if old_cursor_position.to_display_point(&display_map).row()
2482 != new_cursor_position.to_display_point(&display_map).row()
2483 {
2484 self.available_code_actions.take();
2485 }
2486 self.refresh_code_actions(window, cx);
2487 self.refresh_document_highlights(cx);
2488 self.refresh_selected_text_highlights(window, cx);
2489 refresh_matching_bracket_highlights(self, window, cx);
2490 self.update_visible_inline_completion(window, cx);
2491 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2492 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2493 if self.git_blame_inline_enabled {
2494 self.start_inline_blame_timer(window, cx);
2495 }
2496 }
2497
2498 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2499 cx.emit(EditorEvent::SelectionsChanged { local });
2500
2501 let selections = &self.selections.disjoint;
2502 if selections.len() == 1 {
2503 cx.emit(SearchEvent::ActiveMatchChanged)
2504 }
2505 if local {
2506 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2507 let inmemory_selections = selections
2508 .iter()
2509 .map(|s| {
2510 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2511 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2512 })
2513 .collect();
2514 self.update_restoration_data(cx, |data| {
2515 data.selections = inmemory_selections;
2516 });
2517
2518 if WorkspaceSettings::get(None, cx).restore_on_startup
2519 != RestoreOnStartupBehavior::None
2520 {
2521 if let Some(workspace_id) =
2522 self.workspace.as_ref().and_then(|workspace| workspace.1)
2523 {
2524 let snapshot = self.buffer().read(cx).snapshot(cx);
2525 let selections = selections.clone();
2526 let background_executor = cx.background_executor().clone();
2527 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2528 self.serialize_selections = cx.background_spawn(async move {
2529 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2530 let db_selections = selections
2531 .iter()
2532 .map(|selection| {
2533 (
2534 selection.start.to_offset(&snapshot),
2535 selection.end.to_offset(&snapshot),
2536 )
2537 })
2538 .collect();
2539
2540 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2541 .await
2542 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2543 .log_err();
2544 });
2545 }
2546 }
2547 }
2548 }
2549
2550 cx.notify();
2551 }
2552
2553 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2554 use text::ToOffset as _;
2555 use text::ToPoint as _;
2556
2557 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2558 return;
2559 }
2560
2561 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2562 return;
2563 };
2564
2565 let snapshot = singleton.read(cx).snapshot();
2566 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2567 let display_snapshot = display_map.snapshot(cx);
2568
2569 display_snapshot
2570 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2571 .map(|fold| {
2572 fold.range.start.text_anchor.to_point(&snapshot)
2573 ..fold.range.end.text_anchor.to_point(&snapshot)
2574 })
2575 .collect()
2576 });
2577 self.update_restoration_data(cx, |data| {
2578 data.folds = inmemory_folds;
2579 });
2580
2581 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2582 return;
2583 };
2584 let background_executor = cx.background_executor().clone();
2585 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2586 let db_folds = self.display_map.update(cx, |display_map, cx| {
2587 display_map
2588 .snapshot(cx)
2589 .folds_in_range(0..snapshot.len())
2590 .map(|fold| {
2591 (
2592 fold.range.start.text_anchor.to_offset(&snapshot),
2593 fold.range.end.text_anchor.to_offset(&snapshot),
2594 )
2595 })
2596 .collect()
2597 });
2598 self.serialize_folds = cx.background_spawn(async move {
2599 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2600 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2601 .await
2602 .with_context(|| {
2603 format!(
2604 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2605 )
2606 })
2607 .log_err();
2608 });
2609 }
2610
2611 pub fn sync_selections(
2612 &mut self,
2613 other: Entity<Editor>,
2614 cx: &mut Context<Self>,
2615 ) -> gpui::Subscription {
2616 let other_selections = other.read(cx).selections.disjoint.to_vec();
2617 self.selections.change_with(cx, |selections| {
2618 selections.select_anchors(other_selections);
2619 });
2620
2621 let other_subscription =
2622 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2623 EditorEvent::SelectionsChanged { local: true } => {
2624 let other_selections = other.read(cx).selections.disjoint.to_vec();
2625 if other_selections.is_empty() {
2626 return;
2627 }
2628 this.selections.change_with(cx, |selections| {
2629 selections.select_anchors(other_selections);
2630 });
2631 }
2632 _ => {}
2633 });
2634
2635 let this_subscription =
2636 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2637 EditorEvent::SelectionsChanged { local: true } => {
2638 let these_selections = this.selections.disjoint.to_vec();
2639 if these_selections.is_empty() {
2640 return;
2641 }
2642 other.update(cx, |other_editor, cx| {
2643 other_editor.selections.change_with(cx, |selections| {
2644 selections.select_anchors(these_selections);
2645 })
2646 });
2647 }
2648 _ => {}
2649 });
2650
2651 Subscription::join(other_subscription, this_subscription)
2652 }
2653
2654 pub fn change_selections<R>(
2655 &mut self,
2656 autoscroll: Option<Autoscroll>,
2657 window: &mut Window,
2658 cx: &mut Context<Self>,
2659 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2660 ) -> R {
2661 self.change_selections_inner(autoscroll, true, window, cx, change)
2662 }
2663
2664 fn change_selections_inner<R>(
2665 &mut self,
2666 autoscroll: Option<Autoscroll>,
2667 request_completions: bool,
2668 window: &mut Window,
2669 cx: &mut Context<Self>,
2670 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2671 ) -> R {
2672 let old_cursor_position = self.selections.newest_anchor().head();
2673 self.push_to_selection_history();
2674
2675 let (changed, result) = self.selections.change_with(cx, change);
2676
2677 if changed {
2678 if let Some(autoscroll) = autoscroll {
2679 self.request_autoscroll(autoscroll, cx);
2680 }
2681 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2682
2683 if self.should_open_signature_help_automatically(
2684 &old_cursor_position,
2685 self.signature_help_state.backspace_pressed(),
2686 cx,
2687 ) {
2688 self.show_signature_help(&ShowSignatureHelp, window, cx);
2689 }
2690 self.signature_help_state.set_backspace_pressed(false);
2691 }
2692
2693 result
2694 }
2695
2696 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2697 where
2698 I: IntoIterator<Item = (Range<S>, T)>,
2699 S: ToOffset,
2700 T: Into<Arc<str>>,
2701 {
2702 if self.read_only(cx) {
2703 return;
2704 }
2705
2706 self.buffer
2707 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2708 }
2709
2710 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2711 where
2712 I: IntoIterator<Item = (Range<S>, T)>,
2713 S: ToOffset,
2714 T: Into<Arc<str>>,
2715 {
2716 if self.read_only(cx) {
2717 return;
2718 }
2719
2720 self.buffer.update(cx, |buffer, cx| {
2721 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2722 });
2723 }
2724
2725 pub fn edit_with_block_indent<I, S, T>(
2726 &mut self,
2727 edits: I,
2728 original_indent_columns: Vec<Option<u32>>,
2729 cx: &mut Context<Self>,
2730 ) where
2731 I: IntoIterator<Item = (Range<S>, T)>,
2732 S: ToOffset,
2733 T: Into<Arc<str>>,
2734 {
2735 if self.read_only(cx) {
2736 return;
2737 }
2738
2739 self.buffer.update(cx, |buffer, cx| {
2740 buffer.edit(
2741 edits,
2742 Some(AutoindentMode::Block {
2743 original_indent_columns,
2744 }),
2745 cx,
2746 )
2747 });
2748 }
2749
2750 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2751 self.hide_context_menu(window, cx);
2752
2753 match phase {
2754 SelectPhase::Begin {
2755 position,
2756 add,
2757 click_count,
2758 } => self.begin_selection(position, add, click_count, window, cx),
2759 SelectPhase::BeginColumnar {
2760 position,
2761 goal_column,
2762 reset,
2763 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2764 SelectPhase::Extend {
2765 position,
2766 click_count,
2767 } => self.extend_selection(position, click_count, window, cx),
2768 SelectPhase::Update {
2769 position,
2770 goal_column,
2771 scroll_delta,
2772 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2773 SelectPhase::End => self.end_selection(window, cx),
2774 }
2775 }
2776
2777 fn extend_selection(
2778 &mut self,
2779 position: DisplayPoint,
2780 click_count: usize,
2781 window: &mut Window,
2782 cx: &mut Context<Self>,
2783 ) {
2784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2785 let tail = self.selections.newest::<usize>(cx).tail();
2786 self.begin_selection(position, false, click_count, window, cx);
2787
2788 let position = position.to_offset(&display_map, Bias::Left);
2789 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2790
2791 let mut pending_selection = self
2792 .selections
2793 .pending_anchor()
2794 .expect("extend_selection not called with pending selection");
2795 if position >= tail {
2796 pending_selection.start = tail_anchor;
2797 } else {
2798 pending_selection.end = tail_anchor;
2799 pending_selection.reversed = true;
2800 }
2801
2802 let mut pending_mode = self.selections.pending_mode().unwrap();
2803 match &mut pending_mode {
2804 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2805 _ => {}
2806 }
2807
2808 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2809 s.set_pending(pending_selection, pending_mode)
2810 });
2811 }
2812
2813 fn begin_selection(
2814 &mut self,
2815 position: DisplayPoint,
2816 add: bool,
2817 click_count: usize,
2818 window: &mut Window,
2819 cx: &mut Context<Self>,
2820 ) {
2821 if !self.focus_handle.is_focused(window) {
2822 self.last_focused_descendant = None;
2823 window.focus(&self.focus_handle);
2824 }
2825
2826 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2827 let buffer = &display_map.buffer_snapshot;
2828 let newest_selection = self.selections.newest_anchor().clone();
2829 let position = display_map.clip_point(position, Bias::Left);
2830
2831 let start;
2832 let end;
2833 let mode;
2834 let mut auto_scroll;
2835 match click_count {
2836 1 => {
2837 start = buffer.anchor_before(position.to_point(&display_map));
2838 end = start;
2839 mode = SelectMode::Character;
2840 auto_scroll = true;
2841 }
2842 2 => {
2843 let range = movement::surrounding_word(&display_map, position);
2844 start = buffer.anchor_before(range.start.to_point(&display_map));
2845 end = buffer.anchor_before(range.end.to_point(&display_map));
2846 mode = SelectMode::Word(start..end);
2847 auto_scroll = true;
2848 }
2849 3 => {
2850 let position = display_map
2851 .clip_point(position, Bias::Left)
2852 .to_point(&display_map);
2853 let line_start = display_map.prev_line_boundary(position).0;
2854 let next_line_start = buffer.clip_point(
2855 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2856 Bias::Left,
2857 );
2858 start = buffer.anchor_before(line_start);
2859 end = buffer.anchor_before(next_line_start);
2860 mode = SelectMode::Line(start..end);
2861 auto_scroll = true;
2862 }
2863 _ => {
2864 start = buffer.anchor_before(0);
2865 end = buffer.anchor_before(buffer.len());
2866 mode = SelectMode::All;
2867 auto_scroll = false;
2868 }
2869 }
2870 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2871
2872 let point_to_delete: Option<usize> = {
2873 let selected_points: Vec<Selection<Point>> =
2874 self.selections.disjoint_in_range(start..end, cx);
2875
2876 if !add || click_count > 1 {
2877 None
2878 } else if !selected_points.is_empty() {
2879 Some(selected_points[0].id)
2880 } else {
2881 let clicked_point_already_selected =
2882 self.selections.disjoint.iter().find(|selection| {
2883 selection.start.to_point(buffer) == start.to_point(buffer)
2884 || selection.end.to_point(buffer) == end.to_point(buffer)
2885 });
2886
2887 clicked_point_already_selected.map(|selection| selection.id)
2888 }
2889 };
2890
2891 let selections_count = self.selections.count();
2892
2893 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2894 if let Some(point_to_delete) = point_to_delete {
2895 s.delete(point_to_delete);
2896
2897 if selections_count == 1 {
2898 s.set_pending_anchor_range(start..end, mode);
2899 }
2900 } else {
2901 if !add {
2902 s.clear_disjoint();
2903 } else if click_count > 1 {
2904 s.delete(newest_selection.id)
2905 }
2906
2907 s.set_pending_anchor_range(start..end, mode);
2908 }
2909 });
2910 }
2911
2912 fn begin_columnar_selection(
2913 &mut self,
2914 position: DisplayPoint,
2915 goal_column: u32,
2916 reset: bool,
2917 window: &mut Window,
2918 cx: &mut Context<Self>,
2919 ) {
2920 if !self.focus_handle.is_focused(window) {
2921 self.last_focused_descendant = None;
2922 window.focus(&self.focus_handle);
2923 }
2924
2925 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2926
2927 if reset {
2928 let pointer_position = display_map
2929 .buffer_snapshot
2930 .anchor_before(position.to_point(&display_map));
2931
2932 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2933 s.clear_disjoint();
2934 s.set_pending_anchor_range(
2935 pointer_position..pointer_position,
2936 SelectMode::Character,
2937 );
2938 });
2939 }
2940
2941 let tail = self.selections.newest::<Point>(cx).tail();
2942 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2943
2944 if !reset {
2945 self.select_columns(
2946 tail.to_display_point(&display_map),
2947 position,
2948 goal_column,
2949 &display_map,
2950 window,
2951 cx,
2952 );
2953 }
2954 }
2955
2956 fn update_selection(
2957 &mut self,
2958 position: DisplayPoint,
2959 goal_column: u32,
2960 scroll_delta: gpui::Point<f32>,
2961 window: &mut Window,
2962 cx: &mut Context<Self>,
2963 ) {
2964 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2965
2966 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2967 let tail = tail.to_display_point(&display_map);
2968 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2969 } else if let Some(mut pending) = self.selections.pending_anchor() {
2970 let buffer = self.buffer.read(cx).snapshot(cx);
2971 let head;
2972 let tail;
2973 let mode = self.selections.pending_mode().unwrap();
2974 match &mode {
2975 SelectMode::Character => {
2976 head = position.to_point(&display_map);
2977 tail = pending.tail().to_point(&buffer);
2978 }
2979 SelectMode::Word(original_range) => {
2980 let original_display_range = original_range.start.to_display_point(&display_map)
2981 ..original_range.end.to_display_point(&display_map);
2982 let original_buffer_range = original_display_range.start.to_point(&display_map)
2983 ..original_display_range.end.to_point(&display_map);
2984 if movement::is_inside_word(&display_map, position)
2985 || original_display_range.contains(&position)
2986 {
2987 let word_range = movement::surrounding_word(&display_map, position);
2988 if word_range.start < original_display_range.start {
2989 head = word_range.start.to_point(&display_map);
2990 } else {
2991 head = word_range.end.to_point(&display_map);
2992 }
2993 } else {
2994 head = position.to_point(&display_map);
2995 }
2996
2997 if head <= original_buffer_range.start {
2998 tail = original_buffer_range.end;
2999 } else {
3000 tail = original_buffer_range.start;
3001 }
3002 }
3003 SelectMode::Line(original_range) => {
3004 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3005
3006 let position = display_map
3007 .clip_point(position, Bias::Left)
3008 .to_point(&display_map);
3009 let line_start = display_map.prev_line_boundary(position).0;
3010 let next_line_start = buffer.clip_point(
3011 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3012 Bias::Left,
3013 );
3014
3015 if line_start < original_range.start {
3016 head = line_start
3017 } else {
3018 head = next_line_start
3019 }
3020
3021 if head <= original_range.start {
3022 tail = original_range.end;
3023 } else {
3024 tail = original_range.start;
3025 }
3026 }
3027 SelectMode::All => {
3028 return;
3029 }
3030 };
3031
3032 if head < tail {
3033 pending.start = buffer.anchor_before(head);
3034 pending.end = buffer.anchor_before(tail);
3035 pending.reversed = true;
3036 } else {
3037 pending.start = buffer.anchor_before(tail);
3038 pending.end = buffer.anchor_before(head);
3039 pending.reversed = false;
3040 }
3041
3042 self.change_selections(None, window, cx, |s| {
3043 s.set_pending(pending, mode);
3044 });
3045 } else {
3046 log::error!("update_selection dispatched with no pending selection");
3047 return;
3048 }
3049
3050 self.apply_scroll_delta(scroll_delta, window, cx);
3051 cx.notify();
3052 }
3053
3054 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3055 self.columnar_selection_tail.take();
3056 if self.selections.pending_anchor().is_some() {
3057 let selections = self.selections.all::<usize>(cx);
3058 self.change_selections(None, window, cx, |s| {
3059 s.select(selections);
3060 s.clear_pending();
3061 });
3062 }
3063 }
3064
3065 fn select_columns(
3066 &mut self,
3067 tail: DisplayPoint,
3068 head: DisplayPoint,
3069 goal_column: u32,
3070 display_map: &DisplaySnapshot,
3071 window: &mut Window,
3072 cx: &mut Context<Self>,
3073 ) {
3074 let start_row = cmp::min(tail.row(), head.row());
3075 let end_row = cmp::max(tail.row(), head.row());
3076 let start_column = cmp::min(tail.column(), goal_column);
3077 let end_column = cmp::max(tail.column(), goal_column);
3078 let reversed = start_column < tail.column();
3079
3080 let selection_ranges = (start_row.0..=end_row.0)
3081 .map(DisplayRow)
3082 .filter_map(|row| {
3083 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3084 let start = display_map
3085 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3086 .to_point(display_map);
3087 let end = display_map
3088 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3089 .to_point(display_map);
3090 if reversed {
3091 Some(end..start)
3092 } else {
3093 Some(start..end)
3094 }
3095 } else {
3096 None
3097 }
3098 })
3099 .collect::<Vec<_>>();
3100
3101 self.change_selections(None, window, cx, |s| {
3102 s.select_ranges(selection_ranges);
3103 });
3104 cx.notify();
3105 }
3106
3107 pub fn has_pending_nonempty_selection(&self) -> bool {
3108 let pending_nonempty_selection = match self.selections.pending_anchor() {
3109 Some(Selection { start, end, .. }) => start != end,
3110 None => false,
3111 };
3112
3113 pending_nonempty_selection
3114 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3115 }
3116
3117 pub fn has_pending_selection(&self) -> bool {
3118 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3119 }
3120
3121 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3122 self.selection_mark_mode = false;
3123
3124 if self.clear_expanded_diff_hunks(cx) {
3125 cx.notify();
3126 return;
3127 }
3128 if self.dismiss_menus_and_popups(true, window, cx) {
3129 return;
3130 }
3131
3132 if self.mode.is_full()
3133 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3134 {
3135 return;
3136 }
3137
3138 cx.propagate();
3139 }
3140
3141 pub fn dismiss_menus_and_popups(
3142 &mut self,
3143 is_user_requested: bool,
3144 window: &mut Window,
3145 cx: &mut Context<Self>,
3146 ) -> bool {
3147 if self.take_rename(false, window, cx).is_some() {
3148 return true;
3149 }
3150
3151 if hide_hover(self, cx) {
3152 return true;
3153 }
3154
3155 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3156 return true;
3157 }
3158
3159 if self.hide_context_menu(window, cx).is_some() {
3160 return true;
3161 }
3162
3163 if self.mouse_context_menu.take().is_some() {
3164 return true;
3165 }
3166
3167 if is_user_requested && self.discard_inline_completion(true, cx) {
3168 return true;
3169 }
3170
3171 if self.snippet_stack.pop().is_some() {
3172 return true;
3173 }
3174
3175 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3176 self.dismiss_diagnostics(cx);
3177 return true;
3178 }
3179
3180 false
3181 }
3182
3183 fn linked_editing_ranges_for(
3184 &self,
3185 selection: Range<text::Anchor>,
3186 cx: &App,
3187 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3188 if self.linked_edit_ranges.is_empty() {
3189 return None;
3190 }
3191 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3192 selection.end.buffer_id.and_then(|end_buffer_id| {
3193 if selection.start.buffer_id != Some(end_buffer_id) {
3194 return None;
3195 }
3196 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3197 let snapshot = buffer.read(cx).snapshot();
3198 self.linked_edit_ranges
3199 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3200 .map(|ranges| (ranges, snapshot, buffer))
3201 })?;
3202 use text::ToOffset as TO;
3203 // find offset from the start of current range to current cursor position
3204 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3205
3206 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3207 let start_difference = start_offset - start_byte_offset;
3208 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3209 let end_difference = end_offset - start_byte_offset;
3210 // Current range has associated linked ranges.
3211 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3212 for range in linked_ranges.iter() {
3213 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3214 let end_offset = start_offset + end_difference;
3215 let start_offset = start_offset + start_difference;
3216 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3217 continue;
3218 }
3219 if self.selections.disjoint_anchor_ranges().any(|s| {
3220 if s.start.buffer_id != selection.start.buffer_id
3221 || s.end.buffer_id != selection.end.buffer_id
3222 {
3223 return false;
3224 }
3225 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3226 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3227 }) {
3228 continue;
3229 }
3230 let start = buffer_snapshot.anchor_after(start_offset);
3231 let end = buffer_snapshot.anchor_after(end_offset);
3232 linked_edits
3233 .entry(buffer.clone())
3234 .or_default()
3235 .push(start..end);
3236 }
3237 Some(linked_edits)
3238 }
3239
3240 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3241 let text: Arc<str> = text.into();
3242
3243 if self.read_only(cx) {
3244 return;
3245 }
3246
3247 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3248
3249 let selections = self.selections.all_adjusted(cx);
3250 let mut bracket_inserted = false;
3251 let mut edits = Vec::new();
3252 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3253 let mut new_selections = Vec::with_capacity(selections.len());
3254 let mut new_autoclose_regions = Vec::new();
3255 let snapshot = self.buffer.read(cx).read(cx);
3256 let mut clear_linked_edit_ranges = false;
3257
3258 for (selection, autoclose_region) in
3259 self.selections_with_autoclose_regions(selections, &snapshot)
3260 {
3261 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3262 // Determine if the inserted text matches the opening or closing
3263 // bracket of any of this language's bracket pairs.
3264 let mut bracket_pair = None;
3265 let mut is_bracket_pair_start = false;
3266 let mut is_bracket_pair_end = false;
3267 if !text.is_empty() {
3268 let mut bracket_pair_matching_end = None;
3269 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3270 // and they are removing the character that triggered IME popup.
3271 for (pair, enabled) in scope.brackets() {
3272 if !pair.close && !pair.surround {
3273 continue;
3274 }
3275
3276 if enabled && pair.start.ends_with(text.as_ref()) {
3277 let prefix_len = pair.start.len() - text.len();
3278 let preceding_text_matches_prefix = prefix_len == 0
3279 || (selection.start.column >= (prefix_len as u32)
3280 && snapshot.contains_str_at(
3281 Point::new(
3282 selection.start.row,
3283 selection.start.column - (prefix_len as u32),
3284 ),
3285 &pair.start[..prefix_len],
3286 ));
3287 if preceding_text_matches_prefix {
3288 bracket_pair = Some(pair.clone());
3289 is_bracket_pair_start = true;
3290 break;
3291 }
3292 }
3293 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3294 {
3295 // take first bracket pair matching end, but don't break in case a later bracket
3296 // pair matches start
3297 bracket_pair_matching_end = Some(pair.clone());
3298 }
3299 }
3300 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3301 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3302 is_bracket_pair_end = true;
3303 }
3304 }
3305
3306 if let Some(bracket_pair) = bracket_pair {
3307 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3308 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3309 let auto_surround =
3310 self.use_auto_surround && snapshot_settings.use_auto_surround;
3311 if selection.is_empty() {
3312 if is_bracket_pair_start {
3313 // If the inserted text is a suffix of an opening bracket and the
3314 // selection is preceded by the rest of the opening bracket, then
3315 // insert the closing bracket.
3316 let following_text_allows_autoclose = snapshot
3317 .chars_at(selection.start)
3318 .next()
3319 .map_or(true, |c| scope.should_autoclose_before(c));
3320
3321 let preceding_text_allows_autoclose = selection.start.column == 0
3322 || snapshot.reversed_chars_at(selection.start).next().map_or(
3323 true,
3324 |c| {
3325 bracket_pair.start != bracket_pair.end
3326 || !snapshot
3327 .char_classifier_at(selection.start)
3328 .is_word(c)
3329 },
3330 );
3331
3332 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3333 && bracket_pair.start.len() == 1
3334 {
3335 let target = bracket_pair.start.chars().next().unwrap();
3336 let current_line_count = snapshot
3337 .reversed_chars_at(selection.start)
3338 .take_while(|&c| c != '\n')
3339 .filter(|&c| c == target)
3340 .count();
3341 current_line_count % 2 == 1
3342 } else {
3343 false
3344 };
3345
3346 if autoclose
3347 && bracket_pair.close
3348 && following_text_allows_autoclose
3349 && preceding_text_allows_autoclose
3350 && !is_closing_quote
3351 {
3352 let anchor = snapshot.anchor_before(selection.end);
3353 new_selections.push((selection.map(|_| anchor), text.len()));
3354 new_autoclose_regions.push((
3355 anchor,
3356 text.len(),
3357 selection.id,
3358 bracket_pair.clone(),
3359 ));
3360 edits.push((
3361 selection.range(),
3362 format!("{}{}", text, bracket_pair.end).into(),
3363 ));
3364 bracket_inserted = true;
3365 continue;
3366 }
3367 }
3368
3369 if let Some(region) = autoclose_region {
3370 // If the selection is followed by an auto-inserted closing bracket,
3371 // then don't insert that closing bracket again; just move the selection
3372 // past the closing bracket.
3373 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3374 && text.as_ref() == region.pair.end.as_str();
3375 if should_skip {
3376 let anchor = snapshot.anchor_after(selection.end);
3377 new_selections
3378 .push((selection.map(|_| anchor), region.pair.end.len()));
3379 continue;
3380 }
3381 }
3382
3383 let always_treat_brackets_as_autoclosed = snapshot
3384 .language_settings_at(selection.start, cx)
3385 .always_treat_brackets_as_autoclosed;
3386 if always_treat_brackets_as_autoclosed
3387 && is_bracket_pair_end
3388 && snapshot.contains_str_at(selection.end, text.as_ref())
3389 {
3390 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3391 // and the inserted text is a closing bracket and the selection is followed
3392 // by the closing bracket then move the selection past the closing bracket.
3393 let anchor = snapshot.anchor_after(selection.end);
3394 new_selections.push((selection.map(|_| anchor), text.len()));
3395 continue;
3396 }
3397 }
3398 // If an opening bracket is 1 character long and is typed while
3399 // text is selected, then surround that text with the bracket pair.
3400 else if auto_surround
3401 && bracket_pair.surround
3402 && is_bracket_pair_start
3403 && bracket_pair.start.chars().count() == 1
3404 {
3405 edits.push((selection.start..selection.start, text.clone()));
3406 edits.push((
3407 selection.end..selection.end,
3408 bracket_pair.end.as_str().into(),
3409 ));
3410 bracket_inserted = true;
3411 new_selections.push((
3412 Selection {
3413 id: selection.id,
3414 start: snapshot.anchor_after(selection.start),
3415 end: snapshot.anchor_before(selection.end),
3416 reversed: selection.reversed,
3417 goal: selection.goal,
3418 },
3419 0,
3420 ));
3421 continue;
3422 }
3423 }
3424 }
3425
3426 if self.auto_replace_emoji_shortcode
3427 && selection.is_empty()
3428 && text.as_ref().ends_with(':')
3429 {
3430 if let Some(possible_emoji_short_code) =
3431 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3432 {
3433 if !possible_emoji_short_code.is_empty() {
3434 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3435 let emoji_shortcode_start = Point::new(
3436 selection.start.row,
3437 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3438 );
3439
3440 // Remove shortcode from buffer
3441 edits.push((
3442 emoji_shortcode_start..selection.start,
3443 "".to_string().into(),
3444 ));
3445 new_selections.push((
3446 Selection {
3447 id: selection.id,
3448 start: snapshot.anchor_after(emoji_shortcode_start),
3449 end: snapshot.anchor_before(selection.start),
3450 reversed: selection.reversed,
3451 goal: selection.goal,
3452 },
3453 0,
3454 ));
3455
3456 // Insert emoji
3457 let selection_start_anchor = snapshot.anchor_after(selection.start);
3458 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3459 edits.push((selection.start..selection.end, emoji.to_string().into()));
3460
3461 continue;
3462 }
3463 }
3464 }
3465 }
3466
3467 // If not handling any auto-close operation, then just replace the selected
3468 // text with the given input and move the selection to the end of the
3469 // newly inserted text.
3470 let anchor = snapshot.anchor_after(selection.end);
3471 if !self.linked_edit_ranges.is_empty() {
3472 let start_anchor = snapshot.anchor_before(selection.start);
3473
3474 let is_word_char = text.chars().next().map_or(true, |char| {
3475 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3476 classifier.is_word(char)
3477 });
3478
3479 if is_word_char {
3480 if let Some(ranges) = self
3481 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3482 {
3483 for (buffer, edits) in ranges {
3484 linked_edits
3485 .entry(buffer.clone())
3486 .or_default()
3487 .extend(edits.into_iter().map(|range| (range, text.clone())));
3488 }
3489 }
3490 } else {
3491 clear_linked_edit_ranges = true;
3492 }
3493 }
3494
3495 new_selections.push((selection.map(|_| anchor), 0));
3496 edits.push((selection.start..selection.end, text.clone()));
3497 }
3498
3499 drop(snapshot);
3500
3501 self.transact(window, cx, |this, window, cx| {
3502 if clear_linked_edit_ranges {
3503 this.linked_edit_ranges.clear();
3504 }
3505 let initial_buffer_versions =
3506 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3507
3508 this.buffer.update(cx, |buffer, cx| {
3509 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3510 });
3511 for (buffer, edits) in linked_edits {
3512 buffer.update(cx, |buffer, cx| {
3513 let snapshot = buffer.snapshot();
3514 let edits = edits
3515 .into_iter()
3516 .map(|(range, text)| {
3517 use text::ToPoint as TP;
3518 let end_point = TP::to_point(&range.end, &snapshot);
3519 let start_point = TP::to_point(&range.start, &snapshot);
3520 (start_point..end_point, text)
3521 })
3522 .sorted_by_key(|(range, _)| range.start);
3523 buffer.edit(edits, None, cx);
3524 })
3525 }
3526 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3527 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3528 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3529 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3530 .zip(new_selection_deltas)
3531 .map(|(selection, delta)| Selection {
3532 id: selection.id,
3533 start: selection.start + delta,
3534 end: selection.end + delta,
3535 reversed: selection.reversed,
3536 goal: SelectionGoal::None,
3537 })
3538 .collect::<Vec<_>>();
3539
3540 let mut i = 0;
3541 for (position, delta, selection_id, pair) in new_autoclose_regions {
3542 let position = position.to_offset(&map.buffer_snapshot) + delta;
3543 let start = map.buffer_snapshot.anchor_before(position);
3544 let end = map.buffer_snapshot.anchor_after(position);
3545 while let Some(existing_state) = this.autoclose_regions.get(i) {
3546 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3547 Ordering::Less => i += 1,
3548 Ordering::Greater => break,
3549 Ordering::Equal => {
3550 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3551 Ordering::Less => i += 1,
3552 Ordering::Equal => break,
3553 Ordering::Greater => break,
3554 }
3555 }
3556 }
3557 }
3558 this.autoclose_regions.insert(
3559 i,
3560 AutocloseRegion {
3561 selection_id,
3562 range: start..end,
3563 pair,
3564 },
3565 );
3566 }
3567
3568 let had_active_inline_completion = this.has_active_inline_completion();
3569 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3570 s.select(new_selections)
3571 });
3572
3573 if !bracket_inserted {
3574 if let Some(on_type_format_task) =
3575 this.trigger_on_type_formatting(text.to_string(), window, cx)
3576 {
3577 on_type_format_task.detach_and_log_err(cx);
3578 }
3579 }
3580
3581 let editor_settings = EditorSettings::get_global(cx);
3582 if bracket_inserted
3583 && (editor_settings.auto_signature_help
3584 || editor_settings.show_signature_help_after_edits)
3585 {
3586 this.show_signature_help(&ShowSignatureHelp, window, cx);
3587 }
3588
3589 let trigger_in_words =
3590 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3591 if this.hard_wrap.is_some() {
3592 let latest: Range<Point> = this.selections.newest(cx).range();
3593 if latest.is_empty()
3594 && this
3595 .buffer()
3596 .read(cx)
3597 .snapshot(cx)
3598 .line_len(MultiBufferRow(latest.start.row))
3599 == latest.start.column
3600 {
3601 this.rewrap_impl(
3602 RewrapOptions {
3603 override_language_settings: true,
3604 preserve_existing_whitespace: true,
3605 },
3606 cx,
3607 )
3608 }
3609 }
3610 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3611 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3612 this.refresh_inline_completion(true, false, window, cx);
3613 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3614 });
3615 }
3616
3617 fn find_possible_emoji_shortcode_at_position(
3618 snapshot: &MultiBufferSnapshot,
3619 position: Point,
3620 ) -> Option<String> {
3621 let mut chars = Vec::new();
3622 let mut found_colon = false;
3623 for char in snapshot.reversed_chars_at(position).take(100) {
3624 // Found a possible emoji shortcode in the middle of the buffer
3625 if found_colon {
3626 if char.is_whitespace() {
3627 chars.reverse();
3628 return Some(chars.iter().collect());
3629 }
3630 // If the previous character is not a whitespace, we are in the middle of a word
3631 // and we only want to complete the shortcode if the word is made up of other emojis
3632 let mut containing_word = String::new();
3633 for ch in snapshot
3634 .reversed_chars_at(position)
3635 .skip(chars.len() + 1)
3636 .take(100)
3637 {
3638 if ch.is_whitespace() {
3639 break;
3640 }
3641 containing_word.push(ch);
3642 }
3643 let containing_word = containing_word.chars().rev().collect::<String>();
3644 if util::word_consists_of_emojis(containing_word.as_str()) {
3645 chars.reverse();
3646 return Some(chars.iter().collect());
3647 }
3648 }
3649
3650 if char.is_whitespace() || !char.is_ascii() {
3651 return None;
3652 }
3653 if char == ':' {
3654 found_colon = true;
3655 } else {
3656 chars.push(char);
3657 }
3658 }
3659 // Found a possible emoji shortcode at the beginning of the buffer
3660 chars.reverse();
3661 Some(chars.iter().collect())
3662 }
3663
3664 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3665 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3666 self.transact(window, cx, |this, window, cx| {
3667 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3668 let selections = this.selections.all::<usize>(cx);
3669 let multi_buffer = this.buffer.read(cx);
3670 let buffer = multi_buffer.snapshot(cx);
3671 selections
3672 .iter()
3673 .map(|selection| {
3674 let start_point = selection.start.to_point(&buffer);
3675 let mut indent =
3676 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3677 indent.len = cmp::min(indent.len, start_point.column);
3678 let start = selection.start;
3679 let end = selection.end;
3680 let selection_is_empty = start == end;
3681 let language_scope = buffer.language_scope_at(start);
3682 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3683 &language_scope
3684 {
3685 let insert_extra_newline =
3686 insert_extra_newline_brackets(&buffer, start..end, language)
3687 || insert_extra_newline_tree_sitter(&buffer, start..end);
3688
3689 // Comment extension on newline is allowed only for cursor selections
3690 let comment_delimiter = maybe!({
3691 if !selection_is_empty {
3692 return None;
3693 }
3694
3695 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3696 return None;
3697 }
3698
3699 let delimiters = language.line_comment_prefixes();
3700 let max_len_of_delimiter =
3701 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3702 let (snapshot, range) =
3703 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3704
3705 let mut index_of_first_non_whitespace = 0;
3706 let comment_candidate = snapshot
3707 .chars_for_range(range)
3708 .skip_while(|c| {
3709 let should_skip = c.is_whitespace();
3710 if should_skip {
3711 index_of_first_non_whitespace += 1;
3712 }
3713 should_skip
3714 })
3715 .take(max_len_of_delimiter)
3716 .collect::<String>();
3717 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3718 comment_candidate.starts_with(comment_prefix.as_ref())
3719 })?;
3720 let cursor_is_placed_after_comment_marker =
3721 index_of_first_non_whitespace + comment_prefix.len()
3722 <= start_point.column as usize;
3723 if cursor_is_placed_after_comment_marker {
3724 Some(comment_prefix.clone())
3725 } else {
3726 None
3727 }
3728 });
3729 (comment_delimiter, insert_extra_newline)
3730 } else {
3731 (None, false)
3732 };
3733
3734 let capacity_for_delimiter = comment_delimiter
3735 .as_deref()
3736 .map(str::len)
3737 .unwrap_or_default();
3738 let mut new_text =
3739 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3740 new_text.push('\n');
3741 new_text.extend(indent.chars());
3742 if let Some(delimiter) = &comment_delimiter {
3743 new_text.push_str(delimiter);
3744 }
3745 if insert_extra_newline {
3746 new_text = new_text.repeat(2);
3747 }
3748
3749 let anchor = buffer.anchor_after(end);
3750 let new_selection = selection.map(|_| anchor);
3751 (
3752 (start..end, new_text),
3753 (insert_extra_newline, new_selection),
3754 )
3755 })
3756 .unzip()
3757 };
3758
3759 this.edit_with_autoindent(edits, cx);
3760 let buffer = this.buffer.read(cx).snapshot(cx);
3761 let new_selections = selection_fixup_info
3762 .into_iter()
3763 .map(|(extra_newline_inserted, new_selection)| {
3764 let mut cursor = new_selection.end.to_point(&buffer);
3765 if extra_newline_inserted {
3766 cursor.row -= 1;
3767 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3768 }
3769 new_selection.map(|_| cursor)
3770 })
3771 .collect();
3772
3773 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3774 s.select(new_selections)
3775 });
3776 this.refresh_inline_completion(true, false, window, cx);
3777 });
3778 }
3779
3780 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3781 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3782
3783 let buffer = self.buffer.read(cx);
3784 let snapshot = buffer.snapshot(cx);
3785
3786 let mut edits = Vec::new();
3787 let mut rows = Vec::new();
3788
3789 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3790 let cursor = selection.head();
3791 let row = cursor.row;
3792
3793 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3794
3795 let newline = "\n".to_string();
3796 edits.push((start_of_line..start_of_line, newline));
3797
3798 rows.push(row + rows_inserted as u32);
3799 }
3800
3801 self.transact(window, cx, |editor, window, cx| {
3802 editor.edit(edits, cx);
3803
3804 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3805 let mut index = 0;
3806 s.move_cursors_with(|map, _, _| {
3807 let row = rows[index];
3808 index += 1;
3809
3810 let point = Point::new(row, 0);
3811 let boundary = map.next_line_boundary(point).1;
3812 let clipped = map.clip_point(boundary, Bias::Left);
3813
3814 (clipped, SelectionGoal::None)
3815 });
3816 });
3817
3818 let mut indent_edits = Vec::new();
3819 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3820 for row in rows {
3821 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3822 for (row, indent) in indents {
3823 if indent.len == 0 {
3824 continue;
3825 }
3826
3827 let text = match indent.kind {
3828 IndentKind::Space => " ".repeat(indent.len as usize),
3829 IndentKind::Tab => "\t".repeat(indent.len as usize),
3830 };
3831 let point = Point::new(row.0, 0);
3832 indent_edits.push((point..point, text));
3833 }
3834 }
3835 editor.edit(indent_edits, cx);
3836 });
3837 }
3838
3839 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3840 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3841
3842 let buffer = self.buffer.read(cx);
3843 let snapshot = buffer.snapshot(cx);
3844
3845 let mut edits = Vec::new();
3846 let mut rows = Vec::new();
3847 let mut rows_inserted = 0;
3848
3849 for selection in self.selections.all_adjusted(cx) {
3850 let cursor = selection.head();
3851 let row = cursor.row;
3852
3853 let point = Point::new(row + 1, 0);
3854 let start_of_line = snapshot.clip_point(point, Bias::Left);
3855
3856 let newline = "\n".to_string();
3857 edits.push((start_of_line..start_of_line, newline));
3858
3859 rows_inserted += 1;
3860 rows.push(row + rows_inserted);
3861 }
3862
3863 self.transact(window, cx, |editor, window, cx| {
3864 editor.edit(edits, cx);
3865
3866 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3867 let mut index = 0;
3868 s.move_cursors_with(|map, _, _| {
3869 let row = rows[index];
3870 index += 1;
3871
3872 let point = Point::new(row, 0);
3873 let boundary = map.next_line_boundary(point).1;
3874 let clipped = map.clip_point(boundary, Bias::Left);
3875
3876 (clipped, SelectionGoal::None)
3877 });
3878 });
3879
3880 let mut indent_edits = Vec::new();
3881 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3882 for row in rows {
3883 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3884 for (row, indent) in indents {
3885 if indent.len == 0 {
3886 continue;
3887 }
3888
3889 let text = match indent.kind {
3890 IndentKind::Space => " ".repeat(indent.len as usize),
3891 IndentKind::Tab => "\t".repeat(indent.len as usize),
3892 };
3893 let point = Point::new(row.0, 0);
3894 indent_edits.push((point..point, text));
3895 }
3896 }
3897 editor.edit(indent_edits, cx);
3898 });
3899 }
3900
3901 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3902 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3903 original_indent_columns: Vec::new(),
3904 });
3905 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3906 }
3907
3908 fn insert_with_autoindent_mode(
3909 &mut self,
3910 text: &str,
3911 autoindent_mode: Option<AutoindentMode>,
3912 window: &mut Window,
3913 cx: &mut Context<Self>,
3914 ) {
3915 if self.read_only(cx) {
3916 return;
3917 }
3918
3919 let text: Arc<str> = text.into();
3920 self.transact(window, cx, |this, window, cx| {
3921 let old_selections = this.selections.all_adjusted(cx);
3922 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3923 let anchors = {
3924 let snapshot = buffer.read(cx);
3925 old_selections
3926 .iter()
3927 .map(|s| {
3928 let anchor = snapshot.anchor_after(s.head());
3929 s.map(|_| anchor)
3930 })
3931 .collect::<Vec<_>>()
3932 };
3933 buffer.edit(
3934 old_selections
3935 .iter()
3936 .map(|s| (s.start..s.end, text.clone())),
3937 autoindent_mode,
3938 cx,
3939 );
3940 anchors
3941 });
3942
3943 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3944 s.select_anchors(selection_anchors);
3945 });
3946
3947 cx.notify();
3948 });
3949 }
3950
3951 fn trigger_completion_on_input(
3952 &mut self,
3953 text: &str,
3954 trigger_in_words: bool,
3955 window: &mut Window,
3956 cx: &mut Context<Self>,
3957 ) {
3958 let ignore_completion_provider = self
3959 .context_menu
3960 .borrow()
3961 .as_ref()
3962 .map(|menu| match menu {
3963 CodeContextMenu::Completions(completions_menu) => {
3964 completions_menu.ignore_completion_provider
3965 }
3966 CodeContextMenu::CodeActions(_) => false,
3967 })
3968 .unwrap_or(false);
3969
3970 if ignore_completion_provider {
3971 self.show_word_completions(&ShowWordCompletions, window, cx);
3972 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3973 self.show_completions(
3974 &ShowCompletions {
3975 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3976 },
3977 window,
3978 cx,
3979 );
3980 } else {
3981 self.hide_context_menu(window, cx);
3982 }
3983 }
3984
3985 fn is_completion_trigger(
3986 &self,
3987 text: &str,
3988 trigger_in_words: bool,
3989 cx: &mut Context<Self>,
3990 ) -> bool {
3991 let position = self.selections.newest_anchor().head();
3992 let multibuffer = self.buffer.read(cx);
3993 let Some(buffer) = position
3994 .buffer_id
3995 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3996 else {
3997 return false;
3998 };
3999
4000 if let Some(completion_provider) = &self.completion_provider {
4001 completion_provider.is_completion_trigger(
4002 &buffer,
4003 position.text_anchor,
4004 text,
4005 trigger_in_words,
4006 cx,
4007 )
4008 } else {
4009 false
4010 }
4011 }
4012
4013 /// If any empty selections is touching the start of its innermost containing autoclose
4014 /// region, expand it to select the brackets.
4015 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4016 let selections = self.selections.all::<usize>(cx);
4017 let buffer = self.buffer.read(cx).read(cx);
4018 let new_selections = self
4019 .selections_with_autoclose_regions(selections, &buffer)
4020 .map(|(mut selection, region)| {
4021 if !selection.is_empty() {
4022 return selection;
4023 }
4024
4025 if let Some(region) = region {
4026 let mut range = region.range.to_offset(&buffer);
4027 if selection.start == range.start && range.start >= region.pair.start.len() {
4028 range.start -= region.pair.start.len();
4029 if buffer.contains_str_at(range.start, ®ion.pair.start)
4030 && buffer.contains_str_at(range.end, ®ion.pair.end)
4031 {
4032 range.end += region.pair.end.len();
4033 selection.start = range.start;
4034 selection.end = range.end;
4035
4036 return selection;
4037 }
4038 }
4039 }
4040
4041 let always_treat_brackets_as_autoclosed = buffer
4042 .language_settings_at(selection.start, cx)
4043 .always_treat_brackets_as_autoclosed;
4044
4045 if !always_treat_brackets_as_autoclosed {
4046 return selection;
4047 }
4048
4049 if let Some(scope) = buffer.language_scope_at(selection.start) {
4050 for (pair, enabled) in scope.brackets() {
4051 if !enabled || !pair.close {
4052 continue;
4053 }
4054
4055 if buffer.contains_str_at(selection.start, &pair.end) {
4056 let pair_start_len = pair.start.len();
4057 if buffer.contains_str_at(
4058 selection.start.saturating_sub(pair_start_len),
4059 &pair.start,
4060 ) {
4061 selection.start -= pair_start_len;
4062 selection.end += pair.end.len();
4063
4064 return selection;
4065 }
4066 }
4067 }
4068 }
4069
4070 selection
4071 })
4072 .collect();
4073
4074 drop(buffer);
4075 self.change_selections(None, window, cx, |selections| {
4076 selections.select(new_selections)
4077 });
4078 }
4079
4080 /// Iterate the given selections, and for each one, find the smallest surrounding
4081 /// autoclose region. This uses the ordering of the selections and the autoclose
4082 /// regions to avoid repeated comparisons.
4083 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4084 &'a self,
4085 selections: impl IntoIterator<Item = Selection<D>>,
4086 buffer: &'a MultiBufferSnapshot,
4087 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4088 let mut i = 0;
4089 let mut regions = self.autoclose_regions.as_slice();
4090 selections.into_iter().map(move |selection| {
4091 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4092
4093 let mut enclosing = None;
4094 while let Some(pair_state) = regions.get(i) {
4095 if pair_state.range.end.to_offset(buffer) < range.start {
4096 regions = ®ions[i + 1..];
4097 i = 0;
4098 } else if pair_state.range.start.to_offset(buffer) > range.end {
4099 break;
4100 } else {
4101 if pair_state.selection_id == selection.id {
4102 enclosing = Some(pair_state);
4103 }
4104 i += 1;
4105 }
4106 }
4107
4108 (selection, enclosing)
4109 })
4110 }
4111
4112 /// Remove any autoclose regions that no longer contain their selection.
4113 fn invalidate_autoclose_regions(
4114 &mut self,
4115 mut selections: &[Selection<Anchor>],
4116 buffer: &MultiBufferSnapshot,
4117 ) {
4118 self.autoclose_regions.retain(|state| {
4119 let mut i = 0;
4120 while let Some(selection) = selections.get(i) {
4121 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4122 selections = &selections[1..];
4123 continue;
4124 }
4125 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4126 break;
4127 }
4128 if selection.id == state.selection_id {
4129 return true;
4130 } else {
4131 i += 1;
4132 }
4133 }
4134 false
4135 });
4136 }
4137
4138 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4139 let offset = position.to_offset(buffer);
4140 let (word_range, kind) = buffer.surrounding_word(offset, true);
4141 if offset > word_range.start && kind == Some(CharKind::Word) {
4142 Some(
4143 buffer
4144 .text_for_range(word_range.start..offset)
4145 .collect::<String>(),
4146 )
4147 } else {
4148 None
4149 }
4150 }
4151
4152 pub fn toggle_inlay_hints(
4153 &mut self,
4154 _: &ToggleInlayHints,
4155 _: &mut Window,
4156 cx: &mut Context<Self>,
4157 ) {
4158 self.refresh_inlay_hints(
4159 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4160 cx,
4161 );
4162 }
4163
4164 pub fn inlay_hints_enabled(&self) -> bool {
4165 self.inlay_hint_cache.enabled
4166 }
4167
4168 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4169 if self.semantics_provider.is_none() || !self.mode.is_full() {
4170 return;
4171 }
4172
4173 let reason_description = reason.description();
4174 let ignore_debounce = matches!(
4175 reason,
4176 InlayHintRefreshReason::SettingsChange(_)
4177 | InlayHintRefreshReason::Toggle(_)
4178 | InlayHintRefreshReason::ExcerptsRemoved(_)
4179 | InlayHintRefreshReason::ModifiersChanged(_)
4180 );
4181 let (invalidate_cache, required_languages) = match reason {
4182 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4183 match self.inlay_hint_cache.modifiers_override(enabled) {
4184 Some(enabled) => {
4185 if enabled {
4186 (InvalidationStrategy::RefreshRequested, None)
4187 } else {
4188 self.splice_inlays(
4189 &self
4190 .visible_inlay_hints(cx)
4191 .iter()
4192 .map(|inlay| inlay.id)
4193 .collect::<Vec<InlayId>>(),
4194 Vec::new(),
4195 cx,
4196 );
4197 return;
4198 }
4199 }
4200 None => return,
4201 }
4202 }
4203 InlayHintRefreshReason::Toggle(enabled) => {
4204 if self.inlay_hint_cache.toggle(enabled) {
4205 if enabled {
4206 (InvalidationStrategy::RefreshRequested, None)
4207 } else {
4208 self.splice_inlays(
4209 &self
4210 .visible_inlay_hints(cx)
4211 .iter()
4212 .map(|inlay| inlay.id)
4213 .collect::<Vec<InlayId>>(),
4214 Vec::new(),
4215 cx,
4216 );
4217 return;
4218 }
4219 } else {
4220 return;
4221 }
4222 }
4223 InlayHintRefreshReason::SettingsChange(new_settings) => {
4224 match self.inlay_hint_cache.update_settings(
4225 &self.buffer,
4226 new_settings,
4227 self.visible_inlay_hints(cx),
4228 cx,
4229 ) {
4230 ControlFlow::Break(Some(InlaySplice {
4231 to_remove,
4232 to_insert,
4233 })) => {
4234 self.splice_inlays(&to_remove, to_insert, cx);
4235 return;
4236 }
4237 ControlFlow::Break(None) => return,
4238 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4239 }
4240 }
4241 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4242 if let Some(InlaySplice {
4243 to_remove,
4244 to_insert,
4245 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4246 {
4247 self.splice_inlays(&to_remove, to_insert, cx);
4248 }
4249 self.display_map.update(cx, |display_map, _| {
4250 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4251 });
4252 return;
4253 }
4254 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4255 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4256 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4257 }
4258 InlayHintRefreshReason::RefreshRequested => {
4259 (InvalidationStrategy::RefreshRequested, None)
4260 }
4261 };
4262
4263 if let Some(InlaySplice {
4264 to_remove,
4265 to_insert,
4266 }) = self.inlay_hint_cache.spawn_hint_refresh(
4267 reason_description,
4268 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4269 invalidate_cache,
4270 ignore_debounce,
4271 cx,
4272 ) {
4273 self.splice_inlays(&to_remove, to_insert, cx);
4274 }
4275 }
4276
4277 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4278 self.display_map
4279 .read(cx)
4280 .current_inlays()
4281 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4282 .cloned()
4283 .collect()
4284 }
4285
4286 pub fn excerpts_for_inlay_hints_query(
4287 &self,
4288 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4289 cx: &mut Context<Editor>,
4290 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4291 let Some(project) = self.project.as_ref() else {
4292 return HashMap::default();
4293 };
4294 let project = project.read(cx);
4295 let multi_buffer = self.buffer().read(cx);
4296 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4297 let multi_buffer_visible_start = self
4298 .scroll_manager
4299 .anchor()
4300 .anchor
4301 .to_point(&multi_buffer_snapshot);
4302 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4303 multi_buffer_visible_start
4304 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4305 Bias::Left,
4306 );
4307 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4308 multi_buffer_snapshot
4309 .range_to_buffer_ranges(multi_buffer_visible_range)
4310 .into_iter()
4311 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4312 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4313 let buffer_file = project::File::from_dyn(buffer.file())?;
4314 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4315 let worktree_entry = buffer_worktree
4316 .read(cx)
4317 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4318 if worktree_entry.is_ignored {
4319 return None;
4320 }
4321
4322 let language = buffer.language()?;
4323 if let Some(restrict_to_languages) = restrict_to_languages {
4324 if !restrict_to_languages.contains(language) {
4325 return None;
4326 }
4327 }
4328 Some((
4329 excerpt_id,
4330 (
4331 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4332 buffer.version().clone(),
4333 excerpt_visible_range,
4334 ),
4335 ))
4336 })
4337 .collect()
4338 }
4339
4340 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4341 TextLayoutDetails {
4342 text_system: window.text_system().clone(),
4343 editor_style: self.style.clone().unwrap(),
4344 rem_size: window.rem_size(),
4345 scroll_anchor: self.scroll_manager.anchor(),
4346 visible_rows: self.visible_line_count(),
4347 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4348 }
4349 }
4350
4351 pub fn splice_inlays(
4352 &self,
4353 to_remove: &[InlayId],
4354 to_insert: Vec<Inlay>,
4355 cx: &mut Context<Self>,
4356 ) {
4357 self.display_map.update(cx, |display_map, cx| {
4358 display_map.splice_inlays(to_remove, to_insert, cx)
4359 });
4360 cx.notify();
4361 }
4362
4363 fn trigger_on_type_formatting(
4364 &self,
4365 input: String,
4366 window: &mut Window,
4367 cx: &mut Context<Self>,
4368 ) -> Option<Task<Result<()>>> {
4369 if input.len() != 1 {
4370 return None;
4371 }
4372
4373 let project = self.project.as_ref()?;
4374 let position = self.selections.newest_anchor().head();
4375 let (buffer, buffer_position) = self
4376 .buffer
4377 .read(cx)
4378 .text_anchor_for_position(position, cx)?;
4379
4380 let settings = language_settings::language_settings(
4381 buffer
4382 .read(cx)
4383 .language_at(buffer_position)
4384 .map(|l| l.name()),
4385 buffer.read(cx).file(),
4386 cx,
4387 );
4388 if !settings.use_on_type_format {
4389 return None;
4390 }
4391
4392 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4393 // hence we do LSP request & edit on host side only — add formats to host's history.
4394 let push_to_lsp_host_history = true;
4395 // If this is not the host, append its history with new edits.
4396 let push_to_client_history = project.read(cx).is_via_collab();
4397
4398 let on_type_formatting = project.update(cx, |project, cx| {
4399 project.on_type_format(
4400 buffer.clone(),
4401 buffer_position,
4402 input,
4403 push_to_lsp_host_history,
4404 cx,
4405 )
4406 });
4407 Some(cx.spawn_in(window, async move |editor, cx| {
4408 if let Some(transaction) = on_type_formatting.await? {
4409 if push_to_client_history {
4410 buffer
4411 .update(cx, |buffer, _| {
4412 buffer.push_transaction(transaction, Instant::now());
4413 buffer.finalize_last_transaction();
4414 })
4415 .ok();
4416 }
4417 editor.update(cx, |editor, cx| {
4418 editor.refresh_document_highlights(cx);
4419 })?;
4420 }
4421 Ok(())
4422 }))
4423 }
4424
4425 pub fn show_word_completions(
4426 &mut self,
4427 _: &ShowWordCompletions,
4428 window: &mut Window,
4429 cx: &mut Context<Self>,
4430 ) {
4431 self.open_completions_menu(true, None, window, cx);
4432 }
4433
4434 pub fn show_completions(
4435 &mut self,
4436 options: &ShowCompletions,
4437 window: &mut Window,
4438 cx: &mut Context<Self>,
4439 ) {
4440 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4441 }
4442
4443 fn open_completions_menu(
4444 &mut self,
4445 ignore_completion_provider: bool,
4446 trigger: Option<&str>,
4447 window: &mut Window,
4448 cx: &mut Context<Self>,
4449 ) {
4450 if self.pending_rename.is_some() {
4451 return;
4452 }
4453 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4454 return;
4455 }
4456
4457 let position = self.selections.newest_anchor().head();
4458 if position.diff_base_anchor.is_some() {
4459 return;
4460 }
4461 let (buffer, buffer_position) =
4462 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4463 output
4464 } else {
4465 return;
4466 };
4467 let buffer_snapshot = buffer.read(cx).snapshot();
4468 let show_completion_documentation = buffer_snapshot
4469 .settings_at(buffer_position, cx)
4470 .show_completion_documentation;
4471
4472 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4473
4474 let trigger_kind = match trigger {
4475 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4476 CompletionTriggerKind::TRIGGER_CHARACTER
4477 }
4478 _ => CompletionTriggerKind::INVOKED,
4479 };
4480 let completion_context = CompletionContext {
4481 trigger_character: trigger.and_then(|trigger| {
4482 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4483 Some(String::from(trigger))
4484 } else {
4485 None
4486 }
4487 }),
4488 trigger_kind,
4489 };
4490
4491 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4492 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4493 let word_to_exclude = buffer_snapshot
4494 .text_for_range(old_range.clone())
4495 .collect::<String>();
4496 (
4497 buffer_snapshot.anchor_before(old_range.start)
4498 ..buffer_snapshot.anchor_after(old_range.end),
4499 Some(word_to_exclude),
4500 )
4501 } else {
4502 (buffer_position..buffer_position, None)
4503 };
4504
4505 let completion_settings = language_settings(
4506 buffer_snapshot
4507 .language_at(buffer_position)
4508 .map(|language| language.name()),
4509 buffer_snapshot.file(),
4510 cx,
4511 )
4512 .completions;
4513
4514 // The document can be large, so stay in reasonable bounds when searching for words,
4515 // otherwise completion pop-up might be slow to appear.
4516 const WORD_LOOKUP_ROWS: u32 = 5_000;
4517 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4518 let min_word_search = buffer_snapshot.clip_point(
4519 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4520 Bias::Left,
4521 );
4522 let max_word_search = buffer_snapshot.clip_point(
4523 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4524 Bias::Right,
4525 );
4526 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4527 ..buffer_snapshot.point_to_offset(max_word_search);
4528
4529 let provider = self
4530 .completion_provider
4531 .as_ref()
4532 .filter(|_| !ignore_completion_provider);
4533 let skip_digits = query
4534 .as_ref()
4535 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4536
4537 let (mut words, provided_completions) = match provider {
4538 Some(provider) => {
4539 let completions = provider.completions(
4540 position.excerpt_id,
4541 &buffer,
4542 buffer_position,
4543 completion_context,
4544 window,
4545 cx,
4546 );
4547
4548 let words = match completion_settings.words {
4549 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4550 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4551 .background_spawn(async move {
4552 buffer_snapshot.words_in_range(WordsQuery {
4553 fuzzy_contents: None,
4554 range: word_search_range,
4555 skip_digits,
4556 })
4557 }),
4558 };
4559
4560 (words, completions)
4561 }
4562 None => (
4563 cx.background_spawn(async move {
4564 buffer_snapshot.words_in_range(WordsQuery {
4565 fuzzy_contents: None,
4566 range: word_search_range,
4567 skip_digits,
4568 })
4569 }),
4570 Task::ready(Ok(None)),
4571 ),
4572 };
4573
4574 let sort_completions = provider
4575 .as_ref()
4576 .map_or(false, |provider| provider.sort_completions());
4577
4578 let filter_completions = provider
4579 .as_ref()
4580 .map_or(true, |provider| provider.filter_completions());
4581
4582 let id = post_inc(&mut self.next_completion_id);
4583 let task = cx.spawn_in(window, async move |editor, cx| {
4584 async move {
4585 editor.update(cx, |this, _| {
4586 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4587 })?;
4588
4589 let mut completions = Vec::new();
4590 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4591 completions.extend(provided_completions);
4592 if completion_settings.words == WordsCompletionMode::Fallback {
4593 words = Task::ready(BTreeMap::default());
4594 }
4595 }
4596
4597 let mut words = words.await;
4598 if let Some(word_to_exclude) = &word_to_exclude {
4599 words.remove(word_to_exclude);
4600 }
4601 for lsp_completion in &completions {
4602 words.remove(&lsp_completion.new_text);
4603 }
4604 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4605 replace_range: old_range.clone(),
4606 new_text: word.clone(),
4607 label: CodeLabel::plain(word, None),
4608 icon_path: None,
4609 documentation: None,
4610 source: CompletionSource::BufferWord {
4611 word_range,
4612 resolved: false,
4613 },
4614 insert_text_mode: Some(InsertTextMode::AS_IS),
4615 confirm: None,
4616 }));
4617
4618 let menu = if completions.is_empty() {
4619 None
4620 } else {
4621 let mut menu = CompletionsMenu::new(
4622 id,
4623 sort_completions,
4624 show_completion_documentation,
4625 ignore_completion_provider,
4626 position,
4627 buffer.clone(),
4628 completions.into(),
4629 );
4630
4631 menu.filter(
4632 if filter_completions {
4633 query.as_deref()
4634 } else {
4635 None
4636 },
4637 cx.background_executor().clone(),
4638 )
4639 .await;
4640
4641 menu.visible().then_some(menu)
4642 };
4643
4644 editor.update_in(cx, |editor, window, cx| {
4645 match editor.context_menu.borrow().as_ref() {
4646 None => {}
4647 Some(CodeContextMenu::Completions(prev_menu)) => {
4648 if prev_menu.id > id {
4649 return;
4650 }
4651 }
4652 _ => return,
4653 }
4654
4655 if editor.focus_handle.is_focused(window) && menu.is_some() {
4656 let mut menu = menu.unwrap();
4657 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4658
4659 *editor.context_menu.borrow_mut() =
4660 Some(CodeContextMenu::Completions(menu));
4661
4662 if editor.show_edit_predictions_in_menu() {
4663 editor.update_visible_inline_completion(window, cx);
4664 } else {
4665 editor.discard_inline_completion(false, cx);
4666 }
4667
4668 cx.notify();
4669 } else if editor.completion_tasks.len() <= 1 {
4670 // If there are no more completion tasks and the last menu was
4671 // empty, we should hide it.
4672 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4673 // If it was already hidden and we don't show inline
4674 // completions in the menu, we should also show the
4675 // inline-completion when available.
4676 if was_hidden && editor.show_edit_predictions_in_menu() {
4677 editor.update_visible_inline_completion(window, cx);
4678 }
4679 }
4680 })?;
4681
4682 anyhow::Ok(())
4683 }
4684 .log_err()
4685 .await
4686 });
4687
4688 self.completion_tasks.push((id, task));
4689 }
4690
4691 #[cfg(feature = "test-support")]
4692 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4693 let menu = self.context_menu.borrow();
4694 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4695 let completions = menu.completions.borrow();
4696 Some(completions.to_vec())
4697 } else {
4698 None
4699 }
4700 }
4701
4702 pub fn confirm_completion(
4703 &mut self,
4704 action: &ConfirmCompletion,
4705 window: &mut Window,
4706 cx: &mut Context<Self>,
4707 ) -> Option<Task<Result<()>>> {
4708 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4709 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4710 }
4711
4712 pub fn confirm_completion_insert(
4713 &mut self,
4714 _: &ConfirmCompletionInsert,
4715 window: &mut Window,
4716 cx: &mut Context<Self>,
4717 ) -> Option<Task<Result<()>>> {
4718 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4719 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4720 }
4721
4722 pub fn confirm_completion_replace(
4723 &mut self,
4724 _: &ConfirmCompletionReplace,
4725 window: &mut Window,
4726 cx: &mut Context<Self>,
4727 ) -> Option<Task<Result<()>>> {
4728 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4729 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4730 }
4731
4732 pub fn compose_completion(
4733 &mut self,
4734 action: &ComposeCompletion,
4735 window: &mut Window,
4736 cx: &mut Context<Self>,
4737 ) -> Option<Task<Result<()>>> {
4738 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4739 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4740 }
4741
4742 fn do_completion(
4743 &mut self,
4744 item_ix: Option<usize>,
4745 intent: CompletionIntent,
4746 window: &mut Window,
4747 cx: &mut Context<Editor>,
4748 ) -> Option<Task<Result<()>>> {
4749 use language::ToOffset as _;
4750
4751 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4752 else {
4753 return None;
4754 };
4755
4756 let candidate_id = {
4757 let entries = completions_menu.entries.borrow();
4758 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4759 if self.show_edit_predictions_in_menu() {
4760 self.discard_inline_completion(true, cx);
4761 }
4762 mat.candidate_id
4763 };
4764
4765 let buffer_handle = completions_menu.buffer;
4766 let completion = completions_menu
4767 .completions
4768 .borrow()
4769 .get(candidate_id)?
4770 .clone();
4771 cx.stop_propagation();
4772
4773 let snippet;
4774 let new_text;
4775 if completion.is_snippet() {
4776 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4777 new_text = snippet.as_ref().unwrap().text.clone();
4778 } else {
4779 snippet = None;
4780 new_text = completion.new_text.clone();
4781 };
4782
4783 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4784 let buffer = buffer_handle.read(cx);
4785 let snapshot = self.buffer.read(cx).snapshot(cx);
4786 let replace_range_multibuffer = {
4787 let excerpt = snapshot
4788 .excerpt_containing(self.selections.newest_anchor().range())
4789 .unwrap();
4790 let multibuffer_anchor = snapshot
4791 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4792 .unwrap()
4793 ..snapshot
4794 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4795 .unwrap();
4796 multibuffer_anchor.start.to_offset(&snapshot)
4797 ..multibuffer_anchor.end.to_offset(&snapshot)
4798 };
4799 let newest_anchor = self.selections.newest_anchor();
4800 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4801 return None;
4802 }
4803
4804 let old_text = buffer
4805 .text_for_range(replace_range.clone())
4806 .collect::<String>();
4807 let lookbehind = newest_anchor
4808 .start
4809 .text_anchor
4810 .to_offset(buffer)
4811 .saturating_sub(replace_range.start);
4812 let lookahead = replace_range
4813 .end
4814 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4815 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4816 let suffix = &old_text[lookbehind.min(old_text.len())..];
4817
4818 let selections = self.selections.all::<usize>(cx);
4819 let mut ranges = Vec::new();
4820 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4821
4822 for selection in &selections {
4823 let range = if selection.id == newest_anchor.id {
4824 replace_range_multibuffer.clone()
4825 } else {
4826 let mut range = selection.range();
4827
4828 // if prefix is present, don't duplicate it
4829 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4830 range.start = range.start.saturating_sub(lookbehind);
4831
4832 // if suffix is also present, mimic the newest cursor and replace it
4833 if selection.id != newest_anchor.id
4834 && snapshot.contains_str_at(range.end, suffix)
4835 {
4836 range.end += lookahead;
4837 }
4838 }
4839 range
4840 };
4841
4842 ranges.push(range);
4843
4844 if !self.linked_edit_ranges.is_empty() {
4845 let start_anchor = snapshot.anchor_before(selection.head());
4846 let end_anchor = snapshot.anchor_after(selection.tail());
4847 if let Some(ranges) = self
4848 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4849 {
4850 for (buffer, edits) in ranges {
4851 linked_edits
4852 .entry(buffer.clone())
4853 .or_default()
4854 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4855 }
4856 }
4857 }
4858 }
4859
4860 cx.emit(EditorEvent::InputHandled {
4861 utf16_range_to_replace: None,
4862 text: new_text.clone().into(),
4863 });
4864
4865 self.transact(window, cx, |this, window, cx| {
4866 if let Some(mut snippet) = snippet {
4867 snippet.text = new_text.to_string();
4868 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4869 } else {
4870 this.buffer.update(cx, |buffer, cx| {
4871 let auto_indent = match completion.insert_text_mode {
4872 Some(InsertTextMode::AS_IS) => None,
4873 _ => this.autoindent_mode.clone(),
4874 };
4875 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
4876 buffer.edit(edits, auto_indent, cx);
4877 });
4878 }
4879 for (buffer, edits) in linked_edits {
4880 buffer.update(cx, |buffer, cx| {
4881 let snapshot = buffer.snapshot();
4882 let edits = edits
4883 .into_iter()
4884 .map(|(range, text)| {
4885 use text::ToPoint as TP;
4886 let end_point = TP::to_point(&range.end, &snapshot);
4887 let start_point = TP::to_point(&range.start, &snapshot);
4888 (start_point..end_point, text)
4889 })
4890 .sorted_by_key(|(range, _)| range.start);
4891 buffer.edit(edits, None, cx);
4892 })
4893 }
4894
4895 this.refresh_inline_completion(true, false, window, cx);
4896 });
4897
4898 let show_new_completions_on_confirm = completion
4899 .confirm
4900 .as_ref()
4901 .map_or(false, |confirm| confirm(intent, window, cx));
4902 if show_new_completions_on_confirm {
4903 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4904 }
4905
4906 let provider = self.completion_provider.as_ref()?;
4907 drop(completion);
4908 let apply_edits = provider.apply_additional_edits_for_completion(
4909 buffer_handle,
4910 completions_menu.completions.clone(),
4911 candidate_id,
4912 true,
4913 cx,
4914 );
4915
4916 let editor_settings = EditorSettings::get_global(cx);
4917 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4918 // After the code completion is finished, users often want to know what signatures are needed.
4919 // so we should automatically call signature_help
4920 self.show_signature_help(&ShowSignatureHelp, window, cx);
4921 }
4922
4923 Some(cx.foreground_executor().spawn(async move {
4924 apply_edits.await?;
4925 Ok(())
4926 }))
4927 }
4928
4929 pub fn toggle_code_actions(
4930 &mut self,
4931 action: &ToggleCodeActions,
4932 window: &mut Window,
4933 cx: &mut Context<Self>,
4934 ) {
4935 let mut context_menu = self.context_menu.borrow_mut();
4936 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4937 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4938 // Toggle if we're selecting the same one
4939 *context_menu = None;
4940 cx.notify();
4941 return;
4942 } else {
4943 // Otherwise, clear it and start a new one
4944 *context_menu = None;
4945 cx.notify();
4946 }
4947 }
4948 drop(context_menu);
4949 let snapshot = self.snapshot(window, cx);
4950 let deployed_from_indicator = action.deployed_from_indicator;
4951 let mut task = self.code_actions_task.take();
4952 let action = action.clone();
4953 cx.spawn_in(window, async move |editor, cx| {
4954 while let Some(prev_task) = task {
4955 prev_task.await.log_err();
4956 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4957 }
4958
4959 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4960 if editor.focus_handle.is_focused(window) {
4961 let multibuffer_point = action
4962 .deployed_from_indicator
4963 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4964 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4965 let (buffer, buffer_row) = snapshot
4966 .buffer_snapshot
4967 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4968 .and_then(|(buffer_snapshot, range)| {
4969 editor
4970 .buffer
4971 .read(cx)
4972 .buffer(buffer_snapshot.remote_id())
4973 .map(|buffer| (buffer, range.start.row))
4974 })?;
4975 let (_, code_actions) = editor
4976 .available_code_actions
4977 .clone()
4978 .and_then(|(location, code_actions)| {
4979 let snapshot = location.buffer.read(cx).snapshot();
4980 let point_range = location.range.to_point(&snapshot);
4981 let point_range = point_range.start.row..=point_range.end.row;
4982 if point_range.contains(&buffer_row) {
4983 Some((location, code_actions))
4984 } else {
4985 None
4986 }
4987 })
4988 .unzip();
4989 let buffer_id = buffer.read(cx).remote_id();
4990 let tasks = editor
4991 .tasks
4992 .get(&(buffer_id, buffer_row))
4993 .map(|t| Arc::new(t.to_owned()));
4994 if tasks.is_none() && code_actions.is_none() {
4995 return None;
4996 }
4997
4998 editor.completion_tasks.clear();
4999 editor.discard_inline_completion(false, cx);
5000 let task_context =
5001 tasks
5002 .as_ref()
5003 .zip(editor.project.clone())
5004 .map(|(tasks, project)| {
5005 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5006 });
5007
5008 let debugger_flag = cx.has_flag::<Debugger>();
5009
5010 Some(cx.spawn_in(window, async move |editor, cx| {
5011 let task_context = match task_context {
5012 Some(task_context) => task_context.await,
5013 None => None,
5014 };
5015 let resolved_tasks =
5016 tasks.zip(task_context).map(|(tasks, task_context)| {
5017 Rc::new(ResolvedTasks {
5018 templates: tasks.resolve(&task_context).collect(),
5019 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5020 multibuffer_point.row,
5021 tasks.column,
5022 )),
5023 })
5024 });
5025 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
5026 tasks
5027 .templates
5028 .iter()
5029 .filter(|task| {
5030 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
5031 debugger_flag
5032 } else {
5033 true
5034 }
5035 })
5036 .count()
5037 == 1
5038 }) && code_actions
5039 .as_ref()
5040 .map_or(true, |actions| actions.is_empty());
5041 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5042 *editor.context_menu.borrow_mut() =
5043 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5044 buffer,
5045 actions: CodeActionContents {
5046 tasks: resolved_tasks,
5047 actions: code_actions,
5048 },
5049 selected_item: Default::default(),
5050 scroll_handle: UniformListScrollHandle::default(),
5051 deployed_from_indicator,
5052 }));
5053 if spawn_straight_away {
5054 if let Some(task) = editor.confirm_code_action(
5055 &ConfirmCodeAction { item_ix: Some(0) },
5056 window,
5057 cx,
5058 ) {
5059 cx.notify();
5060 return task;
5061 }
5062 }
5063 cx.notify();
5064 Task::ready(Ok(()))
5065 }) {
5066 task.await
5067 } else {
5068 Ok(())
5069 }
5070 }))
5071 } else {
5072 Some(Task::ready(Ok(())))
5073 }
5074 })?;
5075 if let Some(task) = spawned_test_task {
5076 task.await?;
5077 }
5078
5079 Ok::<_, anyhow::Error>(())
5080 })
5081 .detach_and_log_err(cx);
5082 }
5083
5084 pub fn confirm_code_action(
5085 &mut self,
5086 action: &ConfirmCodeAction,
5087 window: &mut Window,
5088 cx: &mut Context<Self>,
5089 ) -> Option<Task<Result<()>>> {
5090 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5091
5092 let actions_menu =
5093 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5094 menu
5095 } else {
5096 return None;
5097 };
5098
5099 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5100 let action = actions_menu.actions.get(action_ix)?;
5101 let title = action.label();
5102 let buffer = actions_menu.buffer;
5103 let workspace = self.workspace()?;
5104
5105 match action {
5106 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5107 match resolved_task.task_type() {
5108 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5109 workspace::tasks::schedule_resolved_task(
5110 workspace,
5111 task_source_kind,
5112 resolved_task,
5113 false,
5114 cx,
5115 );
5116
5117 Some(Task::ready(Ok(())))
5118 }),
5119 task::TaskType::Debug(debug_args) => {
5120 if debug_args.locator.is_some() {
5121 workspace.update(cx, |workspace, cx| {
5122 workspace::tasks::schedule_resolved_task(
5123 workspace,
5124 task_source_kind,
5125 resolved_task,
5126 false,
5127 cx,
5128 );
5129 });
5130
5131 return Some(Task::ready(Ok(())));
5132 }
5133
5134 if let Some(project) = self.project.as_ref() {
5135 project
5136 .update(cx, |project, cx| {
5137 project.start_debug_session(
5138 resolved_task.resolved_debug_adapter_config().unwrap(),
5139 cx,
5140 )
5141 })
5142 .detach_and_log_err(cx);
5143 Some(Task::ready(Ok(())))
5144 } else {
5145 Some(Task::ready(Ok(())))
5146 }
5147 }
5148 }
5149 }
5150 CodeActionsItem::CodeAction {
5151 excerpt_id,
5152 action,
5153 provider,
5154 } => {
5155 let apply_code_action =
5156 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5157 let workspace = workspace.downgrade();
5158 Some(cx.spawn_in(window, async move |editor, cx| {
5159 let project_transaction = apply_code_action.await?;
5160 Self::open_project_transaction(
5161 &editor,
5162 workspace,
5163 project_transaction,
5164 title,
5165 cx,
5166 )
5167 .await
5168 }))
5169 }
5170 }
5171 }
5172
5173 pub async fn open_project_transaction(
5174 this: &WeakEntity<Editor>,
5175 workspace: WeakEntity<Workspace>,
5176 transaction: ProjectTransaction,
5177 title: String,
5178 cx: &mut AsyncWindowContext,
5179 ) -> Result<()> {
5180 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5181 cx.update(|_, cx| {
5182 entries.sort_unstable_by_key(|(buffer, _)| {
5183 buffer.read(cx).file().map(|f| f.path().clone())
5184 });
5185 })?;
5186
5187 // If the project transaction's edits are all contained within this editor, then
5188 // avoid opening a new editor to display them.
5189
5190 if let Some((buffer, transaction)) = entries.first() {
5191 if entries.len() == 1 {
5192 let excerpt = this.update(cx, |editor, cx| {
5193 editor
5194 .buffer()
5195 .read(cx)
5196 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5197 })?;
5198 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5199 if excerpted_buffer == *buffer {
5200 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5201 let excerpt_range = excerpt_range.to_offset(buffer);
5202 buffer
5203 .edited_ranges_for_transaction::<usize>(transaction)
5204 .all(|range| {
5205 excerpt_range.start <= range.start
5206 && excerpt_range.end >= range.end
5207 })
5208 })?;
5209
5210 if all_edits_within_excerpt {
5211 return Ok(());
5212 }
5213 }
5214 }
5215 }
5216 } else {
5217 return Ok(());
5218 }
5219
5220 let mut ranges_to_highlight = Vec::new();
5221 let excerpt_buffer = cx.new(|cx| {
5222 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5223 for (buffer_handle, transaction) in &entries {
5224 let edited_ranges = buffer_handle
5225 .read(cx)
5226 .edited_ranges_for_transaction::<Point>(transaction)
5227 .collect::<Vec<_>>();
5228 let (ranges, _) = multibuffer.set_excerpts_for_path(
5229 PathKey::for_buffer(buffer_handle, cx),
5230 buffer_handle.clone(),
5231 edited_ranges,
5232 DEFAULT_MULTIBUFFER_CONTEXT,
5233 cx,
5234 );
5235
5236 ranges_to_highlight.extend(ranges);
5237 }
5238 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5239 multibuffer
5240 })?;
5241
5242 workspace.update_in(cx, |workspace, window, cx| {
5243 let project = workspace.project().clone();
5244 let editor =
5245 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5246 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5247 editor.update(cx, |editor, cx| {
5248 editor.highlight_background::<Self>(
5249 &ranges_to_highlight,
5250 |theme| theme.editor_highlighted_line_background,
5251 cx,
5252 );
5253 });
5254 })?;
5255
5256 Ok(())
5257 }
5258
5259 pub fn clear_code_action_providers(&mut self) {
5260 self.code_action_providers.clear();
5261 self.available_code_actions.take();
5262 }
5263
5264 pub fn add_code_action_provider(
5265 &mut self,
5266 provider: Rc<dyn CodeActionProvider>,
5267 window: &mut Window,
5268 cx: &mut Context<Self>,
5269 ) {
5270 if self
5271 .code_action_providers
5272 .iter()
5273 .any(|existing_provider| existing_provider.id() == provider.id())
5274 {
5275 return;
5276 }
5277
5278 self.code_action_providers.push(provider);
5279 self.refresh_code_actions(window, cx);
5280 }
5281
5282 pub fn remove_code_action_provider(
5283 &mut self,
5284 id: Arc<str>,
5285 window: &mut Window,
5286 cx: &mut Context<Self>,
5287 ) {
5288 self.code_action_providers
5289 .retain(|provider| provider.id() != id);
5290 self.refresh_code_actions(window, cx);
5291 }
5292
5293 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5294 let newest_selection = self.selections.newest_anchor().clone();
5295 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5296 let buffer = self.buffer.read(cx);
5297 if newest_selection.head().diff_base_anchor.is_some() {
5298 return None;
5299 }
5300 let (start_buffer, start) =
5301 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5302 let (end_buffer, end) =
5303 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5304 if start_buffer != end_buffer {
5305 return None;
5306 }
5307
5308 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5309 cx.background_executor()
5310 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5311 .await;
5312
5313 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5314 let providers = this.code_action_providers.clone();
5315 let tasks = this
5316 .code_action_providers
5317 .iter()
5318 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5319 .collect::<Vec<_>>();
5320 (providers, tasks)
5321 })?;
5322
5323 let mut actions = Vec::new();
5324 for (provider, provider_actions) in
5325 providers.into_iter().zip(future::join_all(tasks).await)
5326 {
5327 if let Some(provider_actions) = provider_actions.log_err() {
5328 actions.extend(provider_actions.into_iter().map(|action| {
5329 AvailableCodeAction {
5330 excerpt_id: newest_selection.start.excerpt_id,
5331 action,
5332 provider: provider.clone(),
5333 }
5334 }));
5335 }
5336 }
5337
5338 this.update(cx, |this, cx| {
5339 this.available_code_actions = if actions.is_empty() {
5340 None
5341 } else {
5342 Some((
5343 Location {
5344 buffer: start_buffer,
5345 range: start..end,
5346 },
5347 actions.into(),
5348 ))
5349 };
5350 cx.notify();
5351 })
5352 }));
5353 None
5354 }
5355
5356 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5357 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5358 self.show_git_blame_inline = false;
5359
5360 self.show_git_blame_inline_delay_task =
5361 Some(cx.spawn_in(window, async move |this, cx| {
5362 cx.background_executor().timer(delay).await;
5363
5364 this.update(cx, |this, cx| {
5365 this.show_git_blame_inline = true;
5366 cx.notify();
5367 })
5368 .log_err();
5369 }));
5370 }
5371 }
5372
5373 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5374 if self.pending_rename.is_some() {
5375 return None;
5376 }
5377
5378 let provider = self.semantics_provider.clone()?;
5379 let buffer = self.buffer.read(cx);
5380 let newest_selection = self.selections.newest_anchor().clone();
5381 let cursor_position = newest_selection.head();
5382 let (cursor_buffer, cursor_buffer_position) =
5383 buffer.text_anchor_for_position(cursor_position, cx)?;
5384 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5385 if cursor_buffer != tail_buffer {
5386 return None;
5387 }
5388 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5389 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5390 cx.background_executor()
5391 .timer(Duration::from_millis(debounce))
5392 .await;
5393
5394 let highlights = if let Some(highlights) = cx
5395 .update(|cx| {
5396 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5397 })
5398 .ok()
5399 .flatten()
5400 {
5401 highlights.await.log_err()
5402 } else {
5403 None
5404 };
5405
5406 if let Some(highlights) = highlights {
5407 this.update(cx, |this, cx| {
5408 if this.pending_rename.is_some() {
5409 return;
5410 }
5411
5412 let buffer_id = cursor_position.buffer_id;
5413 let buffer = this.buffer.read(cx);
5414 if !buffer
5415 .text_anchor_for_position(cursor_position, cx)
5416 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5417 {
5418 return;
5419 }
5420
5421 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5422 let mut write_ranges = Vec::new();
5423 let mut read_ranges = Vec::new();
5424 for highlight in highlights {
5425 for (excerpt_id, excerpt_range) in
5426 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5427 {
5428 let start = highlight
5429 .range
5430 .start
5431 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5432 let end = highlight
5433 .range
5434 .end
5435 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5436 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5437 continue;
5438 }
5439
5440 let range = Anchor {
5441 buffer_id,
5442 excerpt_id,
5443 text_anchor: start,
5444 diff_base_anchor: None,
5445 }..Anchor {
5446 buffer_id,
5447 excerpt_id,
5448 text_anchor: end,
5449 diff_base_anchor: None,
5450 };
5451 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5452 write_ranges.push(range);
5453 } else {
5454 read_ranges.push(range);
5455 }
5456 }
5457 }
5458
5459 this.highlight_background::<DocumentHighlightRead>(
5460 &read_ranges,
5461 |theme| theme.editor_document_highlight_read_background,
5462 cx,
5463 );
5464 this.highlight_background::<DocumentHighlightWrite>(
5465 &write_ranges,
5466 |theme| theme.editor_document_highlight_write_background,
5467 cx,
5468 );
5469 cx.notify();
5470 })
5471 .log_err();
5472 }
5473 }));
5474 None
5475 }
5476
5477 pub fn refresh_selected_text_highlights(
5478 &mut self,
5479 window: &mut Window,
5480 cx: &mut Context<Editor>,
5481 ) {
5482 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5483 return;
5484 }
5485 self.selection_highlight_task.take();
5486 if !EditorSettings::get_global(cx).selection_highlight {
5487 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5488 return;
5489 }
5490 if self.selections.count() != 1 || self.selections.line_mode {
5491 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5492 return;
5493 }
5494 let selection = self.selections.newest::<Point>(cx);
5495 if selection.is_empty() || selection.start.row != selection.end.row {
5496 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5497 return;
5498 }
5499 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5500 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5501 cx.background_executor()
5502 .timer(Duration::from_millis(debounce))
5503 .await;
5504 let Some(Some(matches_task)) = editor
5505 .update_in(cx, |editor, _, cx| {
5506 if editor.selections.count() != 1 || editor.selections.line_mode {
5507 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5508 return None;
5509 }
5510 let selection = editor.selections.newest::<Point>(cx);
5511 if selection.is_empty() || selection.start.row != selection.end.row {
5512 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5513 return None;
5514 }
5515 let buffer = editor.buffer().read(cx).snapshot(cx);
5516 let query = buffer.text_for_range(selection.range()).collect::<String>();
5517 if query.trim().is_empty() {
5518 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5519 return None;
5520 }
5521 Some(cx.background_spawn(async move {
5522 let mut ranges = Vec::new();
5523 let selection_anchors = selection.range().to_anchors(&buffer);
5524 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5525 for (search_buffer, search_range, excerpt_id) in
5526 buffer.range_to_buffer_ranges(range)
5527 {
5528 ranges.extend(
5529 project::search::SearchQuery::text(
5530 query.clone(),
5531 false,
5532 false,
5533 false,
5534 Default::default(),
5535 Default::default(),
5536 None,
5537 )
5538 .unwrap()
5539 .search(search_buffer, Some(search_range.clone()))
5540 .await
5541 .into_iter()
5542 .filter_map(
5543 |match_range| {
5544 let start = search_buffer.anchor_after(
5545 search_range.start + match_range.start,
5546 );
5547 let end = search_buffer.anchor_before(
5548 search_range.start + match_range.end,
5549 );
5550 let range = Anchor::range_in_buffer(
5551 excerpt_id,
5552 search_buffer.remote_id(),
5553 start..end,
5554 );
5555 (range != selection_anchors).then_some(range)
5556 },
5557 ),
5558 );
5559 }
5560 }
5561 ranges
5562 }))
5563 })
5564 .log_err()
5565 else {
5566 return;
5567 };
5568 let matches = matches_task.await;
5569 editor
5570 .update_in(cx, |editor, _, cx| {
5571 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5572 if !matches.is_empty() {
5573 editor.highlight_background::<SelectedTextHighlight>(
5574 &matches,
5575 |theme| theme.editor_document_highlight_bracket_background,
5576 cx,
5577 )
5578 }
5579 })
5580 .log_err();
5581 }));
5582 }
5583
5584 pub fn refresh_inline_completion(
5585 &mut self,
5586 debounce: bool,
5587 user_requested: bool,
5588 window: &mut Window,
5589 cx: &mut Context<Self>,
5590 ) -> Option<()> {
5591 let provider = self.edit_prediction_provider()?;
5592 let cursor = self.selections.newest_anchor().head();
5593 let (buffer, cursor_buffer_position) =
5594 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5595
5596 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5597 self.discard_inline_completion(false, cx);
5598 return None;
5599 }
5600
5601 if !user_requested
5602 && (!self.should_show_edit_predictions()
5603 || !self.is_focused(window)
5604 || buffer.read(cx).is_empty())
5605 {
5606 self.discard_inline_completion(false, cx);
5607 return None;
5608 }
5609
5610 self.update_visible_inline_completion(window, cx);
5611 provider.refresh(
5612 self.project.clone(),
5613 buffer,
5614 cursor_buffer_position,
5615 debounce,
5616 cx,
5617 );
5618 Some(())
5619 }
5620
5621 fn show_edit_predictions_in_menu(&self) -> bool {
5622 match self.edit_prediction_settings {
5623 EditPredictionSettings::Disabled => false,
5624 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5625 }
5626 }
5627
5628 pub fn edit_predictions_enabled(&self) -> bool {
5629 match self.edit_prediction_settings {
5630 EditPredictionSettings::Disabled => false,
5631 EditPredictionSettings::Enabled { .. } => true,
5632 }
5633 }
5634
5635 fn edit_prediction_requires_modifier(&self) -> bool {
5636 match self.edit_prediction_settings {
5637 EditPredictionSettings::Disabled => false,
5638 EditPredictionSettings::Enabled {
5639 preview_requires_modifier,
5640 ..
5641 } => preview_requires_modifier,
5642 }
5643 }
5644
5645 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5646 if self.edit_prediction_provider.is_none() {
5647 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5648 } else {
5649 let selection = self.selections.newest_anchor();
5650 let cursor = selection.head();
5651
5652 if let Some((buffer, cursor_buffer_position)) =
5653 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5654 {
5655 self.edit_prediction_settings =
5656 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5657 }
5658 }
5659 }
5660
5661 fn edit_prediction_settings_at_position(
5662 &self,
5663 buffer: &Entity<Buffer>,
5664 buffer_position: language::Anchor,
5665 cx: &App,
5666 ) -> EditPredictionSettings {
5667 if !self.mode.is_full()
5668 || !self.show_inline_completions_override.unwrap_or(true)
5669 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5670 {
5671 return EditPredictionSettings::Disabled;
5672 }
5673
5674 let buffer = buffer.read(cx);
5675
5676 let file = buffer.file();
5677
5678 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5679 return EditPredictionSettings::Disabled;
5680 };
5681
5682 let by_provider = matches!(
5683 self.menu_inline_completions_policy,
5684 MenuInlineCompletionsPolicy::ByProvider
5685 );
5686
5687 let show_in_menu = by_provider
5688 && self
5689 .edit_prediction_provider
5690 .as_ref()
5691 .map_or(false, |provider| {
5692 provider.provider.show_completions_in_menu()
5693 });
5694
5695 let preview_requires_modifier =
5696 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5697
5698 EditPredictionSettings::Enabled {
5699 show_in_menu,
5700 preview_requires_modifier,
5701 }
5702 }
5703
5704 fn should_show_edit_predictions(&self) -> bool {
5705 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5706 }
5707
5708 pub fn edit_prediction_preview_is_active(&self) -> bool {
5709 matches!(
5710 self.edit_prediction_preview,
5711 EditPredictionPreview::Active { .. }
5712 )
5713 }
5714
5715 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5716 let cursor = self.selections.newest_anchor().head();
5717 if let Some((buffer, cursor_position)) =
5718 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5719 {
5720 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5721 } else {
5722 false
5723 }
5724 }
5725
5726 fn edit_predictions_enabled_in_buffer(
5727 &self,
5728 buffer: &Entity<Buffer>,
5729 buffer_position: language::Anchor,
5730 cx: &App,
5731 ) -> bool {
5732 maybe!({
5733 if self.read_only(cx) {
5734 return Some(false);
5735 }
5736 let provider = self.edit_prediction_provider()?;
5737 if !provider.is_enabled(&buffer, buffer_position, cx) {
5738 return Some(false);
5739 }
5740 let buffer = buffer.read(cx);
5741 let Some(file) = buffer.file() else {
5742 return Some(true);
5743 };
5744 let settings = all_language_settings(Some(file), cx);
5745 Some(settings.edit_predictions_enabled_for_file(file, cx))
5746 })
5747 .unwrap_or(false)
5748 }
5749
5750 fn cycle_inline_completion(
5751 &mut self,
5752 direction: Direction,
5753 window: &mut Window,
5754 cx: &mut Context<Self>,
5755 ) -> Option<()> {
5756 let provider = self.edit_prediction_provider()?;
5757 let cursor = self.selections.newest_anchor().head();
5758 let (buffer, cursor_buffer_position) =
5759 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5760 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5761 return None;
5762 }
5763
5764 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5765 self.update_visible_inline_completion(window, cx);
5766
5767 Some(())
5768 }
5769
5770 pub fn show_inline_completion(
5771 &mut self,
5772 _: &ShowEditPrediction,
5773 window: &mut Window,
5774 cx: &mut Context<Self>,
5775 ) {
5776 if !self.has_active_inline_completion() {
5777 self.refresh_inline_completion(false, true, window, cx);
5778 return;
5779 }
5780
5781 self.update_visible_inline_completion(window, cx);
5782 }
5783
5784 pub fn display_cursor_names(
5785 &mut self,
5786 _: &DisplayCursorNames,
5787 window: &mut Window,
5788 cx: &mut Context<Self>,
5789 ) {
5790 self.show_cursor_names(window, cx);
5791 }
5792
5793 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5794 self.show_cursor_names = true;
5795 cx.notify();
5796 cx.spawn_in(window, async move |this, cx| {
5797 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5798 this.update(cx, |this, cx| {
5799 this.show_cursor_names = false;
5800 cx.notify()
5801 })
5802 .ok()
5803 })
5804 .detach();
5805 }
5806
5807 pub fn next_edit_prediction(
5808 &mut self,
5809 _: &NextEditPrediction,
5810 window: &mut Window,
5811 cx: &mut Context<Self>,
5812 ) {
5813 if self.has_active_inline_completion() {
5814 self.cycle_inline_completion(Direction::Next, window, cx);
5815 } else {
5816 let is_copilot_disabled = self
5817 .refresh_inline_completion(false, true, window, cx)
5818 .is_none();
5819 if is_copilot_disabled {
5820 cx.propagate();
5821 }
5822 }
5823 }
5824
5825 pub fn previous_edit_prediction(
5826 &mut self,
5827 _: &PreviousEditPrediction,
5828 window: &mut Window,
5829 cx: &mut Context<Self>,
5830 ) {
5831 if self.has_active_inline_completion() {
5832 self.cycle_inline_completion(Direction::Prev, window, cx);
5833 } else {
5834 let is_copilot_disabled = self
5835 .refresh_inline_completion(false, true, window, cx)
5836 .is_none();
5837 if is_copilot_disabled {
5838 cx.propagate();
5839 }
5840 }
5841 }
5842
5843 pub fn accept_edit_prediction(
5844 &mut self,
5845 _: &AcceptEditPrediction,
5846 window: &mut Window,
5847 cx: &mut Context<Self>,
5848 ) {
5849 if self.show_edit_predictions_in_menu() {
5850 self.hide_context_menu(window, cx);
5851 }
5852
5853 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5854 return;
5855 };
5856
5857 self.report_inline_completion_event(
5858 active_inline_completion.completion_id.clone(),
5859 true,
5860 cx,
5861 );
5862
5863 match &active_inline_completion.completion {
5864 InlineCompletion::Move { target, .. } => {
5865 let target = *target;
5866
5867 if let Some(position_map) = &self.last_position_map {
5868 if position_map
5869 .visible_row_range
5870 .contains(&target.to_display_point(&position_map.snapshot).row())
5871 || !self.edit_prediction_requires_modifier()
5872 {
5873 self.unfold_ranges(&[target..target], true, false, cx);
5874 // Note that this is also done in vim's handler of the Tab action.
5875 self.change_selections(
5876 Some(Autoscroll::newest()),
5877 window,
5878 cx,
5879 |selections| {
5880 selections.select_anchor_ranges([target..target]);
5881 },
5882 );
5883 self.clear_row_highlights::<EditPredictionPreview>();
5884
5885 self.edit_prediction_preview
5886 .set_previous_scroll_position(None);
5887 } else {
5888 self.edit_prediction_preview
5889 .set_previous_scroll_position(Some(
5890 position_map.snapshot.scroll_anchor,
5891 ));
5892
5893 self.highlight_rows::<EditPredictionPreview>(
5894 target..target,
5895 cx.theme().colors().editor_highlighted_line_background,
5896 true,
5897 cx,
5898 );
5899 self.request_autoscroll(Autoscroll::fit(), cx);
5900 }
5901 }
5902 }
5903 InlineCompletion::Edit { edits, .. } => {
5904 if let Some(provider) = self.edit_prediction_provider() {
5905 provider.accept(cx);
5906 }
5907
5908 let snapshot = self.buffer.read(cx).snapshot(cx);
5909 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5910
5911 self.buffer.update(cx, |buffer, cx| {
5912 buffer.edit(edits.iter().cloned(), None, cx)
5913 });
5914
5915 self.change_selections(None, window, cx, |s| {
5916 s.select_anchor_ranges([last_edit_end..last_edit_end])
5917 });
5918
5919 self.update_visible_inline_completion(window, cx);
5920 if self.active_inline_completion.is_none() {
5921 self.refresh_inline_completion(true, true, window, cx);
5922 }
5923
5924 cx.notify();
5925 }
5926 }
5927
5928 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5929 }
5930
5931 pub fn accept_partial_inline_completion(
5932 &mut self,
5933 _: &AcceptPartialEditPrediction,
5934 window: &mut Window,
5935 cx: &mut Context<Self>,
5936 ) {
5937 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5938 return;
5939 };
5940 if self.selections.count() != 1 {
5941 return;
5942 }
5943
5944 self.report_inline_completion_event(
5945 active_inline_completion.completion_id.clone(),
5946 true,
5947 cx,
5948 );
5949
5950 match &active_inline_completion.completion {
5951 InlineCompletion::Move { target, .. } => {
5952 let target = *target;
5953 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5954 selections.select_anchor_ranges([target..target]);
5955 });
5956 }
5957 InlineCompletion::Edit { edits, .. } => {
5958 // Find an insertion that starts at the cursor position.
5959 let snapshot = self.buffer.read(cx).snapshot(cx);
5960 let cursor_offset = self.selections.newest::<usize>(cx).head();
5961 let insertion = edits.iter().find_map(|(range, text)| {
5962 let range = range.to_offset(&snapshot);
5963 if range.is_empty() && range.start == cursor_offset {
5964 Some(text)
5965 } else {
5966 None
5967 }
5968 });
5969
5970 if let Some(text) = insertion {
5971 let mut partial_completion = text
5972 .chars()
5973 .by_ref()
5974 .take_while(|c| c.is_alphabetic())
5975 .collect::<String>();
5976 if partial_completion.is_empty() {
5977 partial_completion = text
5978 .chars()
5979 .by_ref()
5980 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5981 .collect::<String>();
5982 }
5983
5984 cx.emit(EditorEvent::InputHandled {
5985 utf16_range_to_replace: None,
5986 text: partial_completion.clone().into(),
5987 });
5988
5989 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5990
5991 self.refresh_inline_completion(true, true, window, cx);
5992 cx.notify();
5993 } else {
5994 self.accept_edit_prediction(&Default::default(), window, cx);
5995 }
5996 }
5997 }
5998 }
5999
6000 fn discard_inline_completion(
6001 &mut self,
6002 should_report_inline_completion_event: bool,
6003 cx: &mut Context<Self>,
6004 ) -> bool {
6005 if should_report_inline_completion_event {
6006 let completion_id = self
6007 .active_inline_completion
6008 .as_ref()
6009 .and_then(|active_completion| active_completion.completion_id.clone());
6010
6011 self.report_inline_completion_event(completion_id, false, cx);
6012 }
6013
6014 if let Some(provider) = self.edit_prediction_provider() {
6015 provider.discard(cx);
6016 }
6017
6018 self.take_active_inline_completion(cx)
6019 }
6020
6021 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6022 let Some(provider) = self.edit_prediction_provider() else {
6023 return;
6024 };
6025
6026 let Some((_, buffer, _)) = self
6027 .buffer
6028 .read(cx)
6029 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6030 else {
6031 return;
6032 };
6033
6034 let extension = buffer
6035 .read(cx)
6036 .file()
6037 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6038
6039 let event_type = match accepted {
6040 true => "Edit Prediction Accepted",
6041 false => "Edit Prediction Discarded",
6042 };
6043 telemetry::event!(
6044 event_type,
6045 provider = provider.name(),
6046 prediction_id = id,
6047 suggestion_accepted = accepted,
6048 file_extension = extension,
6049 );
6050 }
6051
6052 pub fn has_active_inline_completion(&self) -> bool {
6053 self.active_inline_completion.is_some()
6054 }
6055
6056 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6057 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6058 return false;
6059 };
6060
6061 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6062 self.clear_highlights::<InlineCompletionHighlight>(cx);
6063 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6064 true
6065 }
6066
6067 /// Returns true when we're displaying the edit prediction popover below the cursor
6068 /// like we are not previewing and the LSP autocomplete menu is visible
6069 /// or we are in `when_holding_modifier` mode.
6070 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6071 if self.edit_prediction_preview_is_active()
6072 || !self.show_edit_predictions_in_menu()
6073 || !self.edit_predictions_enabled()
6074 {
6075 return false;
6076 }
6077
6078 if self.has_visible_completions_menu() {
6079 return true;
6080 }
6081
6082 has_completion && self.edit_prediction_requires_modifier()
6083 }
6084
6085 fn handle_modifiers_changed(
6086 &mut self,
6087 modifiers: Modifiers,
6088 position_map: &PositionMap,
6089 window: &mut Window,
6090 cx: &mut Context<Self>,
6091 ) {
6092 if self.show_edit_predictions_in_menu() {
6093 self.update_edit_prediction_preview(&modifiers, window, cx);
6094 }
6095
6096 self.update_selection_mode(&modifiers, position_map, window, cx);
6097
6098 let mouse_position = window.mouse_position();
6099 if !position_map.text_hitbox.is_hovered(window) {
6100 return;
6101 }
6102
6103 self.update_hovered_link(
6104 position_map.point_for_position(mouse_position),
6105 &position_map.snapshot,
6106 modifiers,
6107 window,
6108 cx,
6109 )
6110 }
6111
6112 fn update_selection_mode(
6113 &mut self,
6114 modifiers: &Modifiers,
6115 position_map: &PositionMap,
6116 window: &mut Window,
6117 cx: &mut Context<Self>,
6118 ) {
6119 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6120 return;
6121 }
6122
6123 let mouse_position = window.mouse_position();
6124 let point_for_position = position_map.point_for_position(mouse_position);
6125 let position = point_for_position.previous_valid;
6126
6127 self.select(
6128 SelectPhase::BeginColumnar {
6129 position,
6130 reset: false,
6131 goal_column: point_for_position.exact_unclipped.column(),
6132 },
6133 window,
6134 cx,
6135 );
6136 }
6137
6138 fn update_edit_prediction_preview(
6139 &mut self,
6140 modifiers: &Modifiers,
6141 window: &mut Window,
6142 cx: &mut Context<Self>,
6143 ) {
6144 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6145 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6146 return;
6147 };
6148
6149 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6150 if matches!(
6151 self.edit_prediction_preview,
6152 EditPredictionPreview::Inactive { .. }
6153 ) {
6154 self.edit_prediction_preview = EditPredictionPreview::Active {
6155 previous_scroll_position: None,
6156 since: Instant::now(),
6157 };
6158
6159 self.update_visible_inline_completion(window, cx);
6160 cx.notify();
6161 }
6162 } else if let EditPredictionPreview::Active {
6163 previous_scroll_position,
6164 since,
6165 } = self.edit_prediction_preview
6166 {
6167 if let (Some(previous_scroll_position), Some(position_map)) =
6168 (previous_scroll_position, self.last_position_map.as_ref())
6169 {
6170 self.set_scroll_position(
6171 previous_scroll_position
6172 .scroll_position(&position_map.snapshot.display_snapshot),
6173 window,
6174 cx,
6175 );
6176 }
6177
6178 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6179 released_too_fast: since.elapsed() < Duration::from_millis(200),
6180 };
6181 self.clear_row_highlights::<EditPredictionPreview>();
6182 self.update_visible_inline_completion(window, cx);
6183 cx.notify();
6184 }
6185 }
6186
6187 fn update_visible_inline_completion(
6188 &mut self,
6189 _window: &mut Window,
6190 cx: &mut Context<Self>,
6191 ) -> Option<()> {
6192 let selection = self.selections.newest_anchor();
6193 let cursor = selection.head();
6194 let multibuffer = self.buffer.read(cx).snapshot(cx);
6195 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6196 let excerpt_id = cursor.excerpt_id;
6197
6198 let show_in_menu = self.show_edit_predictions_in_menu();
6199 let completions_menu_has_precedence = !show_in_menu
6200 && (self.context_menu.borrow().is_some()
6201 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6202
6203 if completions_menu_has_precedence
6204 || !offset_selection.is_empty()
6205 || self
6206 .active_inline_completion
6207 .as_ref()
6208 .map_or(false, |completion| {
6209 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6210 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6211 !invalidation_range.contains(&offset_selection.head())
6212 })
6213 {
6214 self.discard_inline_completion(false, cx);
6215 return None;
6216 }
6217
6218 self.take_active_inline_completion(cx);
6219 let Some(provider) = self.edit_prediction_provider() else {
6220 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6221 return None;
6222 };
6223
6224 let (buffer, cursor_buffer_position) =
6225 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6226
6227 self.edit_prediction_settings =
6228 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6229
6230 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6231
6232 if self.edit_prediction_indent_conflict {
6233 let cursor_point = cursor.to_point(&multibuffer);
6234
6235 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6236
6237 if let Some((_, indent)) = indents.iter().next() {
6238 if indent.len == cursor_point.column {
6239 self.edit_prediction_indent_conflict = false;
6240 }
6241 }
6242 }
6243
6244 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6245 let edits = inline_completion
6246 .edits
6247 .into_iter()
6248 .flat_map(|(range, new_text)| {
6249 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6250 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6251 Some((start..end, new_text))
6252 })
6253 .collect::<Vec<_>>();
6254 if edits.is_empty() {
6255 return None;
6256 }
6257
6258 let first_edit_start = edits.first().unwrap().0.start;
6259 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6260 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6261
6262 let last_edit_end = edits.last().unwrap().0.end;
6263 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6264 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6265
6266 let cursor_row = cursor.to_point(&multibuffer).row;
6267
6268 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6269
6270 let mut inlay_ids = Vec::new();
6271 let invalidation_row_range;
6272 let move_invalidation_row_range = if cursor_row < edit_start_row {
6273 Some(cursor_row..edit_end_row)
6274 } else if cursor_row > edit_end_row {
6275 Some(edit_start_row..cursor_row)
6276 } else {
6277 None
6278 };
6279 let is_move =
6280 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6281 let completion = if is_move {
6282 invalidation_row_range =
6283 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6284 let target = first_edit_start;
6285 InlineCompletion::Move { target, snapshot }
6286 } else {
6287 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6288 && !self.inline_completions_hidden_for_vim_mode;
6289
6290 if show_completions_in_buffer {
6291 if edits
6292 .iter()
6293 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6294 {
6295 let mut inlays = Vec::new();
6296 for (range, new_text) in &edits {
6297 let inlay = Inlay::inline_completion(
6298 post_inc(&mut self.next_inlay_id),
6299 range.start,
6300 new_text.as_str(),
6301 );
6302 inlay_ids.push(inlay.id);
6303 inlays.push(inlay);
6304 }
6305
6306 self.splice_inlays(&[], inlays, cx);
6307 } else {
6308 let background_color = cx.theme().status().deleted_background;
6309 self.highlight_text::<InlineCompletionHighlight>(
6310 edits.iter().map(|(range, _)| range.clone()).collect(),
6311 HighlightStyle {
6312 background_color: Some(background_color),
6313 ..Default::default()
6314 },
6315 cx,
6316 );
6317 }
6318 }
6319
6320 invalidation_row_range = edit_start_row..edit_end_row;
6321
6322 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6323 if provider.show_tab_accept_marker() {
6324 EditDisplayMode::TabAccept
6325 } else {
6326 EditDisplayMode::Inline
6327 }
6328 } else {
6329 EditDisplayMode::DiffPopover
6330 };
6331
6332 InlineCompletion::Edit {
6333 edits,
6334 edit_preview: inline_completion.edit_preview,
6335 display_mode,
6336 snapshot,
6337 }
6338 };
6339
6340 let invalidation_range = multibuffer
6341 .anchor_before(Point::new(invalidation_row_range.start, 0))
6342 ..multibuffer.anchor_after(Point::new(
6343 invalidation_row_range.end,
6344 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6345 ));
6346
6347 self.stale_inline_completion_in_menu = None;
6348 self.active_inline_completion = Some(InlineCompletionState {
6349 inlay_ids,
6350 completion,
6351 completion_id: inline_completion.id,
6352 invalidation_range,
6353 });
6354
6355 cx.notify();
6356
6357 Some(())
6358 }
6359
6360 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6361 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6362 }
6363
6364 fn render_code_actions_indicator(
6365 &self,
6366 _style: &EditorStyle,
6367 row: DisplayRow,
6368 is_active: bool,
6369 breakpoint: Option<&(Anchor, Breakpoint)>,
6370 cx: &mut Context<Self>,
6371 ) -> Option<IconButton> {
6372 let color = Color::Muted;
6373 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6374 let show_tooltip = !self.context_menu_visible();
6375
6376 if self.available_code_actions.is_some() {
6377 Some(
6378 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6379 .shape(ui::IconButtonShape::Square)
6380 .icon_size(IconSize::XSmall)
6381 .icon_color(color)
6382 .toggle_state(is_active)
6383 .when(show_tooltip, |this| {
6384 this.tooltip({
6385 let focus_handle = self.focus_handle.clone();
6386 move |window, cx| {
6387 Tooltip::for_action_in(
6388 "Toggle Code Actions",
6389 &ToggleCodeActions {
6390 deployed_from_indicator: None,
6391 },
6392 &focus_handle,
6393 window,
6394 cx,
6395 )
6396 }
6397 })
6398 })
6399 .on_click(cx.listener(move |editor, _e, window, cx| {
6400 window.focus(&editor.focus_handle(cx));
6401 editor.toggle_code_actions(
6402 &ToggleCodeActions {
6403 deployed_from_indicator: Some(row),
6404 },
6405 window,
6406 cx,
6407 );
6408 }))
6409 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6410 editor.set_breakpoint_context_menu(
6411 row,
6412 position,
6413 event.down.position,
6414 window,
6415 cx,
6416 );
6417 })),
6418 )
6419 } else {
6420 None
6421 }
6422 }
6423
6424 fn clear_tasks(&mut self) {
6425 self.tasks.clear()
6426 }
6427
6428 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6429 if self.tasks.insert(key, value).is_some() {
6430 // This case should hopefully be rare, but just in case...
6431 log::error!(
6432 "multiple different run targets found on a single line, only the last target will be rendered"
6433 )
6434 }
6435 }
6436
6437 /// Get all display points of breakpoints that will be rendered within editor
6438 ///
6439 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6440 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6441 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6442 fn active_breakpoints(
6443 &self,
6444 range: Range<DisplayRow>,
6445 window: &mut Window,
6446 cx: &mut Context<Self>,
6447 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6448 let mut breakpoint_display_points = HashMap::default();
6449
6450 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6451 return breakpoint_display_points;
6452 };
6453
6454 let snapshot = self.snapshot(window, cx);
6455
6456 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6457 let Some(project) = self.project.as_ref() else {
6458 return breakpoint_display_points;
6459 };
6460
6461 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6462 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6463
6464 for (buffer_snapshot, range, excerpt_id) in
6465 multi_buffer_snapshot.range_to_buffer_ranges(range)
6466 {
6467 let Some(buffer) = project.read_with(cx, |this, cx| {
6468 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6469 }) else {
6470 continue;
6471 };
6472 let breakpoints = breakpoint_store.read(cx).breakpoints(
6473 &buffer,
6474 Some(
6475 buffer_snapshot.anchor_before(range.start)
6476 ..buffer_snapshot.anchor_after(range.end),
6477 ),
6478 buffer_snapshot,
6479 cx,
6480 );
6481 for (anchor, breakpoint) in breakpoints {
6482 let multi_buffer_anchor =
6483 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6484 let position = multi_buffer_anchor
6485 .to_point(&multi_buffer_snapshot)
6486 .to_display_point(&snapshot);
6487
6488 breakpoint_display_points
6489 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6490 }
6491 }
6492
6493 breakpoint_display_points
6494 }
6495
6496 fn breakpoint_context_menu(
6497 &self,
6498 anchor: Anchor,
6499 window: &mut Window,
6500 cx: &mut Context<Self>,
6501 ) -> Entity<ui::ContextMenu> {
6502 let weak_editor = cx.weak_entity();
6503 let focus_handle = self.focus_handle(cx);
6504
6505 let row = self
6506 .buffer
6507 .read(cx)
6508 .snapshot(cx)
6509 .summary_for_anchor::<Point>(&anchor)
6510 .row;
6511
6512 let breakpoint = self
6513 .breakpoint_at_row(row, window, cx)
6514 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6515
6516 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6517 "Edit Log Breakpoint"
6518 } else {
6519 "Set Log Breakpoint"
6520 };
6521
6522 let condition_breakpoint_msg = if breakpoint
6523 .as_ref()
6524 .is_some_and(|bp| bp.1.condition.is_some())
6525 {
6526 "Edit Condition Breakpoint"
6527 } else {
6528 "Set Condition Breakpoint"
6529 };
6530
6531 let hit_condition_breakpoint_msg = if breakpoint
6532 .as_ref()
6533 .is_some_and(|bp| bp.1.hit_condition.is_some())
6534 {
6535 "Edit Hit Condition Breakpoint"
6536 } else {
6537 "Set Hit Condition Breakpoint"
6538 };
6539
6540 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6541 "Unset Breakpoint"
6542 } else {
6543 "Set Breakpoint"
6544 };
6545
6546 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6547 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6548
6549 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6550 BreakpointState::Enabled => Some("Disable"),
6551 BreakpointState::Disabled => Some("Enable"),
6552 });
6553
6554 let (anchor, breakpoint) =
6555 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6556
6557 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6558 menu.on_blur_subscription(Subscription::new(|| {}))
6559 .context(focus_handle)
6560 .when(run_to_cursor, |this| {
6561 let weak_editor = weak_editor.clone();
6562 this.entry("Run to cursor", None, move |window, cx| {
6563 weak_editor
6564 .update(cx, |editor, cx| {
6565 editor.change_selections(None, window, cx, |s| {
6566 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6567 });
6568 })
6569 .ok();
6570
6571 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6572 })
6573 .separator()
6574 })
6575 .when_some(toggle_state_msg, |this, msg| {
6576 this.entry(msg, None, {
6577 let weak_editor = weak_editor.clone();
6578 let breakpoint = breakpoint.clone();
6579 move |_window, cx| {
6580 weak_editor
6581 .update(cx, |this, cx| {
6582 this.edit_breakpoint_at_anchor(
6583 anchor,
6584 breakpoint.as_ref().clone(),
6585 BreakpointEditAction::InvertState,
6586 cx,
6587 );
6588 })
6589 .log_err();
6590 }
6591 })
6592 })
6593 .entry(set_breakpoint_msg, None, {
6594 let weak_editor = weak_editor.clone();
6595 let breakpoint = breakpoint.clone();
6596 move |_window, cx| {
6597 weak_editor
6598 .update(cx, |this, cx| {
6599 this.edit_breakpoint_at_anchor(
6600 anchor,
6601 breakpoint.as_ref().clone(),
6602 BreakpointEditAction::Toggle,
6603 cx,
6604 );
6605 })
6606 .log_err();
6607 }
6608 })
6609 .entry(log_breakpoint_msg, None, {
6610 let breakpoint = breakpoint.clone();
6611 let weak_editor = weak_editor.clone();
6612 move |window, cx| {
6613 weak_editor
6614 .update(cx, |this, cx| {
6615 this.add_edit_breakpoint_block(
6616 anchor,
6617 breakpoint.as_ref(),
6618 BreakpointPromptEditAction::Log,
6619 window,
6620 cx,
6621 );
6622 })
6623 .log_err();
6624 }
6625 })
6626 .entry(condition_breakpoint_msg, None, {
6627 let breakpoint = breakpoint.clone();
6628 let weak_editor = weak_editor.clone();
6629 move |window, cx| {
6630 weak_editor
6631 .update(cx, |this, cx| {
6632 this.add_edit_breakpoint_block(
6633 anchor,
6634 breakpoint.as_ref(),
6635 BreakpointPromptEditAction::Condition,
6636 window,
6637 cx,
6638 );
6639 })
6640 .log_err();
6641 }
6642 })
6643 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6644 weak_editor
6645 .update(cx, |this, cx| {
6646 this.add_edit_breakpoint_block(
6647 anchor,
6648 breakpoint.as_ref(),
6649 BreakpointPromptEditAction::HitCondition,
6650 window,
6651 cx,
6652 );
6653 })
6654 .log_err();
6655 })
6656 })
6657 }
6658
6659 fn render_breakpoint(
6660 &self,
6661 position: Anchor,
6662 row: DisplayRow,
6663 breakpoint: &Breakpoint,
6664 cx: &mut Context<Self>,
6665 ) -> IconButton {
6666 let (color, icon) = {
6667 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6668 (false, false) => ui::IconName::DebugBreakpoint,
6669 (true, false) => ui::IconName::DebugLogBreakpoint,
6670 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6671 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6672 };
6673
6674 let color = if self
6675 .gutter_breakpoint_indicator
6676 .0
6677 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6678 {
6679 Color::Hint
6680 } else {
6681 Color::Debugger
6682 };
6683
6684 (color, icon)
6685 };
6686
6687 let breakpoint = Arc::from(breakpoint.clone());
6688
6689 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6690 .icon_size(IconSize::XSmall)
6691 .size(ui::ButtonSize::None)
6692 .icon_color(color)
6693 .style(ButtonStyle::Transparent)
6694 .on_click(cx.listener({
6695 let breakpoint = breakpoint.clone();
6696
6697 move |editor, event: &ClickEvent, window, cx| {
6698 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6699 BreakpointEditAction::InvertState
6700 } else {
6701 BreakpointEditAction::Toggle
6702 };
6703
6704 window.focus(&editor.focus_handle(cx));
6705 editor.edit_breakpoint_at_anchor(
6706 position,
6707 breakpoint.as_ref().clone(),
6708 edit_action,
6709 cx,
6710 );
6711 }
6712 }))
6713 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6714 editor.set_breakpoint_context_menu(
6715 row,
6716 Some(position),
6717 event.down.position,
6718 window,
6719 cx,
6720 );
6721 }))
6722 }
6723
6724 fn build_tasks_context(
6725 project: &Entity<Project>,
6726 buffer: &Entity<Buffer>,
6727 buffer_row: u32,
6728 tasks: &Arc<RunnableTasks>,
6729 cx: &mut Context<Self>,
6730 ) -> Task<Option<task::TaskContext>> {
6731 let position = Point::new(buffer_row, tasks.column);
6732 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6733 let location = Location {
6734 buffer: buffer.clone(),
6735 range: range_start..range_start,
6736 };
6737 // Fill in the environmental variables from the tree-sitter captures
6738 let mut captured_task_variables = TaskVariables::default();
6739 for (capture_name, value) in tasks.extra_variables.clone() {
6740 captured_task_variables.insert(
6741 task::VariableName::Custom(capture_name.into()),
6742 value.clone(),
6743 );
6744 }
6745 project.update(cx, |project, cx| {
6746 project.task_store().update(cx, |task_store, cx| {
6747 task_store.task_context_for_location(captured_task_variables, location, cx)
6748 })
6749 })
6750 }
6751
6752 pub fn spawn_nearest_task(
6753 &mut self,
6754 action: &SpawnNearestTask,
6755 window: &mut Window,
6756 cx: &mut Context<Self>,
6757 ) {
6758 let Some((workspace, _)) = self.workspace.clone() else {
6759 return;
6760 };
6761 let Some(project) = self.project.clone() else {
6762 return;
6763 };
6764
6765 // Try to find a closest, enclosing node using tree-sitter that has a
6766 // task
6767 let Some((buffer, buffer_row, tasks)) = self
6768 .find_enclosing_node_task(cx)
6769 // Or find the task that's closest in row-distance.
6770 .or_else(|| self.find_closest_task(cx))
6771 else {
6772 return;
6773 };
6774
6775 let reveal_strategy = action.reveal;
6776 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6777 cx.spawn_in(window, async move |_, cx| {
6778 let context = task_context.await?;
6779 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6780
6781 let resolved = resolved_task.resolved.as_mut()?;
6782 resolved.reveal = reveal_strategy;
6783
6784 workspace
6785 .update(cx, |workspace, cx| {
6786 workspace::tasks::schedule_resolved_task(
6787 workspace,
6788 task_source_kind,
6789 resolved_task,
6790 false,
6791 cx,
6792 );
6793 })
6794 .ok()
6795 })
6796 .detach();
6797 }
6798
6799 fn find_closest_task(
6800 &mut self,
6801 cx: &mut Context<Self>,
6802 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6803 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6804
6805 let ((buffer_id, row), tasks) = self
6806 .tasks
6807 .iter()
6808 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6809
6810 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6811 let tasks = Arc::new(tasks.to_owned());
6812 Some((buffer, *row, tasks))
6813 }
6814
6815 fn find_enclosing_node_task(
6816 &mut self,
6817 cx: &mut Context<Self>,
6818 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6819 let snapshot = self.buffer.read(cx).snapshot(cx);
6820 let offset = self.selections.newest::<usize>(cx).head();
6821 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6822 let buffer_id = excerpt.buffer().remote_id();
6823
6824 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6825 let mut cursor = layer.node().walk();
6826
6827 while cursor.goto_first_child_for_byte(offset).is_some() {
6828 if cursor.node().end_byte() == offset {
6829 cursor.goto_next_sibling();
6830 }
6831 }
6832
6833 // Ascend to the smallest ancestor that contains the range and has a task.
6834 loop {
6835 let node = cursor.node();
6836 let node_range = node.byte_range();
6837 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6838
6839 // Check if this node contains our offset
6840 if node_range.start <= offset && node_range.end >= offset {
6841 // If it contains offset, check for task
6842 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6843 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6844 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6845 }
6846 }
6847
6848 if !cursor.goto_parent() {
6849 break;
6850 }
6851 }
6852 None
6853 }
6854
6855 fn render_run_indicator(
6856 &self,
6857 _style: &EditorStyle,
6858 is_active: bool,
6859 row: DisplayRow,
6860 breakpoint: Option<(Anchor, Breakpoint)>,
6861 cx: &mut Context<Self>,
6862 ) -> IconButton {
6863 let color = Color::Muted;
6864 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6865
6866 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6867 .shape(ui::IconButtonShape::Square)
6868 .icon_size(IconSize::XSmall)
6869 .icon_color(color)
6870 .toggle_state(is_active)
6871 .on_click(cx.listener(move |editor, _e, window, cx| {
6872 window.focus(&editor.focus_handle(cx));
6873 editor.toggle_code_actions(
6874 &ToggleCodeActions {
6875 deployed_from_indicator: Some(row),
6876 },
6877 window,
6878 cx,
6879 );
6880 }))
6881 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6882 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6883 }))
6884 }
6885
6886 pub fn context_menu_visible(&self) -> bool {
6887 !self.edit_prediction_preview_is_active()
6888 && self
6889 .context_menu
6890 .borrow()
6891 .as_ref()
6892 .map_or(false, |menu| menu.visible())
6893 }
6894
6895 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6896 self.context_menu
6897 .borrow()
6898 .as_ref()
6899 .map(|menu| menu.origin())
6900 }
6901
6902 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6903 self.context_menu_options = Some(options);
6904 }
6905
6906 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6907 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6908
6909 fn render_edit_prediction_popover(
6910 &mut self,
6911 text_bounds: &Bounds<Pixels>,
6912 content_origin: gpui::Point<Pixels>,
6913 editor_snapshot: &EditorSnapshot,
6914 visible_row_range: Range<DisplayRow>,
6915 scroll_top: f32,
6916 scroll_bottom: f32,
6917 line_layouts: &[LineWithInvisibles],
6918 line_height: Pixels,
6919 scroll_pixel_position: gpui::Point<Pixels>,
6920 newest_selection_head: Option<DisplayPoint>,
6921 editor_width: Pixels,
6922 style: &EditorStyle,
6923 window: &mut Window,
6924 cx: &mut App,
6925 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6926 let active_inline_completion = self.active_inline_completion.as_ref()?;
6927
6928 if self.edit_prediction_visible_in_cursor_popover(true) {
6929 return None;
6930 }
6931
6932 match &active_inline_completion.completion {
6933 InlineCompletion::Move { target, .. } => {
6934 let target_display_point = target.to_display_point(editor_snapshot);
6935
6936 if self.edit_prediction_requires_modifier() {
6937 if !self.edit_prediction_preview_is_active() {
6938 return None;
6939 }
6940
6941 self.render_edit_prediction_modifier_jump_popover(
6942 text_bounds,
6943 content_origin,
6944 visible_row_range,
6945 line_layouts,
6946 line_height,
6947 scroll_pixel_position,
6948 newest_selection_head,
6949 target_display_point,
6950 window,
6951 cx,
6952 )
6953 } else {
6954 self.render_edit_prediction_eager_jump_popover(
6955 text_bounds,
6956 content_origin,
6957 editor_snapshot,
6958 visible_row_range,
6959 scroll_top,
6960 scroll_bottom,
6961 line_height,
6962 scroll_pixel_position,
6963 target_display_point,
6964 editor_width,
6965 window,
6966 cx,
6967 )
6968 }
6969 }
6970 InlineCompletion::Edit {
6971 display_mode: EditDisplayMode::Inline,
6972 ..
6973 } => None,
6974 InlineCompletion::Edit {
6975 display_mode: EditDisplayMode::TabAccept,
6976 edits,
6977 ..
6978 } => {
6979 let range = &edits.first()?.0;
6980 let target_display_point = range.end.to_display_point(editor_snapshot);
6981
6982 self.render_edit_prediction_end_of_line_popover(
6983 "Accept",
6984 editor_snapshot,
6985 visible_row_range,
6986 target_display_point,
6987 line_height,
6988 scroll_pixel_position,
6989 content_origin,
6990 editor_width,
6991 window,
6992 cx,
6993 )
6994 }
6995 InlineCompletion::Edit {
6996 edits,
6997 edit_preview,
6998 display_mode: EditDisplayMode::DiffPopover,
6999 snapshot,
7000 } => self.render_edit_prediction_diff_popover(
7001 text_bounds,
7002 content_origin,
7003 editor_snapshot,
7004 visible_row_range,
7005 line_layouts,
7006 line_height,
7007 scroll_pixel_position,
7008 newest_selection_head,
7009 editor_width,
7010 style,
7011 edits,
7012 edit_preview,
7013 snapshot,
7014 window,
7015 cx,
7016 ),
7017 }
7018 }
7019
7020 fn render_edit_prediction_modifier_jump_popover(
7021 &mut self,
7022 text_bounds: &Bounds<Pixels>,
7023 content_origin: gpui::Point<Pixels>,
7024 visible_row_range: Range<DisplayRow>,
7025 line_layouts: &[LineWithInvisibles],
7026 line_height: Pixels,
7027 scroll_pixel_position: gpui::Point<Pixels>,
7028 newest_selection_head: Option<DisplayPoint>,
7029 target_display_point: DisplayPoint,
7030 window: &mut Window,
7031 cx: &mut App,
7032 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7033 let scrolled_content_origin =
7034 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7035
7036 const SCROLL_PADDING_Y: Pixels = px(12.);
7037
7038 if target_display_point.row() < visible_row_range.start {
7039 return self.render_edit_prediction_scroll_popover(
7040 |_| SCROLL_PADDING_Y,
7041 IconName::ArrowUp,
7042 visible_row_range,
7043 line_layouts,
7044 newest_selection_head,
7045 scrolled_content_origin,
7046 window,
7047 cx,
7048 );
7049 } else if target_display_point.row() >= visible_row_range.end {
7050 return self.render_edit_prediction_scroll_popover(
7051 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7052 IconName::ArrowDown,
7053 visible_row_range,
7054 line_layouts,
7055 newest_selection_head,
7056 scrolled_content_origin,
7057 window,
7058 cx,
7059 );
7060 }
7061
7062 const POLE_WIDTH: Pixels = px(2.);
7063
7064 let line_layout =
7065 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7066 let target_column = target_display_point.column() as usize;
7067
7068 let target_x = line_layout.x_for_index(target_column);
7069 let target_y =
7070 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7071
7072 let flag_on_right = target_x < text_bounds.size.width / 2.;
7073
7074 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7075 border_color.l += 0.001;
7076
7077 let mut element = v_flex()
7078 .items_end()
7079 .when(flag_on_right, |el| el.items_start())
7080 .child(if flag_on_right {
7081 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7082 .rounded_bl(px(0.))
7083 .rounded_tl(px(0.))
7084 .border_l_2()
7085 .border_color(border_color)
7086 } else {
7087 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7088 .rounded_br(px(0.))
7089 .rounded_tr(px(0.))
7090 .border_r_2()
7091 .border_color(border_color)
7092 })
7093 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7094 .into_any();
7095
7096 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7097
7098 let mut origin = scrolled_content_origin + point(target_x, target_y)
7099 - point(
7100 if flag_on_right {
7101 POLE_WIDTH
7102 } else {
7103 size.width - POLE_WIDTH
7104 },
7105 size.height - line_height,
7106 );
7107
7108 origin.x = origin.x.max(content_origin.x);
7109
7110 element.prepaint_at(origin, window, cx);
7111
7112 Some((element, origin))
7113 }
7114
7115 fn render_edit_prediction_scroll_popover(
7116 &mut self,
7117 to_y: impl Fn(Size<Pixels>) -> Pixels,
7118 scroll_icon: IconName,
7119 visible_row_range: Range<DisplayRow>,
7120 line_layouts: &[LineWithInvisibles],
7121 newest_selection_head: Option<DisplayPoint>,
7122 scrolled_content_origin: gpui::Point<Pixels>,
7123 window: &mut Window,
7124 cx: &mut App,
7125 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7126 let mut element = self
7127 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7128 .into_any();
7129
7130 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7131
7132 let cursor = newest_selection_head?;
7133 let cursor_row_layout =
7134 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7135 let cursor_column = cursor.column() as usize;
7136
7137 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7138
7139 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7140
7141 element.prepaint_at(origin, window, cx);
7142 Some((element, origin))
7143 }
7144
7145 fn render_edit_prediction_eager_jump_popover(
7146 &mut self,
7147 text_bounds: &Bounds<Pixels>,
7148 content_origin: gpui::Point<Pixels>,
7149 editor_snapshot: &EditorSnapshot,
7150 visible_row_range: Range<DisplayRow>,
7151 scroll_top: f32,
7152 scroll_bottom: f32,
7153 line_height: Pixels,
7154 scroll_pixel_position: gpui::Point<Pixels>,
7155 target_display_point: DisplayPoint,
7156 editor_width: Pixels,
7157 window: &mut Window,
7158 cx: &mut App,
7159 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7160 if target_display_point.row().as_f32() < scroll_top {
7161 let mut element = self
7162 .render_edit_prediction_line_popover(
7163 "Jump to Edit",
7164 Some(IconName::ArrowUp),
7165 window,
7166 cx,
7167 )?
7168 .into_any();
7169
7170 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7171 let offset = point(
7172 (text_bounds.size.width - size.width) / 2.,
7173 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7174 );
7175
7176 let origin = text_bounds.origin + offset;
7177 element.prepaint_at(origin, window, cx);
7178 Some((element, origin))
7179 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7180 let mut element = self
7181 .render_edit_prediction_line_popover(
7182 "Jump to Edit",
7183 Some(IconName::ArrowDown),
7184 window,
7185 cx,
7186 )?
7187 .into_any();
7188
7189 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7190 let offset = point(
7191 (text_bounds.size.width - size.width) / 2.,
7192 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7193 );
7194
7195 let origin = text_bounds.origin + offset;
7196 element.prepaint_at(origin, window, cx);
7197 Some((element, origin))
7198 } else {
7199 self.render_edit_prediction_end_of_line_popover(
7200 "Jump to Edit",
7201 editor_snapshot,
7202 visible_row_range,
7203 target_display_point,
7204 line_height,
7205 scroll_pixel_position,
7206 content_origin,
7207 editor_width,
7208 window,
7209 cx,
7210 )
7211 }
7212 }
7213
7214 fn render_edit_prediction_end_of_line_popover(
7215 self: &mut Editor,
7216 label: &'static str,
7217 editor_snapshot: &EditorSnapshot,
7218 visible_row_range: Range<DisplayRow>,
7219 target_display_point: DisplayPoint,
7220 line_height: Pixels,
7221 scroll_pixel_position: gpui::Point<Pixels>,
7222 content_origin: gpui::Point<Pixels>,
7223 editor_width: Pixels,
7224 window: &mut Window,
7225 cx: &mut App,
7226 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7227 let target_line_end = DisplayPoint::new(
7228 target_display_point.row(),
7229 editor_snapshot.line_len(target_display_point.row()),
7230 );
7231
7232 let mut element = self
7233 .render_edit_prediction_line_popover(label, None, window, cx)?
7234 .into_any();
7235
7236 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7237
7238 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7239
7240 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7241 let mut origin = start_point
7242 + line_origin
7243 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7244 origin.x = origin.x.max(content_origin.x);
7245
7246 let max_x = content_origin.x + editor_width - size.width;
7247
7248 if origin.x > max_x {
7249 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7250
7251 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7252 origin.y += offset;
7253 IconName::ArrowUp
7254 } else {
7255 origin.y -= offset;
7256 IconName::ArrowDown
7257 };
7258
7259 element = self
7260 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7261 .into_any();
7262
7263 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7264
7265 origin.x = content_origin.x + editor_width - size.width - px(2.);
7266 }
7267
7268 element.prepaint_at(origin, window, cx);
7269 Some((element, origin))
7270 }
7271
7272 fn render_edit_prediction_diff_popover(
7273 self: &Editor,
7274 text_bounds: &Bounds<Pixels>,
7275 content_origin: gpui::Point<Pixels>,
7276 editor_snapshot: &EditorSnapshot,
7277 visible_row_range: Range<DisplayRow>,
7278 line_layouts: &[LineWithInvisibles],
7279 line_height: Pixels,
7280 scroll_pixel_position: gpui::Point<Pixels>,
7281 newest_selection_head: Option<DisplayPoint>,
7282 editor_width: Pixels,
7283 style: &EditorStyle,
7284 edits: &Vec<(Range<Anchor>, String)>,
7285 edit_preview: &Option<language::EditPreview>,
7286 snapshot: &language::BufferSnapshot,
7287 window: &mut Window,
7288 cx: &mut App,
7289 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7290 let edit_start = edits
7291 .first()
7292 .unwrap()
7293 .0
7294 .start
7295 .to_display_point(editor_snapshot);
7296 let edit_end = edits
7297 .last()
7298 .unwrap()
7299 .0
7300 .end
7301 .to_display_point(editor_snapshot);
7302
7303 let is_visible = visible_row_range.contains(&edit_start.row())
7304 || visible_row_range.contains(&edit_end.row());
7305 if !is_visible {
7306 return None;
7307 }
7308
7309 let highlighted_edits =
7310 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7311
7312 let styled_text = highlighted_edits.to_styled_text(&style.text);
7313 let line_count = highlighted_edits.text.lines().count();
7314
7315 const BORDER_WIDTH: Pixels = px(1.);
7316
7317 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7318 let has_keybind = keybind.is_some();
7319
7320 let mut element = h_flex()
7321 .items_start()
7322 .child(
7323 h_flex()
7324 .bg(cx.theme().colors().editor_background)
7325 .border(BORDER_WIDTH)
7326 .shadow_sm()
7327 .border_color(cx.theme().colors().border)
7328 .rounded_l_lg()
7329 .when(line_count > 1, |el| el.rounded_br_lg())
7330 .pr_1()
7331 .child(styled_text),
7332 )
7333 .child(
7334 h_flex()
7335 .h(line_height + BORDER_WIDTH * 2.)
7336 .px_1p5()
7337 .gap_1()
7338 // Workaround: For some reason, there's a gap if we don't do this
7339 .ml(-BORDER_WIDTH)
7340 .shadow(smallvec![gpui::BoxShadow {
7341 color: gpui::black().opacity(0.05),
7342 offset: point(px(1.), px(1.)),
7343 blur_radius: px(2.),
7344 spread_radius: px(0.),
7345 }])
7346 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7347 .border(BORDER_WIDTH)
7348 .border_color(cx.theme().colors().border)
7349 .rounded_r_lg()
7350 .id("edit_prediction_diff_popover_keybind")
7351 .when(!has_keybind, |el| {
7352 let status_colors = cx.theme().status();
7353
7354 el.bg(status_colors.error_background)
7355 .border_color(status_colors.error.opacity(0.6))
7356 .child(Icon::new(IconName::Info).color(Color::Error))
7357 .cursor_default()
7358 .hoverable_tooltip(move |_window, cx| {
7359 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7360 })
7361 })
7362 .children(keybind),
7363 )
7364 .into_any();
7365
7366 let longest_row =
7367 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7368 let longest_line_width = if visible_row_range.contains(&longest_row) {
7369 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7370 } else {
7371 layout_line(
7372 longest_row,
7373 editor_snapshot,
7374 style,
7375 editor_width,
7376 |_| false,
7377 window,
7378 cx,
7379 )
7380 .width
7381 };
7382
7383 let viewport_bounds =
7384 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7385 right: -EditorElement::SCROLLBAR_WIDTH,
7386 ..Default::default()
7387 });
7388
7389 let x_after_longest =
7390 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7391 - scroll_pixel_position.x;
7392
7393 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7394
7395 // Fully visible if it can be displayed within the window (allow overlapping other
7396 // panes). However, this is only allowed if the popover starts within text_bounds.
7397 let can_position_to_the_right = x_after_longest < text_bounds.right()
7398 && x_after_longest + element_bounds.width < viewport_bounds.right();
7399
7400 let mut origin = if can_position_to_the_right {
7401 point(
7402 x_after_longest,
7403 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7404 - scroll_pixel_position.y,
7405 )
7406 } else {
7407 let cursor_row = newest_selection_head.map(|head| head.row());
7408 let above_edit = edit_start
7409 .row()
7410 .0
7411 .checked_sub(line_count as u32)
7412 .map(DisplayRow);
7413 let below_edit = Some(edit_end.row() + 1);
7414 let above_cursor =
7415 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7416 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7417
7418 // Place the edit popover adjacent to the edit if there is a location
7419 // available that is onscreen and does not obscure the cursor. Otherwise,
7420 // place it adjacent to the cursor.
7421 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7422 .into_iter()
7423 .flatten()
7424 .find(|&start_row| {
7425 let end_row = start_row + line_count as u32;
7426 visible_row_range.contains(&start_row)
7427 && visible_row_range.contains(&end_row)
7428 && cursor_row.map_or(true, |cursor_row| {
7429 !((start_row..end_row).contains(&cursor_row))
7430 })
7431 })?;
7432
7433 content_origin
7434 + point(
7435 -scroll_pixel_position.x,
7436 row_target.as_f32() * line_height - scroll_pixel_position.y,
7437 )
7438 };
7439
7440 origin.x -= BORDER_WIDTH;
7441
7442 window.defer_draw(element, origin, 1);
7443
7444 // Do not return an element, since it will already be drawn due to defer_draw.
7445 None
7446 }
7447
7448 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7449 px(30.)
7450 }
7451
7452 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7453 if self.read_only(cx) {
7454 cx.theme().players().read_only()
7455 } else {
7456 self.style.as_ref().unwrap().local_player
7457 }
7458 }
7459
7460 fn render_edit_prediction_accept_keybind(
7461 &self,
7462 window: &mut Window,
7463 cx: &App,
7464 ) -> Option<AnyElement> {
7465 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7466 let accept_keystroke = accept_binding.keystroke()?;
7467
7468 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7469
7470 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7471 Color::Accent
7472 } else {
7473 Color::Muted
7474 };
7475
7476 h_flex()
7477 .px_0p5()
7478 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7479 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7480 .text_size(TextSize::XSmall.rems(cx))
7481 .child(h_flex().children(ui::render_modifiers(
7482 &accept_keystroke.modifiers,
7483 PlatformStyle::platform(),
7484 Some(modifiers_color),
7485 Some(IconSize::XSmall.rems().into()),
7486 true,
7487 )))
7488 .when(is_platform_style_mac, |parent| {
7489 parent.child(accept_keystroke.key.clone())
7490 })
7491 .when(!is_platform_style_mac, |parent| {
7492 parent.child(
7493 Key::new(
7494 util::capitalize(&accept_keystroke.key),
7495 Some(Color::Default),
7496 )
7497 .size(Some(IconSize::XSmall.rems().into())),
7498 )
7499 })
7500 .into_any()
7501 .into()
7502 }
7503
7504 fn render_edit_prediction_line_popover(
7505 &self,
7506 label: impl Into<SharedString>,
7507 icon: Option<IconName>,
7508 window: &mut Window,
7509 cx: &App,
7510 ) -> Option<Stateful<Div>> {
7511 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7512
7513 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7514 let has_keybind = keybind.is_some();
7515
7516 let result = h_flex()
7517 .id("ep-line-popover")
7518 .py_0p5()
7519 .pl_1()
7520 .pr(padding_right)
7521 .gap_1()
7522 .rounded_md()
7523 .border_1()
7524 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7525 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7526 .shadow_sm()
7527 .when(!has_keybind, |el| {
7528 let status_colors = cx.theme().status();
7529
7530 el.bg(status_colors.error_background)
7531 .border_color(status_colors.error.opacity(0.6))
7532 .pl_2()
7533 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7534 .cursor_default()
7535 .hoverable_tooltip(move |_window, cx| {
7536 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7537 })
7538 })
7539 .children(keybind)
7540 .child(
7541 Label::new(label)
7542 .size(LabelSize::Small)
7543 .when(!has_keybind, |el| {
7544 el.color(cx.theme().status().error.into()).strikethrough()
7545 }),
7546 )
7547 .when(!has_keybind, |el| {
7548 el.child(
7549 h_flex().ml_1().child(
7550 Icon::new(IconName::Info)
7551 .size(IconSize::Small)
7552 .color(cx.theme().status().error.into()),
7553 ),
7554 )
7555 })
7556 .when_some(icon, |element, icon| {
7557 element.child(
7558 div()
7559 .mt(px(1.5))
7560 .child(Icon::new(icon).size(IconSize::Small)),
7561 )
7562 });
7563
7564 Some(result)
7565 }
7566
7567 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7568 let accent_color = cx.theme().colors().text_accent;
7569 let editor_bg_color = cx.theme().colors().editor_background;
7570 editor_bg_color.blend(accent_color.opacity(0.1))
7571 }
7572
7573 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7574 let accent_color = cx.theme().colors().text_accent;
7575 let editor_bg_color = cx.theme().colors().editor_background;
7576 editor_bg_color.blend(accent_color.opacity(0.6))
7577 }
7578
7579 fn render_edit_prediction_cursor_popover(
7580 &self,
7581 min_width: Pixels,
7582 max_width: Pixels,
7583 cursor_point: Point,
7584 style: &EditorStyle,
7585 accept_keystroke: Option<&gpui::Keystroke>,
7586 _window: &Window,
7587 cx: &mut Context<Editor>,
7588 ) -> Option<AnyElement> {
7589 let provider = self.edit_prediction_provider.as_ref()?;
7590
7591 if provider.provider.needs_terms_acceptance(cx) {
7592 return Some(
7593 h_flex()
7594 .min_w(min_width)
7595 .flex_1()
7596 .px_2()
7597 .py_1()
7598 .gap_3()
7599 .elevation_2(cx)
7600 .hover(|style| style.bg(cx.theme().colors().element_hover))
7601 .id("accept-terms")
7602 .cursor_pointer()
7603 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7604 .on_click(cx.listener(|this, _event, window, cx| {
7605 cx.stop_propagation();
7606 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7607 window.dispatch_action(
7608 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7609 cx,
7610 );
7611 }))
7612 .child(
7613 h_flex()
7614 .flex_1()
7615 .gap_2()
7616 .child(Icon::new(IconName::ZedPredict))
7617 .child(Label::new("Accept Terms of Service"))
7618 .child(div().w_full())
7619 .child(
7620 Icon::new(IconName::ArrowUpRight)
7621 .color(Color::Muted)
7622 .size(IconSize::Small),
7623 )
7624 .into_any_element(),
7625 )
7626 .into_any(),
7627 );
7628 }
7629
7630 let is_refreshing = provider.provider.is_refreshing(cx);
7631
7632 fn pending_completion_container() -> Div {
7633 h_flex()
7634 .h_full()
7635 .flex_1()
7636 .gap_2()
7637 .child(Icon::new(IconName::ZedPredict))
7638 }
7639
7640 let completion = match &self.active_inline_completion {
7641 Some(prediction) => {
7642 if !self.has_visible_completions_menu() {
7643 const RADIUS: Pixels = px(6.);
7644 const BORDER_WIDTH: Pixels = px(1.);
7645
7646 return Some(
7647 h_flex()
7648 .elevation_2(cx)
7649 .border(BORDER_WIDTH)
7650 .border_color(cx.theme().colors().border)
7651 .when(accept_keystroke.is_none(), |el| {
7652 el.border_color(cx.theme().status().error)
7653 })
7654 .rounded(RADIUS)
7655 .rounded_tl(px(0.))
7656 .overflow_hidden()
7657 .child(div().px_1p5().child(match &prediction.completion {
7658 InlineCompletion::Move { target, snapshot } => {
7659 use text::ToPoint as _;
7660 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7661 {
7662 Icon::new(IconName::ZedPredictDown)
7663 } else {
7664 Icon::new(IconName::ZedPredictUp)
7665 }
7666 }
7667 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7668 }))
7669 .child(
7670 h_flex()
7671 .gap_1()
7672 .py_1()
7673 .px_2()
7674 .rounded_r(RADIUS - BORDER_WIDTH)
7675 .border_l_1()
7676 .border_color(cx.theme().colors().border)
7677 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7678 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7679 el.child(
7680 Label::new("Hold")
7681 .size(LabelSize::Small)
7682 .when(accept_keystroke.is_none(), |el| {
7683 el.strikethrough()
7684 })
7685 .line_height_style(LineHeightStyle::UiLabel),
7686 )
7687 })
7688 .id("edit_prediction_cursor_popover_keybind")
7689 .when(accept_keystroke.is_none(), |el| {
7690 let status_colors = cx.theme().status();
7691
7692 el.bg(status_colors.error_background)
7693 .border_color(status_colors.error.opacity(0.6))
7694 .child(Icon::new(IconName::Info).color(Color::Error))
7695 .cursor_default()
7696 .hoverable_tooltip(move |_window, cx| {
7697 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7698 .into()
7699 })
7700 })
7701 .when_some(
7702 accept_keystroke.as_ref(),
7703 |el, accept_keystroke| {
7704 el.child(h_flex().children(ui::render_modifiers(
7705 &accept_keystroke.modifiers,
7706 PlatformStyle::platform(),
7707 Some(Color::Default),
7708 Some(IconSize::XSmall.rems().into()),
7709 false,
7710 )))
7711 },
7712 ),
7713 )
7714 .into_any(),
7715 );
7716 }
7717
7718 self.render_edit_prediction_cursor_popover_preview(
7719 prediction,
7720 cursor_point,
7721 style,
7722 cx,
7723 )?
7724 }
7725
7726 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7727 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7728 stale_completion,
7729 cursor_point,
7730 style,
7731 cx,
7732 )?,
7733
7734 None => {
7735 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7736 }
7737 },
7738
7739 None => pending_completion_container().child(Label::new("No Prediction")),
7740 };
7741
7742 let completion = if is_refreshing {
7743 completion
7744 .with_animation(
7745 "loading-completion",
7746 Animation::new(Duration::from_secs(2))
7747 .repeat()
7748 .with_easing(pulsating_between(0.4, 0.8)),
7749 |label, delta| label.opacity(delta),
7750 )
7751 .into_any_element()
7752 } else {
7753 completion.into_any_element()
7754 };
7755
7756 let has_completion = self.active_inline_completion.is_some();
7757
7758 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7759 Some(
7760 h_flex()
7761 .min_w(min_width)
7762 .max_w(max_width)
7763 .flex_1()
7764 .elevation_2(cx)
7765 .border_color(cx.theme().colors().border)
7766 .child(
7767 div()
7768 .flex_1()
7769 .py_1()
7770 .px_2()
7771 .overflow_hidden()
7772 .child(completion),
7773 )
7774 .when_some(accept_keystroke, |el, accept_keystroke| {
7775 if !accept_keystroke.modifiers.modified() {
7776 return el;
7777 }
7778
7779 el.child(
7780 h_flex()
7781 .h_full()
7782 .border_l_1()
7783 .rounded_r_lg()
7784 .border_color(cx.theme().colors().border)
7785 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7786 .gap_1()
7787 .py_1()
7788 .px_2()
7789 .child(
7790 h_flex()
7791 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7792 .when(is_platform_style_mac, |parent| parent.gap_1())
7793 .child(h_flex().children(ui::render_modifiers(
7794 &accept_keystroke.modifiers,
7795 PlatformStyle::platform(),
7796 Some(if !has_completion {
7797 Color::Muted
7798 } else {
7799 Color::Default
7800 }),
7801 None,
7802 false,
7803 ))),
7804 )
7805 .child(Label::new("Preview").into_any_element())
7806 .opacity(if has_completion { 1.0 } else { 0.4 }),
7807 )
7808 })
7809 .into_any(),
7810 )
7811 }
7812
7813 fn render_edit_prediction_cursor_popover_preview(
7814 &self,
7815 completion: &InlineCompletionState,
7816 cursor_point: Point,
7817 style: &EditorStyle,
7818 cx: &mut Context<Editor>,
7819 ) -> Option<Div> {
7820 use text::ToPoint as _;
7821
7822 fn render_relative_row_jump(
7823 prefix: impl Into<String>,
7824 current_row: u32,
7825 target_row: u32,
7826 ) -> Div {
7827 let (row_diff, arrow) = if target_row < current_row {
7828 (current_row - target_row, IconName::ArrowUp)
7829 } else {
7830 (target_row - current_row, IconName::ArrowDown)
7831 };
7832
7833 h_flex()
7834 .child(
7835 Label::new(format!("{}{}", prefix.into(), row_diff))
7836 .color(Color::Muted)
7837 .size(LabelSize::Small),
7838 )
7839 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7840 }
7841
7842 match &completion.completion {
7843 InlineCompletion::Move {
7844 target, snapshot, ..
7845 } => Some(
7846 h_flex()
7847 .px_2()
7848 .gap_2()
7849 .flex_1()
7850 .child(
7851 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7852 Icon::new(IconName::ZedPredictDown)
7853 } else {
7854 Icon::new(IconName::ZedPredictUp)
7855 },
7856 )
7857 .child(Label::new("Jump to Edit")),
7858 ),
7859
7860 InlineCompletion::Edit {
7861 edits,
7862 edit_preview,
7863 snapshot,
7864 display_mode: _,
7865 } => {
7866 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7867
7868 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7869 &snapshot,
7870 &edits,
7871 edit_preview.as_ref()?,
7872 true,
7873 cx,
7874 )
7875 .first_line_preview();
7876
7877 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7878 .with_default_highlights(&style.text, highlighted_edits.highlights);
7879
7880 let preview = h_flex()
7881 .gap_1()
7882 .min_w_16()
7883 .child(styled_text)
7884 .when(has_more_lines, |parent| parent.child("…"));
7885
7886 let left = if first_edit_row != cursor_point.row {
7887 render_relative_row_jump("", cursor_point.row, first_edit_row)
7888 .into_any_element()
7889 } else {
7890 Icon::new(IconName::ZedPredict).into_any_element()
7891 };
7892
7893 Some(
7894 h_flex()
7895 .h_full()
7896 .flex_1()
7897 .gap_2()
7898 .pr_1()
7899 .overflow_x_hidden()
7900 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7901 .child(left)
7902 .child(preview),
7903 )
7904 }
7905 }
7906 }
7907
7908 fn render_context_menu(
7909 &self,
7910 style: &EditorStyle,
7911 max_height_in_lines: u32,
7912 window: &mut Window,
7913 cx: &mut Context<Editor>,
7914 ) -> Option<AnyElement> {
7915 let menu = self.context_menu.borrow();
7916 let menu = menu.as_ref()?;
7917 if !menu.visible() {
7918 return None;
7919 };
7920 Some(menu.render(style, max_height_in_lines, window, cx))
7921 }
7922
7923 fn render_context_menu_aside(
7924 &mut self,
7925 max_size: Size<Pixels>,
7926 window: &mut Window,
7927 cx: &mut Context<Editor>,
7928 ) -> Option<AnyElement> {
7929 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7930 if menu.visible() {
7931 menu.render_aside(self, max_size, window, cx)
7932 } else {
7933 None
7934 }
7935 })
7936 }
7937
7938 fn hide_context_menu(
7939 &mut self,
7940 window: &mut Window,
7941 cx: &mut Context<Self>,
7942 ) -> Option<CodeContextMenu> {
7943 cx.notify();
7944 self.completion_tasks.clear();
7945 let context_menu = self.context_menu.borrow_mut().take();
7946 self.stale_inline_completion_in_menu.take();
7947 self.update_visible_inline_completion(window, cx);
7948 context_menu
7949 }
7950
7951 fn show_snippet_choices(
7952 &mut self,
7953 choices: &Vec<String>,
7954 selection: Range<Anchor>,
7955 cx: &mut Context<Self>,
7956 ) {
7957 if selection.start.buffer_id.is_none() {
7958 return;
7959 }
7960 let buffer_id = selection.start.buffer_id.unwrap();
7961 let buffer = self.buffer().read(cx).buffer(buffer_id);
7962 let id = post_inc(&mut self.next_completion_id);
7963
7964 if let Some(buffer) = buffer {
7965 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7966 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7967 ));
7968 }
7969 }
7970
7971 pub fn insert_snippet(
7972 &mut self,
7973 insertion_ranges: &[Range<usize>],
7974 snippet: Snippet,
7975 window: &mut Window,
7976 cx: &mut Context<Self>,
7977 ) -> Result<()> {
7978 struct Tabstop<T> {
7979 is_end_tabstop: bool,
7980 ranges: Vec<Range<T>>,
7981 choices: Option<Vec<String>>,
7982 }
7983
7984 let tabstops = self.buffer.update(cx, |buffer, cx| {
7985 let snippet_text: Arc<str> = snippet.text.clone().into();
7986 let edits = insertion_ranges
7987 .iter()
7988 .cloned()
7989 .map(|range| (range, snippet_text.clone()));
7990 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7991
7992 let snapshot = &*buffer.read(cx);
7993 let snippet = &snippet;
7994 snippet
7995 .tabstops
7996 .iter()
7997 .map(|tabstop| {
7998 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7999 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8000 });
8001 let mut tabstop_ranges = tabstop
8002 .ranges
8003 .iter()
8004 .flat_map(|tabstop_range| {
8005 let mut delta = 0_isize;
8006 insertion_ranges.iter().map(move |insertion_range| {
8007 let insertion_start = insertion_range.start as isize + delta;
8008 delta +=
8009 snippet.text.len() as isize - insertion_range.len() as isize;
8010
8011 let start = ((insertion_start + tabstop_range.start) as usize)
8012 .min(snapshot.len());
8013 let end = ((insertion_start + tabstop_range.end) as usize)
8014 .min(snapshot.len());
8015 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8016 })
8017 })
8018 .collect::<Vec<_>>();
8019 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8020
8021 Tabstop {
8022 is_end_tabstop,
8023 ranges: tabstop_ranges,
8024 choices: tabstop.choices.clone(),
8025 }
8026 })
8027 .collect::<Vec<_>>()
8028 });
8029 if let Some(tabstop) = tabstops.first() {
8030 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8031 s.select_ranges(tabstop.ranges.iter().cloned());
8032 });
8033
8034 if let Some(choices) = &tabstop.choices {
8035 if let Some(selection) = tabstop.ranges.first() {
8036 self.show_snippet_choices(choices, selection.clone(), cx)
8037 }
8038 }
8039
8040 // If we're already at the last tabstop and it's at the end of the snippet,
8041 // we're done, we don't need to keep the state around.
8042 if !tabstop.is_end_tabstop {
8043 let choices = tabstops
8044 .iter()
8045 .map(|tabstop| tabstop.choices.clone())
8046 .collect();
8047
8048 let ranges = tabstops
8049 .into_iter()
8050 .map(|tabstop| tabstop.ranges)
8051 .collect::<Vec<_>>();
8052
8053 self.snippet_stack.push(SnippetState {
8054 active_index: 0,
8055 ranges,
8056 choices,
8057 });
8058 }
8059
8060 // Check whether the just-entered snippet ends with an auto-closable bracket.
8061 if self.autoclose_regions.is_empty() {
8062 let snapshot = self.buffer.read(cx).snapshot(cx);
8063 for selection in &mut self.selections.all::<Point>(cx) {
8064 let selection_head = selection.head();
8065 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8066 continue;
8067 };
8068
8069 let mut bracket_pair = None;
8070 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8071 let prev_chars = snapshot
8072 .reversed_chars_at(selection_head)
8073 .collect::<String>();
8074 for (pair, enabled) in scope.brackets() {
8075 if enabled
8076 && pair.close
8077 && prev_chars.starts_with(pair.start.as_str())
8078 && next_chars.starts_with(pair.end.as_str())
8079 {
8080 bracket_pair = Some(pair.clone());
8081 break;
8082 }
8083 }
8084 if let Some(pair) = bracket_pair {
8085 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8086 let autoclose_enabled =
8087 self.use_autoclose && snapshot_settings.use_autoclose;
8088 if autoclose_enabled {
8089 let start = snapshot.anchor_after(selection_head);
8090 let end = snapshot.anchor_after(selection_head);
8091 self.autoclose_regions.push(AutocloseRegion {
8092 selection_id: selection.id,
8093 range: start..end,
8094 pair,
8095 });
8096 }
8097 }
8098 }
8099 }
8100 }
8101 Ok(())
8102 }
8103
8104 pub fn move_to_next_snippet_tabstop(
8105 &mut self,
8106 window: &mut Window,
8107 cx: &mut Context<Self>,
8108 ) -> bool {
8109 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8110 }
8111
8112 pub fn move_to_prev_snippet_tabstop(
8113 &mut self,
8114 window: &mut Window,
8115 cx: &mut Context<Self>,
8116 ) -> bool {
8117 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8118 }
8119
8120 pub fn move_to_snippet_tabstop(
8121 &mut self,
8122 bias: Bias,
8123 window: &mut Window,
8124 cx: &mut Context<Self>,
8125 ) -> bool {
8126 if let Some(mut snippet) = self.snippet_stack.pop() {
8127 match bias {
8128 Bias::Left => {
8129 if snippet.active_index > 0 {
8130 snippet.active_index -= 1;
8131 } else {
8132 self.snippet_stack.push(snippet);
8133 return false;
8134 }
8135 }
8136 Bias::Right => {
8137 if snippet.active_index + 1 < snippet.ranges.len() {
8138 snippet.active_index += 1;
8139 } else {
8140 self.snippet_stack.push(snippet);
8141 return false;
8142 }
8143 }
8144 }
8145 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8146 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8147 s.select_anchor_ranges(current_ranges.iter().cloned())
8148 });
8149
8150 if let Some(choices) = &snippet.choices[snippet.active_index] {
8151 if let Some(selection) = current_ranges.first() {
8152 self.show_snippet_choices(&choices, selection.clone(), cx);
8153 }
8154 }
8155
8156 // If snippet state is not at the last tabstop, push it back on the stack
8157 if snippet.active_index + 1 < snippet.ranges.len() {
8158 self.snippet_stack.push(snippet);
8159 }
8160 return true;
8161 }
8162 }
8163
8164 false
8165 }
8166
8167 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8168 self.transact(window, cx, |this, window, cx| {
8169 this.select_all(&SelectAll, window, cx);
8170 this.insert("", window, cx);
8171 });
8172 }
8173
8174 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8175 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8176 self.transact(window, cx, |this, window, cx| {
8177 this.select_autoclose_pair(window, cx);
8178 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8179 if !this.linked_edit_ranges.is_empty() {
8180 let selections = this.selections.all::<MultiBufferPoint>(cx);
8181 let snapshot = this.buffer.read(cx).snapshot(cx);
8182
8183 for selection in selections.iter() {
8184 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8185 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8186 if selection_start.buffer_id != selection_end.buffer_id {
8187 continue;
8188 }
8189 if let Some(ranges) =
8190 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8191 {
8192 for (buffer, entries) in ranges {
8193 linked_ranges.entry(buffer).or_default().extend(entries);
8194 }
8195 }
8196 }
8197 }
8198
8199 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8200 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8201 for selection in &mut selections {
8202 if selection.is_empty() {
8203 let old_head = selection.head();
8204 let mut new_head =
8205 movement::left(&display_map, old_head.to_display_point(&display_map))
8206 .to_point(&display_map);
8207 if let Some((buffer, line_buffer_range)) = display_map
8208 .buffer_snapshot
8209 .buffer_line_for_row(MultiBufferRow(old_head.row))
8210 {
8211 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8212 let indent_len = match indent_size.kind {
8213 IndentKind::Space => {
8214 buffer.settings_at(line_buffer_range.start, cx).tab_size
8215 }
8216 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8217 };
8218 if old_head.column <= indent_size.len && old_head.column > 0 {
8219 let indent_len = indent_len.get();
8220 new_head = cmp::min(
8221 new_head,
8222 MultiBufferPoint::new(
8223 old_head.row,
8224 ((old_head.column - 1) / indent_len) * indent_len,
8225 ),
8226 );
8227 }
8228 }
8229
8230 selection.set_head(new_head, SelectionGoal::None);
8231 }
8232 }
8233
8234 this.signature_help_state.set_backspace_pressed(true);
8235 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8236 s.select(selections)
8237 });
8238 this.insert("", window, cx);
8239 let empty_str: Arc<str> = Arc::from("");
8240 for (buffer, edits) in linked_ranges {
8241 let snapshot = buffer.read(cx).snapshot();
8242 use text::ToPoint as TP;
8243
8244 let edits = edits
8245 .into_iter()
8246 .map(|range| {
8247 let end_point = TP::to_point(&range.end, &snapshot);
8248 let mut start_point = TP::to_point(&range.start, &snapshot);
8249
8250 if end_point == start_point {
8251 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8252 .saturating_sub(1);
8253 start_point =
8254 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8255 };
8256
8257 (start_point..end_point, empty_str.clone())
8258 })
8259 .sorted_by_key(|(range, _)| range.start)
8260 .collect::<Vec<_>>();
8261 buffer.update(cx, |this, cx| {
8262 this.edit(edits, None, cx);
8263 })
8264 }
8265 this.refresh_inline_completion(true, false, window, cx);
8266 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8267 });
8268 }
8269
8270 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8271 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8272 self.transact(window, cx, |this, window, cx| {
8273 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8274 s.move_with(|map, selection| {
8275 if selection.is_empty() {
8276 let cursor = movement::right(map, selection.head());
8277 selection.end = cursor;
8278 selection.reversed = true;
8279 selection.goal = SelectionGoal::None;
8280 }
8281 })
8282 });
8283 this.insert("", window, cx);
8284 this.refresh_inline_completion(true, false, window, cx);
8285 });
8286 }
8287
8288 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8289 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8290 if self.move_to_prev_snippet_tabstop(window, cx) {
8291 return;
8292 }
8293 self.outdent(&Outdent, window, cx);
8294 }
8295
8296 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8297 if self.move_to_next_snippet_tabstop(window, cx) {
8298 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8299 return;
8300 }
8301 if self.read_only(cx) {
8302 return;
8303 }
8304 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8305 let mut selections = self.selections.all_adjusted(cx);
8306 let buffer = self.buffer.read(cx);
8307 let snapshot = buffer.snapshot(cx);
8308 let rows_iter = selections.iter().map(|s| s.head().row);
8309 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8310
8311 let mut edits = Vec::new();
8312 let mut prev_edited_row = 0;
8313 let mut row_delta = 0;
8314 for selection in &mut selections {
8315 if selection.start.row != prev_edited_row {
8316 row_delta = 0;
8317 }
8318 prev_edited_row = selection.end.row;
8319
8320 // If the selection is non-empty, then increase the indentation of the selected lines.
8321 if !selection.is_empty() {
8322 row_delta =
8323 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8324 continue;
8325 }
8326
8327 // If the selection is empty and the cursor is in the leading whitespace before the
8328 // suggested indentation, then auto-indent the line.
8329 let cursor = selection.head();
8330 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8331 if let Some(suggested_indent) =
8332 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8333 {
8334 if cursor.column < suggested_indent.len
8335 && cursor.column <= current_indent.len
8336 && current_indent.len <= suggested_indent.len
8337 {
8338 selection.start = Point::new(cursor.row, suggested_indent.len);
8339 selection.end = selection.start;
8340 if row_delta == 0 {
8341 edits.extend(Buffer::edit_for_indent_size_adjustment(
8342 cursor.row,
8343 current_indent,
8344 suggested_indent,
8345 ));
8346 row_delta = suggested_indent.len - current_indent.len;
8347 }
8348 continue;
8349 }
8350 }
8351
8352 // Otherwise, insert a hard or soft tab.
8353 let settings = buffer.language_settings_at(cursor, cx);
8354 let tab_size = if settings.hard_tabs {
8355 IndentSize::tab()
8356 } else {
8357 let tab_size = settings.tab_size.get();
8358 let indent_remainder = snapshot
8359 .text_for_range(Point::new(cursor.row, 0)..cursor)
8360 .flat_map(str::chars)
8361 .fold(row_delta % tab_size, |counter: u32, c| {
8362 if c == '\t' {
8363 0
8364 } else {
8365 (counter + 1) % tab_size
8366 }
8367 });
8368
8369 let chars_to_next_tab_stop = tab_size - indent_remainder;
8370 IndentSize::spaces(chars_to_next_tab_stop)
8371 };
8372 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8373 selection.end = selection.start;
8374 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8375 row_delta += tab_size.len;
8376 }
8377
8378 self.transact(window, cx, |this, window, cx| {
8379 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8380 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8381 s.select(selections)
8382 });
8383 this.refresh_inline_completion(true, false, window, cx);
8384 });
8385 }
8386
8387 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8388 if self.read_only(cx) {
8389 return;
8390 }
8391 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8392 let mut selections = self.selections.all::<Point>(cx);
8393 let mut prev_edited_row = 0;
8394 let mut row_delta = 0;
8395 let mut edits = Vec::new();
8396 let buffer = self.buffer.read(cx);
8397 let snapshot = buffer.snapshot(cx);
8398 for selection in &mut selections {
8399 if selection.start.row != prev_edited_row {
8400 row_delta = 0;
8401 }
8402 prev_edited_row = selection.end.row;
8403
8404 row_delta =
8405 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8406 }
8407
8408 self.transact(window, cx, |this, window, cx| {
8409 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8410 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8411 s.select(selections)
8412 });
8413 });
8414 }
8415
8416 fn indent_selection(
8417 buffer: &MultiBuffer,
8418 snapshot: &MultiBufferSnapshot,
8419 selection: &mut Selection<Point>,
8420 edits: &mut Vec<(Range<Point>, String)>,
8421 delta_for_start_row: u32,
8422 cx: &App,
8423 ) -> u32 {
8424 let settings = buffer.language_settings_at(selection.start, cx);
8425 let tab_size = settings.tab_size.get();
8426 let indent_kind = if settings.hard_tabs {
8427 IndentKind::Tab
8428 } else {
8429 IndentKind::Space
8430 };
8431 let mut start_row = selection.start.row;
8432 let mut end_row = selection.end.row + 1;
8433
8434 // If a selection ends at the beginning of a line, don't indent
8435 // that last line.
8436 if selection.end.column == 0 && selection.end.row > selection.start.row {
8437 end_row -= 1;
8438 }
8439
8440 // Avoid re-indenting a row that has already been indented by a
8441 // previous selection, but still update this selection's column
8442 // to reflect that indentation.
8443 if delta_for_start_row > 0 {
8444 start_row += 1;
8445 selection.start.column += delta_for_start_row;
8446 if selection.end.row == selection.start.row {
8447 selection.end.column += delta_for_start_row;
8448 }
8449 }
8450
8451 let mut delta_for_end_row = 0;
8452 let has_multiple_rows = start_row + 1 != end_row;
8453 for row in start_row..end_row {
8454 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8455 let indent_delta = match (current_indent.kind, indent_kind) {
8456 (IndentKind::Space, IndentKind::Space) => {
8457 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8458 IndentSize::spaces(columns_to_next_tab_stop)
8459 }
8460 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8461 (_, IndentKind::Tab) => IndentSize::tab(),
8462 };
8463
8464 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8465 0
8466 } else {
8467 selection.start.column
8468 };
8469 let row_start = Point::new(row, start);
8470 edits.push((
8471 row_start..row_start,
8472 indent_delta.chars().collect::<String>(),
8473 ));
8474
8475 // Update this selection's endpoints to reflect the indentation.
8476 if row == selection.start.row {
8477 selection.start.column += indent_delta.len;
8478 }
8479 if row == selection.end.row {
8480 selection.end.column += indent_delta.len;
8481 delta_for_end_row = indent_delta.len;
8482 }
8483 }
8484
8485 if selection.start.row == selection.end.row {
8486 delta_for_start_row + delta_for_end_row
8487 } else {
8488 delta_for_end_row
8489 }
8490 }
8491
8492 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8493 if self.read_only(cx) {
8494 return;
8495 }
8496 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8497 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8498 let selections = self.selections.all::<Point>(cx);
8499 let mut deletion_ranges = Vec::new();
8500 let mut last_outdent = None;
8501 {
8502 let buffer = self.buffer.read(cx);
8503 let snapshot = buffer.snapshot(cx);
8504 for selection in &selections {
8505 let settings = buffer.language_settings_at(selection.start, cx);
8506 let tab_size = settings.tab_size.get();
8507 let mut rows = selection.spanned_rows(false, &display_map);
8508
8509 // Avoid re-outdenting a row that has already been outdented by a
8510 // previous selection.
8511 if let Some(last_row) = last_outdent {
8512 if last_row == rows.start {
8513 rows.start = rows.start.next_row();
8514 }
8515 }
8516 let has_multiple_rows = rows.len() > 1;
8517 for row in rows.iter_rows() {
8518 let indent_size = snapshot.indent_size_for_line(row);
8519 if indent_size.len > 0 {
8520 let deletion_len = match indent_size.kind {
8521 IndentKind::Space => {
8522 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8523 if columns_to_prev_tab_stop == 0 {
8524 tab_size
8525 } else {
8526 columns_to_prev_tab_stop
8527 }
8528 }
8529 IndentKind::Tab => 1,
8530 };
8531 let start = if has_multiple_rows
8532 || deletion_len > selection.start.column
8533 || indent_size.len < selection.start.column
8534 {
8535 0
8536 } else {
8537 selection.start.column - deletion_len
8538 };
8539 deletion_ranges.push(
8540 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8541 );
8542 last_outdent = Some(row);
8543 }
8544 }
8545 }
8546 }
8547
8548 self.transact(window, cx, |this, window, cx| {
8549 this.buffer.update(cx, |buffer, cx| {
8550 let empty_str: Arc<str> = Arc::default();
8551 buffer.edit(
8552 deletion_ranges
8553 .into_iter()
8554 .map(|range| (range, empty_str.clone())),
8555 None,
8556 cx,
8557 );
8558 });
8559 let selections = this.selections.all::<usize>(cx);
8560 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8561 s.select(selections)
8562 });
8563 });
8564 }
8565
8566 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8567 if self.read_only(cx) {
8568 return;
8569 }
8570 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8571 let selections = self
8572 .selections
8573 .all::<usize>(cx)
8574 .into_iter()
8575 .map(|s| s.range());
8576
8577 self.transact(window, cx, |this, window, cx| {
8578 this.buffer.update(cx, |buffer, cx| {
8579 buffer.autoindent_ranges(selections, cx);
8580 });
8581 let selections = this.selections.all::<usize>(cx);
8582 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8583 s.select(selections)
8584 });
8585 });
8586 }
8587
8588 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8589 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8590 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8591 let selections = self.selections.all::<Point>(cx);
8592
8593 let mut new_cursors = Vec::new();
8594 let mut edit_ranges = Vec::new();
8595 let mut selections = selections.iter().peekable();
8596 while let Some(selection) = selections.next() {
8597 let mut rows = selection.spanned_rows(false, &display_map);
8598 let goal_display_column = selection.head().to_display_point(&display_map).column();
8599
8600 // Accumulate contiguous regions of rows that we want to delete.
8601 while let Some(next_selection) = selections.peek() {
8602 let next_rows = next_selection.spanned_rows(false, &display_map);
8603 if next_rows.start <= rows.end {
8604 rows.end = next_rows.end;
8605 selections.next().unwrap();
8606 } else {
8607 break;
8608 }
8609 }
8610
8611 let buffer = &display_map.buffer_snapshot;
8612 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8613 let edit_end;
8614 let cursor_buffer_row;
8615 if buffer.max_point().row >= rows.end.0 {
8616 // If there's a line after the range, delete the \n from the end of the row range
8617 // and position the cursor on the next line.
8618 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8619 cursor_buffer_row = rows.end;
8620 } else {
8621 // If there isn't a line after the range, delete the \n from the line before the
8622 // start of the row range and position the cursor there.
8623 edit_start = edit_start.saturating_sub(1);
8624 edit_end = buffer.len();
8625 cursor_buffer_row = rows.start.previous_row();
8626 }
8627
8628 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8629 *cursor.column_mut() =
8630 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8631
8632 new_cursors.push((
8633 selection.id,
8634 buffer.anchor_after(cursor.to_point(&display_map)),
8635 ));
8636 edit_ranges.push(edit_start..edit_end);
8637 }
8638
8639 self.transact(window, cx, |this, window, cx| {
8640 let buffer = this.buffer.update(cx, |buffer, cx| {
8641 let empty_str: Arc<str> = Arc::default();
8642 buffer.edit(
8643 edit_ranges
8644 .into_iter()
8645 .map(|range| (range, empty_str.clone())),
8646 None,
8647 cx,
8648 );
8649 buffer.snapshot(cx)
8650 });
8651 let new_selections = new_cursors
8652 .into_iter()
8653 .map(|(id, cursor)| {
8654 let cursor = cursor.to_point(&buffer);
8655 Selection {
8656 id,
8657 start: cursor,
8658 end: cursor,
8659 reversed: false,
8660 goal: SelectionGoal::None,
8661 }
8662 })
8663 .collect();
8664
8665 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8666 s.select(new_selections);
8667 });
8668 });
8669 }
8670
8671 pub fn join_lines_impl(
8672 &mut self,
8673 insert_whitespace: bool,
8674 window: &mut Window,
8675 cx: &mut Context<Self>,
8676 ) {
8677 if self.read_only(cx) {
8678 return;
8679 }
8680 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8681 for selection in self.selections.all::<Point>(cx) {
8682 let start = MultiBufferRow(selection.start.row);
8683 // Treat single line selections as if they include the next line. Otherwise this action
8684 // would do nothing for single line selections individual cursors.
8685 let end = if selection.start.row == selection.end.row {
8686 MultiBufferRow(selection.start.row + 1)
8687 } else {
8688 MultiBufferRow(selection.end.row)
8689 };
8690
8691 if let Some(last_row_range) = row_ranges.last_mut() {
8692 if start <= last_row_range.end {
8693 last_row_range.end = end;
8694 continue;
8695 }
8696 }
8697 row_ranges.push(start..end);
8698 }
8699
8700 let snapshot = self.buffer.read(cx).snapshot(cx);
8701 let mut cursor_positions = Vec::new();
8702 for row_range in &row_ranges {
8703 let anchor = snapshot.anchor_before(Point::new(
8704 row_range.end.previous_row().0,
8705 snapshot.line_len(row_range.end.previous_row()),
8706 ));
8707 cursor_positions.push(anchor..anchor);
8708 }
8709
8710 self.transact(window, cx, |this, window, cx| {
8711 for row_range in row_ranges.into_iter().rev() {
8712 for row in row_range.iter_rows().rev() {
8713 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8714 let next_line_row = row.next_row();
8715 let indent = snapshot.indent_size_for_line(next_line_row);
8716 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8717
8718 let replace =
8719 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8720 " "
8721 } else {
8722 ""
8723 };
8724
8725 this.buffer.update(cx, |buffer, cx| {
8726 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8727 });
8728 }
8729 }
8730
8731 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8732 s.select_anchor_ranges(cursor_positions)
8733 });
8734 });
8735 }
8736
8737 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8738 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8739 self.join_lines_impl(true, window, cx);
8740 }
8741
8742 pub fn sort_lines_case_sensitive(
8743 &mut self,
8744 _: &SortLinesCaseSensitive,
8745 window: &mut Window,
8746 cx: &mut Context<Self>,
8747 ) {
8748 self.manipulate_lines(window, cx, |lines| lines.sort())
8749 }
8750
8751 pub fn sort_lines_case_insensitive(
8752 &mut self,
8753 _: &SortLinesCaseInsensitive,
8754 window: &mut Window,
8755 cx: &mut Context<Self>,
8756 ) {
8757 self.manipulate_lines(window, cx, |lines| {
8758 lines.sort_by_key(|line| line.to_lowercase())
8759 })
8760 }
8761
8762 pub fn unique_lines_case_insensitive(
8763 &mut self,
8764 _: &UniqueLinesCaseInsensitive,
8765 window: &mut Window,
8766 cx: &mut Context<Self>,
8767 ) {
8768 self.manipulate_lines(window, cx, |lines| {
8769 let mut seen = HashSet::default();
8770 lines.retain(|line| seen.insert(line.to_lowercase()));
8771 })
8772 }
8773
8774 pub fn unique_lines_case_sensitive(
8775 &mut self,
8776 _: &UniqueLinesCaseSensitive,
8777 window: &mut Window,
8778 cx: &mut Context<Self>,
8779 ) {
8780 self.manipulate_lines(window, cx, |lines| {
8781 let mut seen = HashSet::default();
8782 lines.retain(|line| seen.insert(*line));
8783 })
8784 }
8785
8786 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8787 let Some(project) = self.project.clone() else {
8788 return;
8789 };
8790 self.reload(project, window, cx)
8791 .detach_and_notify_err(window, cx);
8792 }
8793
8794 pub fn restore_file(
8795 &mut self,
8796 _: &::git::RestoreFile,
8797 window: &mut Window,
8798 cx: &mut Context<Self>,
8799 ) {
8800 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8801 let mut buffer_ids = HashSet::default();
8802 let snapshot = self.buffer().read(cx).snapshot(cx);
8803 for selection in self.selections.all::<usize>(cx) {
8804 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8805 }
8806
8807 let buffer = self.buffer().read(cx);
8808 let ranges = buffer_ids
8809 .into_iter()
8810 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8811 .collect::<Vec<_>>();
8812
8813 self.restore_hunks_in_ranges(ranges, window, cx);
8814 }
8815
8816 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8817 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8818 let selections = self
8819 .selections
8820 .all(cx)
8821 .into_iter()
8822 .map(|s| s.range())
8823 .collect();
8824 self.restore_hunks_in_ranges(selections, window, cx);
8825 }
8826
8827 pub fn restore_hunks_in_ranges(
8828 &mut self,
8829 ranges: Vec<Range<Point>>,
8830 window: &mut Window,
8831 cx: &mut Context<Editor>,
8832 ) {
8833 let mut revert_changes = HashMap::default();
8834 let chunk_by = self
8835 .snapshot(window, cx)
8836 .hunks_for_ranges(ranges)
8837 .into_iter()
8838 .chunk_by(|hunk| hunk.buffer_id);
8839 for (buffer_id, hunks) in &chunk_by {
8840 let hunks = hunks.collect::<Vec<_>>();
8841 for hunk in &hunks {
8842 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8843 }
8844 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8845 }
8846 drop(chunk_by);
8847 if !revert_changes.is_empty() {
8848 self.transact(window, cx, |editor, window, cx| {
8849 editor.restore(revert_changes, window, cx);
8850 });
8851 }
8852 }
8853
8854 pub fn open_active_item_in_terminal(
8855 &mut self,
8856 _: &OpenInTerminal,
8857 window: &mut Window,
8858 cx: &mut Context<Self>,
8859 ) {
8860 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8861 let project_path = buffer.read(cx).project_path(cx)?;
8862 let project = self.project.as_ref()?.read(cx);
8863 let entry = project.entry_for_path(&project_path, cx)?;
8864 let parent = match &entry.canonical_path {
8865 Some(canonical_path) => canonical_path.to_path_buf(),
8866 None => project.absolute_path(&project_path, cx)?,
8867 }
8868 .parent()?
8869 .to_path_buf();
8870 Some(parent)
8871 }) {
8872 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8873 }
8874 }
8875
8876 fn set_breakpoint_context_menu(
8877 &mut self,
8878 display_row: DisplayRow,
8879 position: Option<Anchor>,
8880 clicked_point: gpui::Point<Pixels>,
8881 window: &mut Window,
8882 cx: &mut Context<Self>,
8883 ) {
8884 if !cx.has_flag::<Debugger>() {
8885 return;
8886 }
8887 let source = self
8888 .buffer
8889 .read(cx)
8890 .snapshot(cx)
8891 .anchor_before(Point::new(display_row.0, 0u32));
8892
8893 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8894
8895 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8896 self,
8897 source,
8898 clicked_point,
8899 context_menu,
8900 window,
8901 cx,
8902 );
8903 }
8904
8905 fn add_edit_breakpoint_block(
8906 &mut self,
8907 anchor: Anchor,
8908 breakpoint: &Breakpoint,
8909 edit_action: BreakpointPromptEditAction,
8910 window: &mut Window,
8911 cx: &mut Context<Self>,
8912 ) {
8913 let weak_editor = cx.weak_entity();
8914 let bp_prompt = cx.new(|cx| {
8915 BreakpointPromptEditor::new(
8916 weak_editor,
8917 anchor,
8918 breakpoint.clone(),
8919 edit_action,
8920 window,
8921 cx,
8922 )
8923 });
8924
8925 let height = bp_prompt.update(cx, |this, cx| {
8926 this.prompt
8927 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8928 });
8929 let cloned_prompt = bp_prompt.clone();
8930 let blocks = vec![BlockProperties {
8931 style: BlockStyle::Sticky,
8932 placement: BlockPlacement::Above(anchor),
8933 height: Some(height),
8934 render: Arc::new(move |cx| {
8935 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8936 cloned_prompt.clone().into_any_element()
8937 }),
8938 priority: 0,
8939 }];
8940
8941 let focus_handle = bp_prompt.focus_handle(cx);
8942 window.focus(&focus_handle);
8943
8944 let block_ids = self.insert_blocks(blocks, None, cx);
8945 bp_prompt.update(cx, |prompt, _| {
8946 prompt.add_block_ids(block_ids);
8947 });
8948 }
8949
8950 pub(crate) fn breakpoint_at_row(
8951 &self,
8952 row: u32,
8953 window: &mut Window,
8954 cx: &mut Context<Self>,
8955 ) -> Option<(Anchor, Breakpoint)> {
8956 let snapshot = self.snapshot(window, cx);
8957 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8958
8959 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
8960 }
8961
8962 pub(crate) fn breakpoint_at_anchor(
8963 &self,
8964 breakpoint_position: Anchor,
8965 snapshot: &EditorSnapshot,
8966 cx: &mut Context<Self>,
8967 ) -> Option<(Anchor, Breakpoint)> {
8968 let project = self.project.clone()?;
8969
8970 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8971 snapshot
8972 .buffer_snapshot
8973 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8974 })?;
8975
8976 let enclosing_excerpt = breakpoint_position.excerpt_id;
8977 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8978 let buffer_snapshot = buffer.read(cx).snapshot();
8979
8980 let row = buffer_snapshot
8981 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8982 .row;
8983
8984 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8985 let anchor_end = snapshot
8986 .buffer_snapshot
8987 .anchor_after(Point::new(row, line_len));
8988
8989 let bp = self
8990 .breakpoint_store
8991 .as_ref()?
8992 .read_with(cx, |breakpoint_store, cx| {
8993 breakpoint_store
8994 .breakpoints(
8995 &buffer,
8996 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8997 &buffer_snapshot,
8998 cx,
8999 )
9000 .next()
9001 .and_then(|(anchor, bp)| {
9002 let breakpoint_row = buffer_snapshot
9003 .summary_for_anchor::<text::PointUtf16>(anchor)
9004 .row;
9005
9006 if breakpoint_row == row {
9007 snapshot
9008 .buffer_snapshot
9009 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9010 .map(|anchor| (anchor, bp.clone()))
9011 } else {
9012 None
9013 }
9014 })
9015 });
9016 bp
9017 }
9018
9019 pub fn edit_log_breakpoint(
9020 &mut self,
9021 _: &EditLogBreakpoint,
9022 window: &mut Window,
9023 cx: &mut Context<Self>,
9024 ) {
9025 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9026 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9027 message: None,
9028 state: BreakpointState::Enabled,
9029 condition: None,
9030 hit_condition: None,
9031 });
9032
9033 self.add_edit_breakpoint_block(
9034 anchor,
9035 &breakpoint,
9036 BreakpointPromptEditAction::Log,
9037 window,
9038 cx,
9039 );
9040 }
9041 }
9042
9043 fn breakpoints_at_cursors(
9044 &self,
9045 window: &mut Window,
9046 cx: &mut Context<Self>,
9047 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9048 let snapshot = self.snapshot(window, cx);
9049 let cursors = self
9050 .selections
9051 .disjoint_anchors()
9052 .into_iter()
9053 .map(|selection| {
9054 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9055
9056 let breakpoint_position = self
9057 .breakpoint_at_row(cursor_position.row, window, cx)
9058 .map(|bp| bp.0)
9059 .unwrap_or_else(|| {
9060 snapshot
9061 .display_snapshot
9062 .buffer_snapshot
9063 .anchor_after(Point::new(cursor_position.row, 0))
9064 });
9065
9066 let breakpoint = self
9067 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9068 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9069
9070 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9071 })
9072 // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
9073 .collect::<HashMap<Anchor, _>>();
9074
9075 cursors.into_iter().collect()
9076 }
9077
9078 pub fn enable_breakpoint(
9079 &mut self,
9080 _: &crate::actions::EnableBreakpoint,
9081 window: &mut Window,
9082 cx: &mut Context<Self>,
9083 ) {
9084 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9085 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9086 continue;
9087 };
9088 self.edit_breakpoint_at_anchor(
9089 anchor,
9090 breakpoint,
9091 BreakpointEditAction::InvertState,
9092 cx,
9093 );
9094 }
9095 }
9096
9097 pub fn disable_breakpoint(
9098 &mut self,
9099 _: &crate::actions::DisableBreakpoint,
9100 window: &mut Window,
9101 cx: &mut Context<Self>,
9102 ) {
9103 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9104 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9105 continue;
9106 };
9107 self.edit_breakpoint_at_anchor(
9108 anchor,
9109 breakpoint,
9110 BreakpointEditAction::InvertState,
9111 cx,
9112 );
9113 }
9114 }
9115
9116 pub fn toggle_breakpoint(
9117 &mut self,
9118 _: &crate::actions::ToggleBreakpoint,
9119 window: &mut Window,
9120 cx: &mut Context<Self>,
9121 ) {
9122 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9123 if let Some(breakpoint) = breakpoint {
9124 self.edit_breakpoint_at_anchor(
9125 anchor,
9126 breakpoint,
9127 BreakpointEditAction::Toggle,
9128 cx,
9129 );
9130 } else {
9131 self.edit_breakpoint_at_anchor(
9132 anchor,
9133 Breakpoint::new_standard(),
9134 BreakpointEditAction::Toggle,
9135 cx,
9136 );
9137 }
9138 }
9139 }
9140
9141 pub fn edit_breakpoint_at_anchor(
9142 &mut self,
9143 breakpoint_position: Anchor,
9144 breakpoint: Breakpoint,
9145 edit_action: BreakpointEditAction,
9146 cx: &mut Context<Self>,
9147 ) {
9148 let Some(breakpoint_store) = &self.breakpoint_store else {
9149 return;
9150 };
9151
9152 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9153 if breakpoint_position == Anchor::min() {
9154 self.buffer()
9155 .read(cx)
9156 .excerpt_buffer_ids()
9157 .into_iter()
9158 .next()
9159 } else {
9160 None
9161 }
9162 }) else {
9163 return;
9164 };
9165
9166 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9167 return;
9168 };
9169
9170 breakpoint_store.update(cx, |breakpoint_store, cx| {
9171 breakpoint_store.toggle_breakpoint(
9172 buffer,
9173 (breakpoint_position.text_anchor, breakpoint),
9174 edit_action,
9175 cx,
9176 );
9177 });
9178
9179 cx.notify();
9180 }
9181
9182 #[cfg(any(test, feature = "test-support"))]
9183 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9184 self.breakpoint_store.clone()
9185 }
9186
9187 pub fn prepare_restore_change(
9188 &self,
9189 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9190 hunk: &MultiBufferDiffHunk,
9191 cx: &mut App,
9192 ) -> Option<()> {
9193 if hunk.is_created_file() {
9194 return None;
9195 }
9196 let buffer = self.buffer.read(cx);
9197 let diff = buffer.diff_for(hunk.buffer_id)?;
9198 let buffer = buffer.buffer(hunk.buffer_id)?;
9199 let buffer = buffer.read(cx);
9200 let original_text = diff
9201 .read(cx)
9202 .base_text()
9203 .as_rope()
9204 .slice(hunk.diff_base_byte_range.clone());
9205 let buffer_snapshot = buffer.snapshot();
9206 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9207 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9208 probe
9209 .0
9210 .start
9211 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9212 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9213 }) {
9214 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9215 Some(())
9216 } else {
9217 None
9218 }
9219 }
9220
9221 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9222 self.manipulate_lines(window, cx, |lines| lines.reverse())
9223 }
9224
9225 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9226 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9227 }
9228
9229 fn manipulate_lines<Fn>(
9230 &mut self,
9231 window: &mut Window,
9232 cx: &mut Context<Self>,
9233 mut callback: Fn,
9234 ) where
9235 Fn: FnMut(&mut Vec<&str>),
9236 {
9237 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9238
9239 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9240 let buffer = self.buffer.read(cx).snapshot(cx);
9241
9242 let mut edits = Vec::new();
9243
9244 let selections = self.selections.all::<Point>(cx);
9245 let mut selections = selections.iter().peekable();
9246 let mut contiguous_row_selections = Vec::new();
9247 let mut new_selections = Vec::new();
9248 let mut added_lines = 0;
9249 let mut removed_lines = 0;
9250
9251 while let Some(selection) = selections.next() {
9252 let (start_row, end_row) = consume_contiguous_rows(
9253 &mut contiguous_row_selections,
9254 selection,
9255 &display_map,
9256 &mut selections,
9257 );
9258
9259 let start_point = Point::new(start_row.0, 0);
9260 let end_point = Point::new(
9261 end_row.previous_row().0,
9262 buffer.line_len(end_row.previous_row()),
9263 );
9264 let text = buffer
9265 .text_for_range(start_point..end_point)
9266 .collect::<String>();
9267
9268 let mut lines = text.split('\n').collect_vec();
9269
9270 let lines_before = lines.len();
9271 callback(&mut lines);
9272 let lines_after = lines.len();
9273
9274 edits.push((start_point..end_point, lines.join("\n")));
9275
9276 // Selections must change based on added and removed line count
9277 let start_row =
9278 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9279 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9280 new_selections.push(Selection {
9281 id: selection.id,
9282 start: start_row,
9283 end: end_row,
9284 goal: SelectionGoal::None,
9285 reversed: selection.reversed,
9286 });
9287
9288 if lines_after > lines_before {
9289 added_lines += lines_after - lines_before;
9290 } else if lines_before > lines_after {
9291 removed_lines += lines_before - lines_after;
9292 }
9293 }
9294
9295 self.transact(window, cx, |this, window, cx| {
9296 let buffer = this.buffer.update(cx, |buffer, cx| {
9297 buffer.edit(edits, None, cx);
9298 buffer.snapshot(cx)
9299 });
9300
9301 // Recalculate offsets on newly edited buffer
9302 let new_selections = new_selections
9303 .iter()
9304 .map(|s| {
9305 let start_point = Point::new(s.start.0, 0);
9306 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9307 Selection {
9308 id: s.id,
9309 start: buffer.point_to_offset(start_point),
9310 end: buffer.point_to_offset(end_point),
9311 goal: s.goal,
9312 reversed: s.reversed,
9313 }
9314 })
9315 .collect();
9316
9317 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9318 s.select(new_selections);
9319 });
9320
9321 this.request_autoscroll(Autoscroll::fit(), cx);
9322 });
9323 }
9324
9325 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9326 self.manipulate_text(window, cx, |text| {
9327 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9328 if has_upper_case_characters {
9329 text.to_lowercase()
9330 } else {
9331 text.to_uppercase()
9332 }
9333 })
9334 }
9335
9336 pub fn convert_to_upper_case(
9337 &mut self,
9338 _: &ConvertToUpperCase,
9339 window: &mut Window,
9340 cx: &mut Context<Self>,
9341 ) {
9342 self.manipulate_text(window, cx, |text| text.to_uppercase())
9343 }
9344
9345 pub fn convert_to_lower_case(
9346 &mut self,
9347 _: &ConvertToLowerCase,
9348 window: &mut Window,
9349 cx: &mut Context<Self>,
9350 ) {
9351 self.manipulate_text(window, cx, |text| text.to_lowercase())
9352 }
9353
9354 pub fn convert_to_title_case(
9355 &mut self,
9356 _: &ConvertToTitleCase,
9357 window: &mut Window,
9358 cx: &mut Context<Self>,
9359 ) {
9360 self.manipulate_text(window, cx, |text| {
9361 text.split('\n')
9362 .map(|line| line.to_case(Case::Title))
9363 .join("\n")
9364 })
9365 }
9366
9367 pub fn convert_to_snake_case(
9368 &mut self,
9369 _: &ConvertToSnakeCase,
9370 window: &mut Window,
9371 cx: &mut Context<Self>,
9372 ) {
9373 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9374 }
9375
9376 pub fn convert_to_kebab_case(
9377 &mut self,
9378 _: &ConvertToKebabCase,
9379 window: &mut Window,
9380 cx: &mut Context<Self>,
9381 ) {
9382 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9383 }
9384
9385 pub fn convert_to_upper_camel_case(
9386 &mut self,
9387 _: &ConvertToUpperCamelCase,
9388 window: &mut Window,
9389 cx: &mut Context<Self>,
9390 ) {
9391 self.manipulate_text(window, cx, |text| {
9392 text.split('\n')
9393 .map(|line| line.to_case(Case::UpperCamel))
9394 .join("\n")
9395 })
9396 }
9397
9398 pub fn convert_to_lower_camel_case(
9399 &mut self,
9400 _: &ConvertToLowerCamelCase,
9401 window: &mut Window,
9402 cx: &mut Context<Self>,
9403 ) {
9404 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9405 }
9406
9407 pub fn convert_to_opposite_case(
9408 &mut self,
9409 _: &ConvertToOppositeCase,
9410 window: &mut Window,
9411 cx: &mut Context<Self>,
9412 ) {
9413 self.manipulate_text(window, cx, |text| {
9414 text.chars()
9415 .fold(String::with_capacity(text.len()), |mut t, c| {
9416 if c.is_uppercase() {
9417 t.extend(c.to_lowercase());
9418 } else {
9419 t.extend(c.to_uppercase());
9420 }
9421 t
9422 })
9423 })
9424 }
9425
9426 pub fn convert_to_rot13(
9427 &mut self,
9428 _: &ConvertToRot13,
9429 window: &mut Window,
9430 cx: &mut Context<Self>,
9431 ) {
9432 self.manipulate_text(window, cx, |text| {
9433 text.chars()
9434 .map(|c| match c {
9435 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9436 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9437 _ => c,
9438 })
9439 .collect()
9440 })
9441 }
9442
9443 pub fn convert_to_rot47(
9444 &mut self,
9445 _: &ConvertToRot47,
9446 window: &mut Window,
9447 cx: &mut Context<Self>,
9448 ) {
9449 self.manipulate_text(window, cx, |text| {
9450 text.chars()
9451 .map(|c| {
9452 let code_point = c as u32;
9453 if code_point >= 33 && code_point <= 126 {
9454 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9455 }
9456 c
9457 })
9458 .collect()
9459 })
9460 }
9461
9462 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9463 where
9464 Fn: FnMut(&str) -> String,
9465 {
9466 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9467 let buffer = self.buffer.read(cx).snapshot(cx);
9468
9469 let mut new_selections = Vec::new();
9470 let mut edits = Vec::new();
9471 let mut selection_adjustment = 0i32;
9472
9473 for selection in self.selections.all::<usize>(cx) {
9474 let selection_is_empty = selection.is_empty();
9475
9476 let (start, end) = if selection_is_empty {
9477 let word_range = movement::surrounding_word(
9478 &display_map,
9479 selection.start.to_display_point(&display_map),
9480 );
9481 let start = word_range.start.to_offset(&display_map, Bias::Left);
9482 let end = word_range.end.to_offset(&display_map, Bias::Left);
9483 (start, end)
9484 } else {
9485 (selection.start, selection.end)
9486 };
9487
9488 let text = buffer.text_for_range(start..end).collect::<String>();
9489 let old_length = text.len() as i32;
9490 let text = callback(&text);
9491
9492 new_selections.push(Selection {
9493 start: (start as i32 - selection_adjustment) as usize,
9494 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9495 goal: SelectionGoal::None,
9496 ..selection
9497 });
9498
9499 selection_adjustment += old_length - text.len() as i32;
9500
9501 edits.push((start..end, text));
9502 }
9503
9504 self.transact(window, cx, |this, window, cx| {
9505 this.buffer.update(cx, |buffer, cx| {
9506 buffer.edit(edits, None, cx);
9507 });
9508
9509 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9510 s.select(new_selections);
9511 });
9512
9513 this.request_autoscroll(Autoscroll::fit(), cx);
9514 });
9515 }
9516
9517 pub fn duplicate(
9518 &mut self,
9519 upwards: bool,
9520 whole_lines: bool,
9521 window: &mut Window,
9522 cx: &mut Context<Self>,
9523 ) {
9524 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9525
9526 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9527 let buffer = &display_map.buffer_snapshot;
9528 let selections = self.selections.all::<Point>(cx);
9529
9530 let mut edits = Vec::new();
9531 let mut selections_iter = selections.iter().peekable();
9532 while let Some(selection) = selections_iter.next() {
9533 let mut rows = selection.spanned_rows(false, &display_map);
9534 // duplicate line-wise
9535 if whole_lines || selection.start == selection.end {
9536 // Avoid duplicating the same lines twice.
9537 while let Some(next_selection) = selections_iter.peek() {
9538 let next_rows = next_selection.spanned_rows(false, &display_map);
9539 if next_rows.start < rows.end {
9540 rows.end = next_rows.end;
9541 selections_iter.next().unwrap();
9542 } else {
9543 break;
9544 }
9545 }
9546
9547 // Copy the text from the selected row region and splice it either at the start
9548 // or end of the region.
9549 let start = Point::new(rows.start.0, 0);
9550 let end = Point::new(
9551 rows.end.previous_row().0,
9552 buffer.line_len(rows.end.previous_row()),
9553 );
9554 let text = buffer
9555 .text_for_range(start..end)
9556 .chain(Some("\n"))
9557 .collect::<String>();
9558 let insert_location = if upwards {
9559 Point::new(rows.end.0, 0)
9560 } else {
9561 start
9562 };
9563 edits.push((insert_location..insert_location, text));
9564 } else {
9565 // duplicate character-wise
9566 let start = selection.start;
9567 let end = selection.end;
9568 let text = buffer.text_for_range(start..end).collect::<String>();
9569 edits.push((selection.end..selection.end, text));
9570 }
9571 }
9572
9573 self.transact(window, cx, |this, _, cx| {
9574 this.buffer.update(cx, |buffer, cx| {
9575 buffer.edit(edits, None, cx);
9576 });
9577
9578 this.request_autoscroll(Autoscroll::fit(), cx);
9579 });
9580 }
9581
9582 pub fn duplicate_line_up(
9583 &mut self,
9584 _: &DuplicateLineUp,
9585 window: &mut Window,
9586 cx: &mut Context<Self>,
9587 ) {
9588 self.duplicate(true, true, window, cx);
9589 }
9590
9591 pub fn duplicate_line_down(
9592 &mut self,
9593 _: &DuplicateLineDown,
9594 window: &mut Window,
9595 cx: &mut Context<Self>,
9596 ) {
9597 self.duplicate(false, true, window, cx);
9598 }
9599
9600 pub fn duplicate_selection(
9601 &mut self,
9602 _: &DuplicateSelection,
9603 window: &mut Window,
9604 cx: &mut Context<Self>,
9605 ) {
9606 self.duplicate(false, false, window, cx);
9607 }
9608
9609 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9610 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9611
9612 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9613 let buffer = self.buffer.read(cx).snapshot(cx);
9614
9615 let mut edits = Vec::new();
9616 let mut unfold_ranges = Vec::new();
9617 let mut refold_creases = Vec::new();
9618
9619 let selections = self.selections.all::<Point>(cx);
9620 let mut selections = selections.iter().peekable();
9621 let mut contiguous_row_selections = Vec::new();
9622 let mut new_selections = Vec::new();
9623
9624 while let Some(selection) = selections.next() {
9625 // Find all the selections that span a contiguous row range
9626 let (start_row, end_row) = consume_contiguous_rows(
9627 &mut contiguous_row_selections,
9628 selection,
9629 &display_map,
9630 &mut selections,
9631 );
9632
9633 // Move the text spanned by the row range to be before the line preceding the row range
9634 if start_row.0 > 0 {
9635 let range_to_move = Point::new(
9636 start_row.previous_row().0,
9637 buffer.line_len(start_row.previous_row()),
9638 )
9639 ..Point::new(
9640 end_row.previous_row().0,
9641 buffer.line_len(end_row.previous_row()),
9642 );
9643 let insertion_point = display_map
9644 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9645 .0;
9646
9647 // Don't move lines across excerpts
9648 if buffer
9649 .excerpt_containing(insertion_point..range_to_move.end)
9650 .is_some()
9651 {
9652 let text = buffer
9653 .text_for_range(range_to_move.clone())
9654 .flat_map(|s| s.chars())
9655 .skip(1)
9656 .chain(['\n'])
9657 .collect::<String>();
9658
9659 edits.push((
9660 buffer.anchor_after(range_to_move.start)
9661 ..buffer.anchor_before(range_to_move.end),
9662 String::new(),
9663 ));
9664 let insertion_anchor = buffer.anchor_after(insertion_point);
9665 edits.push((insertion_anchor..insertion_anchor, text));
9666
9667 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9668
9669 // Move selections up
9670 new_selections.extend(contiguous_row_selections.drain(..).map(
9671 |mut selection| {
9672 selection.start.row -= row_delta;
9673 selection.end.row -= row_delta;
9674 selection
9675 },
9676 ));
9677
9678 // Move folds up
9679 unfold_ranges.push(range_to_move.clone());
9680 for fold in display_map.folds_in_range(
9681 buffer.anchor_before(range_to_move.start)
9682 ..buffer.anchor_after(range_to_move.end),
9683 ) {
9684 let mut start = fold.range.start.to_point(&buffer);
9685 let mut end = fold.range.end.to_point(&buffer);
9686 start.row -= row_delta;
9687 end.row -= row_delta;
9688 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9689 }
9690 }
9691 }
9692
9693 // If we didn't move line(s), preserve the existing selections
9694 new_selections.append(&mut contiguous_row_selections);
9695 }
9696
9697 self.transact(window, cx, |this, window, cx| {
9698 this.unfold_ranges(&unfold_ranges, true, true, cx);
9699 this.buffer.update(cx, |buffer, cx| {
9700 for (range, text) in edits {
9701 buffer.edit([(range, text)], None, cx);
9702 }
9703 });
9704 this.fold_creases(refold_creases, true, window, cx);
9705 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9706 s.select(new_selections);
9707 })
9708 });
9709 }
9710
9711 pub fn move_line_down(
9712 &mut self,
9713 _: &MoveLineDown,
9714 window: &mut Window,
9715 cx: &mut Context<Self>,
9716 ) {
9717 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9718
9719 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9720 let buffer = self.buffer.read(cx).snapshot(cx);
9721
9722 let mut edits = Vec::new();
9723 let mut unfold_ranges = Vec::new();
9724 let mut refold_creases = Vec::new();
9725
9726 let selections = self.selections.all::<Point>(cx);
9727 let mut selections = selections.iter().peekable();
9728 let mut contiguous_row_selections = Vec::new();
9729 let mut new_selections = Vec::new();
9730
9731 while let Some(selection) = selections.next() {
9732 // Find all the selections that span a contiguous row range
9733 let (start_row, end_row) = consume_contiguous_rows(
9734 &mut contiguous_row_selections,
9735 selection,
9736 &display_map,
9737 &mut selections,
9738 );
9739
9740 // Move the text spanned by the row range to be after the last line of the row range
9741 if end_row.0 <= buffer.max_point().row {
9742 let range_to_move =
9743 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9744 let insertion_point = display_map
9745 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9746 .0;
9747
9748 // Don't move lines across excerpt boundaries
9749 if buffer
9750 .excerpt_containing(range_to_move.start..insertion_point)
9751 .is_some()
9752 {
9753 let mut text = String::from("\n");
9754 text.extend(buffer.text_for_range(range_to_move.clone()));
9755 text.pop(); // Drop trailing newline
9756 edits.push((
9757 buffer.anchor_after(range_to_move.start)
9758 ..buffer.anchor_before(range_to_move.end),
9759 String::new(),
9760 ));
9761 let insertion_anchor = buffer.anchor_after(insertion_point);
9762 edits.push((insertion_anchor..insertion_anchor, text));
9763
9764 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9765
9766 // Move selections down
9767 new_selections.extend(contiguous_row_selections.drain(..).map(
9768 |mut selection| {
9769 selection.start.row += row_delta;
9770 selection.end.row += row_delta;
9771 selection
9772 },
9773 ));
9774
9775 // Move folds down
9776 unfold_ranges.push(range_to_move.clone());
9777 for fold in display_map.folds_in_range(
9778 buffer.anchor_before(range_to_move.start)
9779 ..buffer.anchor_after(range_to_move.end),
9780 ) {
9781 let mut start = fold.range.start.to_point(&buffer);
9782 let mut end = fold.range.end.to_point(&buffer);
9783 start.row += row_delta;
9784 end.row += row_delta;
9785 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9786 }
9787 }
9788 }
9789
9790 // If we didn't move line(s), preserve the existing selections
9791 new_selections.append(&mut contiguous_row_selections);
9792 }
9793
9794 self.transact(window, cx, |this, window, cx| {
9795 this.unfold_ranges(&unfold_ranges, true, true, cx);
9796 this.buffer.update(cx, |buffer, cx| {
9797 for (range, text) in edits {
9798 buffer.edit([(range, text)], None, cx);
9799 }
9800 });
9801 this.fold_creases(refold_creases, true, window, cx);
9802 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9803 s.select(new_selections)
9804 });
9805 });
9806 }
9807
9808 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9809 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9810 let text_layout_details = &self.text_layout_details(window);
9811 self.transact(window, cx, |this, window, cx| {
9812 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9813 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9814 s.move_with(|display_map, selection| {
9815 if !selection.is_empty() {
9816 return;
9817 }
9818
9819 let mut head = selection.head();
9820 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9821 if head.column() == display_map.line_len(head.row()) {
9822 transpose_offset = display_map
9823 .buffer_snapshot
9824 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9825 }
9826
9827 if transpose_offset == 0 {
9828 return;
9829 }
9830
9831 *head.column_mut() += 1;
9832 head = display_map.clip_point(head, Bias::Right);
9833 let goal = SelectionGoal::HorizontalPosition(
9834 display_map
9835 .x_for_display_point(head, text_layout_details)
9836 .into(),
9837 );
9838 selection.collapse_to(head, goal);
9839
9840 let transpose_start = display_map
9841 .buffer_snapshot
9842 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9843 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9844 let transpose_end = display_map
9845 .buffer_snapshot
9846 .clip_offset(transpose_offset + 1, Bias::Right);
9847 if let Some(ch) =
9848 display_map.buffer_snapshot.chars_at(transpose_start).next()
9849 {
9850 edits.push((transpose_start..transpose_offset, String::new()));
9851 edits.push((transpose_end..transpose_end, ch.to_string()));
9852 }
9853 }
9854 });
9855 edits
9856 });
9857 this.buffer
9858 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9859 let selections = this.selections.all::<usize>(cx);
9860 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9861 s.select(selections);
9862 });
9863 });
9864 }
9865
9866 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9867 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9868 self.rewrap_impl(RewrapOptions::default(), cx)
9869 }
9870
9871 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9872 let buffer = self.buffer.read(cx).snapshot(cx);
9873 let selections = self.selections.all::<Point>(cx);
9874 let mut selections = selections.iter().peekable();
9875
9876 let mut edits = Vec::new();
9877 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9878
9879 while let Some(selection) = selections.next() {
9880 let mut start_row = selection.start.row;
9881 let mut end_row = selection.end.row;
9882
9883 // Skip selections that overlap with a range that has already been rewrapped.
9884 let selection_range = start_row..end_row;
9885 if rewrapped_row_ranges
9886 .iter()
9887 .any(|range| range.overlaps(&selection_range))
9888 {
9889 continue;
9890 }
9891
9892 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9893
9894 // Since not all lines in the selection may be at the same indent
9895 // level, choose the indent size that is the most common between all
9896 // of the lines.
9897 //
9898 // If there is a tie, we use the deepest indent.
9899 let (indent_size, indent_end) = {
9900 let mut indent_size_occurrences = HashMap::default();
9901 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9902
9903 for row in start_row..=end_row {
9904 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9905 rows_by_indent_size.entry(indent).or_default().push(row);
9906 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9907 }
9908
9909 let indent_size = indent_size_occurrences
9910 .into_iter()
9911 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9912 .map(|(indent, _)| indent)
9913 .unwrap_or_default();
9914 let row = rows_by_indent_size[&indent_size][0];
9915 let indent_end = Point::new(row, indent_size.len);
9916
9917 (indent_size, indent_end)
9918 };
9919
9920 let mut line_prefix = indent_size.chars().collect::<String>();
9921
9922 let mut inside_comment = false;
9923 if let Some(comment_prefix) =
9924 buffer
9925 .language_scope_at(selection.head())
9926 .and_then(|language| {
9927 language
9928 .line_comment_prefixes()
9929 .iter()
9930 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9931 .cloned()
9932 })
9933 {
9934 line_prefix.push_str(&comment_prefix);
9935 inside_comment = true;
9936 }
9937
9938 let language_settings = buffer.language_settings_at(selection.head(), cx);
9939 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9940 RewrapBehavior::InComments => inside_comment,
9941 RewrapBehavior::InSelections => !selection.is_empty(),
9942 RewrapBehavior::Anywhere => true,
9943 };
9944
9945 let should_rewrap = options.override_language_settings
9946 || allow_rewrap_based_on_language
9947 || self.hard_wrap.is_some();
9948 if !should_rewrap {
9949 continue;
9950 }
9951
9952 if selection.is_empty() {
9953 'expand_upwards: while start_row > 0 {
9954 let prev_row = start_row - 1;
9955 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9956 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9957 {
9958 start_row = prev_row;
9959 } else {
9960 break 'expand_upwards;
9961 }
9962 }
9963
9964 'expand_downwards: while end_row < buffer.max_point().row {
9965 let next_row = end_row + 1;
9966 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9967 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9968 {
9969 end_row = next_row;
9970 } else {
9971 break 'expand_downwards;
9972 }
9973 }
9974 }
9975
9976 let start = Point::new(start_row, 0);
9977 let start_offset = start.to_offset(&buffer);
9978 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9979 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9980 let Some(lines_without_prefixes) = selection_text
9981 .lines()
9982 .map(|line| {
9983 line.strip_prefix(&line_prefix)
9984 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9985 .ok_or_else(|| {
9986 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9987 })
9988 })
9989 .collect::<Result<Vec<_>, _>>()
9990 .log_err()
9991 else {
9992 continue;
9993 };
9994
9995 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9996 buffer
9997 .language_settings_at(Point::new(start_row, 0), cx)
9998 .preferred_line_length as usize
9999 });
10000 let wrapped_text = wrap_with_prefix(
10001 line_prefix,
10002 lines_without_prefixes.join("\n"),
10003 wrap_column,
10004 tab_size,
10005 options.preserve_existing_whitespace,
10006 );
10007
10008 // TODO: should always use char-based diff while still supporting cursor behavior that
10009 // matches vim.
10010 let mut diff_options = DiffOptions::default();
10011 if options.override_language_settings {
10012 diff_options.max_word_diff_len = 0;
10013 diff_options.max_word_diff_line_count = 0;
10014 } else {
10015 diff_options.max_word_diff_len = usize::MAX;
10016 diff_options.max_word_diff_line_count = usize::MAX;
10017 }
10018
10019 for (old_range, new_text) in
10020 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10021 {
10022 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10023 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10024 edits.push((edit_start..edit_end, new_text));
10025 }
10026
10027 rewrapped_row_ranges.push(start_row..=end_row);
10028 }
10029
10030 self.buffer
10031 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10032 }
10033
10034 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10035 let mut text = String::new();
10036 let buffer = self.buffer.read(cx).snapshot(cx);
10037 let mut selections = self.selections.all::<Point>(cx);
10038 let mut clipboard_selections = Vec::with_capacity(selections.len());
10039 {
10040 let max_point = buffer.max_point();
10041 let mut is_first = true;
10042 for selection in &mut selections {
10043 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10044 if is_entire_line {
10045 selection.start = Point::new(selection.start.row, 0);
10046 if !selection.is_empty() && selection.end.column == 0 {
10047 selection.end = cmp::min(max_point, selection.end);
10048 } else {
10049 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10050 }
10051 selection.goal = SelectionGoal::None;
10052 }
10053 if is_first {
10054 is_first = false;
10055 } else {
10056 text += "\n";
10057 }
10058 let mut len = 0;
10059 for chunk in buffer.text_for_range(selection.start..selection.end) {
10060 text.push_str(chunk);
10061 len += chunk.len();
10062 }
10063 clipboard_selections.push(ClipboardSelection {
10064 len,
10065 is_entire_line,
10066 first_line_indent: buffer
10067 .indent_size_for_line(MultiBufferRow(selection.start.row))
10068 .len,
10069 });
10070 }
10071 }
10072
10073 self.transact(window, cx, |this, window, cx| {
10074 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10075 s.select(selections);
10076 });
10077 this.insert("", window, cx);
10078 });
10079 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10080 }
10081
10082 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10083 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10084 let item = self.cut_common(window, cx);
10085 cx.write_to_clipboard(item);
10086 }
10087
10088 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10089 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10090 self.change_selections(None, window, cx, |s| {
10091 s.move_with(|snapshot, sel| {
10092 if sel.is_empty() {
10093 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10094 }
10095 });
10096 });
10097 let item = self.cut_common(window, cx);
10098 cx.set_global(KillRing(item))
10099 }
10100
10101 pub fn kill_ring_yank(
10102 &mut self,
10103 _: &KillRingYank,
10104 window: &mut Window,
10105 cx: &mut Context<Self>,
10106 ) {
10107 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10108 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10109 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10110 (kill_ring.text().to_string(), kill_ring.metadata_json())
10111 } else {
10112 return;
10113 }
10114 } else {
10115 return;
10116 };
10117 self.do_paste(&text, metadata, false, window, cx);
10118 }
10119
10120 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10121 self.do_copy(true, cx);
10122 }
10123
10124 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10125 self.do_copy(false, cx);
10126 }
10127
10128 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10129 let selections = self.selections.all::<Point>(cx);
10130 let buffer = self.buffer.read(cx).read(cx);
10131 let mut text = String::new();
10132
10133 let mut clipboard_selections = Vec::with_capacity(selections.len());
10134 {
10135 let max_point = buffer.max_point();
10136 let mut is_first = true;
10137 for selection in &selections {
10138 let mut start = selection.start;
10139 let mut end = selection.end;
10140 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10141 if is_entire_line {
10142 start = Point::new(start.row, 0);
10143 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10144 }
10145
10146 let mut trimmed_selections = Vec::new();
10147 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10148 let row = MultiBufferRow(start.row);
10149 let first_indent = buffer.indent_size_for_line(row);
10150 if first_indent.len == 0 || start.column > first_indent.len {
10151 trimmed_selections.push(start..end);
10152 } else {
10153 trimmed_selections.push(
10154 Point::new(row.0, first_indent.len)
10155 ..Point::new(row.0, buffer.line_len(row)),
10156 );
10157 for row in start.row + 1..=end.row {
10158 let mut line_len = buffer.line_len(MultiBufferRow(row));
10159 if row == end.row {
10160 line_len = end.column;
10161 }
10162 if line_len == 0 {
10163 trimmed_selections
10164 .push(Point::new(row, 0)..Point::new(row, line_len));
10165 continue;
10166 }
10167 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10168 if row_indent_size.len >= first_indent.len {
10169 trimmed_selections.push(
10170 Point::new(row, first_indent.len)..Point::new(row, line_len),
10171 );
10172 } else {
10173 trimmed_selections.clear();
10174 trimmed_selections.push(start..end);
10175 break;
10176 }
10177 }
10178 }
10179 } else {
10180 trimmed_selections.push(start..end);
10181 }
10182
10183 for trimmed_range in trimmed_selections {
10184 if is_first {
10185 is_first = false;
10186 } else {
10187 text += "\n";
10188 }
10189 let mut len = 0;
10190 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10191 text.push_str(chunk);
10192 len += chunk.len();
10193 }
10194 clipboard_selections.push(ClipboardSelection {
10195 len,
10196 is_entire_line,
10197 first_line_indent: buffer
10198 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10199 .len,
10200 });
10201 }
10202 }
10203 }
10204
10205 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10206 text,
10207 clipboard_selections,
10208 ));
10209 }
10210
10211 pub fn do_paste(
10212 &mut self,
10213 text: &String,
10214 clipboard_selections: Option<Vec<ClipboardSelection>>,
10215 handle_entire_lines: bool,
10216 window: &mut Window,
10217 cx: &mut Context<Self>,
10218 ) {
10219 if self.read_only(cx) {
10220 return;
10221 }
10222
10223 let clipboard_text = Cow::Borrowed(text);
10224
10225 self.transact(window, cx, |this, window, cx| {
10226 if let Some(mut clipboard_selections) = clipboard_selections {
10227 let old_selections = this.selections.all::<usize>(cx);
10228 let all_selections_were_entire_line =
10229 clipboard_selections.iter().all(|s| s.is_entire_line);
10230 let first_selection_indent_column =
10231 clipboard_selections.first().map(|s| s.first_line_indent);
10232 if clipboard_selections.len() != old_selections.len() {
10233 clipboard_selections.drain(..);
10234 }
10235 let cursor_offset = this.selections.last::<usize>(cx).head();
10236 let mut auto_indent_on_paste = true;
10237
10238 this.buffer.update(cx, |buffer, cx| {
10239 let snapshot = buffer.read(cx);
10240 auto_indent_on_paste = snapshot
10241 .language_settings_at(cursor_offset, cx)
10242 .auto_indent_on_paste;
10243
10244 let mut start_offset = 0;
10245 let mut edits = Vec::new();
10246 let mut original_indent_columns = Vec::new();
10247 for (ix, selection) in old_selections.iter().enumerate() {
10248 let to_insert;
10249 let entire_line;
10250 let original_indent_column;
10251 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10252 let end_offset = start_offset + clipboard_selection.len;
10253 to_insert = &clipboard_text[start_offset..end_offset];
10254 entire_line = clipboard_selection.is_entire_line;
10255 start_offset = end_offset + 1;
10256 original_indent_column = Some(clipboard_selection.first_line_indent);
10257 } else {
10258 to_insert = clipboard_text.as_str();
10259 entire_line = all_selections_were_entire_line;
10260 original_indent_column = first_selection_indent_column
10261 }
10262
10263 // If the corresponding selection was empty when this slice of the
10264 // clipboard text was written, then the entire line containing the
10265 // selection was copied. If this selection is also currently empty,
10266 // then paste the line before the current line of the buffer.
10267 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10268 let column = selection.start.to_point(&snapshot).column as usize;
10269 let line_start = selection.start - column;
10270 line_start..line_start
10271 } else {
10272 selection.range()
10273 };
10274
10275 edits.push((range, to_insert));
10276 original_indent_columns.push(original_indent_column);
10277 }
10278 drop(snapshot);
10279
10280 buffer.edit(
10281 edits,
10282 if auto_indent_on_paste {
10283 Some(AutoindentMode::Block {
10284 original_indent_columns,
10285 })
10286 } else {
10287 None
10288 },
10289 cx,
10290 );
10291 });
10292
10293 let selections = this.selections.all::<usize>(cx);
10294 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10295 s.select(selections)
10296 });
10297 } else {
10298 this.insert(&clipboard_text, window, cx);
10299 }
10300 });
10301 }
10302
10303 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10304 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10305 if let Some(item) = cx.read_from_clipboard() {
10306 let entries = item.entries();
10307
10308 match entries.first() {
10309 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10310 // of all the pasted entries.
10311 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10312 .do_paste(
10313 clipboard_string.text(),
10314 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10315 true,
10316 window,
10317 cx,
10318 ),
10319 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10320 }
10321 }
10322 }
10323
10324 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10325 if self.read_only(cx) {
10326 return;
10327 }
10328
10329 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10330
10331 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10332 if let Some((selections, _)) =
10333 self.selection_history.transaction(transaction_id).cloned()
10334 {
10335 self.change_selections(None, window, cx, |s| {
10336 s.select_anchors(selections.to_vec());
10337 });
10338 } else {
10339 log::error!(
10340 "No entry in selection_history found for undo. \
10341 This may correspond to a bug where undo does not update the selection. \
10342 If this is occurring, please add details to \
10343 https://github.com/zed-industries/zed/issues/22692"
10344 );
10345 }
10346 self.request_autoscroll(Autoscroll::fit(), cx);
10347 self.unmark_text(window, cx);
10348 self.refresh_inline_completion(true, false, window, cx);
10349 cx.emit(EditorEvent::Edited { transaction_id });
10350 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10351 }
10352 }
10353
10354 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10355 if self.read_only(cx) {
10356 return;
10357 }
10358
10359 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10360
10361 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10362 if let Some((_, Some(selections))) =
10363 self.selection_history.transaction(transaction_id).cloned()
10364 {
10365 self.change_selections(None, window, cx, |s| {
10366 s.select_anchors(selections.to_vec());
10367 });
10368 } else {
10369 log::error!(
10370 "No entry in selection_history found for redo. \
10371 This may correspond to a bug where undo does not update the selection. \
10372 If this is occurring, please add details to \
10373 https://github.com/zed-industries/zed/issues/22692"
10374 );
10375 }
10376 self.request_autoscroll(Autoscroll::fit(), cx);
10377 self.unmark_text(window, cx);
10378 self.refresh_inline_completion(true, false, window, cx);
10379 cx.emit(EditorEvent::Edited { transaction_id });
10380 }
10381 }
10382
10383 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10384 self.buffer
10385 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10386 }
10387
10388 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10389 self.buffer
10390 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10391 }
10392
10393 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10394 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10395 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10396 s.move_with(|map, selection| {
10397 let cursor = if selection.is_empty() {
10398 movement::left(map, selection.start)
10399 } else {
10400 selection.start
10401 };
10402 selection.collapse_to(cursor, SelectionGoal::None);
10403 });
10404 })
10405 }
10406
10407 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10408 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10409 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10410 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10411 })
10412 }
10413
10414 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10415 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10416 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10417 s.move_with(|map, selection| {
10418 let cursor = if selection.is_empty() {
10419 movement::right(map, selection.end)
10420 } else {
10421 selection.end
10422 };
10423 selection.collapse_to(cursor, SelectionGoal::None)
10424 });
10425 })
10426 }
10427
10428 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10429 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10430 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10431 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10432 })
10433 }
10434
10435 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10436 if self.take_rename(true, window, cx).is_some() {
10437 return;
10438 }
10439
10440 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10441 cx.propagate();
10442 return;
10443 }
10444
10445 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10446
10447 let text_layout_details = &self.text_layout_details(window);
10448 let selection_count = self.selections.count();
10449 let first_selection = self.selections.first_anchor();
10450
10451 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10452 s.move_with(|map, selection| {
10453 if !selection.is_empty() {
10454 selection.goal = SelectionGoal::None;
10455 }
10456 let (cursor, goal) = movement::up(
10457 map,
10458 selection.start,
10459 selection.goal,
10460 false,
10461 text_layout_details,
10462 );
10463 selection.collapse_to(cursor, goal);
10464 });
10465 });
10466
10467 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10468 {
10469 cx.propagate();
10470 }
10471 }
10472
10473 pub fn move_up_by_lines(
10474 &mut self,
10475 action: &MoveUpByLines,
10476 window: &mut Window,
10477 cx: &mut Context<Self>,
10478 ) {
10479 if self.take_rename(true, window, cx).is_some() {
10480 return;
10481 }
10482
10483 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10484 cx.propagate();
10485 return;
10486 }
10487
10488 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10489
10490 let text_layout_details = &self.text_layout_details(window);
10491
10492 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10493 s.move_with(|map, selection| {
10494 if !selection.is_empty() {
10495 selection.goal = SelectionGoal::None;
10496 }
10497 let (cursor, goal) = movement::up_by_rows(
10498 map,
10499 selection.start,
10500 action.lines,
10501 selection.goal,
10502 false,
10503 text_layout_details,
10504 );
10505 selection.collapse_to(cursor, goal);
10506 });
10507 })
10508 }
10509
10510 pub fn move_down_by_lines(
10511 &mut self,
10512 action: &MoveDownByLines,
10513 window: &mut Window,
10514 cx: &mut Context<Self>,
10515 ) {
10516 if self.take_rename(true, window, cx).is_some() {
10517 return;
10518 }
10519
10520 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10521 cx.propagate();
10522 return;
10523 }
10524
10525 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10526
10527 let text_layout_details = &self.text_layout_details(window);
10528
10529 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10530 s.move_with(|map, selection| {
10531 if !selection.is_empty() {
10532 selection.goal = SelectionGoal::None;
10533 }
10534 let (cursor, goal) = movement::down_by_rows(
10535 map,
10536 selection.start,
10537 action.lines,
10538 selection.goal,
10539 false,
10540 text_layout_details,
10541 );
10542 selection.collapse_to(cursor, goal);
10543 });
10544 })
10545 }
10546
10547 pub fn select_down_by_lines(
10548 &mut self,
10549 action: &SelectDownByLines,
10550 window: &mut Window,
10551 cx: &mut Context<Self>,
10552 ) {
10553 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10554 let text_layout_details = &self.text_layout_details(window);
10555 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10556 s.move_heads_with(|map, head, goal| {
10557 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10558 })
10559 })
10560 }
10561
10562 pub fn select_up_by_lines(
10563 &mut self,
10564 action: &SelectUpByLines,
10565 window: &mut Window,
10566 cx: &mut Context<Self>,
10567 ) {
10568 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10569 let text_layout_details = &self.text_layout_details(window);
10570 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10571 s.move_heads_with(|map, head, goal| {
10572 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10573 })
10574 })
10575 }
10576
10577 pub fn select_page_up(
10578 &mut self,
10579 _: &SelectPageUp,
10580 window: &mut Window,
10581 cx: &mut Context<Self>,
10582 ) {
10583 let Some(row_count) = self.visible_row_count() else {
10584 return;
10585 };
10586
10587 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10588
10589 let text_layout_details = &self.text_layout_details(window);
10590
10591 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10592 s.move_heads_with(|map, head, goal| {
10593 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10594 })
10595 })
10596 }
10597
10598 pub fn move_page_up(
10599 &mut self,
10600 action: &MovePageUp,
10601 window: &mut Window,
10602 cx: &mut Context<Self>,
10603 ) {
10604 if self.take_rename(true, window, cx).is_some() {
10605 return;
10606 }
10607
10608 if self
10609 .context_menu
10610 .borrow_mut()
10611 .as_mut()
10612 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10613 .unwrap_or(false)
10614 {
10615 return;
10616 }
10617
10618 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10619 cx.propagate();
10620 return;
10621 }
10622
10623 let Some(row_count) = self.visible_row_count() else {
10624 return;
10625 };
10626
10627 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10628
10629 let autoscroll = if action.center_cursor {
10630 Autoscroll::center()
10631 } else {
10632 Autoscroll::fit()
10633 };
10634
10635 let text_layout_details = &self.text_layout_details(window);
10636
10637 self.change_selections(Some(autoscroll), window, cx, |s| {
10638 s.move_with(|map, selection| {
10639 if !selection.is_empty() {
10640 selection.goal = SelectionGoal::None;
10641 }
10642 let (cursor, goal) = movement::up_by_rows(
10643 map,
10644 selection.end,
10645 row_count,
10646 selection.goal,
10647 false,
10648 text_layout_details,
10649 );
10650 selection.collapse_to(cursor, goal);
10651 });
10652 });
10653 }
10654
10655 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10656 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10657 let text_layout_details = &self.text_layout_details(window);
10658 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10659 s.move_heads_with(|map, head, goal| {
10660 movement::up(map, head, goal, false, text_layout_details)
10661 })
10662 })
10663 }
10664
10665 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10666 self.take_rename(true, window, cx);
10667
10668 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10669 cx.propagate();
10670 return;
10671 }
10672
10673 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10674
10675 let text_layout_details = &self.text_layout_details(window);
10676 let selection_count = self.selections.count();
10677 let first_selection = self.selections.first_anchor();
10678
10679 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10680 s.move_with(|map, selection| {
10681 if !selection.is_empty() {
10682 selection.goal = SelectionGoal::None;
10683 }
10684 let (cursor, goal) = movement::down(
10685 map,
10686 selection.end,
10687 selection.goal,
10688 false,
10689 text_layout_details,
10690 );
10691 selection.collapse_to(cursor, goal);
10692 });
10693 });
10694
10695 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10696 {
10697 cx.propagate();
10698 }
10699 }
10700
10701 pub fn select_page_down(
10702 &mut self,
10703 _: &SelectPageDown,
10704 window: &mut Window,
10705 cx: &mut Context<Self>,
10706 ) {
10707 let Some(row_count) = self.visible_row_count() else {
10708 return;
10709 };
10710
10711 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10712
10713 let text_layout_details = &self.text_layout_details(window);
10714
10715 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10716 s.move_heads_with(|map, head, goal| {
10717 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10718 })
10719 })
10720 }
10721
10722 pub fn move_page_down(
10723 &mut self,
10724 action: &MovePageDown,
10725 window: &mut Window,
10726 cx: &mut Context<Self>,
10727 ) {
10728 if self.take_rename(true, window, cx).is_some() {
10729 return;
10730 }
10731
10732 if self
10733 .context_menu
10734 .borrow_mut()
10735 .as_mut()
10736 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10737 .unwrap_or(false)
10738 {
10739 return;
10740 }
10741
10742 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10743 cx.propagate();
10744 return;
10745 }
10746
10747 let Some(row_count) = self.visible_row_count() else {
10748 return;
10749 };
10750
10751 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10752
10753 let autoscroll = if action.center_cursor {
10754 Autoscroll::center()
10755 } else {
10756 Autoscroll::fit()
10757 };
10758
10759 let text_layout_details = &self.text_layout_details(window);
10760 self.change_selections(Some(autoscroll), window, cx, |s| {
10761 s.move_with(|map, selection| {
10762 if !selection.is_empty() {
10763 selection.goal = SelectionGoal::None;
10764 }
10765 let (cursor, goal) = movement::down_by_rows(
10766 map,
10767 selection.end,
10768 row_count,
10769 selection.goal,
10770 false,
10771 text_layout_details,
10772 );
10773 selection.collapse_to(cursor, goal);
10774 });
10775 });
10776 }
10777
10778 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10779 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10780 let text_layout_details = &self.text_layout_details(window);
10781 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10782 s.move_heads_with(|map, head, goal| {
10783 movement::down(map, head, goal, false, text_layout_details)
10784 })
10785 });
10786 }
10787
10788 pub fn context_menu_first(
10789 &mut self,
10790 _: &ContextMenuFirst,
10791 _window: &mut Window,
10792 cx: &mut Context<Self>,
10793 ) {
10794 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10795 context_menu.select_first(self.completion_provider.as_deref(), cx);
10796 }
10797 }
10798
10799 pub fn context_menu_prev(
10800 &mut self,
10801 _: &ContextMenuPrevious,
10802 _window: &mut Window,
10803 cx: &mut Context<Self>,
10804 ) {
10805 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10806 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10807 }
10808 }
10809
10810 pub fn context_menu_next(
10811 &mut self,
10812 _: &ContextMenuNext,
10813 _window: &mut Window,
10814 cx: &mut Context<Self>,
10815 ) {
10816 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10817 context_menu.select_next(self.completion_provider.as_deref(), cx);
10818 }
10819 }
10820
10821 pub fn context_menu_last(
10822 &mut self,
10823 _: &ContextMenuLast,
10824 _window: &mut Window,
10825 cx: &mut Context<Self>,
10826 ) {
10827 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10828 context_menu.select_last(self.completion_provider.as_deref(), cx);
10829 }
10830 }
10831
10832 pub fn move_to_previous_word_start(
10833 &mut self,
10834 _: &MoveToPreviousWordStart,
10835 window: &mut Window,
10836 cx: &mut Context<Self>,
10837 ) {
10838 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10839 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10840 s.move_cursors_with(|map, head, _| {
10841 (
10842 movement::previous_word_start(map, head),
10843 SelectionGoal::None,
10844 )
10845 });
10846 })
10847 }
10848
10849 pub fn move_to_previous_subword_start(
10850 &mut self,
10851 _: &MoveToPreviousSubwordStart,
10852 window: &mut Window,
10853 cx: &mut Context<Self>,
10854 ) {
10855 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10856 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10857 s.move_cursors_with(|map, head, _| {
10858 (
10859 movement::previous_subword_start(map, head),
10860 SelectionGoal::None,
10861 )
10862 });
10863 })
10864 }
10865
10866 pub fn select_to_previous_word_start(
10867 &mut self,
10868 _: &SelectToPreviousWordStart,
10869 window: &mut Window,
10870 cx: &mut Context<Self>,
10871 ) {
10872 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10873 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10874 s.move_heads_with(|map, head, _| {
10875 (
10876 movement::previous_word_start(map, head),
10877 SelectionGoal::None,
10878 )
10879 });
10880 })
10881 }
10882
10883 pub fn select_to_previous_subword_start(
10884 &mut self,
10885 _: &SelectToPreviousSubwordStart,
10886 window: &mut Window,
10887 cx: &mut Context<Self>,
10888 ) {
10889 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10890 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10891 s.move_heads_with(|map, head, _| {
10892 (
10893 movement::previous_subword_start(map, head),
10894 SelectionGoal::None,
10895 )
10896 });
10897 })
10898 }
10899
10900 pub fn delete_to_previous_word_start(
10901 &mut self,
10902 action: &DeleteToPreviousWordStart,
10903 window: &mut Window,
10904 cx: &mut Context<Self>,
10905 ) {
10906 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10907 self.transact(window, cx, |this, window, cx| {
10908 this.select_autoclose_pair(window, cx);
10909 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10910 s.move_with(|map, selection| {
10911 if selection.is_empty() {
10912 let cursor = if action.ignore_newlines {
10913 movement::previous_word_start(map, selection.head())
10914 } else {
10915 movement::previous_word_start_or_newline(map, selection.head())
10916 };
10917 selection.set_head(cursor, SelectionGoal::None);
10918 }
10919 });
10920 });
10921 this.insert("", window, cx);
10922 });
10923 }
10924
10925 pub fn delete_to_previous_subword_start(
10926 &mut self,
10927 _: &DeleteToPreviousSubwordStart,
10928 window: &mut Window,
10929 cx: &mut Context<Self>,
10930 ) {
10931 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10932 self.transact(window, cx, |this, window, cx| {
10933 this.select_autoclose_pair(window, cx);
10934 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10935 s.move_with(|map, selection| {
10936 if selection.is_empty() {
10937 let cursor = movement::previous_subword_start(map, selection.head());
10938 selection.set_head(cursor, SelectionGoal::None);
10939 }
10940 });
10941 });
10942 this.insert("", window, cx);
10943 });
10944 }
10945
10946 pub fn move_to_next_word_end(
10947 &mut self,
10948 _: &MoveToNextWordEnd,
10949 window: &mut Window,
10950 cx: &mut Context<Self>,
10951 ) {
10952 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10953 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10954 s.move_cursors_with(|map, head, _| {
10955 (movement::next_word_end(map, head), SelectionGoal::None)
10956 });
10957 })
10958 }
10959
10960 pub fn move_to_next_subword_end(
10961 &mut self,
10962 _: &MoveToNextSubwordEnd,
10963 window: &mut Window,
10964 cx: &mut Context<Self>,
10965 ) {
10966 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10967 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10968 s.move_cursors_with(|map, head, _| {
10969 (movement::next_subword_end(map, head), SelectionGoal::None)
10970 });
10971 })
10972 }
10973
10974 pub fn select_to_next_word_end(
10975 &mut self,
10976 _: &SelectToNextWordEnd,
10977 window: &mut Window,
10978 cx: &mut Context<Self>,
10979 ) {
10980 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10981 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10982 s.move_heads_with(|map, head, _| {
10983 (movement::next_word_end(map, head), SelectionGoal::None)
10984 });
10985 })
10986 }
10987
10988 pub fn select_to_next_subword_end(
10989 &mut self,
10990 _: &SelectToNextSubwordEnd,
10991 window: &mut Window,
10992 cx: &mut Context<Self>,
10993 ) {
10994 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10995 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10996 s.move_heads_with(|map, head, _| {
10997 (movement::next_subword_end(map, head), SelectionGoal::None)
10998 });
10999 })
11000 }
11001
11002 pub fn delete_to_next_word_end(
11003 &mut self,
11004 action: &DeleteToNextWordEnd,
11005 window: &mut Window,
11006 cx: &mut Context<Self>,
11007 ) {
11008 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11009 self.transact(window, cx, |this, window, cx| {
11010 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11011 s.move_with(|map, selection| {
11012 if selection.is_empty() {
11013 let cursor = if action.ignore_newlines {
11014 movement::next_word_end(map, selection.head())
11015 } else {
11016 movement::next_word_end_or_newline(map, selection.head())
11017 };
11018 selection.set_head(cursor, SelectionGoal::None);
11019 }
11020 });
11021 });
11022 this.insert("", window, cx);
11023 });
11024 }
11025
11026 pub fn delete_to_next_subword_end(
11027 &mut self,
11028 _: &DeleteToNextSubwordEnd,
11029 window: &mut Window,
11030 cx: &mut Context<Self>,
11031 ) {
11032 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11033 self.transact(window, cx, |this, window, cx| {
11034 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11035 s.move_with(|map, selection| {
11036 if selection.is_empty() {
11037 let cursor = movement::next_subword_end(map, selection.head());
11038 selection.set_head(cursor, SelectionGoal::None);
11039 }
11040 });
11041 });
11042 this.insert("", window, cx);
11043 });
11044 }
11045
11046 pub fn move_to_beginning_of_line(
11047 &mut self,
11048 action: &MoveToBeginningOfLine,
11049 window: &mut Window,
11050 cx: &mut Context<Self>,
11051 ) {
11052 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11053 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11054 s.move_cursors_with(|map, head, _| {
11055 (
11056 movement::indented_line_beginning(
11057 map,
11058 head,
11059 action.stop_at_soft_wraps,
11060 action.stop_at_indent,
11061 ),
11062 SelectionGoal::None,
11063 )
11064 });
11065 })
11066 }
11067
11068 pub fn select_to_beginning_of_line(
11069 &mut self,
11070 action: &SelectToBeginningOfLine,
11071 window: &mut Window,
11072 cx: &mut Context<Self>,
11073 ) {
11074 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11075 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11076 s.move_heads_with(|map, head, _| {
11077 (
11078 movement::indented_line_beginning(
11079 map,
11080 head,
11081 action.stop_at_soft_wraps,
11082 action.stop_at_indent,
11083 ),
11084 SelectionGoal::None,
11085 )
11086 });
11087 });
11088 }
11089
11090 pub fn delete_to_beginning_of_line(
11091 &mut self,
11092 action: &DeleteToBeginningOfLine,
11093 window: &mut Window,
11094 cx: &mut Context<Self>,
11095 ) {
11096 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11097 self.transact(window, cx, |this, window, cx| {
11098 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11099 s.move_with(|_, selection| {
11100 selection.reversed = true;
11101 });
11102 });
11103
11104 this.select_to_beginning_of_line(
11105 &SelectToBeginningOfLine {
11106 stop_at_soft_wraps: false,
11107 stop_at_indent: action.stop_at_indent,
11108 },
11109 window,
11110 cx,
11111 );
11112 this.backspace(&Backspace, window, cx);
11113 });
11114 }
11115
11116 pub fn move_to_end_of_line(
11117 &mut self,
11118 action: &MoveToEndOfLine,
11119 window: &mut Window,
11120 cx: &mut Context<Self>,
11121 ) {
11122 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11123 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11124 s.move_cursors_with(|map, head, _| {
11125 (
11126 movement::line_end(map, head, action.stop_at_soft_wraps),
11127 SelectionGoal::None,
11128 )
11129 });
11130 })
11131 }
11132
11133 pub fn select_to_end_of_line(
11134 &mut self,
11135 action: &SelectToEndOfLine,
11136 window: &mut Window,
11137 cx: &mut Context<Self>,
11138 ) {
11139 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11140 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11141 s.move_heads_with(|map, head, _| {
11142 (
11143 movement::line_end(map, head, action.stop_at_soft_wraps),
11144 SelectionGoal::None,
11145 )
11146 });
11147 })
11148 }
11149
11150 pub fn delete_to_end_of_line(
11151 &mut self,
11152 _: &DeleteToEndOfLine,
11153 window: &mut Window,
11154 cx: &mut Context<Self>,
11155 ) {
11156 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11157 self.transact(window, cx, |this, window, cx| {
11158 this.select_to_end_of_line(
11159 &SelectToEndOfLine {
11160 stop_at_soft_wraps: false,
11161 },
11162 window,
11163 cx,
11164 );
11165 this.delete(&Delete, window, cx);
11166 });
11167 }
11168
11169 pub fn cut_to_end_of_line(
11170 &mut self,
11171 _: &CutToEndOfLine,
11172 window: &mut Window,
11173 cx: &mut Context<Self>,
11174 ) {
11175 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11176 self.transact(window, cx, |this, window, cx| {
11177 this.select_to_end_of_line(
11178 &SelectToEndOfLine {
11179 stop_at_soft_wraps: false,
11180 },
11181 window,
11182 cx,
11183 );
11184 this.cut(&Cut, window, cx);
11185 });
11186 }
11187
11188 pub fn move_to_start_of_paragraph(
11189 &mut self,
11190 _: &MoveToStartOfParagraph,
11191 window: &mut Window,
11192 cx: &mut Context<Self>,
11193 ) {
11194 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11195 cx.propagate();
11196 return;
11197 }
11198 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11199 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11200 s.move_with(|map, selection| {
11201 selection.collapse_to(
11202 movement::start_of_paragraph(map, selection.head(), 1),
11203 SelectionGoal::None,
11204 )
11205 });
11206 })
11207 }
11208
11209 pub fn move_to_end_of_paragraph(
11210 &mut self,
11211 _: &MoveToEndOfParagraph,
11212 window: &mut Window,
11213 cx: &mut Context<Self>,
11214 ) {
11215 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11216 cx.propagate();
11217 return;
11218 }
11219 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11220 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11221 s.move_with(|map, selection| {
11222 selection.collapse_to(
11223 movement::end_of_paragraph(map, selection.head(), 1),
11224 SelectionGoal::None,
11225 )
11226 });
11227 })
11228 }
11229
11230 pub fn select_to_start_of_paragraph(
11231 &mut self,
11232 _: &SelectToStartOfParagraph,
11233 window: &mut Window,
11234 cx: &mut Context<Self>,
11235 ) {
11236 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11237 cx.propagate();
11238 return;
11239 }
11240 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11241 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11242 s.move_heads_with(|map, head, _| {
11243 (
11244 movement::start_of_paragraph(map, head, 1),
11245 SelectionGoal::None,
11246 )
11247 });
11248 })
11249 }
11250
11251 pub fn select_to_end_of_paragraph(
11252 &mut self,
11253 _: &SelectToEndOfParagraph,
11254 window: &mut Window,
11255 cx: &mut Context<Self>,
11256 ) {
11257 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11258 cx.propagate();
11259 return;
11260 }
11261 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11262 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11263 s.move_heads_with(|map, head, _| {
11264 (
11265 movement::end_of_paragraph(map, head, 1),
11266 SelectionGoal::None,
11267 )
11268 });
11269 })
11270 }
11271
11272 pub fn move_to_start_of_excerpt(
11273 &mut self,
11274 _: &MoveToStartOfExcerpt,
11275 window: &mut Window,
11276 cx: &mut Context<Self>,
11277 ) {
11278 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11279 cx.propagate();
11280 return;
11281 }
11282 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11283 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11284 s.move_with(|map, selection| {
11285 selection.collapse_to(
11286 movement::start_of_excerpt(
11287 map,
11288 selection.head(),
11289 workspace::searchable::Direction::Prev,
11290 ),
11291 SelectionGoal::None,
11292 )
11293 });
11294 })
11295 }
11296
11297 pub fn move_to_start_of_next_excerpt(
11298 &mut self,
11299 _: &MoveToStartOfNextExcerpt,
11300 window: &mut Window,
11301 cx: &mut Context<Self>,
11302 ) {
11303 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11304 cx.propagate();
11305 return;
11306 }
11307
11308 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11309 s.move_with(|map, selection| {
11310 selection.collapse_to(
11311 movement::start_of_excerpt(
11312 map,
11313 selection.head(),
11314 workspace::searchable::Direction::Next,
11315 ),
11316 SelectionGoal::None,
11317 )
11318 });
11319 })
11320 }
11321
11322 pub fn move_to_end_of_excerpt(
11323 &mut self,
11324 _: &MoveToEndOfExcerpt,
11325 window: &mut Window,
11326 cx: &mut Context<Self>,
11327 ) {
11328 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11329 cx.propagate();
11330 return;
11331 }
11332 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11333 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11334 s.move_with(|map, selection| {
11335 selection.collapse_to(
11336 movement::end_of_excerpt(
11337 map,
11338 selection.head(),
11339 workspace::searchable::Direction::Next,
11340 ),
11341 SelectionGoal::None,
11342 )
11343 });
11344 })
11345 }
11346
11347 pub fn move_to_end_of_previous_excerpt(
11348 &mut self,
11349 _: &MoveToEndOfPreviousExcerpt,
11350 window: &mut Window,
11351 cx: &mut Context<Self>,
11352 ) {
11353 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11354 cx.propagate();
11355 return;
11356 }
11357 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11358 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11359 s.move_with(|map, selection| {
11360 selection.collapse_to(
11361 movement::end_of_excerpt(
11362 map,
11363 selection.head(),
11364 workspace::searchable::Direction::Prev,
11365 ),
11366 SelectionGoal::None,
11367 )
11368 });
11369 })
11370 }
11371
11372 pub fn select_to_start_of_excerpt(
11373 &mut self,
11374 _: &SelectToStartOfExcerpt,
11375 window: &mut Window,
11376 cx: &mut Context<Self>,
11377 ) {
11378 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11379 cx.propagate();
11380 return;
11381 }
11382 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11383 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11384 s.move_heads_with(|map, head, _| {
11385 (
11386 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11387 SelectionGoal::None,
11388 )
11389 });
11390 })
11391 }
11392
11393 pub fn select_to_start_of_next_excerpt(
11394 &mut self,
11395 _: &SelectToStartOfNextExcerpt,
11396 window: &mut Window,
11397 cx: &mut Context<Self>,
11398 ) {
11399 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11400 cx.propagate();
11401 return;
11402 }
11403 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11404 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11405 s.move_heads_with(|map, head, _| {
11406 (
11407 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11408 SelectionGoal::None,
11409 )
11410 });
11411 })
11412 }
11413
11414 pub fn select_to_end_of_excerpt(
11415 &mut self,
11416 _: &SelectToEndOfExcerpt,
11417 window: &mut Window,
11418 cx: &mut Context<Self>,
11419 ) {
11420 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11421 cx.propagate();
11422 return;
11423 }
11424 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11425 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11426 s.move_heads_with(|map, head, _| {
11427 (
11428 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11429 SelectionGoal::None,
11430 )
11431 });
11432 })
11433 }
11434
11435 pub fn select_to_end_of_previous_excerpt(
11436 &mut self,
11437 _: &SelectToEndOfPreviousExcerpt,
11438 window: &mut Window,
11439 cx: &mut Context<Self>,
11440 ) {
11441 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11442 cx.propagate();
11443 return;
11444 }
11445 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11446 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11447 s.move_heads_with(|map, head, _| {
11448 (
11449 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11450 SelectionGoal::None,
11451 )
11452 });
11453 })
11454 }
11455
11456 pub fn move_to_beginning(
11457 &mut self,
11458 _: &MoveToBeginning,
11459 window: &mut Window,
11460 cx: &mut Context<Self>,
11461 ) {
11462 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11463 cx.propagate();
11464 return;
11465 }
11466 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11467 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11468 s.select_ranges(vec![0..0]);
11469 });
11470 }
11471
11472 pub fn select_to_beginning(
11473 &mut self,
11474 _: &SelectToBeginning,
11475 window: &mut Window,
11476 cx: &mut Context<Self>,
11477 ) {
11478 let mut selection = self.selections.last::<Point>(cx);
11479 selection.set_head(Point::zero(), SelectionGoal::None);
11480 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11481 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11482 s.select(vec![selection]);
11483 });
11484 }
11485
11486 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11487 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11488 cx.propagate();
11489 return;
11490 }
11491 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11492 let cursor = self.buffer.read(cx).read(cx).len();
11493 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11494 s.select_ranges(vec![cursor..cursor])
11495 });
11496 }
11497
11498 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11499 self.nav_history = nav_history;
11500 }
11501
11502 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11503 self.nav_history.as_ref()
11504 }
11505
11506 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11507 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11508 }
11509
11510 fn push_to_nav_history(
11511 &mut self,
11512 cursor_anchor: Anchor,
11513 new_position: Option<Point>,
11514 is_deactivate: bool,
11515 cx: &mut Context<Self>,
11516 ) {
11517 if let Some(nav_history) = self.nav_history.as_mut() {
11518 let buffer = self.buffer.read(cx).read(cx);
11519 let cursor_position = cursor_anchor.to_point(&buffer);
11520 let scroll_state = self.scroll_manager.anchor();
11521 let scroll_top_row = scroll_state.top_row(&buffer);
11522 drop(buffer);
11523
11524 if let Some(new_position) = new_position {
11525 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11526 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11527 return;
11528 }
11529 }
11530
11531 nav_history.push(
11532 Some(NavigationData {
11533 cursor_anchor,
11534 cursor_position,
11535 scroll_anchor: scroll_state,
11536 scroll_top_row,
11537 }),
11538 cx,
11539 );
11540 cx.emit(EditorEvent::PushedToNavHistory {
11541 anchor: cursor_anchor,
11542 is_deactivate,
11543 })
11544 }
11545 }
11546
11547 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11548 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11549 let buffer = self.buffer.read(cx).snapshot(cx);
11550 let mut selection = self.selections.first::<usize>(cx);
11551 selection.set_head(buffer.len(), SelectionGoal::None);
11552 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11553 s.select(vec![selection]);
11554 });
11555 }
11556
11557 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11558 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11559 let end = self.buffer.read(cx).read(cx).len();
11560 self.change_selections(None, window, cx, |s| {
11561 s.select_ranges(vec![0..end]);
11562 });
11563 }
11564
11565 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11566 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11567 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11568 let mut selections = self.selections.all::<Point>(cx);
11569 let max_point = display_map.buffer_snapshot.max_point();
11570 for selection in &mut selections {
11571 let rows = selection.spanned_rows(true, &display_map);
11572 selection.start = Point::new(rows.start.0, 0);
11573 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11574 selection.reversed = false;
11575 }
11576 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11577 s.select(selections);
11578 });
11579 }
11580
11581 pub fn split_selection_into_lines(
11582 &mut self,
11583 _: &SplitSelectionIntoLines,
11584 window: &mut Window,
11585 cx: &mut Context<Self>,
11586 ) {
11587 let selections = self
11588 .selections
11589 .all::<Point>(cx)
11590 .into_iter()
11591 .map(|selection| selection.start..selection.end)
11592 .collect::<Vec<_>>();
11593 self.unfold_ranges(&selections, true, true, cx);
11594
11595 let mut new_selection_ranges = Vec::new();
11596 {
11597 let buffer = self.buffer.read(cx).read(cx);
11598 for selection in selections {
11599 for row in selection.start.row..selection.end.row {
11600 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11601 new_selection_ranges.push(cursor..cursor);
11602 }
11603
11604 let is_multiline_selection = selection.start.row != selection.end.row;
11605 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11606 // so this action feels more ergonomic when paired with other selection operations
11607 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11608 if !should_skip_last {
11609 new_selection_ranges.push(selection.end..selection.end);
11610 }
11611 }
11612 }
11613 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11614 s.select_ranges(new_selection_ranges);
11615 });
11616 }
11617
11618 pub fn add_selection_above(
11619 &mut self,
11620 _: &AddSelectionAbove,
11621 window: &mut Window,
11622 cx: &mut Context<Self>,
11623 ) {
11624 self.add_selection(true, window, cx);
11625 }
11626
11627 pub fn add_selection_below(
11628 &mut self,
11629 _: &AddSelectionBelow,
11630 window: &mut Window,
11631 cx: &mut Context<Self>,
11632 ) {
11633 self.add_selection(false, window, cx);
11634 }
11635
11636 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11637 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11638
11639 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11640 let mut selections = self.selections.all::<Point>(cx);
11641 let text_layout_details = self.text_layout_details(window);
11642 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11643 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11644 let range = oldest_selection.display_range(&display_map).sorted();
11645
11646 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11647 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11648 let positions = start_x.min(end_x)..start_x.max(end_x);
11649
11650 selections.clear();
11651 let mut stack = Vec::new();
11652 for row in range.start.row().0..=range.end.row().0 {
11653 if let Some(selection) = self.selections.build_columnar_selection(
11654 &display_map,
11655 DisplayRow(row),
11656 &positions,
11657 oldest_selection.reversed,
11658 &text_layout_details,
11659 ) {
11660 stack.push(selection.id);
11661 selections.push(selection);
11662 }
11663 }
11664
11665 if above {
11666 stack.reverse();
11667 }
11668
11669 AddSelectionsState { above, stack }
11670 });
11671
11672 let last_added_selection = *state.stack.last().unwrap();
11673 let mut new_selections = Vec::new();
11674 if above == state.above {
11675 let end_row = if above {
11676 DisplayRow(0)
11677 } else {
11678 display_map.max_point().row()
11679 };
11680
11681 'outer: for selection in selections {
11682 if selection.id == last_added_selection {
11683 let range = selection.display_range(&display_map).sorted();
11684 debug_assert_eq!(range.start.row(), range.end.row());
11685 let mut row = range.start.row();
11686 let positions =
11687 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11688 px(start)..px(end)
11689 } else {
11690 let start_x =
11691 display_map.x_for_display_point(range.start, &text_layout_details);
11692 let end_x =
11693 display_map.x_for_display_point(range.end, &text_layout_details);
11694 start_x.min(end_x)..start_x.max(end_x)
11695 };
11696
11697 while row != end_row {
11698 if above {
11699 row.0 -= 1;
11700 } else {
11701 row.0 += 1;
11702 }
11703
11704 if let Some(new_selection) = self.selections.build_columnar_selection(
11705 &display_map,
11706 row,
11707 &positions,
11708 selection.reversed,
11709 &text_layout_details,
11710 ) {
11711 state.stack.push(new_selection.id);
11712 if above {
11713 new_selections.push(new_selection);
11714 new_selections.push(selection);
11715 } else {
11716 new_selections.push(selection);
11717 new_selections.push(new_selection);
11718 }
11719
11720 continue 'outer;
11721 }
11722 }
11723 }
11724
11725 new_selections.push(selection);
11726 }
11727 } else {
11728 new_selections = selections;
11729 new_selections.retain(|s| s.id != last_added_selection);
11730 state.stack.pop();
11731 }
11732
11733 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11734 s.select(new_selections);
11735 });
11736 if state.stack.len() > 1 {
11737 self.add_selections_state = Some(state);
11738 }
11739 }
11740
11741 pub fn select_next_match_internal(
11742 &mut self,
11743 display_map: &DisplaySnapshot,
11744 replace_newest: bool,
11745 autoscroll: Option<Autoscroll>,
11746 window: &mut Window,
11747 cx: &mut Context<Self>,
11748 ) -> Result<()> {
11749 fn select_next_match_ranges(
11750 this: &mut Editor,
11751 range: Range<usize>,
11752 replace_newest: bool,
11753 auto_scroll: Option<Autoscroll>,
11754 window: &mut Window,
11755 cx: &mut Context<Editor>,
11756 ) {
11757 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11758 this.change_selections(auto_scroll, window, cx, |s| {
11759 if replace_newest {
11760 s.delete(s.newest_anchor().id);
11761 }
11762 s.insert_range(range.clone());
11763 });
11764 }
11765
11766 let buffer = &display_map.buffer_snapshot;
11767 let mut selections = self.selections.all::<usize>(cx);
11768 if let Some(mut select_next_state) = self.select_next_state.take() {
11769 let query = &select_next_state.query;
11770 if !select_next_state.done {
11771 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11772 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11773 let mut next_selected_range = None;
11774
11775 let bytes_after_last_selection =
11776 buffer.bytes_in_range(last_selection.end..buffer.len());
11777 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11778 let query_matches = query
11779 .stream_find_iter(bytes_after_last_selection)
11780 .map(|result| (last_selection.end, result))
11781 .chain(
11782 query
11783 .stream_find_iter(bytes_before_first_selection)
11784 .map(|result| (0, result)),
11785 );
11786
11787 for (start_offset, query_match) in query_matches {
11788 let query_match = query_match.unwrap(); // can only fail due to I/O
11789 let offset_range =
11790 start_offset + query_match.start()..start_offset + query_match.end();
11791 let display_range = offset_range.start.to_display_point(display_map)
11792 ..offset_range.end.to_display_point(display_map);
11793
11794 if !select_next_state.wordwise
11795 || (!movement::is_inside_word(display_map, display_range.start)
11796 && !movement::is_inside_word(display_map, display_range.end))
11797 {
11798 // TODO: This is n^2, because we might check all the selections
11799 if !selections
11800 .iter()
11801 .any(|selection| selection.range().overlaps(&offset_range))
11802 {
11803 next_selected_range = Some(offset_range);
11804 break;
11805 }
11806 }
11807 }
11808
11809 if let Some(next_selected_range) = next_selected_range {
11810 select_next_match_ranges(
11811 self,
11812 next_selected_range,
11813 replace_newest,
11814 autoscroll,
11815 window,
11816 cx,
11817 );
11818 } else {
11819 select_next_state.done = true;
11820 }
11821 }
11822
11823 self.select_next_state = Some(select_next_state);
11824 } else {
11825 let mut only_carets = true;
11826 let mut same_text_selected = true;
11827 let mut selected_text = None;
11828
11829 let mut selections_iter = selections.iter().peekable();
11830 while let Some(selection) = selections_iter.next() {
11831 if selection.start != selection.end {
11832 only_carets = false;
11833 }
11834
11835 if same_text_selected {
11836 if selected_text.is_none() {
11837 selected_text =
11838 Some(buffer.text_for_range(selection.range()).collect::<String>());
11839 }
11840
11841 if let Some(next_selection) = selections_iter.peek() {
11842 if next_selection.range().len() == selection.range().len() {
11843 let next_selected_text = buffer
11844 .text_for_range(next_selection.range())
11845 .collect::<String>();
11846 if Some(next_selected_text) != selected_text {
11847 same_text_selected = false;
11848 selected_text = None;
11849 }
11850 } else {
11851 same_text_selected = false;
11852 selected_text = None;
11853 }
11854 }
11855 }
11856 }
11857
11858 if only_carets {
11859 for selection in &mut selections {
11860 let word_range = movement::surrounding_word(
11861 display_map,
11862 selection.start.to_display_point(display_map),
11863 );
11864 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11865 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11866 selection.goal = SelectionGoal::None;
11867 selection.reversed = false;
11868 select_next_match_ranges(
11869 self,
11870 selection.start..selection.end,
11871 replace_newest,
11872 autoscroll,
11873 window,
11874 cx,
11875 );
11876 }
11877
11878 if selections.len() == 1 {
11879 let selection = selections
11880 .last()
11881 .expect("ensured that there's only one selection");
11882 let query = buffer
11883 .text_for_range(selection.start..selection.end)
11884 .collect::<String>();
11885 let is_empty = query.is_empty();
11886 let select_state = SelectNextState {
11887 query: AhoCorasick::new(&[query])?,
11888 wordwise: true,
11889 done: is_empty,
11890 };
11891 self.select_next_state = Some(select_state);
11892 } else {
11893 self.select_next_state = None;
11894 }
11895 } else if let Some(selected_text) = selected_text {
11896 self.select_next_state = Some(SelectNextState {
11897 query: AhoCorasick::new(&[selected_text])?,
11898 wordwise: false,
11899 done: false,
11900 });
11901 self.select_next_match_internal(
11902 display_map,
11903 replace_newest,
11904 autoscroll,
11905 window,
11906 cx,
11907 )?;
11908 }
11909 }
11910 Ok(())
11911 }
11912
11913 pub fn select_all_matches(
11914 &mut self,
11915 _action: &SelectAllMatches,
11916 window: &mut Window,
11917 cx: &mut Context<Self>,
11918 ) -> Result<()> {
11919 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11920
11921 self.push_to_selection_history();
11922 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11923
11924 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11925 let Some(select_next_state) = self.select_next_state.as_mut() else {
11926 return Ok(());
11927 };
11928 if select_next_state.done {
11929 return Ok(());
11930 }
11931
11932 let mut new_selections = Vec::new();
11933
11934 let reversed = self.selections.oldest::<usize>(cx).reversed;
11935 let buffer = &display_map.buffer_snapshot;
11936 let query_matches = select_next_state
11937 .query
11938 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11939
11940 for query_match in query_matches.into_iter() {
11941 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11942 let offset_range = if reversed {
11943 query_match.end()..query_match.start()
11944 } else {
11945 query_match.start()..query_match.end()
11946 };
11947 let display_range = offset_range.start.to_display_point(&display_map)
11948 ..offset_range.end.to_display_point(&display_map);
11949
11950 if !select_next_state.wordwise
11951 || (!movement::is_inside_word(&display_map, display_range.start)
11952 && !movement::is_inside_word(&display_map, display_range.end))
11953 {
11954 new_selections.push(offset_range.start..offset_range.end);
11955 }
11956 }
11957
11958 select_next_state.done = true;
11959 self.unfold_ranges(&new_selections.clone(), false, false, cx);
11960 self.change_selections(None, window, cx, |selections| {
11961 selections.select_ranges(new_selections)
11962 });
11963
11964 Ok(())
11965 }
11966
11967 pub fn select_next(
11968 &mut self,
11969 action: &SelectNext,
11970 window: &mut Window,
11971 cx: &mut Context<Self>,
11972 ) -> Result<()> {
11973 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11974 self.push_to_selection_history();
11975 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11976 self.select_next_match_internal(
11977 &display_map,
11978 action.replace_newest,
11979 Some(Autoscroll::newest()),
11980 window,
11981 cx,
11982 )?;
11983 Ok(())
11984 }
11985
11986 pub fn select_previous(
11987 &mut self,
11988 action: &SelectPrevious,
11989 window: &mut Window,
11990 cx: &mut Context<Self>,
11991 ) -> Result<()> {
11992 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11993 self.push_to_selection_history();
11994 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11995 let buffer = &display_map.buffer_snapshot;
11996 let mut selections = self.selections.all::<usize>(cx);
11997 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11998 let query = &select_prev_state.query;
11999 if !select_prev_state.done {
12000 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12001 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12002 let mut next_selected_range = None;
12003 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12004 let bytes_before_last_selection =
12005 buffer.reversed_bytes_in_range(0..last_selection.start);
12006 let bytes_after_first_selection =
12007 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12008 let query_matches = query
12009 .stream_find_iter(bytes_before_last_selection)
12010 .map(|result| (last_selection.start, result))
12011 .chain(
12012 query
12013 .stream_find_iter(bytes_after_first_selection)
12014 .map(|result| (buffer.len(), result)),
12015 );
12016 for (end_offset, query_match) in query_matches {
12017 let query_match = query_match.unwrap(); // can only fail due to I/O
12018 let offset_range =
12019 end_offset - query_match.end()..end_offset - query_match.start();
12020 let display_range = offset_range.start.to_display_point(&display_map)
12021 ..offset_range.end.to_display_point(&display_map);
12022
12023 if !select_prev_state.wordwise
12024 || (!movement::is_inside_word(&display_map, display_range.start)
12025 && !movement::is_inside_word(&display_map, display_range.end))
12026 {
12027 next_selected_range = Some(offset_range);
12028 break;
12029 }
12030 }
12031
12032 if let Some(next_selected_range) = next_selected_range {
12033 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12034 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12035 if action.replace_newest {
12036 s.delete(s.newest_anchor().id);
12037 }
12038 s.insert_range(next_selected_range);
12039 });
12040 } else {
12041 select_prev_state.done = true;
12042 }
12043 }
12044
12045 self.select_prev_state = Some(select_prev_state);
12046 } else {
12047 let mut only_carets = true;
12048 let mut same_text_selected = true;
12049 let mut selected_text = None;
12050
12051 let mut selections_iter = selections.iter().peekable();
12052 while let Some(selection) = selections_iter.next() {
12053 if selection.start != selection.end {
12054 only_carets = false;
12055 }
12056
12057 if same_text_selected {
12058 if selected_text.is_none() {
12059 selected_text =
12060 Some(buffer.text_for_range(selection.range()).collect::<String>());
12061 }
12062
12063 if let Some(next_selection) = selections_iter.peek() {
12064 if next_selection.range().len() == selection.range().len() {
12065 let next_selected_text = buffer
12066 .text_for_range(next_selection.range())
12067 .collect::<String>();
12068 if Some(next_selected_text) != selected_text {
12069 same_text_selected = false;
12070 selected_text = None;
12071 }
12072 } else {
12073 same_text_selected = false;
12074 selected_text = None;
12075 }
12076 }
12077 }
12078 }
12079
12080 if only_carets {
12081 for selection in &mut selections {
12082 let word_range = movement::surrounding_word(
12083 &display_map,
12084 selection.start.to_display_point(&display_map),
12085 );
12086 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12087 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12088 selection.goal = SelectionGoal::None;
12089 selection.reversed = false;
12090 }
12091 if selections.len() == 1 {
12092 let selection = selections
12093 .last()
12094 .expect("ensured that there's only one selection");
12095 let query = buffer
12096 .text_for_range(selection.start..selection.end)
12097 .collect::<String>();
12098 let is_empty = query.is_empty();
12099 let select_state = SelectNextState {
12100 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12101 wordwise: true,
12102 done: is_empty,
12103 };
12104 self.select_prev_state = Some(select_state);
12105 } else {
12106 self.select_prev_state = None;
12107 }
12108
12109 self.unfold_ranges(
12110 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12111 false,
12112 true,
12113 cx,
12114 );
12115 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12116 s.select(selections);
12117 });
12118 } else if let Some(selected_text) = selected_text {
12119 self.select_prev_state = Some(SelectNextState {
12120 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12121 wordwise: false,
12122 done: false,
12123 });
12124 self.select_previous(action, window, cx)?;
12125 }
12126 }
12127 Ok(())
12128 }
12129
12130 pub fn find_next_match(
12131 &mut self,
12132 _: &FindNextMatch,
12133 window: &mut Window,
12134 cx: &mut Context<Self>,
12135 ) -> Result<()> {
12136 let selections = self.selections.disjoint_anchors();
12137 match selections.first() {
12138 Some(first) if selections.len() >= 2 => {
12139 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12140 s.select_ranges([first.range()]);
12141 });
12142 }
12143 _ => self.select_next(
12144 &SelectNext {
12145 replace_newest: true,
12146 },
12147 window,
12148 cx,
12149 )?,
12150 }
12151 Ok(())
12152 }
12153
12154 pub fn find_previous_match(
12155 &mut self,
12156 _: &FindPreviousMatch,
12157 window: &mut Window,
12158 cx: &mut Context<Self>,
12159 ) -> Result<()> {
12160 let selections = self.selections.disjoint_anchors();
12161 match selections.last() {
12162 Some(last) if selections.len() >= 2 => {
12163 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12164 s.select_ranges([last.range()]);
12165 });
12166 }
12167 _ => self.select_previous(
12168 &SelectPrevious {
12169 replace_newest: true,
12170 },
12171 window,
12172 cx,
12173 )?,
12174 }
12175 Ok(())
12176 }
12177
12178 pub fn toggle_comments(
12179 &mut self,
12180 action: &ToggleComments,
12181 window: &mut Window,
12182 cx: &mut Context<Self>,
12183 ) {
12184 if self.read_only(cx) {
12185 return;
12186 }
12187 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12188 let text_layout_details = &self.text_layout_details(window);
12189 self.transact(window, cx, |this, window, cx| {
12190 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12191 let mut edits = Vec::new();
12192 let mut selection_edit_ranges = Vec::new();
12193 let mut last_toggled_row = None;
12194 let snapshot = this.buffer.read(cx).read(cx);
12195 let empty_str: Arc<str> = Arc::default();
12196 let mut suffixes_inserted = Vec::new();
12197 let ignore_indent = action.ignore_indent;
12198
12199 fn comment_prefix_range(
12200 snapshot: &MultiBufferSnapshot,
12201 row: MultiBufferRow,
12202 comment_prefix: &str,
12203 comment_prefix_whitespace: &str,
12204 ignore_indent: bool,
12205 ) -> Range<Point> {
12206 let indent_size = if ignore_indent {
12207 0
12208 } else {
12209 snapshot.indent_size_for_line(row).len
12210 };
12211
12212 let start = Point::new(row.0, indent_size);
12213
12214 let mut line_bytes = snapshot
12215 .bytes_in_range(start..snapshot.max_point())
12216 .flatten()
12217 .copied();
12218
12219 // If this line currently begins with the line comment prefix, then record
12220 // the range containing the prefix.
12221 if line_bytes
12222 .by_ref()
12223 .take(comment_prefix.len())
12224 .eq(comment_prefix.bytes())
12225 {
12226 // Include any whitespace that matches the comment prefix.
12227 let matching_whitespace_len = line_bytes
12228 .zip(comment_prefix_whitespace.bytes())
12229 .take_while(|(a, b)| a == b)
12230 .count() as u32;
12231 let end = Point::new(
12232 start.row,
12233 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12234 );
12235 start..end
12236 } else {
12237 start..start
12238 }
12239 }
12240
12241 fn comment_suffix_range(
12242 snapshot: &MultiBufferSnapshot,
12243 row: MultiBufferRow,
12244 comment_suffix: &str,
12245 comment_suffix_has_leading_space: bool,
12246 ) -> Range<Point> {
12247 let end = Point::new(row.0, snapshot.line_len(row));
12248 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12249
12250 let mut line_end_bytes = snapshot
12251 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12252 .flatten()
12253 .copied();
12254
12255 let leading_space_len = if suffix_start_column > 0
12256 && line_end_bytes.next() == Some(b' ')
12257 && comment_suffix_has_leading_space
12258 {
12259 1
12260 } else {
12261 0
12262 };
12263
12264 // If this line currently begins with the line comment prefix, then record
12265 // the range containing the prefix.
12266 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12267 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12268 start..end
12269 } else {
12270 end..end
12271 }
12272 }
12273
12274 // TODO: Handle selections that cross excerpts
12275 for selection in &mut selections {
12276 let start_column = snapshot
12277 .indent_size_for_line(MultiBufferRow(selection.start.row))
12278 .len;
12279 let language = if let Some(language) =
12280 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12281 {
12282 language
12283 } else {
12284 continue;
12285 };
12286
12287 selection_edit_ranges.clear();
12288
12289 // If multiple selections contain a given row, avoid processing that
12290 // row more than once.
12291 let mut start_row = MultiBufferRow(selection.start.row);
12292 if last_toggled_row == Some(start_row) {
12293 start_row = start_row.next_row();
12294 }
12295 let end_row =
12296 if selection.end.row > selection.start.row && selection.end.column == 0 {
12297 MultiBufferRow(selection.end.row - 1)
12298 } else {
12299 MultiBufferRow(selection.end.row)
12300 };
12301 last_toggled_row = Some(end_row);
12302
12303 if start_row > end_row {
12304 continue;
12305 }
12306
12307 // If the language has line comments, toggle those.
12308 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12309
12310 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12311 if ignore_indent {
12312 full_comment_prefixes = full_comment_prefixes
12313 .into_iter()
12314 .map(|s| Arc::from(s.trim_end()))
12315 .collect();
12316 }
12317
12318 if !full_comment_prefixes.is_empty() {
12319 let first_prefix = full_comment_prefixes
12320 .first()
12321 .expect("prefixes is non-empty");
12322 let prefix_trimmed_lengths = full_comment_prefixes
12323 .iter()
12324 .map(|p| p.trim_end_matches(' ').len())
12325 .collect::<SmallVec<[usize; 4]>>();
12326
12327 let mut all_selection_lines_are_comments = true;
12328
12329 for row in start_row.0..=end_row.0 {
12330 let row = MultiBufferRow(row);
12331 if start_row < end_row && snapshot.is_line_blank(row) {
12332 continue;
12333 }
12334
12335 let prefix_range = full_comment_prefixes
12336 .iter()
12337 .zip(prefix_trimmed_lengths.iter().copied())
12338 .map(|(prefix, trimmed_prefix_len)| {
12339 comment_prefix_range(
12340 snapshot.deref(),
12341 row,
12342 &prefix[..trimmed_prefix_len],
12343 &prefix[trimmed_prefix_len..],
12344 ignore_indent,
12345 )
12346 })
12347 .max_by_key(|range| range.end.column - range.start.column)
12348 .expect("prefixes is non-empty");
12349
12350 if prefix_range.is_empty() {
12351 all_selection_lines_are_comments = false;
12352 }
12353
12354 selection_edit_ranges.push(prefix_range);
12355 }
12356
12357 if all_selection_lines_are_comments {
12358 edits.extend(
12359 selection_edit_ranges
12360 .iter()
12361 .cloned()
12362 .map(|range| (range, empty_str.clone())),
12363 );
12364 } else {
12365 let min_column = selection_edit_ranges
12366 .iter()
12367 .map(|range| range.start.column)
12368 .min()
12369 .unwrap_or(0);
12370 edits.extend(selection_edit_ranges.iter().map(|range| {
12371 let position = Point::new(range.start.row, min_column);
12372 (position..position, first_prefix.clone())
12373 }));
12374 }
12375 } else if let Some((full_comment_prefix, comment_suffix)) =
12376 language.block_comment_delimiters()
12377 {
12378 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12379 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12380 let prefix_range = comment_prefix_range(
12381 snapshot.deref(),
12382 start_row,
12383 comment_prefix,
12384 comment_prefix_whitespace,
12385 ignore_indent,
12386 );
12387 let suffix_range = comment_suffix_range(
12388 snapshot.deref(),
12389 end_row,
12390 comment_suffix.trim_start_matches(' '),
12391 comment_suffix.starts_with(' '),
12392 );
12393
12394 if prefix_range.is_empty() || suffix_range.is_empty() {
12395 edits.push((
12396 prefix_range.start..prefix_range.start,
12397 full_comment_prefix.clone(),
12398 ));
12399 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12400 suffixes_inserted.push((end_row, comment_suffix.len()));
12401 } else {
12402 edits.push((prefix_range, empty_str.clone()));
12403 edits.push((suffix_range, empty_str.clone()));
12404 }
12405 } else {
12406 continue;
12407 }
12408 }
12409
12410 drop(snapshot);
12411 this.buffer.update(cx, |buffer, cx| {
12412 buffer.edit(edits, None, cx);
12413 });
12414
12415 // Adjust selections so that they end before any comment suffixes that
12416 // were inserted.
12417 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12418 let mut selections = this.selections.all::<Point>(cx);
12419 let snapshot = this.buffer.read(cx).read(cx);
12420 for selection in &mut selections {
12421 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12422 match row.cmp(&MultiBufferRow(selection.end.row)) {
12423 Ordering::Less => {
12424 suffixes_inserted.next();
12425 continue;
12426 }
12427 Ordering::Greater => break,
12428 Ordering::Equal => {
12429 if selection.end.column == snapshot.line_len(row) {
12430 if selection.is_empty() {
12431 selection.start.column -= suffix_len as u32;
12432 }
12433 selection.end.column -= suffix_len as u32;
12434 }
12435 break;
12436 }
12437 }
12438 }
12439 }
12440
12441 drop(snapshot);
12442 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12443 s.select(selections)
12444 });
12445
12446 let selections = this.selections.all::<Point>(cx);
12447 let selections_on_single_row = selections.windows(2).all(|selections| {
12448 selections[0].start.row == selections[1].start.row
12449 && selections[0].end.row == selections[1].end.row
12450 && selections[0].start.row == selections[0].end.row
12451 });
12452 let selections_selecting = selections
12453 .iter()
12454 .any(|selection| selection.start != selection.end);
12455 let advance_downwards = action.advance_downwards
12456 && selections_on_single_row
12457 && !selections_selecting
12458 && !matches!(this.mode, EditorMode::SingleLine { .. });
12459
12460 if advance_downwards {
12461 let snapshot = this.buffer.read(cx).snapshot(cx);
12462
12463 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12464 s.move_cursors_with(|display_snapshot, display_point, _| {
12465 let mut point = display_point.to_point(display_snapshot);
12466 point.row += 1;
12467 point = snapshot.clip_point(point, Bias::Left);
12468 let display_point = point.to_display_point(display_snapshot);
12469 let goal = SelectionGoal::HorizontalPosition(
12470 display_snapshot
12471 .x_for_display_point(display_point, text_layout_details)
12472 .into(),
12473 );
12474 (display_point, goal)
12475 })
12476 });
12477 }
12478 });
12479 }
12480
12481 pub fn select_enclosing_symbol(
12482 &mut self,
12483 _: &SelectEnclosingSymbol,
12484 window: &mut Window,
12485 cx: &mut Context<Self>,
12486 ) {
12487 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12488
12489 let buffer = self.buffer.read(cx).snapshot(cx);
12490 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12491
12492 fn update_selection(
12493 selection: &Selection<usize>,
12494 buffer_snap: &MultiBufferSnapshot,
12495 ) -> Option<Selection<usize>> {
12496 let cursor = selection.head();
12497 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12498 for symbol in symbols.iter().rev() {
12499 let start = symbol.range.start.to_offset(buffer_snap);
12500 let end = symbol.range.end.to_offset(buffer_snap);
12501 let new_range = start..end;
12502 if start < selection.start || end > selection.end {
12503 return Some(Selection {
12504 id: selection.id,
12505 start: new_range.start,
12506 end: new_range.end,
12507 goal: SelectionGoal::None,
12508 reversed: selection.reversed,
12509 });
12510 }
12511 }
12512 None
12513 }
12514
12515 let mut selected_larger_symbol = false;
12516 let new_selections = old_selections
12517 .iter()
12518 .map(|selection| match update_selection(selection, &buffer) {
12519 Some(new_selection) => {
12520 if new_selection.range() != selection.range() {
12521 selected_larger_symbol = true;
12522 }
12523 new_selection
12524 }
12525 None => selection.clone(),
12526 })
12527 .collect::<Vec<_>>();
12528
12529 if selected_larger_symbol {
12530 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12531 s.select(new_selections);
12532 });
12533 }
12534 }
12535
12536 pub fn select_larger_syntax_node(
12537 &mut self,
12538 _: &SelectLargerSyntaxNode,
12539 window: &mut Window,
12540 cx: &mut Context<Self>,
12541 ) {
12542 let Some(visible_row_count) = self.visible_row_count() else {
12543 return;
12544 };
12545 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12546 if old_selections.is_empty() {
12547 return;
12548 }
12549
12550 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12551
12552 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12553 let buffer = self.buffer.read(cx).snapshot(cx);
12554
12555 let mut selected_larger_node = false;
12556 let mut new_selections = old_selections
12557 .iter()
12558 .map(|selection| {
12559 let old_range = selection.start..selection.end;
12560
12561 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12562 // manually select word at selection
12563 if ["string_content", "inline"].contains(&node.kind()) {
12564 let word_range = {
12565 let display_point = buffer
12566 .offset_to_point(old_range.start)
12567 .to_display_point(&display_map);
12568 let Range { start, end } =
12569 movement::surrounding_word(&display_map, display_point);
12570 start.to_point(&display_map).to_offset(&buffer)
12571 ..end.to_point(&display_map).to_offset(&buffer)
12572 };
12573 // ignore if word is already selected
12574 if !word_range.is_empty() && old_range != word_range {
12575 let last_word_range = {
12576 let display_point = buffer
12577 .offset_to_point(old_range.end)
12578 .to_display_point(&display_map);
12579 let Range { start, end } =
12580 movement::surrounding_word(&display_map, display_point);
12581 start.to_point(&display_map).to_offset(&buffer)
12582 ..end.to_point(&display_map).to_offset(&buffer)
12583 };
12584 // only select word if start and end point belongs to same word
12585 if word_range == last_word_range {
12586 selected_larger_node = true;
12587 return Selection {
12588 id: selection.id,
12589 start: word_range.start,
12590 end: word_range.end,
12591 goal: SelectionGoal::None,
12592 reversed: selection.reversed,
12593 };
12594 }
12595 }
12596 }
12597 }
12598
12599 let mut new_range = old_range.clone();
12600 let mut new_node = None;
12601 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12602 {
12603 new_node = Some(node);
12604 new_range = match containing_range {
12605 MultiOrSingleBufferOffsetRange::Single(_) => break,
12606 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12607 };
12608 if !display_map.intersects_fold(new_range.start)
12609 && !display_map.intersects_fold(new_range.end)
12610 {
12611 break;
12612 }
12613 }
12614
12615 if let Some(node) = new_node {
12616 // Log the ancestor, to support using this action as a way to explore TreeSitter
12617 // nodes. Parent and grandparent are also logged because this operation will not
12618 // visit nodes that have the same range as their parent.
12619 log::info!("Node: {node:?}");
12620 let parent = node.parent();
12621 log::info!("Parent: {parent:?}");
12622 let grandparent = parent.and_then(|x| x.parent());
12623 log::info!("Grandparent: {grandparent:?}");
12624 }
12625
12626 selected_larger_node |= new_range != old_range;
12627 Selection {
12628 id: selection.id,
12629 start: new_range.start,
12630 end: new_range.end,
12631 goal: SelectionGoal::None,
12632 reversed: selection.reversed,
12633 }
12634 })
12635 .collect::<Vec<_>>();
12636
12637 if !selected_larger_node {
12638 return; // don't put this call in the history
12639 }
12640
12641 // scroll based on transformation done to the last selection created by the user
12642 let (last_old, last_new) = old_selections
12643 .last()
12644 .zip(new_selections.last().cloned())
12645 .expect("old_selections isn't empty");
12646
12647 // revert selection
12648 let is_selection_reversed = {
12649 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12650 new_selections.last_mut().expect("checked above").reversed =
12651 should_newest_selection_be_reversed;
12652 should_newest_selection_be_reversed
12653 };
12654
12655 if selected_larger_node {
12656 self.select_syntax_node_history.disable_clearing = true;
12657 self.change_selections(None, window, cx, |s| {
12658 s.select(new_selections.clone());
12659 });
12660 self.select_syntax_node_history.disable_clearing = false;
12661 }
12662
12663 let start_row = last_new.start.to_display_point(&display_map).row().0;
12664 let end_row = last_new.end.to_display_point(&display_map).row().0;
12665 let selection_height = end_row - start_row + 1;
12666 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12667
12668 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12669 let scroll_behavior = if fits_on_the_screen {
12670 self.request_autoscroll(Autoscroll::fit(), cx);
12671 SelectSyntaxNodeScrollBehavior::FitSelection
12672 } else if is_selection_reversed {
12673 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12674 SelectSyntaxNodeScrollBehavior::CursorTop
12675 } else {
12676 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12677 SelectSyntaxNodeScrollBehavior::CursorBottom
12678 };
12679
12680 self.select_syntax_node_history.push((
12681 old_selections,
12682 scroll_behavior,
12683 is_selection_reversed,
12684 ));
12685 }
12686
12687 pub fn select_smaller_syntax_node(
12688 &mut self,
12689 _: &SelectSmallerSyntaxNode,
12690 window: &mut Window,
12691 cx: &mut Context<Self>,
12692 ) {
12693 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12694
12695 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12696 self.select_syntax_node_history.pop()
12697 {
12698 if let Some(selection) = selections.last_mut() {
12699 selection.reversed = is_selection_reversed;
12700 }
12701
12702 self.select_syntax_node_history.disable_clearing = true;
12703 self.change_selections(None, window, cx, |s| {
12704 s.select(selections.to_vec());
12705 });
12706 self.select_syntax_node_history.disable_clearing = false;
12707
12708 match scroll_behavior {
12709 SelectSyntaxNodeScrollBehavior::CursorTop => {
12710 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12711 }
12712 SelectSyntaxNodeScrollBehavior::FitSelection => {
12713 self.request_autoscroll(Autoscroll::fit(), cx);
12714 }
12715 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12716 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12717 }
12718 }
12719 }
12720 }
12721
12722 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12723 if !EditorSettings::get_global(cx).gutter.runnables {
12724 self.clear_tasks();
12725 return Task::ready(());
12726 }
12727 let project = self.project.as_ref().map(Entity::downgrade);
12728 let task_sources = self.lsp_task_sources(cx);
12729 cx.spawn_in(window, async move |editor, cx| {
12730 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12731 let Some(project) = project.and_then(|p| p.upgrade()) else {
12732 return;
12733 };
12734 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12735 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12736 }) else {
12737 return;
12738 };
12739
12740 let hide_runnables = project
12741 .update(cx, |project, cx| {
12742 // Do not display any test indicators in non-dev server remote projects.
12743 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12744 })
12745 .unwrap_or(true);
12746 if hide_runnables {
12747 return;
12748 }
12749 let new_rows =
12750 cx.background_spawn({
12751 let snapshot = display_snapshot.clone();
12752 async move {
12753 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12754 }
12755 })
12756 .await;
12757 let Ok(lsp_tasks) =
12758 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12759 else {
12760 return;
12761 };
12762 let lsp_tasks = lsp_tasks.await;
12763
12764 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12765 lsp_tasks
12766 .into_iter()
12767 .flat_map(|(kind, tasks)| {
12768 tasks.into_iter().filter_map(move |(location, task)| {
12769 Some((kind.clone(), location?, task))
12770 })
12771 })
12772 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12773 let buffer = location.target.buffer;
12774 let buffer_snapshot = buffer.read(cx).snapshot();
12775 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12776 |(excerpt_id, snapshot, _)| {
12777 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12778 display_snapshot
12779 .buffer_snapshot
12780 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12781 } else {
12782 None
12783 }
12784 },
12785 );
12786 if let Some(offset) = offset {
12787 let task_buffer_range =
12788 location.target.range.to_point(&buffer_snapshot);
12789 let context_buffer_range =
12790 task_buffer_range.to_offset(&buffer_snapshot);
12791 let context_range = BufferOffset(context_buffer_range.start)
12792 ..BufferOffset(context_buffer_range.end);
12793
12794 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12795 .or_insert_with(|| RunnableTasks {
12796 templates: Vec::new(),
12797 offset,
12798 column: task_buffer_range.start.column,
12799 extra_variables: HashMap::default(),
12800 context_range,
12801 })
12802 .templates
12803 .push((kind, task.original_task().clone()));
12804 }
12805
12806 acc
12807 })
12808 }) else {
12809 return;
12810 };
12811
12812 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12813 editor
12814 .update(cx, |editor, _| {
12815 editor.clear_tasks();
12816 for (key, mut value) in rows {
12817 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12818 value.templates.extend(lsp_tasks.templates);
12819 }
12820
12821 editor.insert_tasks(key, value);
12822 }
12823 for (key, value) in lsp_tasks_by_rows {
12824 editor.insert_tasks(key, value);
12825 }
12826 })
12827 .ok();
12828 })
12829 }
12830 fn fetch_runnable_ranges(
12831 snapshot: &DisplaySnapshot,
12832 range: Range<Anchor>,
12833 ) -> Vec<language::RunnableRange> {
12834 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12835 }
12836
12837 fn runnable_rows(
12838 project: Entity<Project>,
12839 snapshot: DisplaySnapshot,
12840 runnable_ranges: Vec<RunnableRange>,
12841 mut cx: AsyncWindowContext,
12842 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12843 runnable_ranges
12844 .into_iter()
12845 .filter_map(|mut runnable| {
12846 let tasks = cx
12847 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12848 .ok()?;
12849 if tasks.is_empty() {
12850 return None;
12851 }
12852
12853 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12854
12855 let row = snapshot
12856 .buffer_snapshot
12857 .buffer_line_for_row(MultiBufferRow(point.row))?
12858 .1
12859 .start
12860 .row;
12861
12862 let context_range =
12863 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12864 Some((
12865 (runnable.buffer_id, row),
12866 RunnableTasks {
12867 templates: tasks,
12868 offset: snapshot
12869 .buffer_snapshot
12870 .anchor_before(runnable.run_range.start),
12871 context_range,
12872 column: point.column,
12873 extra_variables: runnable.extra_captures,
12874 },
12875 ))
12876 })
12877 .collect()
12878 }
12879
12880 fn templates_with_tags(
12881 project: &Entity<Project>,
12882 runnable: &mut Runnable,
12883 cx: &mut App,
12884 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12885 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12886 let (worktree_id, file) = project
12887 .buffer_for_id(runnable.buffer, cx)
12888 .and_then(|buffer| buffer.read(cx).file())
12889 .map(|file| (file.worktree_id(cx), file.clone()))
12890 .unzip();
12891
12892 (
12893 project.task_store().read(cx).task_inventory().cloned(),
12894 worktree_id,
12895 file,
12896 )
12897 });
12898
12899 let mut templates_with_tags = mem::take(&mut runnable.tags)
12900 .into_iter()
12901 .flat_map(|RunnableTag(tag)| {
12902 inventory
12903 .as_ref()
12904 .into_iter()
12905 .flat_map(|inventory| {
12906 inventory.read(cx).list_tasks(
12907 file.clone(),
12908 Some(runnable.language.clone()),
12909 worktree_id,
12910 cx,
12911 )
12912 })
12913 .filter(move |(_, template)| {
12914 template.tags.iter().any(|source_tag| source_tag == &tag)
12915 })
12916 })
12917 .sorted_by_key(|(kind, _)| kind.to_owned())
12918 .collect::<Vec<_>>();
12919 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12920 // Strongest source wins; if we have worktree tag binding, prefer that to
12921 // global and language bindings;
12922 // if we have a global binding, prefer that to language binding.
12923 let first_mismatch = templates_with_tags
12924 .iter()
12925 .position(|(tag_source, _)| tag_source != leading_tag_source);
12926 if let Some(index) = first_mismatch {
12927 templates_with_tags.truncate(index);
12928 }
12929 }
12930
12931 templates_with_tags
12932 }
12933
12934 pub fn move_to_enclosing_bracket(
12935 &mut self,
12936 _: &MoveToEnclosingBracket,
12937 window: &mut Window,
12938 cx: &mut Context<Self>,
12939 ) {
12940 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12941 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12942 s.move_offsets_with(|snapshot, selection| {
12943 let Some(enclosing_bracket_ranges) =
12944 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12945 else {
12946 return;
12947 };
12948
12949 let mut best_length = usize::MAX;
12950 let mut best_inside = false;
12951 let mut best_in_bracket_range = false;
12952 let mut best_destination = None;
12953 for (open, close) in enclosing_bracket_ranges {
12954 let close = close.to_inclusive();
12955 let length = close.end() - open.start;
12956 let inside = selection.start >= open.end && selection.end <= *close.start();
12957 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12958 || close.contains(&selection.head());
12959
12960 // If best is next to a bracket and current isn't, skip
12961 if !in_bracket_range && best_in_bracket_range {
12962 continue;
12963 }
12964
12965 // Prefer smaller lengths unless best is inside and current isn't
12966 if length > best_length && (best_inside || !inside) {
12967 continue;
12968 }
12969
12970 best_length = length;
12971 best_inside = inside;
12972 best_in_bracket_range = in_bracket_range;
12973 best_destination = Some(
12974 if close.contains(&selection.start) && close.contains(&selection.end) {
12975 if inside { open.end } else { open.start }
12976 } else if inside {
12977 *close.start()
12978 } else {
12979 *close.end()
12980 },
12981 );
12982 }
12983
12984 if let Some(destination) = best_destination {
12985 selection.collapse_to(destination, SelectionGoal::None);
12986 }
12987 })
12988 });
12989 }
12990
12991 pub fn undo_selection(
12992 &mut self,
12993 _: &UndoSelection,
12994 window: &mut Window,
12995 cx: &mut Context<Self>,
12996 ) {
12997 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12998 self.end_selection(window, cx);
12999 self.selection_history.mode = SelectionHistoryMode::Undoing;
13000 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13001 self.change_selections(None, window, cx, |s| {
13002 s.select_anchors(entry.selections.to_vec())
13003 });
13004 self.select_next_state = entry.select_next_state;
13005 self.select_prev_state = entry.select_prev_state;
13006 self.add_selections_state = entry.add_selections_state;
13007 self.request_autoscroll(Autoscroll::newest(), cx);
13008 }
13009 self.selection_history.mode = SelectionHistoryMode::Normal;
13010 }
13011
13012 pub fn redo_selection(
13013 &mut self,
13014 _: &RedoSelection,
13015 window: &mut Window,
13016 cx: &mut Context<Self>,
13017 ) {
13018 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13019 self.end_selection(window, cx);
13020 self.selection_history.mode = SelectionHistoryMode::Redoing;
13021 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13022 self.change_selections(None, window, cx, |s| {
13023 s.select_anchors(entry.selections.to_vec())
13024 });
13025 self.select_next_state = entry.select_next_state;
13026 self.select_prev_state = entry.select_prev_state;
13027 self.add_selections_state = entry.add_selections_state;
13028 self.request_autoscroll(Autoscroll::newest(), cx);
13029 }
13030 self.selection_history.mode = SelectionHistoryMode::Normal;
13031 }
13032
13033 pub fn expand_excerpts(
13034 &mut self,
13035 action: &ExpandExcerpts,
13036 _: &mut Window,
13037 cx: &mut Context<Self>,
13038 ) {
13039 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13040 }
13041
13042 pub fn expand_excerpts_down(
13043 &mut self,
13044 action: &ExpandExcerptsDown,
13045 _: &mut Window,
13046 cx: &mut Context<Self>,
13047 ) {
13048 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13049 }
13050
13051 pub fn expand_excerpts_up(
13052 &mut self,
13053 action: &ExpandExcerptsUp,
13054 _: &mut Window,
13055 cx: &mut Context<Self>,
13056 ) {
13057 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13058 }
13059
13060 pub fn expand_excerpts_for_direction(
13061 &mut self,
13062 lines: u32,
13063 direction: ExpandExcerptDirection,
13064
13065 cx: &mut Context<Self>,
13066 ) {
13067 let selections = self.selections.disjoint_anchors();
13068
13069 let lines = if lines == 0 {
13070 EditorSettings::get_global(cx).expand_excerpt_lines
13071 } else {
13072 lines
13073 };
13074
13075 self.buffer.update(cx, |buffer, cx| {
13076 let snapshot = buffer.snapshot(cx);
13077 let mut excerpt_ids = selections
13078 .iter()
13079 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13080 .collect::<Vec<_>>();
13081 excerpt_ids.sort();
13082 excerpt_ids.dedup();
13083 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13084 })
13085 }
13086
13087 pub fn expand_excerpt(
13088 &mut self,
13089 excerpt: ExcerptId,
13090 direction: ExpandExcerptDirection,
13091 window: &mut Window,
13092 cx: &mut Context<Self>,
13093 ) {
13094 let current_scroll_position = self.scroll_position(cx);
13095 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13096 let mut should_scroll_up = false;
13097
13098 if direction == ExpandExcerptDirection::Down {
13099 let multi_buffer = self.buffer.read(cx);
13100 let snapshot = multi_buffer.snapshot(cx);
13101 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13102 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13103 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13104 let buffer_snapshot = buffer.read(cx).snapshot();
13105 let excerpt_end_row =
13106 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13107 let last_row = buffer_snapshot.max_point().row;
13108 let lines_below = last_row.saturating_sub(excerpt_end_row);
13109 should_scroll_up = lines_below >= lines_to_expand;
13110 }
13111 }
13112 }
13113 }
13114
13115 self.buffer.update(cx, |buffer, cx| {
13116 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13117 });
13118
13119 if should_scroll_up {
13120 let new_scroll_position =
13121 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13122 self.set_scroll_position(new_scroll_position, window, cx);
13123 }
13124 }
13125
13126 pub fn go_to_singleton_buffer_point(
13127 &mut self,
13128 point: Point,
13129 window: &mut Window,
13130 cx: &mut Context<Self>,
13131 ) {
13132 self.go_to_singleton_buffer_range(point..point, window, cx);
13133 }
13134
13135 pub fn go_to_singleton_buffer_range(
13136 &mut self,
13137 range: Range<Point>,
13138 window: &mut Window,
13139 cx: &mut Context<Self>,
13140 ) {
13141 let multibuffer = self.buffer().read(cx);
13142 let Some(buffer) = multibuffer.as_singleton() else {
13143 return;
13144 };
13145 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13146 return;
13147 };
13148 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13149 return;
13150 };
13151 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13152 s.select_anchor_ranges([start..end])
13153 });
13154 }
13155
13156 pub fn go_to_diagnostic(
13157 &mut self,
13158 _: &GoToDiagnostic,
13159 window: &mut Window,
13160 cx: &mut Context<Self>,
13161 ) {
13162 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13163 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13164 }
13165
13166 pub fn go_to_prev_diagnostic(
13167 &mut self,
13168 _: &GoToPreviousDiagnostic,
13169 window: &mut Window,
13170 cx: &mut Context<Self>,
13171 ) {
13172 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13173 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13174 }
13175
13176 pub fn go_to_diagnostic_impl(
13177 &mut self,
13178 direction: Direction,
13179 window: &mut Window,
13180 cx: &mut Context<Self>,
13181 ) {
13182 let buffer = self.buffer.read(cx).snapshot(cx);
13183 let selection = self.selections.newest::<usize>(cx);
13184
13185 let mut active_group_id = None;
13186 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13187 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13188 active_group_id = Some(active_group.group_id);
13189 }
13190 }
13191
13192 fn filtered(
13193 snapshot: EditorSnapshot,
13194 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13195 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13196 diagnostics
13197 .filter(|entry| entry.range.start != entry.range.end)
13198 .filter(|entry| !entry.diagnostic.is_unnecessary)
13199 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13200 }
13201
13202 let snapshot = self.snapshot(window, cx);
13203 let before = filtered(
13204 snapshot.clone(),
13205 buffer
13206 .diagnostics_in_range(0..selection.start)
13207 .filter(|entry| entry.range.start <= selection.start),
13208 );
13209 let after = filtered(
13210 snapshot,
13211 buffer
13212 .diagnostics_in_range(selection.start..buffer.len())
13213 .filter(|entry| entry.range.start >= selection.start),
13214 );
13215
13216 let mut found: Option<DiagnosticEntry<usize>> = None;
13217 if direction == Direction::Prev {
13218 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13219 {
13220 for diagnostic in prev_diagnostics.into_iter().rev() {
13221 if diagnostic.range.start != selection.start
13222 || active_group_id
13223 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13224 {
13225 found = Some(diagnostic);
13226 break 'outer;
13227 }
13228 }
13229 }
13230 } else {
13231 for diagnostic in after.chain(before) {
13232 if diagnostic.range.start != selection.start
13233 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13234 {
13235 found = Some(diagnostic);
13236 break;
13237 }
13238 }
13239 }
13240 let Some(next_diagnostic) = found else {
13241 return;
13242 };
13243
13244 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13245 return;
13246 };
13247 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13248 s.select_ranges(vec![
13249 next_diagnostic.range.start..next_diagnostic.range.start,
13250 ])
13251 });
13252 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13253 self.refresh_inline_completion(false, true, window, cx);
13254 }
13255
13256 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13257 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13258 let snapshot = self.snapshot(window, cx);
13259 let selection = self.selections.newest::<Point>(cx);
13260 self.go_to_hunk_before_or_after_position(
13261 &snapshot,
13262 selection.head(),
13263 Direction::Next,
13264 window,
13265 cx,
13266 );
13267 }
13268
13269 pub fn go_to_hunk_before_or_after_position(
13270 &mut self,
13271 snapshot: &EditorSnapshot,
13272 position: Point,
13273 direction: Direction,
13274 window: &mut Window,
13275 cx: &mut Context<Editor>,
13276 ) {
13277 let row = if direction == Direction::Next {
13278 self.hunk_after_position(snapshot, position)
13279 .map(|hunk| hunk.row_range.start)
13280 } else {
13281 self.hunk_before_position(snapshot, position)
13282 };
13283
13284 if let Some(row) = row {
13285 let destination = Point::new(row.0, 0);
13286 let autoscroll = Autoscroll::center();
13287
13288 self.unfold_ranges(&[destination..destination], false, false, cx);
13289 self.change_selections(Some(autoscroll), window, cx, |s| {
13290 s.select_ranges([destination..destination]);
13291 });
13292 }
13293 }
13294
13295 fn hunk_after_position(
13296 &mut self,
13297 snapshot: &EditorSnapshot,
13298 position: Point,
13299 ) -> Option<MultiBufferDiffHunk> {
13300 snapshot
13301 .buffer_snapshot
13302 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13303 .find(|hunk| hunk.row_range.start.0 > position.row)
13304 .or_else(|| {
13305 snapshot
13306 .buffer_snapshot
13307 .diff_hunks_in_range(Point::zero()..position)
13308 .find(|hunk| hunk.row_range.end.0 < position.row)
13309 })
13310 }
13311
13312 fn go_to_prev_hunk(
13313 &mut self,
13314 _: &GoToPreviousHunk,
13315 window: &mut Window,
13316 cx: &mut Context<Self>,
13317 ) {
13318 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13319 let snapshot = self.snapshot(window, cx);
13320 let selection = self.selections.newest::<Point>(cx);
13321 self.go_to_hunk_before_or_after_position(
13322 &snapshot,
13323 selection.head(),
13324 Direction::Prev,
13325 window,
13326 cx,
13327 );
13328 }
13329
13330 fn hunk_before_position(
13331 &mut self,
13332 snapshot: &EditorSnapshot,
13333 position: Point,
13334 ) -> Option<MultiBufferRow> {
13335 snapshot
13336 .buffer_snapshot
13337 .diff_hunk_before(position)
13338 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13339 }
13340
13341 fn go_to_next_change(
13342 &mut self,
13343 _: &GoToNextChange,
13344 window: &mut Window,
13345 cx: &mut Context<Self>,
13346 ) {
13347 if let Some(selections) = self
13348 .change_list
13349 .next_change(1, Direction::Next)
13350 .map(|s| s.to_vec())
13351 {
13352 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13353 let map = s.display_map();
13354 s.select_display_ranges(selections.iter().map(|a| {
13355 let point = a.to_display_point(&map);
13356 point..point
13357 }))
13358 })
13359 }
13360 }
13361
13362 fn go_to_previous_change(
13363 &mut self,
13364 _: &GoToPreviousChange,
13365 window: &mut Window,
13366 cx: &mut Context<Self>,
13367 ) {
13368 if let Some(selections) = self
13369 .change_list
13370 .next_change(1, Direction::Prev)
13371 .map(|s| s.to_vec())
13372 {
13373 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13374 let map = s.display_map();
13375 s.select_display_ranges(selections.iter().map(|a| {
13376 let point = a.to_display_point(&map);
13377 point..point
13378 }))
13379 })
13380 }
13381 }
13382
13383 fn go_to_line<T: 'static>(
13384 &mut self,
13385 position: Anchor,
13386 highlight_color: Option<Hsla>,
13387 window: &mut Window,
13388 cx: &mut Context<Self>,
13389 ) {
13390 let snapshot = self.snapshot(window, cx).display_snapshot;
13391 let position = position.to_point(&snapshot.buffer_snapshot);
13392 let start = snapshot
13393 .buffer_snapshot
13394 .clip_point(Point::new(position.row, 0), Bias::Left);
13395 let end = start + Point::new(1, 0);
13396 let start = snapshot.buffer_snapshot.anchor_before(start);
13397 let end = snapshot.buffer_snapshot.anchor_before(end);
13398
13399 self.highlight_rows::<T>(
13400 start..end,
13401 highlight_color
13402 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13403 false,
13404 cx,
13405 );
13406 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13407 }
13408
13409 pub fn go_to_definition(
13410 &mut self,
13411 _: &GoToDefinition,
13412 window: &mut Window,
13413 cx: &mut Context<Self>,
13414 ) -> Task<Result<Navigated>> {
13415 let definition =
13416 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13417 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13418 cx.spawn_in(window, async move |editor, cx| {
13419 if definition.await? == Navigated::Yes {
13420 return Ok(Navigated::Yes);
13421 }
13422 match fallback_strategy {
13423 GoToDefinitionFallback::None => Ok(Navigated::No),
13424 GoToDefinitionFallback::FindAllReferences => {
13425 match editor.update_in(cx, |editor, window, cx| {
13426 editor.find_all_references(&FindAllReferences, window, cx)
13427 })? {
13428 Some(references) => references.await,
13429 None => Ok(Navigated::No),
13430 }
13431 }
13432 }
13433 })
13434 }
13435
13436 pub fn go_to_declaration(
13437 &mut self,
13438 _: &GoToDeclaration,
13439 window: &mut Window,
13440 cx: &mut Context<Self>,
13441 ) -> Task<Result<Navigated>> {
13442 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13443 }
13444
13445 pub fn go_to_declaration_split(
13446 &mut self,
13447 _: &GoToDeclaration,
13448 window: &mut Window,
13449 cx: &mut Context<Self>,
13450 ) -> Task<Result<Navigated>> {
13451 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13452 }
13453
13454 pub fn go_to_implementation(
13455 &mut self,
13456 _: &GoToImplementation,
13457 window: &mut Window,
13458 cx: &mut Context<Self>,
13459 ) -> Task<Result<Navigated>> {
13460 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13461 }
13462
13463 pub fn go_to_implementation_split(
13464 &mut self,
13465 _: &GoToImplementationSplit,
13466 window: &mut Window,
13467 cx: &mut Context<Self>,
13468 ) -> Task<Result<Navigated>> {
13469 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13470 }
13471
13472 pub fn go_to_type_definition(
13473 &mut self,
13474 _: &GoToTypeDefinition,
13475 window: &mut Window,
13476 cx: &mut Context<Self>,
13477 ) -> Task<Result<Navigated>> {
13478 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13479 }
13480
13481 pub fn go_to_definition_split(
13482 &mut self,
13483 _: &GoToDefinitionSplit,
13484 window: &mut Window,
13485 cx: &mut Context<Self>,
13486 ) -> Task<Result<Navigated>> {
13487 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13488 }
13489
13490 pub fn go_to_type_definition_split(
13491 &mut self,
13492 _: &GoToTypeDefinitionSplit,
13493 window: &mut Window,
13494 cx: &mut Context<Self>,
13495 ) -> Task<Result<Navigated>> {
13496 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13497 }
13498
13499 fn go_to_definition_of_kind(
13500 &mut self,
13501 kind: GotoDefinitionKind,
13502 split: bool,
13503 window: &mut Window,
13504 cx: &mut Context<Self>,
13505 ) -> Task<Result<Navigated>> {
13506 let Some(provider) = self.semantics_provider.clone() else {
13507 return Task::ready(Ok(Navigated::No));
13508 };
13509 let head = self.selections.newest::<usize>(cx).head();
13510 let buffer = self.buffer.read(cx);
13511 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13512 text_anchor
13513 } else {
13514 return Task::ready(Ok(Navigated::No));
13515 };
13516
13517 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13518 return Task::ready(Ok(Navigated::No));
13519 };
13520
13521 cx.spawn_in(window, async move |editor, cx| {
13522 let definitions = definitions.await?;
13523 let navigated = editor
13524 .update_in(cx, |editor, window, cx| {
13525 editor.navigate_to_hover_links(
13526 Some(kind),
13527 definitions
13528 .into_iter()
13529 .filter(|location| {
13530 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13531 })
13532 .map(HoverLink::Text)
13533 .collect::<Vec<_>>(),
13534 split,
13535 window,
13536 cx,
13537 )
13538 })?
13539 .await?;
13540 anyhow::Ok(navigated)
13541 })
13542 }
13543
13544 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13545 let selection = self.selections.newest_anchor();
13546 let head = selection.head();
13547 let tail = selection.tail();
13548
13549 let Some((buffer, start_position)) =
13550 self.buffer.read(cx).text_anchor_for_position(head, cx)
13551 else {
13552 return;
13553 };
13554
13555 let end_position = if head != tail {
13556 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13557 return;
13558 };
13559 Some(pos)
13560 } else {
13561 None
13562 };
13563
13564 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13565 let url = if let Some(end_pos) = end_position {
13566 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13567 } else {
13568 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13569 };
13570
13571 if let Some(url) = url {
13572 editor.update(cx, |_, cx| {
13573 cx.open_url(&url);
13574 })
13575 } else {
13576 Ok(())
13577 }
13578 });
13579
13580 url_finder.detach();
13581 }
13582
13583 pub fn open_selected_filename(
13584 &mut self,
13585 _: &OpenSelectedFilename,
13586 window: &mut Window,
13587 cx: &mut Context<Self>,
13588 ) {
13589 let Some(workspace) = self.workspace() else {
13590 return;
13591 };
13592
13593 let position = self.selections.newest_anchor().head();
13594
13595 let Some((buffer, buffer_position)) =
13596 self.buffer.read(cx).text_anchor_for_position(position, cx)
13597 else {
13598 return;
13599 };
13600
13601 let project = self.project.clone();
13602
13603 cx.spawn_in(window, async move |_, cx| {
13604 let result = find_file(&buffer, project, buffer_position, cx).await;
13605
13606 if let Some((_, path)) = result {
13607 workspace
13608 .update_in(cx, |workspace, window, cx| {
13609 workspace.open_resolved_path(path, window, cx)
13610 })?
13611 .await?;
13612 }
13613 anyhow::Ok(())
13614 })
13615 .detach();
13616 }
13617
13618 pub(crate) fn navigate_to_hover_links(
13619 &mut self,
13620 kind: Option<GotoDefinitionKind>,
13621 mut definitions: Vec<HoverLink>,
13622 split: bool,
13623 window: &mut Window,
13624 cx: &mut Context<Editor>,
13625 ) -> Task<Result<Navigated>> {
13626 // If there is one definition, just open it directly
13627 if definitions.len() == 1 {
13628 let definition = definitions.pop().unwrap();
13629
13630 enum TargetTaskResult {
13631 Location(Option<Location>),
13632 AlreadyNavigated,
13633 }
13634
13635 let target_task = match definition {
13636 HoverLink::Text(link) => {
13637 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13638 }
13639 HoverLink::InlayHint(lsp_location, server_id) => {
13640 let computation =
13641 self.compute_target_location(lsp_location, server_id, window, cx);
13642 cx.background_spawn(async move {
13643 let location = computation.await?;
13644 Ok(TargetTaskResult::Location(location))
13645 })
13646 }
13647 HoverLink::Url(url) => {
13648 cx.open_url(&url);
13649 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13650 }
13651 HoverLink::File(path) => {
13652 if let Some(workspace) = self.workspace() {
13653 cx.spawn_in(window, async move |_, cx| {
13654 workspace
13655 .update_in(cx, |workspace, window, cx| {
13656 workspace.open_resolved_path(path, window, cx)
13657 })?
13658 .await
13659 .map(|_| TargetTaskResult::AlreadyNavigated)
13660 })
13661 } else {
13662 Task::ready(Ok(TargetTaskResult::Location(None)))
13663 }
13664 }
13665 };
13666 cx.spawn_in(window, async move |editor, cx| {
13667 let target = match target_task.await.context("target resolution task")? {
13668 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13669 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13670 TargetTaskResult::Location(Some(target)) => target,
13671 };
13672
13673 editor.update_in(cx, |editor, window, cx| {
13674 let Some(workspace) = editor.workspace() else {
13675 return Navigated::No;
13676 };
13677 let pane = workspace.read(cx).active_pane().clone();
13678
13679 let range = target.range.to_point(target.buffer.read(cx));
13680 let range = editor.range_for_match(&range);
13681 let range = collapse_multiline_range(range);
13682
13683 if !split
13684 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13685 {
13686 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13687 } else {
13688 window.defer(cx, move |window, cx| {
13689 let target_editor: Entity<Self> =
13690 workspace.update(cx, |workspace, cx| {
13691 let pane = if split {
13692 workspace.adjacent_pane(window, cx)
13693 } else {
13694 workspace.active_pane().clone()
13695 };
13696
13697 workspace.open_project_item(
13698 pane,
13699 target.buffer.clone(),
13700 true,
13701 true,
13702 window,
13703 cx,
13704 )
13705 });
13706 target_editor.update(cx, |target_editor, cx| {
13707 // When selecting a definition in a different buffer, disable the nav history
13708 // to avoid creating a history entry at the previous cursor location.
13709 pane.update(cx, |pane, _| pane.disable_history());
13710 target_editor.go_to_singleton_buffer_range(range, window, cx);
13711 pane.update(cx, |pane, _| pane.enable_history());
13712 });
13713 });
13714 }
13715 Navigated::Yes
13716 })
13717 })
13718 } else if !definitions.is_empty() {
13719 cx.spawn_in(window, async move |editor, cx| {
13720 let (title, location_tasks, workspace) = editor
13721 .update_in(cx, |editor, window, cx| {
13722 let tab_kind = match kind {
13723 Some(GotoDefinitionKind::Implementation) => "Implementations",
13724 _ => "Definitions",
13725 };
13726 let title = definitions
13727 .iter()
13728 .find_map(|definition| match definition {
13729 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13730 let buffer = origin.buffer.read(cx);
13731 format!(
13732 "{} for {}",
13733 tab_kind,
13734 buffer
13735 .text_for_range(origin.range.clone())
13736 .collect::<String>()
13737 )
13738 }),
13739 HoverLink::InlayHint(_, _) => None,
13740 HoverLink::Url(_) => None,
13741 HoverLink::File(_) => None,
13742 })
13743 .unwrap_or(tab_kind.to_string());
13744 let location_tasks = definitions
13745 .into_iter()
13746 .map(|definition| match definition {
13747 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13748 HoverLink::InlayHint(lsp_location, server_id) => editor
13749 .compute_target_location(lsp_location, server_id, window, cx),
13750 HoverLink::Url(_) => Task::ready(Ok(None)),
13751 HoverLink::File(_) => Task::ready(Ok(None)),
13752 })
13753 .collect::<Vec<_>>();
13754 (title, location_tasks, editor.workspace().clone())
13755 })
13756 .context("location tasks preparation")?;
13757
13758 let locations = future::join_all(location_tasks)
13759 .await
13760 .into_iter()
13761 .filter_map(|location| location.transpose())
13762 .collect::<Result<_>>()
13763 .context("location tasks")?;
13764
13765 let Some(workspace) = workspace else {
13766 return Ok(Navigated::No);
13767 };
13768 let opened = workspace
13769 .update_in(cx, |workspace, window, cx| {
13770 Self::open_locations_in_multibuffer(
13771 workspace,
13772 locations,
13773 title,
13774 split,
13775 MultibufferSelectionMode::First,
13776 window,
13777 cx,
13778 )
13779 })
13780 .ok();
13781
13782 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13783 })
13784 } else {
13785 Task::ready(Ok(Navigated::No))
13786 }
13787 }
13788
13789 fn compute_target_location(
13790 &self,
13791 lsp_location: lsp::Location,
13792 server_id: LanguageServerId,
13793 window: &mut Window,
13794 cx: &mut Context<Self>,
13795 ) -> Task<anyhow::Result<Option<Location>>> {
13796 let Some(project) = self.project.clone() else {
13797 return Task::ready(Ok(None));
13798 };
13799
13800 cx.spawn_in(window, async move |editor, cx| {
13801 let location_task = editor.update(cx, |_, cx| {
13802 project.update(cx, |project, cx| {
13803 let language_server_name = project
13804 .language_server_statuses(cx)
13805 .find(|(id, _)| server_id == *id)
13806 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13807 language_server_name.map(|language_server_name| {
13808 project.open_local_buffer_via_lsp(
13809 lsp_location.uri.clone(),
13810 server_id,
13811 language_server_name,
13812 cx,
13813 )
13814 })
13815 })
13816 })?;
13817 let location = match location_task {
13818 Some(task) => Some({
13819 let target_buffer_handle = task.await.context("open local buffer")?;
13820 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13821 let target_start = target_buffer
13822 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13823 let target_end = target_buffer
13824 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13825 target_buffer.anchor_after(target_start)
13826 ..target_buffer.anchor_before(target_end)
13827 })?;
13828 Location {
13829 buffer: target_buffer_handle,
13830 range,
13831 }
13832 }),
13833 None => None,
13834 };
13835 Ok(location)
13836 })
13837 }
13838
13839 pub fn find_all_references(
13840 &mut self,
13841 _: &FindAllReferences,
13842 window: &mut Window,
13843 cx: &mut Context<Self>,
13844 ) -> Option<Task<Result<Navigated>>> {
13845 let selection = self.selections.newest::<usize>(cx);
13846 let multi_buffer = self.buffer.read(cx);
13847 let head = selection.head();
13848
13849 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13850 let head_anchor = multi_buffer_snapshot.anchor_at(
13851 head,
13852 if head < selection.tail() {
13853 Bias::Right
13854 } else {
13855 Bias::Left
13856 },
13857 );
13858
13859 match self
13860 .find_all_references_task_sources
13861 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13862 {
13863 Ok(_) => {
13864 log::info!(
13865 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13866 );
13867 return None;
13868 }
13869 Err(i) => {
13870 self.find_all_references_task_sources.insert(i, head_anchor);
13871 }
13872 }
13873
13874 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13875 let workspace = self.workspace()?;
13876 let project = workspace.read(cx).project().clone();
13877 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13878 Some(cx.spawn_in(window, async move |editor, cx| {
13879 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13880 if let Ok(i) = editor
13881 .find_all_references_task_sources
13882 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13883 {
13884 editor.find_all_references_task_sources.remove(i);
13885 }
13886 });
13887
13888 let locations = references.await?;
13889 if locations.is_empty() {
13890 return anyhow::Ok(Navigated::No);
13891 }
13892
13893 workspace.update_in(cx, |workspace, window, cx| {
13894 let title = locations
13895 .first()
13896 .as_ref()
13897 .map(|location| {
13898 let buffer = location.buffer.read(cx);
13899 format!(
13900 "References to `{}`",
13901 buffer
13902 .text_for_range(location.range.clone())
13903 .collect::<String>()
13904 )
13905 })
13906 .unwrap();
13907 Self::open_locations_in_multibuffer(
13908 workspace,
13909 locations,
13910 title,
13911 false,
13912 MultibufferSelectionMode::First,
13913 window,
13914 cx,
13915 );
13916 Navigated::Yes
13917 })
13918 }))
13919 }
13920
13921 /// Opens a multibuffer with the given project locations in it
13922 pub fn open_locations_in_multibuffer(
13923 workspace: &mut Workspace,
13924 mut locations: Vec<Location>,
13925 title: String,
13926 split: bool,
13927 multibuffer_selection_mode: MultibufferSelectionMode,
13928 window: &mut Window,
13929 cx: &mut Context<Workspace>,
13930 ) {
13931 // If there are multiple definitions, open them in a multibuffer
13932 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13933 let mut locations = locations.into_iter().peekable();
13934 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13935 let capability = workspace.project().read(cx).capability();
13936
13937 let excerpt_buffer = cx.new(|cx| {
13938 let mut multibuffer = MultiBuffer::new(capability);
13939 while let Some(location) = locations.next() {
13940 let buffer = location.buffer.read(cx);
13941 let mut ranges_for_buffer = Vec::new();
13942 let range = location.range.to_point(buffer);
13943 ranges_for_buffer.push(range.clone());
13944
13945 while let Some(next_location) = locations.peek() {
13946 if next_location.buffer == location.buffer {
13947 ranges_for_buffer.push(next_location.range.to_point(buffer));
13948 locations.next();
13949 } else {
13950 break;
13951 }
13952 }
13953
13954 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13955 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13956 PathKey::for_buffer(&location.buffer, cx),
13957 location.buffer.clone(),
13958 ranges_for_buffer,
13959 DEFAULT_MULTIBUFFER_CONTEXT,
13960 cx,
13961 );
13962 ranges.extend(new_ranges)
13963 }
13964
13965 multibuffer.with_title(title)
13966 });
13967
13968 let editor = cx.new(|cx| {
13969 Editor::for_multibuffer(
13970 excerpt_buffer,
13971 Some(workspace.project().clone()),
13972 window,
13973 cx,
13974 )
13975 });
13976 editor.update(cx, |editor, cx| {
13977 match multibuffer_selection_mode {
13978 MultibufferSelectionMode::First => {
13979 if let Some(first_range) = ranges.first() {
13980 editor.change_selections(None, window, cx, |selections| {
13981 selections.clear_disjoint();
13982 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13983 });
13984 }
13985 editor.highlight_background::<Self>(
13986 &ranges,
13987 |theme| theme.editor_highlighted_line_background,
13988 cx,
13989 );
13990 }
13991 MultibufferSelectionMode::All => {
13992 editor.change_selections(None, window, cx, |selections| {
13993 selections.clear_disjoint();
13994 selections.select_anchor_ranges(ranges);
13995 });
13996 }
13997 }
13998 editor.register_buffers_with_language_servers(cx);
13999 });
14000
14001 let item = Box::new(editor);
14002 let item_id = item.item_id();
14003
14004 if split {
14005 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14006 } else {
14007 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14008 let (preview_item_id, preview_item_idx) =
14009 workspace.active_pane().update(cx, |pane, _| {
14010 (pane.preview_item_id(), pane.preview_item_idx())
14011 });
14012
14013 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14014
14015 if let Some(preview_item_id) = preview_item_id {
14016 workspace.active_pane().update(cx, |pane, cx| {
14017 pane.remove_item(preview_item_id, false, false, window, cx);
14018 });
14019 }
14020 } else {
14021 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14022 }
14023 }
14024 workspace.active_pane().update(cx, |pane, cx| {
14025 pane.set_preview_item_id(Some(item_id), cx);
14026 });
14027 }
14028
14029 pub fn rename(
14030 &mut self,
14031 _: &Rename,
14032 window: &mut Window,
14033 cx: &mut Context<Self>,
14034 ) -> Option<Task<Result<()>>> {
14035 use language::ToOffset as _;
14036
14037 let provider = self.semantics_provider.clone()?;
14038 let selection = self.selections.newest_anchor().clone();
14039 let (cursor_buffer, cursor_buffer_position) = self
14040 .buffer
14041 .read(cx)
14042 .text_anchor_for_position(selection.head(), cx)?;
14043 let (tail_buffer, cursor_buffer_position_end) = self
14044 .buffer
14045 .read(cx)
14046 .text_anchor_for_position(selection.tail(), cx)?;
14047 if tail_buffer != cursor_buffer {
14048 return None;
14049 }
14050
14051 let snapshot = cursor_buffer.read(cx).snapshot();
14052 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14053 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14054 let prepare_rename = provider
14055 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14056 .unwrap_or_else(|| Task::ready(Ok(None)));
14057 drop(snapshot);
14058
14059 Some(cx.spawn_in(window, async move |this, cx| {
14060 let rename_range = if let Some(range) = prepare_rename.await? {
14061 Some(range)
14062 } else {
14063 this.update(cx, |this, cx| {
14064 let buffer = this.buffer.read(cx).snapshot(cx);
14065 let mut buffer_highlights = this
14066 .document_highlights_for_position(selection.head(), &buffer)
14067 .filter(|highlight| {
14068 highlight.start.excerpt_id == selection.head().excerpt_id
14069 && highlight.end.excerpt_id == selection.head().excerpt_id
14070 });
14071 buffer_highlights
14072 .next()
14073 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14074 })?
14075 };
14076 if let Some(rename_range) = rename_range {
14077 this.update_in(cx, |this, window, cx| {
14078 let snapshot = cursor_buffer.read(cx).snapshot();
14079 let rename_buffer_range = rename_range.to_offset(&snapshot);
14080 let cursor_offset_in_rename_range =
14081 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14082 let cursor_offset_in_rename_range_end =
14083 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14084
14085 this.take_rename(false, window, cx);
14086 let buffer = this.buffer.read(cx).read(cx);
14087 let cursor_offset = selection.head().to_offset(&buffer);
14088 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14089 let rename_end = rename_start + rename_buffer_range.len();
14090 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14091 let mut old_highlight_id = None;
14092 let old_name: Arc<str> = buffer
14093 .chunks(rename_start..rename_end, true)
14094 .map(|chunk| {
14095 if old_highlight_id.is_none() {
14096 old_highlight_id = chunk.syntax_highlight_id;
14097 }
14098 chunk.text
14099 })
14100 .collect::<String>()
14101 .into();
14102
14103 drop(buffer);
14104
14105 // Position the selection in the rename editor so that it matches the current selection.
14106 this.show_local_selections = false;
14107 let rename_editor = cx.new(|cx| {
14108 let mut editor = Editor::single_line(window, cx);
14109 editor.buffer.update(cx, |buffer, cx| {
14110 buffer.edit([(0..0, old_name.clone())], None, cx)
14111 });
14112 let rename_selection_range = match cursor_offset_in_rename_range
14113 .cmp(&cursor_offset_in_rename_range_end)
14114 {
14115 Ordering::Equal => {
14116 editor.select_all(&SelectAll, window, cx);
14117 return editor;
14118 }
14119 Ordering::Less => {
14120 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14121 }
14122 Ordering::Greater => {
14123 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14124 }
14125 };
14126 if rename_selection_range.end > old_name.len() {
14127 editor.select_all(&SelectAll, window, cx);
14128 } else {
14129 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14130 s.select_ranges([rename_selection_range]);
14131 });
14132 }
14133 editor
14134 });
14135 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14136 if e == &EditorEvent::Focused {
14137 cx.emit(EditorEvent::FocusedIn)
14138 }
14139 })
14140 .detach();
14141
14142 let write_highlights =
14143 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14144 let read_highlights =
14145 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14146 let ranges = write_highlights
14147 .iter()
14148 .flat_map(|(_, ranges)| ranges.iter())
14149 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14150 .cloned()
14151 .collect();
14152
14153 this.highlight_text::<Rename>(
14154 ranges,
14155 HighlightStyle {
14156 fade_out: Some(0.6),
14157 ..Default::default()
14158 },
14159 cx,
14160 );
14161 let rename_focus_handle = rename_editor.focus_handle(cx);
14162 window.focus(&rename_focus_handle);
14163 let block_id = this.insert_blocks(
14164 [BlockProperties {
14165 style: BlockStyle::Flex,
14166 placement: BlockPlacement::Below(range.start),
14167 height: Some(1),
14168 render: Arc::new({
14169 let rename_editor = rename_editor.clone();
14170 move |cx: &mut BlockContext| {
14171 let mut text_style = cx.editor_style.text.clone();
14172 if let Some(highlight_style) = old_highlight_id
14173 .and_then(|h| h.style(&cx.editor_style.syntax))
14174 {
14175 text_style = text_style.highlight(highlight_style);
14176 }
14177 div()
14178 .block_mouse_down()
14179 .pl(cx.anchor_x)
14180 .child(EditorElement::new(
14181 &rename_editor,
14182 EditorStyle {
14183 background: cx.theme().system().transparent,
14184 local_player: cx.editor_style.local_player,
14185 text: text_style,
14186 scrollbar_width: cx.editor_style.scrollbar_width,
14187 syntax: cx.editor_style.syntax.clone(),
14188 status: cx.editor_style.status.clone(),
14189 inlay_hints_style: HighlightStyle {
14190 font_weight: Some(FontWeight::BOLD),
14191 ..make_inlay_hints_style(cx.app)
14192 },
14193 inline_completion_styles: make_suggestion_styles(
14194 cx.app,
14195 ),
14196 ..EditorStyle::default()
14197 },
14198 ))
14199 .into_any_element()
14200 }
14201 }),
14202 priority: 0,
14203 }],
14204 Some(Autoscroll::fit()),
14205 cx,
14206 )[0];
14207 this.pending_rename = Some(RenameState {
14208 range,
14209 old_name,
14210 editor: rename_editor,
14211 block_id,
14212 });
14213 })?;
14214 }
14215
14216 Ok(())
14217 }))
14218 }
14219
14220 pub fn confirm_rename(
14221 &mut self,
14222 _: &ConfirmRename,
14223 window: &mut Window,
14224 cx: &mut Context<Self>,
14225 ) -> Option<Task<Result<()>>> {
14226 let rename = self.take_rename(false, window, cx)?;
14227 let workspace = self.workspace()?.downgrade();
14228 let (buffer, start) = self
14229 .buffer
14230 .read(cx)
14231 .text_anchor_for_position(rename.range.start, cx)?;
14232 let (end_buffer, _) = self
14233 .buffer
14234 .read(cx)
14235 .text_anchor_for_position(rename.range.end, cx)?;
14236 if buffer != end_buffer {
14237 return None;
14238 }
14239
14240 let old_name = rename.old_name;
14241 let new_name = rename.editor.read(cx).text(cx);
14242
14243 let rename = self.semantics_provider.as_ref()?.perform_rename(
14244 &buffer,
14245 start,
14246 new_name.clone(),
14247 cx,
14248 )?;
14249
14250 Some(cx.spawn_in(window, async move |editor, cx| {
14251 let project_transaction = rename.await?;
14252 Self::open_project_transaction(
14253 &editor,
14254 workspace,
14255 project_transaction,
14256 format!("Rename: {} → {}", old_name, new_name),
14257 cx,
14258 )
14259 .await?;
14260
14261 editor.update(cx, |editor, cx| {
14262 editor.refresh_document_highlights(cx);
14263 })?;
14264 Ok(())
14265 }))
14266 }
14267
14268 fn take_rename(
14269 &mut self,
14270 moving_cursor: bool,
14271 window: &mut Window,
14272 cx: &mut Context<Self>,
14273 ) -> Option<RenameState> {
14274 let rename = self.pending_rename.take()?;
14275 if rename.editor.focus_handle(cx).is_focused(window) {
14276 window.focus(&self.focus_handle);
14277 }
14278
14279 self.remove_blocks(
14280 [rename.block_id].into_iter().collect(),
14281 Some(Autoscroll::fit()),
14282 cx,
14283 );
14284 self.clear_highlights::<Rename>(cx);
14285 self.show_local_selections = true;
14286
14287 if moving_cursor {
14288 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14289 editor.selections.newest::<usize>(cx).head()
14290 });
14291
14292 // Update the selection to match the position of the selection inside
14293 // the rename editor.
14294 let snapshot = self.buffer.read(cx).read(cx);
14295 let rename_range = rename.range.to_offset(&snapshot);
14296 let cursor_in_editor = snapshot
14297 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14298 .min(rename_range.end);
14299 drop(snapshot);
14300
14301 self.change_selections(None, window, cx, |s| {
14302 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14303 });
14304 } else {
14305 self.refresh_document_highlights(cx);
14306 }
14307
14308 Some(rename)
14309 }
14310
14311 pub fn pending_rename(&self) -> Option<&RenameState> {
14312 self.pending_rename.as_ref()
14313 }
14314
14315 fn format(
14316 &mut self,
14317 _: &Format,
14318 window: &mut Window,
14319 cx: &mut Context<Self>,
14320 ) -> Option<Task<Result<()>>> {
14321 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14322
14323 let project = match &self.project {
14324 Some(project) => project.clone(),
14325 None => return None,
14326 };
14327
14328 Some(self.perform_format(
14329 project,
14330 FormatTrigger::Manual,
14331 FormatTarget::Buffers,
14332 window,
14333 cx,
14334 ))
14335 }
14336
14337 fn format_selections(
14338 &mut self,
14339 _: &FormatSelections,
14340 window: &mut Window,
14341 cx: &mut Context<Self>,
14342 ) -> Option<Task<Result<()>>> {
14343 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14344
14345 let project = match &self.project {
14346 Some(project) => project.clone(),
14347 None => return None,
14348 };
14349
14350 let ranges = self
14351 .selections
14352 .all_adjusted(cx)
14353 .into_iter()
14354 .map(|selection| selection.range())
14355 .collect_vec();
14356
14357 Some(self.perform_format(
14358 project,
14359 FormatTrigger::Manual,
14360 FormatTarget::Ranges(ranges),
14361 window,
14362 cx,
14363 ))
14364 }
14365
14366 fn perform_format(
14367 &mut self,
14368 project: Entity<Project>,
14369 trigger: FormatTrigger,
14370 target: FormatTarget,
14371 window: &mut Window,
14372 cx: &mut Context<Self>,
14373 ) -> Task<Result<()>> {
14374 let buffer = self.buffer.clone();
14375 let (buffers, target) = match target {
14376 FormatTarget::Buffers => {
14377 let mut buffers = buffer.read(cx).all_buffers();
14378 if trigger == FormatTrigger::Save {
14379 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14380 }
14381 (buffers, LspFormatTarget::Buffers)
14382 }
14383 FormatTarget::Ranges(selection_ranges) => {
14384 let multi_buffer = buffer.read(cx);
14385 let snapshot = multi_buffer.read(cx);
14386 let mut buffers = HashSet::default();
14387 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14388 BTreeMap::new();
14389 for selection_range in selection_ranges {
14390 for (buffer, buffer_range, _) in
14391 snapshot.range_to_buffer_ranges(selection_range)
14392 {
14393 let buffer_id = buffer.remote_id();
14394 let start = buffer.anchor_before(buffer_range.start);
14395 let end = buffer.anchor_after(buffer_range.end);
14396 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14397 buffer_id_to_ranges
14398 .entry(buffer_id)
14399 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14400 .or_insert_with(|| vec![start..end]);
14401 }
14402 }
14403 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14404 }
14405 };
14406
14407 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14408 let selections_prev = transaction_id_prev
14409 .and_then(|transaction_id_prev| {
14410 // default to selections as they were after the last edit, if we have them,
14411 // instead of how they are now.
14412 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14413 // will take you back to where you made the last edit, instead of staying where you scrolled
14414 self.selection_history
14415 .transaction(transaction_id_prev)
14416 .map(|t| t.0.clone())
14417 })
14418 .unwrap_or_else(|| {
14419 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14420 self.selections.disjoint_anchors()
14421 });
14422
14423 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14424 let format = project.update(cx, |project, cx| {
14425 project.format(buffers, target, true, trigger, cx)
14426 });
14427
14428 cx.spawn_in(window, async move |editor, cx| {
14429 let transaction = futures::select_biased! {
14430 transaction = format.log_err().fuse() => transaction,
14431 () = timeout => {
14432 log::warn!("timed out waiting for formatting");
14433 None
14434 }
14435 };
14436
14437 buffer
14438 .update(cx, |buffer, cx| {
14439 if let Some(transaction) = transaction {
14440 if !buffer.is_singleton() {
14441 buffer.push_transaction(&transaction.0, cx);
14442 }
14443 }
14444 cx.notify();
14445 })
14446 .ok();
14447
14448 if let Some(transaction_id_now) =
14449 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14450 {
14451 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14452 if has_new_transaction {
14453 _ = editor.update(cx, |editor, _| {
14454 editor
14455 .selection_history
14456 .insert_transaction(transaction_id_now, selections_prev);
14457 });
14458 }
14459 }
14460
14461 Ok(())
14462 })
14463 }
14464
14465 fn organize_imports(
14466 &mut self,
14467 _: &OrganizeImports,
14468 window: &mut Window,
14469 cx: &mut Context<Self>,
14470 ) -> Option<Task<Result<()>>> {
14471 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14472 let project = match &self.project {
14473 Some(project) => project.clone(),
14474 None => return None,
14475 };
14476 Some(self.perform_code_action_kind(
14477 project,
14478 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14479 window,
14480 cx,
14481 ))
14482 }
14483
14484 fn perform_code_action_kind(
14485 &mut self,
14486 project: Entity<Project>,
14487 kind: CodeActionKind,
14488 window: &mut Window,
14489 cx: &mut Context<Self>,
14490 ) -> Task<Result<()>> {
14491 let buffer = self.buffer.clone();
14492 let buffers = buffer.read(cx).all_buffers();
14493 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14494 let apply_action = project.update(cx, |project, cx| {
14495 project.apply_code_action_kind(buffers, kind, true, cx)
14496 });
14497 cx.spawn_in(window, async move |_, cx| {
14498 let transaction = futures::select_biased! {
14499 () = timeout => {
14500 log::warn!("timed out waiting for executing code action");
14501 None
14502 }
14503 transaction = apply_action.log_err().fuse() => transaction,
14504 };
14505 buffer
14506 .update(cx, |buffer, cx| {
14507 // check if we need this
14508 if let Some(transaction) = transaction {
14509 if !buffer.is_singleton() {
14510 buffer.push_transaction(&transaction.0, cx);
14511 }
14512 }
14513 cx.notify();
14514 })
14515 .ok();
14516 Ok(())
14517 })
14518 }
14519
14520 fn restart_language_server(
14521 &mut self,
14522 _: &RestartLanguageServer,
14523 _: &mut Window,
14524 cx: &mut Context<Self>,
14525 ) {
14526 if let Some(project) = self.project.clone() {
14527 self.buffer.update(cx, |multi_buffer, cx| {
14528 project.update(cx, |project, cx| {
14529 project.restart_language_servers_for_buffers(
14530 multi_buffer.all_buffers().into_iter().collect(),
14531 cx,
14532 );
14533 });
14534 })
14535 }
14536 }
14537
14538 fn stop_language_server(
14539 &mut self,
14540 _: &StopLanguageServer,
14541 _: &mut Window,
14542 cx: &mut Context<Self>,
14543 ) {
14544 if let Some(project) = self.project.clone() {
14545 self.buffer.update(cx, |multi_buffer, cx| {
14546 project.update(cx, |project, cx| {
14547 project.stop_language_servers_for_buffers(
14548 multi_buffer.all_buffers().into_iter().collect(),
14549 cx,
14550 );
14551 cx.emit(project::Event::RefreshInlayHints);
14552 });
14553 });
14554 }
14555 }
14556
14557 fn cancel_language_server_work(
14558 workspace: &mut Workspace,
14559 _: &actions::CancelLanguageServerWork,
14560 _: &mut Window,
14561 cx: &mut Context<Workspace>,
14562 ) {
14563 let project = workspace.project();
14564 let buffers = workspace
14565 .active_item(cx)
14566 .and_then(|item| item.act_as::<Editor>(cx))
14567 .map_or(HashSet::default(), |editor| {
14568 editor.read(cx).buffer.read(cx).all_buffers()
14569 });
14570 project.update(cx, |project, cx| {
14571 project.cancel_language_server_work_for_buffers(buffers, cx);
14572 });
14573 }
14574
14575 fn show_character_palette(
14576 &mut self,
14577 _: &ShowCharacterPalette,
14578 window: &mut Window,
14579 _: &mut Context<Self>,
14580 ) {
14581 window.show_character_palette();
14582 }
14583
14584 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14585 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14586 let buffer = self.buffer.read(cx).snapshot(cx);
14587 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14588 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14589 let is_valid = buffer
14590 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14591 .any(|entry| {
14592 entry.diagnostic.is_primary
14593 && !entry.range.is_empty()
14594 && entry.range.start == primary_range_start
14595 && entry.diagnostic.message == active_diagnostics.active_message
14596 });
14597
14598 if !is_valid {
14599 self.dismiss_diagnostics(cx);
14600 }
14601 }
14602 }
14603
14604 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14605 match &self.active_diagnostics {
14606 ActiveDiagnostic::Group(group) => Some(group),
14607 _ => None,
14608 }
14609 }
14610
14611 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14612 self.dismiss_diagnostics(cx);
14613 self.active_diagnostics = ActiveDiagnostic::All;
14614 }
14615
14616 fn activate_diagnostics(
14617 &mut self,
14618 buffer_id: BufferId,
14619 diagnostic: DiagnosticEntry<usize>,
14620 window: &mut Window,
14621 cx: &mut Context<Self>,
14622 ) {
14623 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14624 return;
14625 }
14626 self.dismiss_diagnostics(cx);
14627 let snapshot = self.snapshot(window, cx);
14628 let Some(diagnostic_renderer) = cx
14629 .try_global::<GlobalDiagnosticRenderer>()
14630 .map(|g| g.0.clone())
14631 else {
14632 return;
14633 };
14634 let buffer = self.buffer.read(cx).snapshot(cx);
14635
14636 let diagnostic_group = buffer
14637 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14638 .collect::<Vec<_>>();
14639
14640 let blocks = diagnostic_renderer.render_group(
14641 diagnostic_group,
14642 buffer_id,
14643 snapshot,
14644 cx.weak_entity(),
14645 cx,
14646 );
14647
14648 let blocks = self.display_map.update(cx, |display_map, cx| {
14649 display_map.insert_blocks(blocks, cx).into_iter().collect()
14650 });
14651 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14652 active_range: buffer.anchor_before(diagnostic.range.start)
14653 ..buffer.anchor_after(diagnostic.range.end),
14654 active_message: diagnostic.diagnostic.message.clone(),
14655 group_id: diagnostic.diagnostic.group_id,
14656 blocks,
14657 });
14658 cx.notify();
14659 }
14660
14661 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14662 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14663 return;
14664 };
14665
14666 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14667 if let ActiveDiagnostic::Group(group) = prev {
14668 self.display_map.update(cx, |display_map, cx| {
14669 display_map.remove_blocks(group.blocks, cx);
14670 });
14671 cx.notify();
14672 }
14673 }
14674
14675 /// Disable inline diagnostics rendering for this editor.
14676 pub fn disable_inline_diagnostics(&mut self) {
14677 self.inline_diagnostics_enabled = false;
14678 self.inline_diagnostics_update = Task::ready(());
14679 self.inline_diagnostics.clear();
14680 }
14681
14682 pub fn inline_diagnostics_enabled(&self) -> bool {
14683 self.inline_diagnostics_enabled
14684 }
14685
14686 pub fn show_inline_diagnostics(&self) -> bool {
14687 self.show_inline_diagnostics
14688 }
14689
14690 pub fn toggle_inline_diagnostics(
14691 &mut self,
14692 _: &ToggleInlineDiagnostics,
14693 window: &mut Window,
14694 cx: &mut Context<Editor>,
14695 ) {
14696 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14697 self.refresh_inline_diagnostics(false, window, cx);
14698 }
14699
14700 fn refresh_inline_diagnostics(
14701 &mut self,
14702 debounce: bool,
14703 window: &mut Window,
14704 cx: &mut Context<Self>,
14705 ) {
14706 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14707 self.inline_diagnostics_update = Task::ready(());
14708 self.inline_diagnostics.clear();
14709 return;
14710 }
14711
14712 let debounce_ms = ProjectSettings::get_global(cx)
14713 .diagnostics
14714 .inline
14715 .update_debounce_ms;
14716 let debounce = if debounce && debounce_ms > 0 {
14717 Some(Duration::from_millis(debounce_ms))
14718 } else {
14719 None
14720 };
14721 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14722 let editor = editor.upgrade().unwrap();
14723
14724 if let Some(debounce) = debounce {
14725 cx.background_executor().timer(debounce).await;
14726 }
14727 let Some(snapshot) = editor
14728 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14729 .ok()
14730 else {
14731 return;
14732 };
14733
14734 let new_inline_diagnostics = cx
14735 .background_spawn(async move {
14736 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14737 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14738 let message = diagnostic_entry
14739 .diagnostic
14740 .message
14741 .split_once('\n')
14742 .map(|(line, _)| line)
14743 .map(SharedString::new)
14744 .unwrap_or_else(|| {
14745 SharedString::from(diagnostic_entry.diagnostic.message)
14746 });
14747 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14748 let (Ok(i) | Err(i)) = inline_diagnostics
14749 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14750 inline_diagnostics.insert(
14751 i,
14752 (
14753 start_anchor,
14754 InlineDiagnostic {
14755 message,
14756 group_id: diagnostic_entry.diagnostic.group_id,
14757 start: diagnostic_entry.range.start.to_point(&snapshot),
14758 is_primary: diagnostic_entry.diagnostic.is_primary,
14759 severity: diagnostic_entry.diagnostic.severity,
14760 },
14761 ),
14762 );
14763 }
14764 inline_diagnostics
14765 })
14766 .await;
14767
14768 editor
14769 .update(cx, |editor, cx| {
14770 editor.inline_diagnostics = new_inline_diagnostics;
14771 cx.notify();
14772 })
14773 .ok();
14774 });
14775 }
14776
14777 pub fn set_selections_from_remote(
14778 &mut self,
14779 selections: Vec<Selection<Anchor>>,
14780 pending_selection: Option<Selection<Anchor>>,
14781 window: &mut Window,
14782 cx: &mut Context<Self>,
14783 ) {
14784 let old_cursor_position = self.selections.newest_anchor().head();
14785 self.selections.change_with(cx, |s| {
14786 s.select_anchors(selections);
14787 if let Some(pending_selection) = pending_selection {
14788 s.set_pending(pending_selection, SelectMode::Character);
14789 } else {
14790 s.clear_pending();
14791 }
14792 });
14793 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14794 }
14795
14796 fn push_to_selection_history(&mut self) {
14797 self.selection_history.push(SelectionHistoryEntry {
14798 selections: self.selections.disjoint_anchors(),
14799 select_next_state: self.select_next_state.clone(),
14800 select_prev_state: self.select_prev_state.clone(),
14801 add_selections_state: self.add_selections_state.clone(),
14802 });
14803 }
14804
14805 pub fn transact(
14806 &mut self,
14807 window: &mut Window,
14808 cx: &mut Context<Self>,
14809 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14810 ) -> Option<TransactionId> {
14811 self.start_transaction_at(Instant::now(), window, cx);
14812 update(self, window, cx);
14813 self.end_transaction_at(Instant::now(), cx)
14814 }
14815
14816 pub fn start_transaction_at(
14817 &mut self,
14818 now: Instant,
14819 window: &mut Window,
14820 cx: &mut Context<Self>,
14821 ) {
14822 self.end_selection(window, cx);
14823 if let Some(tx_id) = self
14824 .buffer
14825 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14826 {
14827 self.selection_history
14828 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14829 cx.emit(EditorEvent::TransactionBegun {
14830 transaction_id: tx_id,
14831 })
14832 }
14833 }
14834
14835 pub fn end_transaction_at(
14836 &mut self,
14837 now: Instant,
14838 cx: &mut Context<Self>,
14839 ) -> Option<TransactionId> {
14840 if let Some(transaction_id) = self
14841 .buffer
14842 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14843 {
14844 if let Some((_, end_selections)) =
14845 self.selection_history.transaction_mut(transaction_id)
14846 {
14847 *end_selections = Some(self.selections.disjoint_anchors());
14848 } else {
14849 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14850 }
14851
14852 cx.emit(EditorEvent::Edited { transaction_id });
14853 Some(transaction_id)
14854 } else {
14855 None
14856 }
14857 }
14858
14859 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14860 if self.selection_mark_mode {
14861 self.change_selections(None, window, cx, |s| {
14862 s.move_with(|_, sel| {
14863 sel.collapse_to(sel.head(), SelectionGoal::None);
14864 });
14865 })
14866 }
14867 self.selection_mark_mode = true;
14868 cx.notify();
14869 }
14870
14871 pub fn swap_selection_ends(
14872 &mut self,
14873 _: &actions::SwapSelectionEnds,
14874 window: &mut Window,
14875 cx: &mut Context<Self>,
14876 ) {
14877 self.change_selections(None, window, cx, |s| {
14878 s.move_with(|_, sel| {
14879 if sel.start != sel.end {
14880 sel.reversed = !sel.reversed
14881 }
14882 });
14883 });
14884 self.request_autoscroll(Autoscroll::newest(), cx);
14885 cx.notify();
14886 }
14887
14888 pub fn toggle_fold(
14889 &mut self,
14890 _: &actions::ToggleFold,
14891 window: &mut Window,
14892 cx: &mut Context<Self>,
14893 ) {
14894 if self.is_singleton(cx) {
14895 let selection = self.selections.newest::<Point>(cx);
14896
14897 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14898 let range = if selection.is_empty() {
14899 let point = selection.head().to_display_point(&display_map);
14900 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14901 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14902 .to_point(&display_map);
14903 start..end
14904 } else {
14905 selection.range()
14906 };
14907 if display_map.folds_in_range(range).next().is_some() {
14908 self.unfold_lines(&Default::default(), window, cx)
14909 } else {
14910 self.fold(&Default::default(), window, cx)
14911 }
14912 } else {
14913 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14914 let buffer_ids: HashSet<_> = self
14915 .selections
14916 .disjoint_anchor_ranges()
14917 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14918 .collect();
14919
14920 let should_unfold = buffer_ids
14921 .iter()
14922 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14923
14924 for buffer_id in buffer_ids {
14925 if should_unfold {
14926 self.unfold_buffer(buffer_id, cx);
14927 } else {
14928 self.fold_buffer(buffer_id, cx);
14929 }
14930 }
14931 }
14932 }
14933
14934 pub fn toggle_fold_recursive(
14935 &mut self,
14936 _: &actions::ToggleFoldRecursive,
14937 window: &mut Window,
14938 cx: &mut Context<Self>,
14939 ) {
14940 let selection = self.selections.newest::<Point>(cx);
14941
14942 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14943 let range = if selection.is_empty() {
14944 let point = selection.head().to_display_point(&display_map);
14945 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14946 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14947 .to_point(&display_map);
14948 start..end
14949 } else {
14950 selection.range()
14951 };
14952 if display_map.folds_in_range(range).next().is_some() {
14953 self.unfold_recursive(&Default::default(), window, cx)
14954 } else {
14955 self.fold_recursive(&Default::default(), window, cx)
14956 }
14957 }
14958
14959 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14960 if self.is_singleton(cx) {
14961 let mut to_fold = Vec::new();
14962 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14963 let selections = self.selections.all_adjusted(cx);
14964
14965 for selection in selections {
14966 let range = selection.range().sorted();
14967 let buffer_start_row = range.start.row;
14968
14969 if range.start.row != range.end.row {
14970 let mut found = false;
14971 let mut row = range.start.row;
14972 while row <= range.end.row {
14973 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14974 {
14975 found = true;
14976 row = crease.range().end.row + 1;
14977 to_fold.push(crease);
14978 } else {
14979 row += 1
14980 }
14981 }
14982 if found {
14983 continue;
14984 }
14985 }
14986
14987 for row in (0..=range.start.row).rev() {
14988 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14989 if crease.range().end.row >= buffer_start_row {
14990 to_fold.push(crease);
14991 if row <= range.start.row {
14992 break;
14993 }
14994 }
14995 }
14996 }
14997 }
14998
14999 self.fold_creases(to_fold, true, window, cx);
15000 } else {
15001 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15002 let buffer_ids = self
15003 .selections
15004 .disjoint_anchor_ranges()
15005 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15006 .collect::<HashSet<_>>();
15007 for buffer_id in buffer_ids {
15008 self.fold_buffer(buffer_id, cx);
15009 }
15010 }
15011 }
15012
15013 fn fold_at_level(
15014 &mut self,
15015 fold_at: &FoldAtLevel,
15016 window: &mut Window,
15017 cx: &mut Context<Self>,
15018 ) {
15019 if !self.buffer.read(cx).is_singleton() {
15020 return;
15021 }
15022
15023 let fold_at_level = fold_at.0;
15024 let snapshot = self.buffer.read(cx).snapshot(cx);
15025 let mut to_fold = Vec::new();
15026 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15027
15028 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15029 while start_row < end_row {
15030 match self
15031 .snapshot(window, cx)
15032 .crease_for_buffer_row(MultiBufferRow(start_row))
15033 {
15034 Some(crease) => {
15035 let nested_start_row = crease.range().start.row + 1;
15036 let nested_end_row = crease.range().end.row;
15037
15038 if current_level < fold_at_level {
15039 stack.push((nested_start_row, nested_end_row, current_level + 1));
15040 } else if current_level == fold_at_level {
15041 to_fold.push(crease);
15042 }
15043
15044 start_row = nested_end_row + 1;
15045 }
15046 None => start_row += 1,
15047 }
15048 }
15049 }
15050
15051 self.fold_creases(to_fold, true, window, cx);
15052 }
15053
15054 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15055 if self.buffer.read(cx).is_singleton() {
15056 let mut fold_ranges = Vec::new();
15057 let snapshot = self.buffer.read(cx).snapshot(cx);
15058
15059 for row in 0..snapshot.max_row().0 {
15060 if let Some(foldable_range) = self
15061 .snapshot(window, cx)
15062 .crease_for_buffer_row(MultiBufferRow(row))
15063 {
15064 fold_ranges.push(foldable_range);
15065 }
15066 }
15067
15068 self.fold_creases(fold_ranges, true, window, cx);
15069 } else {
15070 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15071 editor
15072 .update_in(cx, |editor, _, cx| {
15073 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15074 editor.fold_buffer(buffer_id, cx);
15075 }
15076 })
15077 .ok();
15078 });
15079 }
15080 }
15081
15082 pub fn fold_function_bodies(
15083 &mut self,
15084 _: &actions::FoldFunctionBodies,
15085 window: &mut Window,
15086 cx: &mut Context<Self>,
15087 ) {
15088 let snapshot = self.buffer.read(cx).snapshot(cx);
15089
15090 let ranges = snapshot
15091 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15092 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15093 .collect::<Vec<_>>();
15094
15095 let creases = ranges
15096 .into_iter()
15097 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15098 .collect();
15099
15100 self.fold_creases(creases, true, window, cx);
15101 }
15102
15103 pub fn fold_recursive(
15104 &mut self,
15105 _: &actions::FoldRecursive,
15106 window: &mut Window,
15107 cx: &mut Context<Self>,
15108 ) {
15109 let mut to_fold = Vec::new();
15110 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15111 let selections = self.selections.all_adjusted(cx);
15112
15113 for selection in selections {
15114 let range = selection.range().sorted();
15115 let buffer_start_row = range.start.row;
15116
15117 if range.start.row != range.end.row {
15118 let mut found = false;
15119 for row in range.start.row..=range.end.row {
15120 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15121 found = true;
15122 to_fold.push(crease);
15123 }
15124 }
15125 if found {
15126 continue;
15127 }
15128 }
15129
15130 for row in (0..=range.start.row).rev() {
15131 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15132 if crease.range().end.row >= buffer_start_row {
15133 to_fold.push(crease);
15134 } else {
15135 break;
15136 }
15137 }
15138 }
15139 }
15140
15141 self.fold_creases(to_fold, true, window, cx);
15142 }
15143
15144 pub fn fold_at(
15145 &mut self,
15146 buffer_row: MultiBufferRow,
15147 window: &mut Window,
15148 cx: &mut Context<Self>,
15149 ) {
15150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15151
15152 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15153 let autoscroll = self
15154 .selections
15155 .all::<Point>(cx)
15156 .iter()
15157 .any(|selection| crease.range().overlaps(&selection.range()));
15158
15159 self.fold_creases(vec![crease], autoscroll, window, cx);
15160 }
15161 }
15162
15163 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15164 if self.is_singleton(cx) {
15165 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15166 let buffer = &display_map.buffer_snapshot;
15167 let selections = self.selections.all::<Point>(cx);
15168 let ranges = selections
15169 .iter()
15170 .map(|s| {
15171 let range = s.display_range(&display_map).sorted();
15172 let mut start = range.start.to_point(&display_map);
15173 let mut end = range.end.to_point(&display_map);
15174 start.column = 0;
15175 end.column = buffer.line_len(MultiBufferRow(end.row));
15176 start..end
15177 })
15178 .collect::<Vec<_>>();
15179
15180 self.unfold_ranges(&ranges, true, true, cx);
15181 } else {
15182 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15183 let buffer_ids = self
15184 .selections
15185 .disjoint_anchor_ranges()
15186 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15187 .collect::<HashSet<_>>();
15188 for buffer_id in buffer_ids {
15189 self.unfold_buffer(buffer_id, cx);
15190 }
15191 }
15192 }
15193
15194 pub fn unfold_recursive(
15195 &mut self,
15196 _: &UnfoldRecursive,
15197 _window: &mut Window,
15198 cx: &mut Context<Self>,
15199 ) {
15200 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15201 let selections = self.selections.all::<Point>(cx);
15202 let ranges = selections
15203 .iter()
15204 .map(|s| {
15205 let mut range = s.display_range(&display_map).sorted();
15206 *range.start.column_mut() = 0;
15207 *range.end.column_mut() = display_map.line_len(range.end.row());
15208 let start = range.start.to_point(&display_map);
15209 let end = range.end.to_point(&display_map);
15210 start..end
15211 })
15212 .collect::<Vec<_>>();
15213
15214 self.unfold_ranges(&ranges, true, true, cx);
15215 }
15216
15217 pub fn unfold_at(
15218 &mut self,
15219 buffer_row: MultiBufferRow,
15220 _window: &mut Window,
15221 cx: &mut Context<Self>,
15222 ) {
15223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15224
15225 let intersection_range = Point::new(buffer_row.0, 0)
15226 ..Point::new(
15227 buffer_row.0,
15228 display_map.buffer_snapshot.line_len(buffer_row),
15229 );
15230
15231 let autoscroll = self
15232 .selections
15233 .all::<Point>(cx)
15234 .iter()
15235 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15236
15237 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15238 }
15239
15240 pub fn unfold_all(
15241 &mut self,
15242 _: &actions::UnfoldAll,
15243 _window: &mut Window,
15244 cx: &mut Context<Self>,
15245 ) {
15246 if self.buffer.read(cx).is_singleton() {
15247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15248 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15249 } else {
15250 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15251 editor
15252 .update(cx, |editor, cx| {
15253 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15254 editor.unfold_buffer(buffer_id, cx);
15255 }
15256 })
15257 .ok();
15258 });
15259 }
15260 }
15261
15262 pub fn fold_selected_ranges(
15263 &mut self,
15264 _: &FoldSelectedRanges,
15265 window: &mut Window,
15266 cx: &mut Context<Self>,
15267 ) {
15268 let selections = self.selections.all_adjusted(cx);
15269 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15270 let ranges = selections
15271 .into_iter()
15272 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15273 .collect::<Vec<_>>();
15274 self.fold_creases(ranges, true, window, cx);
15275 }
15276
15277 pub fn fold_ranges<T: ToOffset + Clone>(
15278 &mut self,
15279 ranges: Vec<Range<T>>,
15280 auto_scroll: bool,
15281 window: &mut Window,
15282 cx: &mut Context<Self>,
15283 ) {
15284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15285 let ranges = ranges
15286 .into_iter()
15287 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15288 .collect::<Vec<_>>();
15289 self.fold_creases(ranges, auto_scroll, window, cx);
15290 }
15291
15292 pub fn fold_creases<T: ToOffset + Clone>(
15293 &mut self,
15294 creases: Vec<Crease<T>>,
15295 auto_scroll: bool,
15296 _window: &mut Window,
15297 cx: &mut Context<Self>,
15298 ) {
15299 if creases.is_empty() {
15300 return;
15301 }
15302
15303 let mut buffers_affected = HashSet::default();
15304 let multi_buffer = self.buffer().read(cx);
15305 for crease in &creases {
15306 if let Some((_, buffer, _)) =
15307 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15308 {
15309 buffers_affected.insert(buffer.read(cx).remote_id());
15310 };
15311 }
15312
15313 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15314
15315 if auto_scroll {
15316 self.request_autoscroll(Autoscroll::fit(), cx);
15317 }
15318
15319 cx.notify();
15320
15321 self.scrollbar_marker_state.dirty = true;
15322 self.folds_did_change(cx);
15323 }
15324
15325 /// Removes any folds whose ranges intersect any of the given ranges.
15326 pub fn unfold_ranges<T: ToOffset + Clone>(
15327 &mut self,
15328 ranges: &[Range<T>],
15329 inclusive: bool,
15330 auto_scroll: bool,
15331 cx: &mut Context<Self>,
15332 ) {
15333 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15334 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15335 });
15336 self.folds_did_change(cx);
15337 }
15338
15339 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15340 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15341 return;
15342 }
15343 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15344 self.display_map.update(cx, |display_map, cx| {
15345 display_map.fold_buffers([buffer_id], cx)
15346 });
15347 cx.emit(EditorEvent::BufferFoldToggled {
15348 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15349 folded: true,
15350 });
15351 cx.notify();
15352 }
15353
15354 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15355 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15356 return;
15357 }
15358 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15359 self.display_map.update(cx, |display_map, cx| {
15360 display_map.unfold_buffers([buffer_id], cx);
15361 });
15362 cx.emit(EditorEvent::BufferFoldToggled {
15363 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15364 folded: false,
15365 });
15366 cx.notify();
15367 }
15368
15369 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15370 self.display_map.read(cx).is_buffer_folded(buffer)
15371 }
15372
15373 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15374 self.display_map.read(cx).folded_buffers()
15375 }
15376
15377 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15378 self.display_map.update(cx, |display_map, cx| {
15379 display_map.disable_header_for_buffer(buffer_id, cx);
15380 });
15381 cx.notify();
15382 }
15383
15384 /// Removes any folds with the given ranges.
15385 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15386 &mut self,
15387 ranges: &[Range<T>],
15388 type_id: TypeId,
15389 auto_scroll: bool,
15390 cx: &mut Context<Self>,
15391 ) {
15392 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15393 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15394 });
15395 self.folds_did_change(cx);
15396 }
15397
15398 fn remove_folds_with<T: ToOffset + Clone>(
15399 &mut self,
15400 ranges: &[Range<T>],
15401 auto_scroll: bool,
15402 cx: &mut Context<Self>,
15403 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15404 ) {
15405 if ranges.is_empty() {
15406 return;
15407 }
15408
15409 let mut buffers_affected = HashSet::default();
15410 let multi_buffer = self.buffer().read(cx);
15411 for range in ranges {
15412 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15413 buffers_affected.insert(buffer.read(cx).remote_id());
15414 };
15415 }
15416
15417 self.display_map.update(cx, update);
15418
15419 if auto_scroll {
15420 self.request_autoscroll(Autoscroll::fit(), cx);
15421 }
15422
15423 cx.notify();
15424 self.scrollbar_marker_state.dirty = true;
15425 self.active_indent_guides_state.dirty = true;
15426 }
15427
15428 pub fn update_fold_widths(
15429 &mut self,
15430 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15431 cx: &mut Context<Self>,
15432 ) -> bool {
15433 self.display_map
15434 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15435 }
15436
15437 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15438 self.display_map.read(cx).fold_placeholder.clone()
15439 }
15440
15441 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15442 self.buffer.update(cx, |buffer, cx| {
15443 buffer.set_all_diff_hunks_expanded(cx);
15444 });
15445 }
15446
15447 pub fn expand_all_diff_hunks(
15448 &mut self,
15449 _: &ExpandAllDiffHunks,
15450 _window: &mut Window,
15451 cx: &mut Context<Self>,
15452 ) {
15453 self.buffer.update(cx, |buffer, cx| {
15454 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15455 });
15456 }
15457
15458 pub fn toggle_selected_diff_hunks(
15459 &mut self,
15460 _: &ToggleSelectedDiffHunks,
15461 _window: &mut Window,
15462 cx: &mut Context<Self>,
15463 ) {
15464 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15465 self.toggle_diff_hunks_in_ranges(ranges, cx);
15466 }
15467
15468 pub fn diff_hunks_in_ranges<'a>(
15469 &'a self,
15470 ranges: &'a [Range<Anchor>],
15471 buffer: &'a MultiBufferSnapshot,
15472 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15473 ranges.iter().flat_map(move |range| {
15474 let end_excerpt_id = range.end.excerpt_id;
15475 let range = range.to_point(buffer);
15476 let mut peek_end = range.end;
15477 if range.end.row < buffer.max_row().0 {
15478 peek_end = Point::new(range.end.row + 1, 0);
15479 }
15480 buffer
15481 .diff_hunks_in_range(range.start..peek_end)
15482 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15483 })
15484 }
15485
15486 pub fn has_stageable_diff_hunks_in_ranges(
15487 &self,
15488 ranges: &[Range<Anchor>],
15489 snapshot: &MultiBufferSnapshot,
15490 ) -> bool {
15491 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15492 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15493 }
15494
15495 pub fn toggle_staged_selected_diff_hunks(
15496 &mut self,
15497 _: &::git::ToggleStaged,
15498 _: &mut Window,
15499 cx: &mut Context<Self>,
15500 ) {
15501 let snapshot = self.buffer.read(cx).snapshot(cx);
15502 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15503 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15504 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15505 }
15506
15507 pub fn set_render_diff_hunk_controls(
15508 &mut self,
15509 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15510 cx: &mut Context<Self>,
15511 ) {
15512 self.render_diff_hunk_controls = render_diff_hunk_controls;
15513 cx.notify();
15514 }
15515
15516 pub fn stage_and_next(
15517 &mut self,
15518 _: &::git::StageAndNext,
15519 window: &mut Window,
15520 cx: &mut Context<Self>,
15521 ) {
15522 self.do_stage_or_unstage_and_next(true, window, cx);
15523 }
15524
15525 pub fn unstage_and_next(
15526 &mut self,
15527 _: &::git::UnstageAndNext,
15528 window: &mut Window,
15529 cx: &mut Context<Self>,
15530 ) {
15531 self.do_stage_or_unstage_and_next(false, window, cx);
15532 }
15533
15534 pub fn stage_or_unstage_diff_hunks(
15535 &mut self,
15536 stage: bool,
15537 ranges: Vec<Range<Anchor>>,
15538 cx: &mut Context<Self>,
15539 ) {
15540 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15541 cx.spawn(async move |this, cx| {
15542 task.await?;
15543 this.update(cx, |this, cx| {
15544 let snapshot = this.buffer.read(cx).snapshot(cx);
15545 let chunk_by = this
15546 .diff_hunks_in_ranges(&ranges, &snapshot)
15547 .chunk_by(|hunk| hunk.buffer_id);
15548 for (buffer_id, hunks) in &chunk_by {
15549 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15550 }
15551 })
15552 })
15553 .detach_and_log_err(cx);
15554 }
15555
15556 fn save_buffers_for_ranges_if_needed(
15557 &mut self,
15558 ranges: &[Range<Anchor>],
15559 cx: &mut Context<Editor>,
15560 ) -> Task<Result<()>> {
15561 let multibuffer = self.buffer.read(cx);
15562 let snapshot = multibuffer.read(cx);
15563 let buffer_ids: HashSet<_> = ranges
15564 .iter()
15565 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15566 .collect();
15567 drop(snapshot);
15568
15569 let mut buffers = HashSet::default();
15570 for buffer_id in buffer_ids {
15571 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15572 let buffer = buffer_entity.read(cx);
15573 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15574 {
15575 buffers.insert(buffer_entity);
15576 }
15577 }
15578 }
15579
15580 if let Some(project) = &self.project {
15581 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15582 } else {
15583 Task::ready(Ok(()))
15584 }
15585 }
15586
15587 fn do_stage_or_unstage_and_next(
15588 &mut self,
15589 stage: bool,
15590 window: &mut Window,
15591 cx: &mut Context<Self>,
15592 ) {
15593 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15594
15595 if ranges.iter().any(|range| range.start != range.end) {
15596 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15597 return;
15598 }
15599
15600 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15601 let snapshot = self.snapshot(window, cx);
15602 let position = self.selections.newest::<Point>(cx).head();
15603 let mut row = snapshot
15604 .buffer_snapshot
15605 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15606 .find(|hunk| hunk.row_range.start.0 > position.row)
15607 .map(|hunk| hunk.row_range.start);
15608
15609 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15610 // Outside of the project diff editor, wrap around to the beginning.
15611 if !all_diff_hunks_expanded {
15612 row = row.or_else(|| {
15613 snapshot
15614 .buffer_snapshot
15615 .diff_hunks_in_range(Point::zero()..position)
15616 .find(|hunk| hunk.row_range.end.0 < position.row)
15617 .map(|hunk| hunk.row_range.start)
15618 });
15619 }
15620
15621 if let Some(row) = row {
15622 let destination = Point::new(row.0, 0);
15623 let autoscroll = Autoscroll::center();
15624
15625 self.unfold_ranges(&[destination..destination], false, false, cx);
15626 self.change_selections(Some(autoscroll), window, cx, |s| {
15627 s.select_ranges([destination..destination]);
15628 });
15629 }
15630 }
15631
15632 fn do_stage_or_unstage(
15633 &self,
15634 stage: bool,
15635 buffer_id: BufferId,
15636 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15637 cx: &mut App,
15638 ) -> Option<()> {
15639 let project = self.project.as_ref()?;
15640 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15641 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15642 let buffer_snapshot = buffer.read(cx).snapshot();
15643 let file_exists = buffer_snapshot
15644 .file()
15645 .is_some_and(|file| file.disk_state().exists());
15646 diff.update(cx, |diff, cx| {
15647 diff.stage_or_unstage_hunks(
15648 stage,
15649 &hunks
15650 .map(|hunk| buffer_diff::DiffHunk {
15651 buffer_range: hunk.buffer_range,
15652 diff_base_byte_range: hunk.diff_base_byte_range,
15653 secondary_status: hunk.secondary_status,
15654 range: Point::zero()..Point::zero(), // unused
15655 })
15656 .collect::<Vec<_>>(),
15657 &buffer_snapshot,
15658 file_exists,
15659 cx,
15660 )
15661 });
15662 None
15663 }
15664
15665 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15666 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15667 self.buffer
15668 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15669 }
15670
15671 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15672 self.buffer.update(cx, |buffer, cx| {
15673 let ranges = vec![Anchor::min()..Anchor::max()];
15674 if !buffer.all_diff_hunks_expanded()
15675 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15676 {
15677 buffer.collapse_diff_hunks(ranges, cx);
15678 true
15679 } else {
15680 false
15681 }
15682 })
15683 }
15684
15685 fn toggle_diff_hunks_in_ranges(
15686 &mut self,
15687 ranges: Vec<Range<Anchor>>,
15688 cx: &mut Context<Editor>,
15689 ) {
15690 self.buffer.update(cx, |buffer, cx| {
15691 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15692 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15693 })
15694 }
15695
15696 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15697 self.buffer.update(cx, |buffer, cx| {
15698 let snapshot = buffer.snapshot(cx);
15699 let excerpt_id = range.end.excerpt_id;
15700 let point_range = range.to_point(&snapshot);
15701 let expand = !buffer.single_hunk_is_expanded(range, cx);
15702 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15703 })
15704 }
15705
15706 pub(crate) fn apply_all_diff_hunks(
15707 &mut self,
15708 _: &ApplyAllDiffHunks,
15709 window: &mut Window,
15710 cx: &mut Context<Self>,
15711 ) {
15712 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15713
15714 let buffers = self.buffer.read(cx).all_buffers();
15715 for branch_buffer in buffers {
15716 branch_buffer.update(cx, |branch_buffer, cx| {
15717 branch_buffer.merge_into_base(Vec::new(), cx);
15718 });
15719 }
15720
15721 if let Some(project) = self.project.clone() {
15722 self.save(true, project, window, cx).detach_and_log_err(cx);
15723 }
15724 }
15725
15726 pub(crate) fn apply_selected_diff_hunks(
15727 &mut self,
15728 _: &ApplyDiffHunk,
15729 window: &mut Window,
15730 cx: &mut Context<Self>,
15731 ) {
15732 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15733 let snapshot = self.snapshot(window, cx);
15734 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15735 let mut ranges_by_buffer = HashMap::default();
15736 self.transact(window, cx, |editor, _window, cx| {
15737 for hunk in hunks {
15738 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15739 ranges_by_buffer
15740 .entry(buffer.clone())
15741 .or_insert_with(Vec::new)
15742 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15743 }
15744 }
15745
15746 for (buffer, ranges) in ranges_by_buffer {
15747 buffer.update(cx, |buffer, cx| {
15748 buffer.merge_into_base(ranges, cx);
15749 });
15750 }
15751 });
15752
15753 if let Some(project) = self.project.clone() {
15754 self.save(true, project, window, cx).detach_and_log_err(cx);
15755 }
15756 }
15757
15758 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15759 if hovered != self.gutter_hovered {
15760 self.gutter_hovered = hovered;
15761 cx.notify();
15762 }
15763 }
15764
15765 pub fn insert_blocks(
15766 &mut self,
15767 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15768 autoscroll: Option<Autoscroll>,
15769 cx: &mut Context<Self>,
15770 ) -> Vec<CustomBlockId> {
15771 let blocks = self
15772 .display_map
15773 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15774 if let Some(autoscroll) = autoscroll {
15775 self.request_autoscroll(autoscroll, cx);
15776 }
15777 cx.notify();
15778 blocks
15779 }
15780
15781 pub fn resize_blocks(
15782 &mut self,
15783 heights: HashMap<CustomBlockId, u32>,
15784 autoscroll: Option<Autoscroll>,
15785 cx: &mut Context<Self>,
15786 ) {
15787 self.display_map
15788 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15789 if let Some(autoscroll) = autoscroll {
15790 self.request_autoscroll(autoscroll, cx);
15791 }
15792 cx.notify();
15793 }
15794
15795 pub fn replace_blocks(
15796 &mut self,
15797 renderers: HashMap<CustomBlockId, RenderBlock>,
15798 autoscroll: Option<Autoscroll>,
15799 cx: &mut Context<Self>,
15800 ) {
15801 self.display_map
15802 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15803 if let Some(autoscroll) = autoscroll {
15804 self.request_autoscroll(autoscroll, cx);
15805 }
15806 cx.notify();
15807 }
15808
15809 pub fn remove_blocks(
15810 &mut self,
15811 block_ids: HashSet<CustomBlockId>,
15812 autoscroll: Option<Autoscroll>,
15813 cx: &mut Context<Self>,
15814 ) {
15815 self.display_map.update(cx, |display_map, cx| {
15816 display_map.remove_blocks(block_ids, cx)
15817 });
15818 if let Some(autoscroll) = autoscroll {
15819 self.request_autoscroll(autoscroll, cx);
15820 }
15821 cx.notify();
15822 }
15823
15824 pub fn row_for_block(
15825 &self,
15826 block_id: CustomBlockId,
15827 cx: &mut Context<Self>,
15828 ) -> Option<DisplayRow> {
15829 self.display_map
15830 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15831 }
15832
15833 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15834 self.focused_block = Some(focused_block);
15835 }
15836
15837 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15838 self.focused_block.take()
15839 }
15840
15841 pub fn insert_creases(
15842 &mut self,
15843 creases: impl IntoIterator<Item = Crease<Anchor>>,
15844 cx: &mut Context<Self>,
15845 ) -> Vec<CreaseId> {
15846 self.display_map
15847 .update(cx, |map, cx| map.insert_creases(creases, cx))
15848 }
15849
15850 pub fn remove_creases(
15851 &mut self,
15852 ids: impl IntoIterator<Item = CreaseId>,
15853 cx: &mut Context<Self>,
15854 ) {
15855 self.display_map
15856 .update(cx, |map, cx| map.remove_creases(ids, cx));
15857 }
15858
15859 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15860 self.display_map
15861 .update(cx, |map, cx| map.snapshot(cx))
15862 .longest_row()
15863 }
15864
15865 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15866 self.display_map
15867 .update(cx, |map, cx| map.snapshot(cx))
15868 .max_point()
15869 }
15870
15871 pub fn text(&self, cx: &App) -> String {
15872 self.buffer.read(cx).read(cx).text()
15873 }
15874
15875 pub fn is_empty(&self, cx: &App) -> bool {
15876 self.buffer.read(cx).read(cx).is_empty()
15877 }
15878
15879 pub fn text_option(&self, cx: &App) -> Option<String> {
15880 let text = self.text(cx);
15881 let text = text.trim();
15882
15883 if text.is_empty() {
15884 return None;
15885 }
15886
15887 Some(text.to_string())
15888 }
15889
15890 pub fn set_text(
15891 &mut self,
15892 text: impl Into<Arc<str>>,
15893 window: &mut Window,
15894 cx: &mut Context<Self>,
15895 ) {
15896 self.transact(window, cx, |this, _, cx| {
15897 this.buffer
15898 .read(cx)
15899 .as_singleton()
15900 .expect("you can only call set_text on editors for singleton buffers")
15901 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15902 });
15903 }
15904
15905 pub fn display_text(&self, cx: &mut App) -> String {
15906 self.display_map
15907 .update(cx, |map, cx| map.snapshot(cx))
15908 .text()
15909 }
15910
15911 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15912 let mut wrap_guides = smallvec::smallvec![];
15913
15914 if self.show_wrap_guides == Some(false) {
15915 return wrap_guides;
15916 }
15917
15918 let settings = self.buffer.read(cx).language_settings(cx);
15919 if settings.show_wrap_guides {
15920 match self.soft_wrap_mode(cx) {
15921 SoftWrap::Column(soft_wrap) => {
15922 wrap_guides.push((soft_wrap as usize, true));
15923 }
15924 SoftWrap::Bounded(soft_wrap) => {
15925 wrap_guides.push((soft_wrap as usize, true));
15926 }
15927 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15928 }
15929 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15930 }
15931
15932 wrap_guides
15933 }
15934
15935 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15936 let settings = self.buffer.read(cx).language_settings(cx);
15937 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15938 match mode {
15939 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15940 SoftWrap::None
15941 }
15942 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15943 language_settings::SoftWrap::PreferredLineLength => {
15944 SoftWrap::Column(settings.preferred_line_length)
15945 }
15946 language_settings::SoftWrap::Bounded => {
15947 SoftWrap::Bounded(settings.preferred_line_length)
15948 }
15949 }
15950 }
15951
15952 pub fn set_soft_wrap_mode(
15953 &mut self,
15954 mode: language_settings::SoftWrap,
15955
15956 cx: &mut Context<Self>,
15957 ) {
15958 self.soft_wrap_mode_override = Some(mode);
15959 cx.notify();
15960 }
15961
15962 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15963 self.hard_wrap = hard_wrap;
15964 cx.notify();
15965 }
15966
15967 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15968 self.text_style_refinement = Some(style);
15969 }
15970
15971 /// called by the Element so we know what style we were most recently rendered with.
15972 pub(crate) fn set_style(
15973 &mut self,
15974 style: EditorStyle,
15975 window: &mut Window,
15976 cx: &mut Context<Self>,
15977 ) {
15978 let rem_size = window.rem_size();
15979 self.display_map.update(cx, |map, cx| {
15980 map.set_font(
15981 style.text.font(),
15982 style.text.font_size.to_pixels(rem_size),
15983 cx,
15984 )
15985 });
15986 self.style = Some(style);
15987 }
15988
15989 pub fn style(&self) -> Option<&EditorStyle> {
15990 self.style.as_ref()
15991 }
15992
15993 // Called by the element. This method is not designed to be called outside of the editor
15994 // element's layout code because it does not notify when rewrapping is computed synchronously.
15995 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15996 self.display_map
15997 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15998 }
15999
16000 pub fn set_soft_wrap(&mut self) {
16001 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16002 }
16003
16004 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16005 if self.soft_wrap_mode_override.is_some() {
16006 self.soft_wrap_mode_override.take();
16007 } else {
16008 let soft_wrap = match self.soft_wrap_mode(cx) {
16009 SoftWrap::GitDiff => return,
16010 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16011 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16012 language_settings::SoftWrap::None
16013 }
16014 };
16015 self.soft_wrap_mode_override = Some(soft_wrap);
16016 }
16017 cx.notify();
16018 }
16019
16020 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16021 let Some(workspace) = self.workspace() else {
16022 return;
16023 };
16024 let fs = workspace.read(cx).app_state().fs.clone();
16025 let current_show = TabBarSettings::get_global(cx).show;
16026 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16027 setting.show = Some(!current_show);
16028 });
16029 }
16030
16031 pub fn toggle_indent_guides(
16032 &mut self,
16033 _: &ToggleIndentGuides,
16034 _: &mut Window,
16035 cx: &mut Context<Self>,
16036 ) {
16037 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16038 self.buffer
16039 .read(cx)
16040 .language_settings(cx)
16041 .indent_guides
16042 .enabled
16043 });
16044 self.show_indent_guides = Some(!currently_enabled);
16045 cx.notify();
16046 }
16047
16048 fn should_show_indent_guides(&self) -> Option<bool> {
16049 self.show_indent_guides
16050 }
16051
16052 pub fn toggle_line_numbers(
16053 &mut self,
16054 _: &ToggleLineNumbers,
16055 _: &mut Window,
16056 cx: &mut Context<Self>,
16057 ) {
16058 let mut editor_settings = EditorSettings::get_global(cx).clone();
16059 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16060 EditorSettings::override_global(editor_settings, cx);
16061 }
16062
16063 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16064 if let Some(show_line_numbers) = self.show_line_numbers {
16065 return show_line_numbers;
16066 }
16067 EditorSettings::get_global(cx).gutter.line_numbers
16068 }
16069
16070 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16071 self.use_relative_line_numbers
16072 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16073 }
16074
16075 pub fn toggle_relative_line_numbers(
16076 &mut self,
16077 _: &ToggleRelativeLineNumbers,
16078 _: &mut Window,
16079 cx: &mut Context<Self>,
16080 ) {
16081 let is_relative = self.should_use_relative_line_numbers(cx);
16082 self.set_relative_line_number(Some(!is_relative), cx)
16083 }
16084
16085 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16086 self.use_relative_line_numbers = is_relative;
16087 cx.notify();
16088 }
16089
16090 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16091 self.show_gutter = show_gutter;
16092 cx.notify();
16093 }
16094
16095 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16096 self.show_scrollbars = show_scrollbars;
16097 cx.notify();
16098 }
16099
16100 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16101 self.show_line_numbers = Some(show_line_numbers);
16102 cx.notify();
16103 }
16104
16105 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16106 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16107 cx.notify();
16108 }
16109
16110 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16111 self.show_code_actions = Some(show_code_actions);
16112 cx.notify();
16113 }
16114
16115 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16116 self.show_runnables = Some(show_runnables);
16117 cx.notify();
16118 }
16119
16120 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16121 self.show_breakpoints = Some(show_breakpoints);
16122 cx.notify();
16123 }
16124
16125 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16126 if self.display_map.read(cx).masked != masked {
16127 self.display_map.update(cx, |map, _| map.masked = masked);
16128 }
16129 cx.notify()
16130 }
16131
16132 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16133 self.show_wrap_guides = Some(show_wrap_guides);
16134 cx.notify();
16135 }
16136
16137 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16138 self.show_indent_guides = Some(show_indent_guides);
16139 cx.notify();
16140 }
16141
16142 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16143 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16144 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16145 if let Some(dir) = file.abs_path(cx).parent() {
16146 return Some(dir.to_owned());
16147 }
16148 }
16149
16150 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16151 return Some(project_path.path.to_path_buf());
16152 }
16153 }
16154
16155 None
16156 }
16157
16158 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16159 self.active_excerpt(cx)?
16160 .1
16161 .read(cx)
16162 .file()
16163 .and_then(|f| f.as_local())
16164 }
16165
16166 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16167 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16168 let buffer = buffer.read(cx);
16169 if let Some(project_path) = buffer.project_path(cx) {
16170 let project = self.project.as_ref()?.read(cx);
16171 project.absolute_path(&project_path, cx)
16172 } else {
16173 buffer
16174 .file()
16175 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16176 }
16177 })
16178 }
16179
16180 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16181 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16182 let project_path = buffer.read(cx).project_path(cx)?;
16183 let project = self.project.as_ref()?.read(cx);
16184 let entry = project.entry_for_path(&project_path, cx)?;
16185 let path = entry.path.to_path_buf();
16186 Some(path)
16187 })
16188 }
16189
16190 pub fn reveal_in_finder(
16191 &mut self,
16192 _: &RevealInFileManager,
16193 _window: &mut Window,
16194 cx: &mut Context<Self>,
16195 ) {
16196 if let Some(target) = self.target_file(cx) {
16197 cx.reveal_path(&target.abs_path(cx));
16198 }
16199 }
16200
16201 pub fn copy_path(
16202 &mut self,
16203 _: &zed_actions::workspace::CopyPath,
16204 _window: &mut Window,
16205 cx: &mut Context<Self>,
16206 ) {
16207 if let Some(path) = self.target_file_abs_path(cx) {
16208 if let Some(path) = path.to_str() {
16209 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16210 }
16211 }
16212 }
16213
16214 pub fn copy_relative_path(
16215 &mut self,
16216 _: &zed_actions::workspace::CopyRelativePath,
16217 _window: &mut Window,
16218 cx: &mut Context<Self>,
16219 ) {
16220 if let Some(path) = self.target_file_path(cx) {
16221 if let Some(path) = path.to_str() {
16222 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16223 }
16224 }
16225 }
16226
16227 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16228 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16229 buffer.read(cx).project_path(cx)
16230 } else {
16231 None
16232 }
16233 }
16234
16235 // Returns true if the editor handled a go-to-line request
16236 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16237 maybe!({
16238 let breakpoint_store = self.breakpoint_store.as_ref()?;
16239
16240 let Some((_, _, active_position)) =
16241 breakpoint_store.read(cx).active_position().cloned()
16242 else {
16243 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16244 return None;
16245 };
16246
16247 let snapshot = self
16248 .project
16249 .as_ref()?
16250 .read(cx)
16251 .buffer_for_id(active_position.buffer_id?, cx)?
16252 .read(cx)
16253 .snapshot();
16254
16255 let mut handled = false;
16256 for (id, ExcerptRange { context, .. }) in self
16257 .buffer
16258 .read(cx)
16259 .excerpts_for_buffer(active_position.buffer_id?, cx)
16260 {
16261 if context.start.cmp(&active_position, &snapshot).is_ge()
16262 || context.end.cmp(&active_position, &snapshot).is_lt()
16263 {
16264 continue;
16265 }
16266 let snapshot = self.buffer.read(cx).snapshot(cx);
16267 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16268
16269 handled = true;
16270 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16271 self.go_to_line::<DebugCurrentRowHighlight>(
16272 multibuffer_anchor,
16273 Some(cx.theme().colors().editor_debugger_active_line_background),
16274 window,
16275 cx,
16276 );
16277
16278 cx.notify();
16279 }
16280 handled.then_some(())
16281 })
16282 .is_some()
16283 }
16284
16285 pub fn copy_file_name_without_extension(
16286 &mut self,
16287 _: &CopyFileNameWithoutExtension,
16288 _: &mut Window,
16289 cx: &mut Context<Self>,
16290 ) {
16291 if let Some(file) = self.target_file(cx) {
16292 if let Some(file_stem) = file.path().file_stem() {
16293 if let Some(name) = file_stem.to_str() {
16294 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16295 }
16296 }
16297 }
16298 }
16299
16300 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16301 if let Some(file) = self.target_file(cx) {
16302 if let Some(file_name) = file.path().file_name() {
16303 if let Some(name) = file_name.to_str() {
16304 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16305 }
16306 }
16307 }
16308 }
16309
16310 pub fn toggle_git_blame(
16311 &mut self,
16312 _: &::git::Blame,
16313 window: &mut Window,
16314 cx: &mut Context<Self>,
16315 ) {
16316 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16317
16318 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16319 self.start_git_blame(true, window, cx);
16320 }
16321
16322 cx.notify();
16323 }
16324
16325 pub fn toggle_git_blame_inline(
16326 &mut self,
16327 _: &ToggleGitBlameInline,
16328 window: &mut Window,
16329 cx: &mut Context<Self>,
16330 ) {
16331 self.toggle_git_blame_inline_internal(true, window, cx);
16332 cx.notify();
16333 }
16334
16335 pub fn open_git_blame_commit(
16336 &mut self,
16337 _: &OpenGitBlameCommit,
16338 window: &mut Window,
16339 cx: &mut Context<Self>,
16340 ) {
16341 self.open_git_blame_commit_internal(window, cx);
16342 }
16343
16344 fn open_git_blame_commit_internal(
16345 &mut self,
16346 window: &mut Window,
16347 cx: &mut Context<Self>,
16348 ) -> Option<()> {
16349 let blame = self.blame.as_ref()?;
16350 let snapshot = self.snapshot(window, cx);
16351 let cursor = self.selections.newest::<Point>(cx).head();
16352 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16353 let blame_entry = blame
16354 .update(cx, |blame, cx| {
16355 blame
16356 .blame_for_rows(
16357 &[RowInfo {
16358 buffer_id: Some(buffer.remote_id()),
16359 buffer_row: Some(point.row),
16360 ..Default::default()
16361 }],
16362 cx,
16363 )
16364 .next()
16365 })
16366 .flatten()?;
16367 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16368 let repo = blame.read(cx).repository(cx)?;
16369 let workspace = self.workspace()?.downgrade();
16370 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16371 None
16372 }
16373
16374 pub fn git_blame_inline_enabled(&self) -> bool {
16375 self.git_blame_inline_enabled
16376 }
16377
16378 pub fn toggle_selection_menu(
16379 &mut self,
16380 _: &ToggleSelectionMenu,
16381 _: &mut Window,
16382 cx: &mut Context<Self>,
16383 ) {
16384 self.show_selection_menu = self
16385 .show_selection_menu
16386 .map(|show_selections_menu| !show_selections_menu)
16387 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16388
16389 cx.notify();
16390 }
16391
16392 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16393 self.show_selection_menu
16394 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16395 }
16396
16397 fn start_git_blame(
16398 &mut self,
16399 user_triggered: bool,
16400 window: &mut Window,
16401 cx: &mut Context<Self>,
16402 ) {
16403 if let Some(project) = self.project.as_ref() {
16404 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16405 return;
16406 };
16407
16408 if buffer.read(cx).file().is_none() {
16409 return;
16410 }
16411
16412 let focused = self.focus_handle(cx).contains_focused(window, cx);
16413
16414 let project = project.clone();
16415 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16416 self.blame_subscription =
16417 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16418 self.blame = Some(blame);
16419 }
16420 }
16421
16422 fn toggle_git_blame_inline_internal(
16423 &mut self,
16424 user_triggered: bool,
16425 window: &mut Window,
16426 cx: &mut Context<Self>,
16427 ) {
16428 if self.git_blame_inline_enabled {
16429 self.git_blame_inline_enabled = false;
16430 self.show_git_blame_inline = false;
16431 self.show_git_blame_inline_delay_task.take();
16432 } else {
16433 self.git_blame_inline_enabled = true;
16434 self.start_git_blame_inline(user_triggered, window, cx);
16435 }
16436
16437 cx.notify();
16438 }
16439
16440 fn start_git_blame_inline(
16441 &mut self,
16442 user_triggered: bool,
16443 window: &mut Window,
16444 cx: &mut Context<Self>,
16445 ) {
16446 self.start_git_blame(user_triggered, window, cx);
16447
16448 if ProjectSettings::get_global(cx)
16449 .git
16450 .inline_blame_delay()
16451 .is_some()
16452 {
16453 self.start_inline_blame_timer(window, cx);
16454 } else {
16455 self.show_git_blame_inline = true
16456 }
16457 }
16458
16459 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16460 self.blame.as_ref()
16461 }
16462
16463 pub fn show_git_blame_gutter(&self) -> bool {
16464 self.show_git_blame_gutter
16465 }
16466
16467 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16468 self.show_git_blame_gutter && self.has_blame_entries(cx)
16469 }
16470
16471 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16472 self.show_git_blame_inline
16473 && (self.focus_handle.is_focused(window)
16474 || self
16475 .git_blame_inline_tooltip
16476 .as_ref()
16477 .and_then(|t| t.upgrade())
16478 .is_some())
16479 && !self.newest_selection_head_on_empty_line(cx)
16480 && self.has_blame_entries(cx)
16481 }
16482
16483 fn has_blame_entries(&self, cx: &App) -> bool {
16484 self.blame()
16485 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16486 }
16487
16488 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16489 let cursor_anchor = self.selections.newest_anchor().head();
16490
16491 let snapshot = self.buffer.read(cx).snapshot(cx);
16492 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16493
16494 snapshot.line_len(buffer_row) == 0
16495 }
16496
16497 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16498 let buffer_and_selection = maybe!({
16499 let selection = self.selections.newest::<Point>(cx);
16500 let selection_range = selection.range();
16501
16502 let multi_buffer = self.buffer().read(cx);
16503 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16504 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16505
16506 let (buffer, range, _) = if selection.reversed {
16507 buffer_ranges.first()
16508 } else {
16509 buffer_ranges.last()
16510 }?;
16511
16512 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16513 ..text::ToPoint::to_point(&range.end, &buffer).row;
16514 Some((
16515 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16516 selection,
16517 ))
16518 });
16519
16520 let Some((buffer, selection)) = buffer_and_selection else {
16521 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16522 };
16523
16524 let Some(project) = self.project.as_ref() else {
16525 return Task::ready(Err(anyhow!("editor does not have project")));
16526 };
16527
16528 project.update(cx, |project, cx| {
16529 project.get_permalink_to_line(&buffer, selection, cx)
16530 })
16531 }
16532
16533 pub fn copy_permalink_to_line(
16534 &mut self,
16535 _: &CopyPermalinkToLine,
16536 window: &mut Window,
16537 cx: &mut Context<Self>,
16538 ) {
16539 let permalink_task = self.get_permalink_to_line(cx);
16540 let workspace = self.workspace();
16541
16542 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16543 Ok(permalink) => {
16544 cx.update(|_, cx| {
16545 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16546 })
16547 .ok();
16548 }
16549 Err(err) => {
16550 let message = format!("Failed to copy permalink: {err}");
16551
16552 Err::<(), anyhow::Error>(err).log_err();
16553
16554 if let Some(workspace) = workspace {
16555 workspace
16556 .update_in(cx, |workspace, _, cx| {
16557 struct CopyPermalinkToLine;
16558
16559 workspace.show_toast(
16560 Toast::new(
16561 NotificationId::unique::<CopyPermalinkToLine>(),
16562 message,
16563 ),
16564 cx,
16565 )
16566 })
16567 .ok();
16568 }
16569 }
16570 })
16571 .detach();
16572 }
16573
16574 pub fn copy_file_location(
16575 &mut self,
16576 _: &CopyFileLocation,
16577 _: &mut Window,
16578 cx: &mut Context<Self>,
16579 ) {
16580 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16581 if let Some(file) = self.target_file(cx) {
16582 if let Some(path) = file.path().to_str() {
16583 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16584 }
16585 }
16586 }
16587
16588 pub fn open_permalink_to_line(
16589 &mut self,
16590 _: &OpenPermalinkToLine,
16591 window: &mut Window,
16592 cx: &mut Context<Self>,
16593 ) {
16594 let permalink_task = self.get_permalink_to_line(cx);
16595 let workspace = self.workspace();
16596
16597 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16598 Ok(permalink) => {
16599 cx.update(|_, cx| {
16600 cx.open_url(permalink.as_ref());
16601 })
16602 .ok();
16603 }
16604 Err(err) => {
16605 let message = format!("Failed to open permalink: {err}");
16606
16607 Err::<(), anyhow::Error>(err).log_err();
16608
16609 if let Some(workspace) = workspace {
16610 workspace
16611 .update(cx, |workspace, cx| {
16612 struct OpenPermalinkToLine;
16613
16614 workspace.show_toast(
16615 Toast::new(
16616 NotificationId::unique::<OpenPermalinkToLine>(),
16617 message,
16618 ),
16619 cx,
16620 )
16621 })
16622 .ok();
16623 }
16624 }
16625 })
16626 .detach();
16627 }
16628
16629 pub fn insert_uuid_v4(
16630 &mut self,
16631 _: &InsertUuidV4,
16632 window: &mut Window,
16633 cx: &mut Context<Self>,
16634 ) {
16635 self.insert_uuid(UuidVersion::V4, window, cx);
16636 }
16637
16638 pub fn insert_uuid_v7(
16639 &mut self,
16640 _: &InsertUuidV7,
16641 window: &mut Window,
16642 cx: &mut Context<Self>,
16643 ) {
16644 self.insert_uuid(UuidVersion::V7, window, cx);
16645 }
16646
16647 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16648 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16649 self.transact(window, cx, |this, window, cx| {
16650 let edits = this
16651 .selections
16652 .all::<Point>(cx)
16653 .into_iter()
16654 .map(|selection| {
16655 let uuid = match version {
16656 UuidVersion::V4 => uuid::Uuid::new_v4(),
16657 UuidVersion::V7 => uuid::Uuid::now_v7(),
16658 };
16659
16660 (selection.range(), uuid.to_string())
16661 });
16662 this.edit(edits, cx);
16663 this.refresh_inline_completion(true, false, window, cx);
16664 });
16665 }
16666
16667 pub fn open_selections_in_multibuffer(
16668 &mut self,
16669 _: &OpenSelectionsInMultibuffer,
16670 window: &mut Window,
16671 cx: &mut Context<Self>,
16672 ) {
16673 let multibuffer = self.buffer.read(cx);
16674
16675 let Some(buffer) = multibuffer.as_singleton() else {
16676 return;
16677 };
16678
16679 let Some(workspace) = self.workspace() else {
16680 return;
16681 };
16682
16683 let locations = self
16684 .selections
16685 .disjoint_anchors()
16686 .iter()
16687 .map(|range| Location {
16688 buffer: buffer.clone(),
16689 range: range.start.text_anchor..range.end.text_anchor,
16690 })
16691 .collect::<Vec<_>>();
16692
16693 let title = multibuffer.title(cx).to_string();
16694
16695 cx.spawn_in(window, async move |_, cx| {
16696 workspace.update_in(cx, |workspace, window, cx| {
16697 Self::open_locations_in_multibuffer(
16698 workspace,
16699 locations,
16700 format!("Selections for '{title}'"),
16701 false,
16702 MultibufferSelectionMode::All,
16703 window,
16704 cx,
16705 );
16706 })
16707 })
16708 .detach();
16709 }
16710
16711 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16712 /// last highlight added will be used.
16713 ///
16714 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16715 pub fn highlight_rows<T: 'static>(
16716 &mut self,
16717 range: Range<Anchor>,
16718 color: Hsla,
16719 should_autoscroll: bool,
16720 cx: &mut Context<Self>,
16721 ) {
16722 let snapshot = self.buffer().read(cx).snapshot(cx);
16723 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16724 let ix = row_highlights.binary_search_by(|highlight| {
16725 Ordering::Equal
16726 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16727 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16728 });
16729
16730 if let Err(mut ix) = ix {
16731 let index = post_inc(&mut self.highlight_order);
16732
16733 // If this range intersects with the preceding highlight, then merge it with
16734 // the preceding highlight. Otherwise insert a new highlight.
16735 let mut merged = false;
16736 if ix > 0 {
16737 let prev_highlight = &mut row_highlights[ix - 1];
16738 if prev_highlight
16739 .range
16740 .end
16741 .cmp(&range.start, &snapshot)
16742 .is_ge()
16743 {
16744 ix -= 1;
16745 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16746 prev_highlight.range.end = range.end;
16747 }
16748 merged = true;
16749 prev_highlight.index = index;
16750 prev_highlight.color = color;
16751 prev_highlight.should_autoscroll = should_autoscroll;
16752 }
16753 }
16754
16755 if !merged {
16756 row_highlights.insert(
16757 ix,
16758 RowHighlight {
16759 range: range.clone(),
16760 index,
16761 color,
16762 should_autoscroll,
16763 },
16764 );
16765 }
16766
16767 // If any of the following highlights intersect with this one, merge them.
16768 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16769 let highlight = &row_highlights[ix];
16770 if next_highlight
16771 .range
16772 .start
16773 .cmp(&highlight.range.end, &snapshot)
16774 .is_le()
16775 {
16776 if next_highlight
16777 .range
16778 .end
16779 .cmp(&highlight.range.end, &snapshot)
16780 .is_gt()
16781 {
16782 row_highlights[ix].range.end = next_highlight.range.end;
16783 }
16784 row_highlights.remove(ix + 1);
16785 } else {
16786 break;
16787 }
16788 }
16789 }
16790 }
16791
16792 /// Remove any highlighted row ranges of the given type that intersect the
16793 /// given ranges.
16794 pub fn remove_highlighted_rows<T: 'static>(
16795 &mut self,
16796 ranges_to_remove: Vec<Range<Anchor>>,
16797 cx: &mut Context<Self>,
16798 ) {
16799 let snapshot = self.buffer().read(cx).snapshot(cx);
16800 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16801 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16802 row_highlights.retain(|highlight| {
16803 while let Some(range_to_remove) = ranges_to_remove.peek() {
16804 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16805 Ordering::Less | Ordering::Equal => {
16806 ranges_to_remove.next();
16807 }
16808 Ordering::Greater => {
16809 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16810 Ordering::Less | Ordering::Equal => {
16811 return false;
16812 }
16813 Ordering::Greater => break,
16814 }
16815 }
16816 }
16817 }
16818
16819 true
16820 })
16821 }
16822
16823 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16824 pub fn clear_row_highlights<T: 'static>(&mut self) {
16825 self.highlighted_rows.remove(&TypeId::of::<T>());
16826 }
16827
16828 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16829 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16830 self.highlighted_rows
16831 .get(&TypeId::of::<T>())
16832 .map_or(&[] as &[_], |vec| vec.as_slice())
16833 .iter()
16834 .map(|highlight| (highlight.range.clone(), highlight.color))
16835 }
16836
16837 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16838 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16839 /// Allows to ignore certain kinds of highlights.
16840 pub fn highlighted_display_rows(
16841 &self,
16842 window: &mut Window,
16843 cx: &mut App,
16844 ) -> BTreeMap<DisplayRow, LineHighlight> {
16845 let snapshot = self.snapshot(window, cx);
16846 let mut used_highlight_orders = HashMap::default();
16847 self.highlighted_rows
16848 .iter()
16849 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16850 .fold(
16851 BTreeMap::<DisplayRow, LineHighlight>::new(),
16852 |mut unique_rows, highlight| {
16853 let start = highlight.range.start.to_display_point(&snapshot);
16854 let end = highlight.range.end.to_display_point(&snapshot);
16855 let start_row = start.row().0;
16856 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16857 && end.column() == 0
16858 {
16859 end.row().0.saturating_sub(1)
16860 } else {
16861 end.row().0
16862 };
16863 for row in start_row..=end_row {
16864 let used_index =
16865 used_highlight_orders.entry(row).or_insert(highlight.index);
16866 if highlight.index >= *used_index {
16867 *used_index = highlight.index;
16868 unique_rows.insert(DisplayRow(row), highlight.color.into());
16869 }
16870 }
16871 unique_rows
16872 },
16873 )
16874 }
16875
16876 pub fn highlighted_display_row_for_autoscroll(
16877 &self,
16878 snapshot: &DisplaySnapshot,
16879 ) -> Option<DisplayRow> {
16880 self.highlighted_rows
16881 .values()
16882 .flat_map(|highlighted_rows| highlighted_rows.iter())
16883 .filter_map(|highlight| {
16884 if highlight.should_autoscroll {
16885 Some(highlight.range.start.to_display_point(snapshot).row())
16886 } else {
16887 None
16888 }
16889 })
16890 .min()
16891 }
16892
16893 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16894 self.highlight_background::<SearchWithinRange>(
16895 ranges,
16896 |colors| colors.editor_document_highlight_read_background,
16897 cx,
16898 )
16899 }
16900
16901 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16902 self.breadcrumb_header = Some(new_header);
16903 }
16904
16905 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16906 self.clear_background_highlights::<SearchWithinRange>(cx);
16907 }
16908
16909 pub fn highlight_background<T: 'static>(
16910 &mut self,
16911 ranges: &[Range<Anchor>],
16912 color_fetcher: fn(&ThemeColors) -> Hsla,
16913 cx: &mut Context<Self>,
16914 ) {
16915 self.background_highlights
16916 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16917 self.scrollbar_marker_state.dirty = true;
16918 cx.notify();
16919 }
16920
16921 pub fn clear_background_highlights<T: 'static>(
16922 &mut self,
16923 cx: &mut Context<Self>,
16924 ) -> Option<BackgroundHighlight> {
16925 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16926 if !text_highlights.1.is_empty() {
16927 self.scrollbar_marker_state.dirty = true;
16928 cx.notify();
16929 }
16930 Some(text_highlights)
16931 }
16932
16933 pub fn highlight_gutter<T: 'static>(
16934 &mut self,
16935 ranges: &[Range<Anchor>],
16936 color_fetcher: fn(&App) -> Hsla,
16937 cx: &mut Context<Self>,
16938 ) {
16939 self.gutter_highlights
16940 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16941 cx.notify();
16942 }
16943
16944 pub fn clear_gutter_highlights<T: 'static>(
16945 &mut self,
16946 cx: &mut Context<Self>,
16947 ) -> Option<GutterHighlight> {
16948 cx.notify();
16949 self.gutter_highlights.remove(&TypeId::of::<T>())
16950 }
16951
16952 #[cfg(feature = "test-support")]
16953 pub fn all_text_background_highlights(
16954 &self,
16955 window: &mut Window,
16956 cx: &mut Context<Self>,
16957 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16958 let snapshot = self.snapshot(window, cx);
16959 let buffer = &snapshot.buffer_snapshot;
16960 let start = buffer.anchor_before(0);
16961 let end = buffer.anchor_after(buffer.len());
16962 let theme = cx.theme().colors();
16963 self.background_highlights_in_range(start..end, &snapshot, theme)
16964 }
16965
16966 #[cfg(feature = "test-support")]
16967 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16968 let snapshot = self.buffer().read(cx).snapshot(cx);
16969
16970 let highlights = self
16971 .background_highlights
16972 .get(&TypeId::of::<items::BufferSearchHighlights>());
16973
16974 if let Some((_color, ranges)) = highlights {
16975 ranges
16976 .iter()
16977 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16978 .collect_vec()
16979 } else {
16980 vec![]
16981 }
16982 }
16983
16984 fn document_highlights_for_position<'a>(
16985 &'a self,
16986 position: Anchor,
16987 buffer: &'a MultiBufferSnapshot,
16988 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16989 let read_highlights = self
16990 .background_highlights
16991 .get(&TypeId::of::<DocumentHighlightRead>())
16992 .map(|h| &h.1);
16993 let write_highlights = self
16994 .background_highlights
16995 .get(&TypeId::of::<DocumentHighlightWrite>())
16996 .map(|h| &h.1);
16997 let left_position = position.bias_left(buffer);
16998 let right_position = position.bias_right(buffer);
16999 read_highlights
17000 .into_iter()
17001 .chain(write_highlights)
17002 .flat_map(move |ranges| {
17003 let start_ix = match ranges.binary_search_by(|probe| {
17004 let cmp = probe.end.cmp(&left_position, buffer);
17005 if cmp.is_ge() {
17006 Ordering::Greater
17007 } else {
17008 Ordering::Less
17009 }
17010 }) {
17011 Ok(i) | Err(i) => i,
17012 };
17013
17014 ranges[start_ix..]
17015 .iter()
17016 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17017 })
17018 }
17019
17020 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17021 self.background_highlights
17022 .get(&TypeId::of::<T>())
17023 .map_or(false, |(_, highlights)| !highlights.is_empty())
17024 }
17025
17026 pub fn background_highlights_in_range(
17027 &self,
17028 search_range: Range<Anchor>,
17029 display_snapshot: &DisplaySnapshot,
17030 theme: &ThemeColors,
17031 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17032 let mut results = Vec::new();
17033 for (color_fetcher, ranges) in self.background_highlights.values() {
17034 let color = color_fetcher(theme);
17035 let start_ix = match ranges.binary_search_by(|probe| {
17036 let cmp = probe
17037 .end
17038 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17039 if cmp.is_gt() {
17040 Ordering::Greater
17041 } else {
17042 Ordering::Less
17043 }
17044 }) {
17045 Ok(i) | Err(i) => i,
17046 };
17047 for range in &ranges[start_ix..] {
17048 if range
17049 .start
17050 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17051 .is_ge()
17052 {
17053 break;
17054 }
17055
17056 let start = range.start.to_display_point(display_snapshot);
17057 let end = range.end.to_display_point(display_snapshot);
17058 results.push((start..end, color))
17059 }
17060 }
17061 results
17062 }
17063
17064 pub fn background_highlight_row_ranges<T: 'static>(
17065 &self,
17066 search_range: Range<Anchor>,
17067 display_snapshot: &DisplaySnapshot,
17068 count: usize,
17069 ) -> Vec<RangeInclusive<DisplayPoint>> {
17070 let mut results = Vec::new();
17071 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17072 return vec![];
17073 };
17074
17075 let start_ix = match ranges.binary_search_by(|probe| {
17076 let cmp = probe
17077 .end
17078 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17079 if cmp.is_gt() {
17080 Ordering::Greater
17081 } else {
17082 Ordering::Less
17083 }
17084 }) {
17085 Ok(i) | Err(i) => i,
17086 };
17087 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17088 if let (Some(start_display), Some(end_display)) = (start, end) {
17089 results.push(
17090 start_display.to_display_point(display_snapshot)
17091 ..=end_display.to_display_point(display_snapshot),
17092 );
17093 }
17094 };
17095 let mut start_row: Option<Point> = None;
17096 let mut end_row: Option<Point> = None;
17097 if ranges.len() > count {
17098 return Vec::new();
17099 }
17100 for range in &ranges[start_ix..] {
17101 if range
17102 .start
17103 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17104 .is_ge()
17105 {
17106 break;
17107 }
17108 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17109 if let Some(current_row) = &end_row {
17110 if end.row == current_row.row {
17111 continue;
17112 }
17113 }
17114 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17115 if start_row.is_none() {
17116 assert_eq!(end_row, None);
17117 start_row = Some(start);
17118 end_row = Some(end);
17119 continue;
17120 }
17121 if let Some(current_end) = end_row.as_mut() {
17122 if start.row > current_end.row + 1 {
17123 push_region(start_row, end_row);
17124 start_row = Some(start);
17125 end_row = Some(end);
17126 } else {
17127 // Merge two hunks.
17128 *current_end = end;
17129 }
17130 } else {
17131 unreachable!();
17132 }
17133 }
17134 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17135 push_region(start_row, end_row);
17136 results
17137 }
17138
17139 pub fn gutter_highlights_in_range(
17140 &self,
17141 search_range: Range<Anchor>,
17142 display_snapshot: &DisplaySnapshot,
17143 cx: &App,
17144 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17145 let mut results = Vec::new();
17146 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17147 let color = color_fetcher(cx);
17148 let start_ix = match ranges.binary_search_by(|probe| {
17149 let cmp = probe
17150 .end
17151 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17152 if cmp.is_gt() {
17153 Ordering::Greater
17154 } else {
17155 Ordering::Less
17156 }
17157 }) {
17158 Ok(i) | Err(i) => i,
17159 };
17160 for range in &ranges[start_ix..] {
17161 if range
17162 .start
17163 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17164 .is_ge()
17165 {
17166 break;
17167 }
17168
17169 let start = range.start.to_display_point(display_snapshot);
17170 let end = range.end.to_display_point(display_snapshot);
17171 results.push((start..end, color))
17172 }
17173 }
17174 results
17175 }
17176
17177 /// Get the text ranges corresponding to the redaction query
17178 pub fn redacted_ranges(
17179 &self,
17180 search_range: Range<Anchor>,
17181 display_snapshot: &DisplaySnapshot,
17182 cx: &App,
17183 ) -> Vec<Range<DisplayPoint>> {
17184 display_snapshot
17185 .buffer_snapshot
17186 .redacted_ranges(search_range, |file| {
17187 if let Some(file) = file {
17188 file.is_private()
17189 && EditorSettings::get(
17190 Some(SettingsLocation {
17191 worktree_id: file.worktree_id(cx),
17192 path: file.path().as_ref(),
17193 }),
17194 cx,
17195 )
17196 .redact_private_values
17197 } else {
17198 false
17199 }
17200 })
17201 .map(|range| {
17202 range.start.to_display_point(display_snapshot)
17203 ..range.end.to_display_point(display_snapshot)
17204 })
17205 .collect()
17206 }
17207
17208 pub fn highlight_text<T: 'static>(
17209 &mut self,
17210 ranges: Vec<Range<Anchor>>,
17211 style: HighlightStyle,
17212 cx: &mut Context<Self>,
17213 ) {
17214 self.display_map.update(cx, |map, _| {
17215 map.highlight_text(TypeId::of::<T>(), ranges, style)
17216 });
17217 cx.notify();
17218 }
17219
17220 pub(crate) fn highlight_inlays<T: 'static>(
17221 &mut self,
17222 highlights: Vec<InlayHighlight>,
17223 style: HighlightStyle,
17224 cx: &mut Context<Self>,
17225 ) {
17226 self.display_map.update(cx, |map, _| {
17227 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17228 });
17229 cx.notify();
17230 }
17231
17232 pub fn text_highlights<'a, T: 'static>(
17233 &'a self,
17234 cx: &'a App,
17235 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17236 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17237 }
17238
17239 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17240 let cleared = self
17241 .display_map
17242 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17243 if cleared {
17244 cx.notify();
17245 }
17246 }
17247
17248 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17249 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17250 && self.focus_handle.is_focused(window)
17251 }
17252
17253 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17254 self.show_cursor_when_unfocused = is_enabled;
17255 cx.notify();
17256 }
17257
17258 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17259 cx.notify();
17260 }
17261
17262 fn on_buffer_event(
17263 &mut self,
17264 multibuffer: &Entity<MultiBuffer>,
17265 event: &multi_buffer::Event,
17266 window: &mut Window,
17267 cx: &mut Context<Self>,
17268 ) {
17269 match event {
17270 multi_buffer::Event::Edited {
17271 singleton_buffer_edited,
17272 edited_buffer: buffer_edited,
17273 } => {
17274 self.scrollbar_marker_state.dirty = true;
17275 self.active_indent_guides_state.dirty = true;
17276 self.refresh_active_diagnostics(cx);
17277 self.refresh_code_actions(window, cx);
17278 if self.has_active_inline_completion() {
17279 self.update_visible_inline_completion(window, cx);
17280 }
17281 if let Some(buffer) = buffer_edited {
17282 let buffer_id = buffer.read(cx).remote_id();
17283 if !self.registered_buffers.contains_key(&buffer_id) {
17284 if let Some(project) = self.project.as_ref() {
17285 project.update(cx, |project, cx| {
17286 self.registered_buffers.insert(
17287 buffer_id,
17288 project.register_buffer_with_language_servers(&buffer, cx),
17289 );
17290 })
17291 }
17292 }
17293 }
17294 cx.emit(EditorEvent::BufferEdited);
17295 cx.emit(SearchEvent::MatchesInvalidated);
17296 if *singleton_buffer_edited {
17297 if let Some(project) = &self.project {
17298 #[allow(clippy::mutable_key_type)]
17299 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17300 multibuffer
17301 .all_buffers()
17302 .into_iter()
17303 .filter_map(|buffer| {
17304 buffer.update(cx, |buffer, cx| {
17305 let language = buffer.language()?;
17306 let should_discard = project.update(cx, |project, cx| {
17307 project.is_local()
17308 && !project.has_language_servers_for(buffer, cx)
17309 });
17310 should_discard.not().then_some(language.clone())
17311 })
17312 })
17313 .collect::<HashSet<_>>()
17314 });
17315 if !languages_affected.is_empty() {
17316 self.refresh_inlay_hints(
17317 InlayHintRefreshReason::BufferEdited(languages_affected),
17318 cx,
17319 );
17320 }
17321 }
17322 }
17323
17324 let Some(project) = &self.project else { return };
17325 let (telemetry, is_via_ssh) = {
17326 let project = project.read(cx);
17327 let telemetry = project.client().telemetry().clone();
17328 let is_via_ssh = project.is_via_ssh();
17329 (telemetry, is_via_ssh)
17330 };
17331 refresh_linked_ranges(self, window, cx);
17332 telemetry.log_edit_event("editor", is_via_ssh);
17333 }
17334 multi_buffer::Event::ExcerptsAdded {
17335 buffer,
17336 predecessor,
17337 excerpts,
17338 } => {
17339 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17340 let buffer_id = buffer.read(cx).remote_id();
17341 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17342 if let Some(project) = &self.project {
17343 get_uncommitted_diff_for_buffer(
17344 project,
17345 [buffer.clone()],
17346 self.buffer.clone(),
17347 cx,
17348 )
17349 .detach();
17350 }
17351 }
17352 cx.emit(EditorEvent::ExcerptsAdded {
17353 buffer: buffer.clone(),
17354 predecessor: *predecessor,
17355 excerpts: excerpts.clone(),
17356 });
17357 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17358 }
17359 multi_buffer::Event::ExcerptsRemoved { ids } => {
17360 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17361 let buffer = self.buffer.read(cx);
17362 self.registered_buffers
17363 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17364 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17365 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17366 }
17367 multi_buffer::Event::ExcerptsEdited {
17368 excerpt_ids,
17369 buffer_ids,
17370 } => {
17371 self.display_map.update(cx, |map, cx| {
17372 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17373 });
17374 cx.emit(EditorEvent::ExcerptsEdited {
17375 ids: excerpt_ids.clone(),
17376 })
17377 }
17378 multi_buffer::Event::ExcerptsExpanded { ids } => {
17379 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17380 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17381 }
17382 multi_buffer::Event::Reparsed(buffer_id) => {
17383 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17384 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17385
17386 cx.emit(EditorEvent::Reparsed(*buffer_id));
17387 }
17388 multi_buffer::Event::DiffHunksToggled => {
17389 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17390 }
17391 multi_buffer::Event::LanguageChanged(buffer_id) => {
17392 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17393 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17394 cx.emit(EditorEvent::Reparsed(*buffer_id));
17395 cx.notify();
17396 }
17397 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17398 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17399 multi_buffer::Event::FileHandleChanged
17400 | multi_buffer::Event::Reloaded
17401 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17402 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17403 multi_buffer::Event::DiagnosticsUpdated => {
17404 self.refresh_active_diagnostics(cx);
17405 self.refresh_inline_diagnostics(true, window, cx);
17406 self.scrollbar_marker_state.dirty = true;
17407 cx.notify();
17408 }
17409 _ => {}
17410 };
17411 }
17412
17413 fn on_display_map_changed(
17414 &mut self,
17415 _: Entity<DisplayMap>,
17416 _: &mut Window,
17417 cx: &mut Context<Self>,
17418 ) {
17419 cx.notify();
17420 }
17421
17422 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17423 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17424 self.update_edit_prediction_settings(cx);
17425 self.refresh_inline_completion(true, false, window, cx);
17426 self.refresh_inlay_hints(
17427 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17428 self.selections.newest_anchor().head(),
17429 &self.buffer.read(cx).snapshot(cx),
17430 cx,
17431 )),
17432 cx,
17433 );
17434
17435 let old_cursor_shape = self.cursor_shape;
17436
17437 {
17438 let editor_settings = EditorSettings::get_global(cx);
17439 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17440 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17441 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17442 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17443 }
17444
17445 if old_cursor_shape != self.cursor_shape {
17446 cx.emit(EditorEvent::CursorShapeChanged);
17447 }
17448
17449 let project_settings = ProjectSettings::get_global(cx);
17450 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17451
17452 if self.mode.is_full() {
17453 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17454 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17455 if self.show_inline_diagnostics != show_inline_diagnostics {
17456 self.show_inline_diagnostics = show_inline_diagnostics;
17457 self.refresh_inline_diagnostics(false, window, cx);
17458 }
17459
17460 if self.git_blame_inline_enabled != inline_blame_enabled {
17461 self.toggle_git_blame_inline_internal(false, window, cx);
17462 }
17463 }
17464
17465 cx.notify();
17466 }
17467
17468 pub fn set_searchable(&mut self, searchable: bool) {
17469 self.searchable = searchable;
17470 }
17471
17472 pub fn searchable(&self) -> bool {
17473 self.searchable
17474 }
17475
17476 fn open_proposed_changes_editor(
17477 &mut self,
17478 _: &OpenProposedChangesEditor,
17479 window: &mut Window,
17480 cx: &mut Context<Self>,
17481 ) {
17482 let Some(workspace) = self.workspace() else {
17483 cx.propagate();
17484 return;
17485 };
17486
17487 let selections = self.selections.all::<usize>(cx);
17488 let multi_buffer = self.buffer.read(cx);
17489 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17490 let mut new_selections_by_buffer = HashMap::default();
17491 for selection in selections {
17492 for (buffer, range, _) in
17493 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17494 {
17495 let mut range = range.to_point(buffer);
17496 range.start.column = 0;
17497 range.end.column = buffer.line_len(range.end.row);
17498 new_selections_by_buffer
17499 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17500 .or_insert(Vec::new())
17501 .push(range)
17502 }
17503 }
17504
17505 let proposed_changes_buffers = new_selections_by_buffer
17506 .into_iter()
17507 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17508 .collect::<Vec<_>>();
17509 let proposed_changes_editor = cx.new(|cx| {
17510 ProposedChangesEditor::new(
17511 "Proposed changes",
17512 proposed_changes_buffers,
17513 self.project.clone(),
17514 window,
17515 cx,
17516 )
17517 });
17518
17519 window.defer(cx, move |window, cx| {
17520 workspace.update(cx, |workspace, cx| {
17521 workspace.active_pane().update(cx, |pane, cx| {
17522 pane.add_item(
17523 Box::new(proposed_changes_editor),
17524 true,
17525 true,
17526 None,
17527 window,
17528 cx,
17529 );
17530 });
17531 });
17532 });
17533 }
17534
17535 pub fn open_excerpts_in_split(
17536 &mut self,
17537 _: &OpenExcerptsSplit,
17538 window: &mut Window,
17539 cx: &mut Context<Self>,
17540 ) {
17541 self.open_excerpts_common(None, true, window, cx)
17542 }
17543
17544 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17545 self.open_excerpts_common(None, false, window, cx)
17546 }
17547
17548 fn open_excerpts_common(
17549 &mut self,
17550 jump_data: Option<JumpData>,
17551 split: bool,
17552 window: &mut Window,
17553 cx: &mut Context<Self>,
17554 ) {
17555 let Some(workspace) = self.workspace() else {
17556 cx.propagate();
17557 return;
17558 };
17559
17560 if self.buffer.read(cx).is_singleton() {
17561 cx.propagate();
17562 return;
17563 }
17564
17565 let mut new_selections_by_buffer = HashMap::default();
17566 match &jump_data {
17567 Some(JumpData::MultiBufferPoint {
17568 excerpt_id,
17569 position,
17570 anchor,
17571 line_offset_from_top,
17572 }) => {
17573 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17574 if let Some(buffer) = multi_buffer_snapshot
17575 .buffer_id_for_excerpt(*excerpt_id)
17576 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17577 {
17578 let buffer_snapshot = buffer.read(cx).snapshot();
17579 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17580 language::ToPoint::to_point(anchor, &buffer_snapshot)
17581 } else {
17582 buffer_snapshot.clip_point(*position, Bias::Left)
17583 };
17584 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17585 new_selections_by_buffer.insert(
17586 buffer,
17587 (
17588 vec![jump_to_offset..jump_to_offset],
17589 Some(*line_offset_from_top),
17590 ),
17591 );
17592 }
17593 }
17594 Some(JumpData::MultiBufferRow {
17595 row,
17596 line_offset_from_top,
17597 }) => {
17598 let point = MultiBufferPoint::new(row.0, 0);
17599 if let Some((buffer, buffer_point, _)) =
17600 self.buffer.read(cx).point_to_buffer_point(point, cx)
17601 {
17602 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17603 new_selections_by_buffer
17604 .entry(buffer)
17605 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17606 .0
17607 .push(buffer_offset..buffer_offset)
17608 }
17609 }
17610 None => {
17611 let selections = self.selections.all::<usize>(cx);
17612 let multi_buffer = self.buffer.read(cx);
17613 for selection in selections {
17614 for (snapshot, range, _, anchor) in multi_buffer
17615 .snapshot(cx)
17616 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17617 {
17618 if let Some(anchor) = anchor {
17619 // selection is in a deleted hunk
17620 let Some(buffer_id) = anchor.buffer_id else {
17621 continue;
17622 };
17623 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17624 continue;
17625 };
17626 let offset = text::ToOffset::to_offset(
17627 &anchor.text_anchor,
17628 &buffer_handle.read(cx).snapshot(),
17629 );
17630 let range = offset..offset;
17631 new_selections_by_buffer
17632 .entry(buffer_handle)
17633 .or_insert((Vec::new(), None))
17634 .0
17635 .push(range)
17636 } else {
17637 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17638 else {
17639 continue;
17640 };
17641 new_selections_by_buffer
17642 .entry(buffer_handle)
17643 .or_insert((Vec::new(), None))
17644 .0
17645 .push(range)
17646 }
17647 }
17648 }
17649 }
17650 }
17651
17652 new_selections_by_buffer
17653 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17654
17655 if new_selections_by_buffer.is_empty() {
17656 return;
17657 }
17658
17659 // We defer the pane interaction because we ourselves are a workspace item
17660 // and activating a new item causes the pane to call a method on us reentrantly,
17661 // which panics if we're on the stack.
17662 window.defer(cx, move |window, cx| {
17663 workspace.update(cx, |workspace, cx| {
17664 let pane = if split {
17665 workspace.adjacent_pane(window, cx)
17666 } else {
17667 workspace.active_pane().clone()
17668 };
17669
17670 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17671 let editor = buffer
17672 .read(cx)
17673 .file()
17674 .is_none()
17675 .then(|| {
17676 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17677 // so `workspace.open_project_item` will never find them, always opening a new editor.
17678 // Instead, we try to activate the existing editor in the pane first.
17679 let (editor, pane_item_index) =
17680 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17681 let editor = item.downcast::<Editor>()?;
17682 let singleton_buffer =
17683 editor.read(cx).buffer().read(cx).as_singleton()?;
17684 if singleton_buffer == buffer {
17685 Some((editor, i))
17686 } else {
17687 None
17688 }
17689 })?;
17690 pane.update(cx, |pane, cx| {
17691 pane.activate_item(pane_item_index, true, true, window, cx)
17692 });
17693 Some(editor)
17694 })
17695 .flatten()
17696 .unwrap_or_else(|| {
17697 workspace.open_project_item::<Self>(
17698 pane.clone(),
17699 buffer,
17700 true,
17701 true,
17702 window,
17703 cx,
17704 )
17705 });
17706
17707 editor.update(cx, |editor, cx| {
17708 let autoscroll = match scroll_offset {
17709 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17710 None => Autoscroll::newest(),
17711 };
17712 let nav_history = editor.nav_history.take();
17713 editor.change_selections(Some(autoscroll), window, cx, |s| {
17714 s.select_ranges(ranges);
17715 });
17716 editor.nav_history = nav_history;
17717 });
17718 }
17719 })
17720 });
17721 }
17722
17723 // For now, don't allow opening excerpts in buffers that aren't backed by
17724 // regular project files.
17725 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17726 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17727 }
17728
17729 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17730 let snapshot = self.buffer.read(cx).read(cx);
17731 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17732 Some(
17733 ranges
17734 .iter()
17735 .map(move |range| {
17736 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17737 })
17738 .collect(),
17739 )
17740 }
17741
17742 fn selection_replacement_ranges(
17743 &self,
17744 range: Range<OffsetUtf16>,
17745 cx: &mut App,
17746 ) -> Vec<Range<OffsetUtf16>> {
17747 let selections = self.selections.all::<OffsetUtf16>(cx);
17748 let newest_selection = selections
17749 .iter()
17750 .max_by_key(|selection| selection.id)
17751 .unwrap();
17752 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17753 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17754 let snapshot = self.buffer.read(cx).read(cx);
17755 selections
17756 .into_iter()
17757 .map(|mut selection| {
17758 selection.start.0 =
17759 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17760 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17761 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17762 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17763 })
17764 .collect()
17765 }
17766
17767 fn report_editor_event(
17768 &self,
17769 event_type: &'static str,
17770 file_extension: Option<String>,
17771 cx: &App,
17772 ) {
17773 if cfg!(any(test, feature = "test-support")) {
17774 return;
17775 }
17776
17777 let Some(project) = &self.project else { return };
17778
17779 // If None, we are in a file without an extension
17780 let file = self
17781 .buffer
17782 .read(cx)
17783 .as_singleton()
17784 .and_then(|b| b.read(cx).file());
17785 let file_extension = file_extension.or(file
17786 .as_ref()
17787 .and_then(|file| Path::new(file.file_name(cx)).extension())
17788 .and_then(|e| e.to_str())
17789 .map(|a| a.to_string()));
17790
17791 let vim_mode = vim_enabled(cx);
17792
17793 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17794 let copilot_enabled = edit_predictions_provider
17795 == language::language_settings::EditPredictionProvider::Copilot;
17796 let copilot_enabled_for_language = self
17797 .buffer
17798 .read(cx)
17799 .language_settings(cx)
17800 .show_edit_predictions;
17801
17802 let project = project.read(cx);
17803 telemetry::event!(
17804 event_type,
17805 file_extension,
17806 vim_mode,
17807 copilot_enabled,
17808 copilot_enabled_for_language,
17809 edit_predictions_provider,
17810 is_via_ssh = project.is_via_ssh(),
17811 );
17812 }
17813
17814 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17815 /// with each line being an array of {text, highlight} objects.
17816 fn copy_highlight_json(
17817 &mut self,
17818 _: &CopyHighlightJson,
17819 window: &mut Window,
17820 cx: &mut Context<Self>,
17821 ) {
17822 #[derive(Serialize)]
17823 struct Chunk<'a> {
17824 text: String,
17825 highlight: Option<&'a str>,
17826 }
17827
17828 let snapshot = self.buffer.read(cx).snapshot(cx);
17829 let range = self
17830 .selected_text_range(false, window, cx)
17831 .and_then(|selection| {
17832 if selection.range.is_empty() {
17833 None
17834 } else {
17835 Some(selection.range)
17836 }
17837 })
17838 .unwrap_or_else(|| 0..snapshot.len());
17839
17840 let chunks = snapshot.chunks(range, true);
17841 let mut lines = Vec::new();
17842 let mut line: VecDeque<Chunk> = VecDeque::new();
17843
17844 let Some(style) = self.style.as_ref() else {
17845 return;
17846 };
17847
17848 for chunk in chunks {
17849 let highlight = chunk
17850 .syntax_highlight_id
17851 .and_then(|id| id.name(&style.syntax));
17852 let mut chunk_lines = chunk.text.split('\n').peekable();
17853 while let Some(text) = chunk_lines.next() {
17854 let mut merged_with_last_token = false;
17855 if let Some(last_token) = line.back_mut() {
17856 if last_token.highlight == highlight {
17857 last_token.text.push_str(text);
17858 merged_with_last_token = true;
17859 }
17860 }
17861
17862 if !merged_with_last_token {
17863 line.push_back(Chunk {
17864 text: text.into(),
17865 highlight,
17866 });
17867 }
17868
17869 if chunk_lines.peek().is_some() {
17870 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17871 line.pop_front();
17872 }
17873 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17874 line.pop_back();
17875 }
17876
17877 lines.push(mem::take(&mut line));
17878 }
17879 }
17880 }
17881
17882 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17883 return;
17884 };
17885 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17886 }
17887
17888 pub fn open_context_menu(
17889 &mut self,
17890 _: &OpenContextMenu,
17891 window: &mut Window,
17892 cx: &mut Context<Self>,
17893 ) {
17894 self.request_autoscroll(Autoscroll::newest(), cx);
17895 let position = self.selections.newest_display(cx).start;
17896 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17897 }
17898
17899 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17900 &self.inlay_hint_cache
17901 }
17902
17903 pub fn replay_insert_event(
17904 &mut self,
17905 text: &str,
17906 relative_utf16_range: Option<Range<isize>>,
17907 window: &mut Window,
17908 cx: &mut Context<Self>,
17909 ) {
17910 if !self.input_enabled {
17911 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17912 return;
17913 }
17914 if let Some(relative_utf16_range) = relative_utf16_range {
17915 let selections = self.selections.all::<OffsetUtf16>(cx);
17916 self.change_selections(None, window, cx, |s| {
17917 let new_ranges = selections.into_iter().map(|range| {
17918 let start = OffsetUtf16(
17919 range
17920 .head()
17921 .0
17922 .saturating_add_signed(relative_utf16_range.start),
17923 );
17924 let end = OffsetUtf16(
17925 range
17926 .head()
17927 .0
17928 .saturating_add_signed(relative_utf16_range.end),
17929 );
17930 start..end
17931 });
17932 s.select_ranges(new_ranges);
17933 });
17934 }
17935
17936 self.handle_input(text, window, cx);
17937 }
17938
17939 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17940 let Some(provider) = self.semantics_provider.as_ref() else {
17941 return false;
17942 };
17943
17944 let mut supports = false;
17945 self.buffer().update(cx, |this, cx| {
17946 this.for_each_buffer(|buffer| {
17947 supports |= provider.supports_inlay_hints(buffer, cx);
17948 });
17949 });
17950
17951 supports
17952 }
17953
17954 pub fn is_focused(&self, window: &Window) -> bool {
17955 self.focus_handle.is_focused(window)
17956 }
17957
17958 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17959 cx.emit(EditorEvent::Focused);
17960
17961 if let Some(descendant) = self
17962 .last_focused_descendant
17963 .take()
17964 .and_then(|descendant| descendant.upgrade())
17965 {
17966 window.focus(&descendant);
17967 } else {
17968 if let Some(blame) = self.blame.as_ref() {
17969 blame.update(cx, GitBlame::focus)
17970 }
17971
17972 self.blink_manager.update(cx, BlinkManager::enable);
17973 self.show_cursor_names(window, cx);
17974 self.buffer.update(cx, |buffer, cx| {
17975 buffer.finalize_last_transaction(cx);
17976 if self.leader_peer_id.is_none() {
17977 buffer.set_active_selections(
17978 &self.selections.disjoint_anchors(),
17979 self.selections.line_mode,
17980 self.cursor_shape,
17981 cx,
17982 );
17983 }
17984 });
17985 }
17986 }
17987
17988 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17989 cx.emit(EditorEvent::FocusedIn)
17990 }
17991
17992 fn handle_focus_out(
17993 &mut self,
17994 event: FocusOutEvent,
17995 _window: &mut Window,
17996 cx: &mut Context<Self>,
17997 ) {
17998 if event.blurred != self.focus_handle {
17999 self.last_focused_descendant = Some(event.blurred);
18000 }
18001 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18002 }
18003
18004 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18005 self.blink_manager.update(cx, BlinkManager::disable);
18006 self.buffer
18007 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18008
18009 if let Some(blame) = self.blame.as_ref() {
18010 blame.update(cx, GitBlame::blur)
18011 }
18012 if !self.hover_state.focused(window, cx) {
18013 hide_hover(self, cx);
18014 }
18015 if !self
18016 .context_menu
18017 .borrow()
18018 .as_ref()
18019 .is_some_and(|context_menu| context_menu.focused(window, cx))
18020 {
18021 self.hide_context_menu(window, cx);
18022 }
18023 self.discard_inline_completion(false, cx);
18024 cx.emit(EditorEvent::Blurred);
18025 cx.notify();
18026 }
18027
18028 pub fn register_action<A: Action>(
18029 &mut self,
18030 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18031 ) -> Subscription {
18032 let id = self.next_editor_action_id.post_inc();
18033 let listener = Arc::new(listener);
18034 self.editor_actions.borrow_mut().insert(
18035 id,
18036 Box::new(move |window, _| {
18037 let listener = listener.clone();
18038 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18039 let action = action.downcast_ref().unwrap();
18040 if phase == DispatchPhase::Bubble {
18041 listener(action, window, cx)
18042 }
18043 })
18044 }),
18045 );
18046
18047 let editor_actions = self.editor_actions.clone();
18048 Subscription::new(move || {
18049 editor_actions.borrow_mut().remove(&id);
18050 })
18051 }
18052
18053 pub fn file_header_size(&self) -> u32 {
18054 FILE_HEADER_HEIGHT
18055 }
18056
18057 pub fn restore(
18058 &mut self,
18059 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18060 window: &mut Window,
18061 cx: &mut Context<Self>,
18062 ) {
18063 let workspace = self.workspace();
18064 let project = self.project.as_ref();
18065 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18066 let mut tasks = Vec::new();
18067 for (buffer_id, changes) in revert_changes {
18068 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18069 buffer.update(cx, |buffer, cx| {
18070 buffer.edit(
18071 changes
18072 .into_iter()
18073 .map(|(range, text)| (range, text.to_string())),
18074 None,
18075 cx,
18076 );
18077 });
18078
18079 if let Some(project) =
18080 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18081 {
18082 project.update(cx, |project, cx| {
18083 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18084 })
18085 }
18086 }
18087 }
18088 tasks
18089 });
18090 cx.spawn_in(window, async move |_, cx| {
18091 for (buffer, task) in save_tasks {
18092 let result = task.await;
18093 if result.is_err() {
18094 let Some(path) = buffer
18095 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18096 .ok()
18097 else {
18098 continue;
18099 };
18100 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18101 let Some(task) = cx
18102 .update_window_entity(&workspace, |workspace, window, cx| {
18103 workspace
18104 .open_path_preview(path, None, false, false, false, window, cx)
18105 })
18106 .ok()
18107 else {
18108 continue;
18109 };
18110 task.await.log_err();
18111 }
18112 }
18113 }
18114 })
18115 .detach();
18116 self.change_selections(None, window, cx, |selections| selections.refresh());
18117 }
18118
18119 pub fn to_pixel_point(
18120 &self,
18121 source: multi_buffer::Anchor,
18122 editor_snapshot: &EditorSnapshot,
18123 window: &mut Window,
18124 ) -> Option<gpui::Point<Pixels>> {
18125 let source_point = source.to_display_point(editor_snapshot);
18126 self.display_to_pixel_point(source_point, editor_snapshot, window)
18127 }
18128
18129 pub fn display_to_pixel_point(
18130 &self,
18131 source: DisplayPoint,
18132 editor_snapshot: &EditorSnapshot,
18133 window: &mut Window,
18134 ) -> Option<gpui::Point<Pixels>> {
18135 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18136 let text_layout_details = self.text_layout_details(window);
18137 let scroll_top = text_layout_details
18138 .scroll_anchor
18139 .scroll_position(editor_snapshot)
18140 .y;
18141
18142 if source.row().as_f32() < scroll_top.floor() {
18143 return None;
18144 }
18145 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18146 let source_y = line_height * (source.row().as_f32() - scroll_top);
18147 Some(gpui::Point::new(source_x, source_y))
18148 }
18149
18150 pub fn has_visible_completions_menu(&self) -> bool {
18151 !self.edit_prediction_preview_is_active()
18152 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18153 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18154 })
18155 }
18156
18157 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18158 self.addons
18159 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18160 }
18161
18162 pub fn unregister_addon<T: Addon>(&mut self) {
18163 self.addons.remove(&std::any::TypeId::of::<T>());
18164 }
18165
18166 pub fn addon<T: Addon>(&self) -> Option<&T> {
18167 let type_id = std::any::TypeId::of::<T>();
18168 self.addons
18169 .get(&type_id)
18170 .and_then(|item| item.to_any().downcast_ref::<T>())
18171 }
18172
18173 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18174 let text_layout_details = self.text_layout_details(window);
18175 let style = &text_layout_details.editor_style;
18176 let font_id = window.text_system().resolve_font(&style.text.font());
18177 let font_size = style.text.font_size.to_pixels(window.rem_size());
18178 let line_height = style.text.line_height_in_pixels(window.rem_size());
18179 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18180
18181 gpui::Size::new(em_width, line_height)
18182 }
18183
18184 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18185 self.load_diff_task.clone()
18186 }
18187
18188 fn read_metadata_from_db(
18189 &mut self,
18190 item_id: u64,
18191 workspace_id: WorkspaceId,
18192 window: &mut Window,
18193 cx: &mut Context<Editor>,
18194 ) {
18195 if self.is_singleton(cx)
18196 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18197 {
18198 let buffer_snapshot = OnceCell::new();
18199
18200 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18201 if !folds.is_empty() {
18202 let snapshot =
18203 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18204 self.fold_ranges(
18205 folds
18206 .into_iter()
18207 .map(|(start, end)| {
18208 snapshot.clip_offset(start, Bias::Left)
18209 ..snapshot.clip_offset(end, Bias::Right)
18210 })
18211 .collect(),
18212 false,
18213 window,
18214 cx,
18215 );
18216 }
18217 }
18218
18219 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18220 if !selections.is_empty() {
18221 let snapshot =
18222 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18223 self.change_selections(None, window, cx, |s| {
18224 s.select_ranges(selections.into_iter().map(|(start, end)| {
18225 snapshot.clip_offset(start, Bias::Left)
18226 ..snapshot.clip_offset(end, Bias::Right)
18227 }));
18228 });
18229 }
18230 };
18231 }
18232
18233 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18234 }
18235}
18236
18237fn vim_enabled(cx: &App) -> bool {
18238 cx.global::<SettingsStore>()
18239 .raw_user_settings()
18240 .get("vim_mode")
18241 == Some(&serde_json::Value::Bool(true))
18242}
18243
18244// Consider user intent and default settings
18245fn choose_completion_range(
18246 completion: &Completion,
18247 intent: CompletionIntent,
18248 buffer: &Entity<Buffer>,
18249 cx: &mut Context<Editor>,
18250) -> Range<usize> {
18251 fn should_replace(
18252 completion: &Completion,
18253 insert_range: &Range<text::Anchor>,
18254 intent: CompletionIntent,
18255 completion_mode_setting: LspInsertMode,
18256 buffer: &Buffer,
18257 ) -> bool {
18258 // specific actions take precedence over settings
18259 match intent {
18260 CompletionIntent::CompleteWithInsert => return false,
18261 CompletionIntent::CompleteWithReplace => return true,
18262 CompletionIntent::Complete | CompletionIntent::Compose => {}
18263 }
18264
18265 match completion_mode_setting {
18266 LspInsertMode::Insert => false,
18267 LspInsertMode::Replace => true,
18268 LspInsertMode::ReplaceSubsequence => {
18269 let mut text_to_replace = buffer.chars_for_range(
18270 buffer.anchor_before(completion.replace_range.start)
18271 ..buffer.anchor_after(completion.replace_range.end),
18272 );
18273 let mut completion_text = completion.new_text.chars();
18274
18275 // is `text_to_replace` a subsequence of `completion_text`
18276 text_to_replace
18277 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18278 }
18279 LspInsertMode::ReplaceSuffix => {
18280 let range_after_cursor = insert_range.end..completion.replace_range.end;
18281
18282 let text_after_cursor = buffer
18283 .text_for_range(
18284 buffer.anchor_before(range_after_cursor.start)
18285 ..buffer.anchor_after(range_after_cursor.end),
18286 )
18287 .collect::<String>();
18288 completion.new_text.ends_with(&text_after_cursor)
18289 }
18290 }
18291 }
18292
18293 let buffer = buffer.read(cx);
18294
18295 if let CompletionSource::Lsp {
18296 insert_range: Some(insert_range),
18297 ..
18298 } = &completion.source
18299 {
18300 let completion_mode_setting =
18301 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18302 .completions
18303 .lsp_insert_mode;
18304
18305 if !should_replace(
18306 completion,
18307 &insert_range,
18308 intent,
18309 completion_mode_setting,
18310 buffer,
18311 ) {
18312 return insert_range.to_offset(buffer);
18313 }
18314 }
18315
18316 completion.replace_range.to_offset(buffer)
18317}
18318
18319fn insert_extra_newline_brackets(
18320 buffer: &MultiBufferSnapshot,
18321 range: Range<usize>,
18322 language: &language::LanguageScope,
18323) -> bool {
18324 let leading_whitespace_len = buffer
18325 .reversed_chars_at(range.start)
18326 .take_while(|c| c.is_whitespace() && *c != '\n')
18327 .map(|c| c.len_utf8())
18328 .sum::<usize>();
18329 let trailing_whitespace_len = buffer
18330 .chars_at(range.end)
18331 .take_while(|c| c.is_whitespace() && *c != '\n')
18332 .map(|c| c.len_utf8())
18333 .sum::<usize>();
18334 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18335
18336 language.brackets().any(|(pair, enabled)| {
18337 let pair_start = pair.start.trim_end();
18338 let pair_end = pair.end.trim_start();
18339
18340 enabled
18341 && pair.newline
18342 && buffer.contains_str_at(range.end, pair_end)
18343 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18344 })
18345}
18346
18347fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18348 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18349 [(buffer, range, _)] => (*buffer, range.clone()),
18350 _ => return false,
18351 };
18352 let pair = {
18353 let mut result: Option<BracketMatch> = None;
18354
18355 for pair in buffer
18356 .all_bracket_ranges(range.clone())
18357 .filter(move |pair| {
18358 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18359 })
18360 {
18361 let len = pair.close_range.end - pair.open_range.start;
18362
18363 if let Some(existing) = &result {
18364 let existing_len = existing.close_range.end - existing.open_range.start;
18365 if len > existing_len {
18366 continue;
18367 }
18368 }
18369
18370 result = Some(pair);
18371 }
18372
18373 result
18374 };
18375 let Some(pair) = pair else {
18376 return false;
18377 };
18378 pair.newline_only
18379 && buffer
18380 .chars_for_range(pair.open_range.end..range.start)
18381 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18382 .all(|c| c.is_whitespace() && c != '\n')
18383}
18384
18385fn get_uncommitted_diff_for_buffer(
18386 project: &Entity<Project>,
18387 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18388 buffer: Entity<MultiBuffer>,
18389 cx: &mut App,
18390) -> Task<()> {
18391 let mut tasks = Vec::new();
18392 project.update(cx, |project, cx| {
18393 for buffer in buffers {
18394 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18395 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18396 }
18397 }
18398 });
18399 cx.spawn(async move |cx| {
18400 let diffs = future::join_all(tasks).await;
18401 buffer
18402 .update(cx, |buffer, cx| {
18403 for diff in diffs.into_iter().flatten() {
18404 buffer.add_diff(diff, cx);
18405 }
18406 })
18407 .ok();
18408 })
18409}
18410
18411fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18412 let tab_size = tab_size.get() as usize;
18413 let mut width = offset;
18414
18415 for ch in text.chars() {
18416 width += if ch == '\t' {
18417 tab_size - (width % tab_size)
18418 } else {
18419 1
18420 };
18421 }
18422
18423 width - offset
18424}
18425
18426#[cfg(test)]
18427mod tests {
18428 use super::*;
18429
18430 #[test]
18431 fn test_string_size_with_expanded_tabs() {
18432 let nz = |val| NonZeroU32::new(val).unwrap();
18433 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18434 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18435 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18436 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18437 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18438 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18439 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18440 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18441 }
18442}
18443
18444/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18445struct WordBreakingTokenizer<'a> {
18446 input: &'a str,
18447}
18448
18449impl<'a> WordBreakingTokenizer<'a> {
18450 fn new(input: &'a str) -> Self {
18451 Self { input }
18452 }
18453}
18454
18455fn is_char_ideographic(ch: char) -> bool {
18456 use unicode_script::Script::*;
18457 use unicode_script::UnicodeScript;
18458 matches!(ch.script(), Han | Tangut | Yi)
18459}
18460
18461fn is_grapheme_ideographic(text: &str) -> bool {
18462 text.chars().any(is_char_ideographic)
18463}
18464
18465fn is_grapheme_whitespace(text: &str) -> bool {
18466 text.chars().any(|x| x.is_whitespace())
18467}
18468
18469fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18470 text.chars().next().map_or(false, |ch| {
18471 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18472 })
18473}
18474
18475#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18476enum WordBreakToken<'a> {
18477 Word { token: &'a str, grapheme_len: usize },
18478 InlineWhitespace { token: &'a str, grapheme_len: usize },
18479 Newline,
18480}
18481
18482impl<'a> Iterator for WordBreakingTokenizer<'a> {
18483 /// Yields a span, the count of graphemes in the token, and whether it was
18484 /// whitespace. Note that it also breaks at word boundaries.
18485 type Item = WordBreakToken<'a>;
18486
18487 fn next(&mut self) -> Option<Self::Item> {
18488 use unicode_segmentation::UnicodeSegmentation;
18489 if self.input.is_empty() {
18490 return None;
18491 }
18492
18493 let mut iter = self.input.graphemes(true).peekable();
18494 let mut offset = 0;
18495 let mut grapheme_len = 0;
18496 if let Some(first_grapheme) = iter.next() {
18497 let is_newline = first_grapheme == "\n";
18498 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18499 offset += first_grapheme.len();
18500 grapheme_len += 1;
18501 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18502 if let Some(grapheme) = iter.peek().copied() {
18503 if should_stay_with_preceding_ideograph(grapheme) {
18504 offset += grapheme.len();
18505 grapheme_len += 1;
18506 }
18507 }
18508 } else {
18509 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18510 let mut next_word_bound = words.peek().copied();
18511 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18512 next_word_bound = words.next();
18513 }
18514 while let Some(grapheme) = iter.peek().copied() {
18515 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18516 break;
18517 };
18518 if is_grapheme_whitespace(grapheme) != is_whitespace
18519 || (grapheme == "\n") != is_newline
18520 {
18521 break;
18522 };
18523 offset += grapheme.len();
18524 grapheme_len += 1;
18525 iter.next();
18526 }
18527 }
18528 let token = &self.input[..offset];
18529 self.input = &self.input[offset..];
18530 if token == "\n" {
18531 Some(WordBreakToken::Newline)
18532 } else if is_whitespace {
18533 Some(WordBreakToken::InlineWhitespace {
18534 token,
18535 grapheme_len,
18536 })
18537 } else {
18538 Some(WordBreakToken::Word {
18539 token,
18540 grapheme_len,
18541 })
18542 }
18543 } else {
18544 None
18545 }
18546 }
18547}
18548
18549#[test]
18550fn test_word_breaking_tokenizer() {
18551 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18552 ("", &[]),
18553 (" ", &[whitespace(" ", 2)]),
18554 ("Ʒ", &[word("Ʒ", 1)]),
18555 ("Ǽ", &[word("Ǽ", 1)]),
18556 ("⋑", &[word("⋑", 1)]),
18557 ("⋑⋑", &[word("⋑⋑", 2)]),
18558 (
18559 "原理,进而",
18560 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18561 ),
18562 (
18563 "hello world",
18564 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18565 ),
18566 (
18567 "hello, world",
18568 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18569 ),
18570 (
18571 " hello world",
18572 &[
18573 whitespace(" ", 2),
18574 word("hello", 5),
18575 whitespace(" ", 1),
18576 word("world", 5),
18577 ],
18578 ),
18579 (
18580 "这是什么 \n 钢笔",
18581 &[
18582 word("这", 1),
18583 word("是", 1),
18584 word("什", 1),
18585 word("么", 1),
18586 whitespace(" ", 1),
18587 newline(),
18588 whitespace(" ", 1),
18589 word("钢", 1),
18590 word("笔", 1),
18591 ],
18592 ),
18593 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18594 ];
18595
18596 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18597 WordBreakToken::Word {
18598 token,
18599 grapheme_len,
18600 }
18601 }
18602
18603 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18604 WordBreakToken::InlineWhitespace {
18605 token,
18606 grapheme_len,
18607 }
18608 }
18609
18610 fn newline() -> WordBreakToken<'static> {
18611 WordBreakToken::Newline
18612 }
18613
18614 for (input, result) in tests {
18615 assert_eq!(
18616 WordBreakingTokenizer::new(input)
18617 .collect::<Vec<_>>()
18618 .as_slice(),
18619 *result,
18620 );
18621 }
18622}
18623
18624fn wrap_with_prefix(
18625 line_prefix: String,
18626 unwrapped_text: String,
18627 wrap_column: usize,
18628 tab_size: NonZeroU32,
18629 preserve_existing_whitespace: bool,
18630) -> String {
18631 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18632 let mut wrapped_text = String::new();
18633 let mut current_line = line_prefix.clone();
18634
18635 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18636 let mut current_line_len = line_prefix_len;
18637 let mut in_whitespace = false;
18638 for token in tokenizer {
18639 let have_preceding_whitespace = in_whitespace;
18640 match token {
18641 WordBreakToken::Word {
18642 token,
18643 grapheme_len,
18644 } => {
18645 in_whitespace = false;
18646 if current_line_len + grapheme_len > wrap_column
18647 && current_line_len != line_prefix_len
18648 {
18649 wrapped_text.push_str(current_line.trim_end());
18650 wrapped_text.push('\n');
18651 current_line.truncate(line_prefix.len());
18652 current_line_len = line_prefix_len;
18653 }
18654 current_line.push_str(token);
18655 current_line_len += grapheme_len;
18656 }
18657 WordBreakToken::InlineWhitespace {
18658 mut token,
18659 mut grapheme_len,
18660 } => {
18661 in_whitespace = true;
18662 if have_preceding_whitespace && !preserve_existing_whitespace {
18663 continue;
18664 }
18665 if !preserve_existing_whitespace {
18666 token = " ";
18667 grapheme_len = 1;
18668 }
18669 if current_line_len + grapheme_len > wrap_column {
18670 wrapped_text.push_str(current_line.trim_end());
18671 wrapped_text.push('\n');
18672 current_line.truncate(line_prefix.len());
18673 current_line_len = line_prefix_len;
18674 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18675 current_line.push_str(token);
18676 current_line_len += grapheme_len;
18677 }
18678 }
18679 WordBreakToken::Newline => {
18680 in_whitespace = true;
18681 if preserve_existing_whitespace {
18682 wrapped_text.push_str(current_line.trim_end());
18683 wrapped_text.push('\n');
18684 current_line.truncate(line_prefix.len());
18685 current_line_len = line_prefix_len;
18686 } else if have_preceding_whitespace {
18687 continue;
18688 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18689 {
18690 wrapped_text.push_str(current_line.trim_end());
18691 wrapped_text.push('\n');
18692 current_line.truncate(line_prefix.len());
18693 current_line_len = line_prefix_len;
18694 } else if current_line_len != line_prefix_len {
18695 current_line.push(' ');
18696 current_line_len += 1;
18697 }
18698 }
18699 }
18700 }
18701
18702 if !current_line.is_empty() {
18703 wrapped_text.push_str(¤t_line);
18704 }
18705 wrapped_text
18706}
18707
18708#[test]
18709fn test_wrap_with_prefix() {
18710 assert_eq!(
18711 wrap_with_prefix(
18712 "# ".to_string(),
18713 "abcdefg".to_string(),
18714 4,
18715 NonZeroU32::new(4).unwrap(),
18716 false,
18717 ),
18718 "# abcdefg"
18719 );
18720 assert_eq!(
18721 wrap_with_prefix(
18722 "".to_string(),
18723 "\thello world".to_string(),
18724 8,
18725 NonZeroU32::new(4).unwrap(),
18726 false,
18727 ),
18728 "hello\nworld"
18729 );
18730 assert_eq!(
18731 wrap_with_prefix(
18732 "// ".to_string(),
18733 "xx \nyy zz aa bb cc".to_string(),
18734 12,
18735 NonZeroU32::new(4).unwrap(),
18736 false,
18737 ),
18738 "// xx yy zz\n// aa bb cc"
18739 );
18740 assert_eq!(
18741 wrap_with_prefix(
18742 String::new(),
18743 "这是什么 \n 钢笔".to_string(),
18744 3,
18745 NonZeroU32::new(4).unwrap(),
18746 false,
18747 ),
18748 "这是什\n么 钢\n笔"
18749 );
18750}
18751
18752pub trait CollaborationHub {
18753 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18754 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18755 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18756}
18757
18758impl CollaborationHub for Entity<Project> {
18759 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18760 self.read(cx).collaborators()
18761 }
18762
18763 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18764 self.read(cx).user_store().read(cx).participant_indices()
18765 }
18766
18767 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18768 let this = self.read(cx);
18769 let user_ids = this.collaborators().values().map(|c| c.user_id);
18770 this.user_store().read_with(cx, |user_store, cx| {
18771 user_store.participant_names(user_ids, cx)
18772 })
18773 }
18774}
18775
18776pub trait SemanticsProvider {
18777 fn hover(
18778 &self,
18779 buffer: &Entity<Buffer>,
18780 position: text::Anchor,
18781 cx: &mut App,
18782 ) -> Option<Task<Vec<project::Hover>>>;
18783
18784 fn inlay_hints(
18785 &self,
18786 buffer_handle: Entity<Buffer>,
18787 range: Range<text::Anchor>,
18788 cx: &mut App,
18789 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18790
18791 fn resolve_inlay_hint(
18792 &self,
18793 hint: InlayHint,
18794 buffer_handle: Entity<Buffer>,
18795 server_id: LanguageServerId,
18796 cx: &mut App,
18797 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18798
18799 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18800
18801 fn document_highlights(
18802 &self,
18803 buffer: &Entity<Buffer>,
18804 position: text::Anchor,
18805 cx: &mut App,
18806 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18807
18808 fn definitions(
18809 &self,
18810 buffer: &Entity<Buffer>,
18811 position: text::Anchor,
18812 kind: GotoDefinitionKind,
18813 cx: &mut App,
18814 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18815
18816 fn range_for_rename(
18817 &self,
18818 buffer: &Entity<Buffer>,
18819 position: text::Anchor,
18820 cx: &mut App,
18821 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18822
18823 fn perform_rename(
18824 &self,
18825 buffer: &Entity<Buffer>,
18826 position: text::Anchor,
18827 new_name: String,
18828 cx: &mut App,
18829 ) -> Option<Task<Result<ProjectTransaction>>>;
18830}
18831
18832pub trait CompletionProvider {
18833 fn completions(
18834 &self,
18835 excerpt_id: ExcerptId,
18836 buffer: &Entity<Buffer>,
18837 buffer_position: text::Anchor,
18838 trigger: CompletionContext,
18839 window: &mut Window,
18840 cx: &mut Context<Editor>,
18841 ) -> Task<Result<Option<Vec<Completion>>>>;
18842
18843 fn resolve_completions(
18844 &self,
18845 buffer: Entity<Buffer>,
18846 completion_indices: Vec<usize>,
18847 completions: Rc<RefCell<Box<[Completion]>>>,
18848 cx: &mut Context<Editor>,
18849 ) -> Task<Result<bool>>;
18850
18851 fn apply_additional_edits_for_completion(
18852 &self,
18853 _buffer: Entity<Buffer>,
18854 _completions: Rc<RefCell<Box<[Completion]>>>,
18855 _completion_index: usize,
18856 _push_to_history: bool,
18857 _cx: &mut Context<Editor>,
18858 ) -> Task<Result<Option<language::Transaction>>> {
18859 Task::ready(Ok(None))
18860 }
18861
18862 fn is_completion_trigger(
18863 &self,
18864 buffer: &Entity<Buffer>,
18865 position: language::Anchor,
18866 text: &str,
18867 trigger_in_words: bool,
18868 cx: &mut Context<Editor>,
18869 ) -> bool;
18870
18871 fn sort_completions(&self) -> bool {
18872 true
18873 }
18874
18875 fn filter_completions(&self) -> bool {
18876 true
18877 }
18878}
18879
18880pub trait CodeActionProvider {
18881 fn id(&self) -> Arc<str>;
18882
18883 fn code_actions(
18884 &self,
18885 buffer: &Entity<Buffer>,
18886 range: Range<text::Anchor>,
18887 window: &mut Window,
18888 cx: &mut App,
18889 ) -> Task<Result<Vec<CodeAction>>>;
18890
18891 fn apply_code_action(
18892 &self,
18893 buffer_handle: Entity<Buffer>,
18894 action: CodeAction,
18895 excerpt_id: ExcerptId,
18896 push_to_history: bool,
18897 window: &mut Window,
18898 cx: &mut App,
18899 ) -> Task<Result<ProjectTransaction>>;
18900}
18901
18902impl CodeActionProvider for Entity<Project> {
18903 fn id(&self) -> Arc<str> {
18904 "project".into()
18905 }
18906
18907 fn code_actions(
18908 &self,
18909 buffer: &Entity<Buffer>,
18910 range: Range<text::Anchor>,
18911 _window: &mut Window,
18912 cx: &mut App,
18913 ) -> Task<Result<Vec<CodeAction>>> {
18914 self.update(cx, |project, cx| {
18915 let code_lens = project.code_lens(buffer, range.clone(), cx);
18916 let code_actions = project.code_actions(buffer, range, None, cx);
18917 cx.background_spawn(async move {
18918 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18919 Ok(code_lens
18920 .context("code lens fetch")?
18921 .into_iter()
18922 .chain(code_actions.context("code action fetch")?)
18923 .collect())
18924 })
18925 })
18926 }
18927
18928 fn apply_code_action(
18929 &self,
18930 buffer_handle: Entity<Buffer>,
18931 action: CodeAction,
18932 _excerpt_id: ExcerptId,
18933 push_to_history: bool,
18934 _window: &mut Window,
18935 cx: &mut App,
18936 ) -> Task<Result<ProjectTransaction>> {
18937 self.update(cx, |project, cx| {
18938 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18939 })
18940 }
18941}
18942
18943fn snippet_completions(
18944 project: &Project,
18945 buffer: &Entity<Buffer>,
18946 buffer_position: text::Anchor,
18947 cx: &mut App,
18948) -> Task<Result<Vec<Completion>>> {
18949 let languages = buffer.read(cx).languages_at(buffer_position);
18950 let snippet_store = project.snippets().read(cx);
18951
18952 let scopes: Vec<_> = languages
18953 .iter()
18954 .filter_map(|language| {
18955 let language_name = language.lsp_id();
18956 let snippets = snippet_store.snippets_for(Some(language_name), cx);
18957
18958 if snippets.is_empty() {
18959 None
18960 } else {
18961 Some((language.default_scope(), snippets))
18962 }
18963 })
18964 .collect();
18965
18966 if scopes.is_empty() {
18967 return Task::ready(Ok(vec![]));
18968 }
18969
18970 let snapshot = buffer.read(cx).text_snapshot();
18971 let chars: String = snapshot
18972 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18973 .collect();
18974 let executor = cx.background_executor().clone();
18975
18976 cx.background_spawn(async move {
18977 let mut all_results: Vec<Completion> = Vec::new();
18978 for (scope, snippets) in scopes.into_iter() {
18979 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18980 let mut last_word = chars
18981 .chars()
18982 .take_while(|c| classifier.is_word(*c))
18983 .collect::<String>();
18984 last_word = last_word.chars().rev().collect();
18985
18986 if last_word.is_empty() {
18987 return Ok(vec![]);
18988 }
18989
18990 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18991 let to_lsp = |point: &text::Anchor| {
18992 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18993 point_to_lsp(end)
18994 };
18995 let lsp_end = to_lsp(&buffer_position);
18996
18997 let candidates = snippets
18998 .iter()
18999 .enumerate()
19000 .flat_map(|(ix, snippet)| {
19001 snippet
19002 .prefix
19003 .iter()
19004 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19005 })
19006 .collect::<Vec<StringMatchCandidate>>();
19007
19008 let mut matches = fuzzy::match_strings(
19009 &candidates,
19010 &last_word,
19011 last_word.chars().any(|c| c.is_uppercase()),
19012 100,
19013 &Default::default(),
19014 executor.clone(),
19015 )
19016 .await;
19017
19018 // Remove all candidates where the query's start does not match the start of any word in the candidate
19019 if let Some(query_start) = last_word.chars().next() {
19020 matches.retain(|string_match| {
19021 split_words(&string_match.string).any(|word| {
19022 // Check that the first codepoint of the word as lowercase matches the first
19023 // codepoint of the query as lowercase
19024 word.chars()
19025 .flat_map(|codepoint| codepoint.to_lowercase())
19026 .zip(query_start.to_lowercase())
19027 .all(|(word_cp, query_cp)| word_cp == query_cp)
19028 })
19029 });
19030 }
19031
19032 let matched_strings = matches
19033 .into_iter()
19034 .map(|m| m.string)
19035 .collect::<HashSet<_>>();
19036
19037 let mut result: Vec<Completion> = snippets
19038 .iter()
19039 .filter_map(|snippet| {
19040 let matching_prefix = snippet
19041 .prefix
19042 .iter()
19043 .find(|prefix| matched_strings.contains(*prefix))?;
19044 let start = as_offset - last_word.len();
19045 let start = snapshot.anchor_before(start);
19046 let range = start..buffer_position;
19047 let lsp_start = to_lsp(&start);
19048 let lsp_range = lsp::Range {
19049 start: lsp_start,
19050 end: lsp_end,
19051 };
19052 Some(Completion {
19053 replace_range: range,
19054 new_text: snippet.body.clone(),
19055 source: CompletionSource::Lsp {
19056 insert_range: None,
19057 server_id: LanguageServerId(usize::MAX),
19058 resolved: true,
19059 lsp_completion: Box::new(lsp::CompletionItem {
19060 label: snippet.prefix.first().unwrap().clone(),
19061 kind: Some(CompletionItemKind::SNIPPET),
19062 label_details: snippet.description.as_ref().map(|description| {
19063 lsp::CompletionItemLabelDetails {
19064 detail: Some(description.clone()),
19065 description: None,
19066 }
19067 }),
19068 insert_text_format: Some(InsertTextFormat::SNIPPET),
19069 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19070 lsp::InsertReplaceEdit {
19071 new_text: snippet.body.clone(),
19072 insert: lsp_range,
19073 replace: lsp_range,
19074 },
19075 )),
19076 filter_text: Some(snippet.body.clone()),
19077 sort_text: Some(char::MAX.to_string()),
19078 ..lsp::CompletionItem::default()
19079 }),
19080 lsp_defaults: None,
19081 },
19082 label: CodeLabel {
19083 text: matching_prefix.clone(),
19084 runs: Vec::new(),
19085 filter_range: 0..matching_prefix.len(),
19086 },
19087 icon_path: None,
19088 documentation: snippet.description.clone().map(|description| {
19089 CompletionDocumentation::SingleLine(description.into())
19090 }),
19091 insert_text_mode: None,
19092 confirm: None,
19093 })
19094 })
19095 .collect();
19096
19097 all_results.append(&mut result);
19098 }
19099
19100 Ok(all_results)
19101 })
19102}
19103
19104impl CompletionProvider for Entity<Project> {
19105 fn completions(
19106 &self,
19107 _excerpt_id: ExcerptId,
19108 buffer: &Entity<Buffer>,
19109 buffer_position: text::Anchor,
19110 options: CompletionContext,
19111 _window: &mut Window,
19112 cx: &mut Context<Editor>,
19113 ) -> Task<Result<Option<Vec<Completion>>>> {
19114 self.update(cx, |project, cx| {
19115 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19116 let project_completions = project.completions(buffer, buffer_position, options, cx);
19117 cx.background_spawn(async move {
19118 let snippets_completions = snippets.await?;
19119 match project_completions.await? {
19120 Some(mut completions) => {
19121 completions.extend(snippets_completions);
19122 Ok(Some(completions))
19123 }
19124 None => {
19125 if snippets_completions.is_empty() {
19126 Ok(None)
19127 } else {
19128 Ok(Some(snippets_completions))
19129 }
19130 }
19131 }
19132 })
19133 })
19134 }
19135
19136 fn resolve_completions(
19137 &self,
19138 buffer: Entity<Buffer>,
19139 completion_indices: Vec<usize>,
19140 completions: Rc<RefCell<Box<[Completion]>>>,
19141 cx: &mut Context<Editor>,
19142 ) -> Task<Result<bool>> {
19143 self.update(cx, |project, cx| {
19144 project.lsp_store().update(cx, |lsp_store, cx| {
19145 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19146 })
19147 })
19148 }
19149
19150 fn apply_additional_edits_for_completion(
19151 &self,
19152 buffer: Entity<Buffer>,
19153 completions: Rc<RefCell<Box<[Completion]>>>,
19154 completion_index: usize,
19155 push_to_history: bool,
19156 cx: &mut Context<Editor>,
19157 ) -> Task<Result<Option<language::Transaction>>> {
19158 self.update(cx, |project, cx| {
19159 project.lsp_store().update(cx, |lsp_store, cx| {
19160 lsp_store.apply_additional_edits_for_completion(
19161 buffer,
19162 completions,
19163 completion_index,
19164 push_to_history,
19165 cx,
19166 )
19167 })
19168 })
19169 }
19170
19171 fn is_completion_trigger(
19172 &self,
19173 buffer: &Entity<Buffer>,
19174 position: language::Anchor,
19175 text: &str,
19176 trigger_in_words: bool,
19177 cx: &mut Context<Editor>,
19178 ) -> bool {
19179 let mut chars = text.chars();
19180 let char = if let Some(char) = chars.next() {
19181 char
19182 } else {
19183 return false;
19184 };
19185 if chars.next().is_some() {
19186 return false;
19187 }
19188
19189 let buffer = buffer.read(cx);
19190 let snapshot = buffer.snapshot();
19191 if !snapshot.settings_at(position, cx).show_completions_on_input {
19192 return false;
19193 }
19194 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19195 if trigger_in_words && classifier.is_word(char) {
19196 return true;
19197 }
19198
19199 buffer.completion_triggers().contains(text)
19200 }
19201}
19202
19203impl SemanticsProvider for Entity<Project> {
19204 fn hover(
19205 &self,
19206 buffer: &Entity<Buffer>,
19207 position: text::Anchor,
19208 cx: &mut App,
19209 ) -> Option<Task<Vec<project::Hover>>> {
19210 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19211 }
19212
19213 fn document_highlights(
19214 &self,
19215 buffer: &Entity<Buffer>,
19216 position: text::Anchor,
19217 cx: &mut App,
19218 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19219 Some(self.update(cx, |project, cx| {
19220 project.document_highlights(buffer, position, cx)
19221 }))
19222 }
19223
19224 fn definitions(
19225 &self,
19226 buffer: &Entity<Buffer>,
19227 position: text::Anchor,
19228 kind: GotoDefinitionKind,
19229 cx: &mut App,
19230 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19231 Some(self.update(cx, |project, cx| match kind {
19232 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19233 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19234 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19235 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19236 }))
19237 }
19238
19239 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19240 // TODO: make this work for remote projects
19241 self.update(cx, |this, cx| {
19242 buffer.update(cx, |buffer, cx| {
19243 this.any_language_server_supports_inlay_hints(buffer, cx)
19244 })
19245 })
19246 }
19247
19248 fn inlay_hints(
19249 &self,
19250 buffer_handle: Entity<Buffer>,
19251 range: Range<text::Anchor>,
19252 cx: &mut App,
19253 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19254 Some(self.update(cx, |project, cx| {
19255 project.inlay_hints(buffer_handle, range, cx)
19256 }))
19257 }
19258
19259 fn resolve_inlay_hint(
19260 &self,
19261 hint: InlayHint,
19262 buffer_handle: Entity<Buffer>,
19263 server_id: LanguageServerId,
19264 cx: &mut App,
19265 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19266 Some(self.update(cx, |project, cx| {
19267 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19268 }))
19269 }
19270
19271 fn range_for_rename(
19272 &self,
19273 buffer: &Entity<Buffer>,
19274 position: text::Anchor,
19275 cx: &mut App,
19276 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19277 Some(self.update(cx, |project, cx| {
19278 let buffer = buffer.clone();
19279 let task = project.prepare_rename(buffer.clone(), position, cx);
19280 cx.spawn(async move |_, cx| {
19281 Ok(match task.await? {
19282 PrepareRenameResponse::Success(range) => Some(range),
19283 PrepareRenameResponse::InvalidPosition => None,
19284 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19285 // Fallback on using TreeSitter info to determine identifier range
19286 buffer.update(cx, |buffer, _| {
19287 let snapshot = buffer.snapshot();
19288 let (range, kind) = snapshot.surrounding_word(position);
19289 if kind != Some(CharKind::Word) {
19290 return None;
19291 }
19292 Some(
19293 snapshot.anchor_before(range.start)
19294 ..snapshot.anchor_after(range.end),
19295 )
19296 })?
19297 }
19298 })
19299 })
19300 }))
19301 }
19302
19303 fn perform_rename(
19304 &self,
19305 buffer: &Entity<Buffer>,
19306 position: text::Anchor,
19307 new_name: String,
19308 cx: &mut App,
19309 ) -> Option<Task<Result<ProjectTransaction>>> {
19310 Some(self.update(cx, |project, cx| {
19311 project.perform_rename(buffer.clone(), position, new_name, cx)
19312 }))
19313 }
19314}
19315
19316fn inlay_hint_settings(
19317 location: Anchor,
19318 snapshot: &MultiBufferSnapshot,
19319 cx: &mut Context<Editor>,
19320) -> InlayHintSettings {
19321 let file = snapshot.file_at(location);
19322 let language = snapshot.language_at(location).map(|l| l.name());
19323 language_settings(language, file, cx).inlay_hints
19324}
19325
19326fn consume_contiguous_rows(
19327 contiguous_row_selections: &mut Vec<Selection<Point>>,
19328 selection: &Selection<Point>,
19329 display_map: &DisplaySnapshot,
19330 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19331) -> (MultiBufferRow, MultiBufferRow) {
19332 contiguous_row_selections.push(selection.clone());
19333 let start_row = MultiBufferRow(selection.start.row);
19334 let mut end_row = ending_row(selection, display_map);
19335
19336 while let Some(next_selection) = selections.peek() {
19337 if next_selection.start.row <= end_row.0 {
19338 end_row = ending_row(next_selection, display_map);
19339 contiguous_row_selections.push(selections.next().unwrap().clone());
19340 } else {
19341 break;
19342 }
19343 }
19344 (start_row, end_row)
19345}
19346
19347fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19348 if next_selection.end.column > 0 || next_selection.is_empty() {
19349 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19350 } else {
19351 MultiBufferRow(next_selection.end.row)
19352 }
19353}
19354
19355impl EditorSnapshot {
19356 pub fn remote_selections_in_range<'a>(
19357 &'a self,
19358 range: &'a Range<Anchor>,
19359 collaboration_hub: &dyn CollaborationHub,
19360 cx: &'a App,
19361 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19362 let participant_names = collaboration_hub.user_names(cx);
19363 let participant_indices = collaboration_hub.user_participant_indices(cx);
19364 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19365 let collaborators_by_replica_id = collaborators_by_peer_id
19366 .iter()
19367 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19368 .collect::<HashMap<_, _>>();
19369 self.buffer_snapshot
19370 .selections_in_range(range, false)
19371 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19372 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19373 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19374 let user_name = participant_names.get(&collaborator.user_id).cloned();
19375 Some(RemoteSelection {
19376 replica_id,
19377 selection,
19378 cursor_shape,
19379 line_mode,
19380 participant_index,
19381 peer_id: collaborator.peer_id,
19382 user_name,
19383 })
19384 })
19385 }
19386
19387 pub fn hunks_for_ranges(
19388 &self,
19389 ranges: impl IntoIterator<Item = Range<Point>>,
19390 ) -> Vec<MultiBufferDiffHunk> {
19391 let mut hunks = Vec::new();
19392 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19393 HashMap::default();
19394 for query_range in ranges {
19395 let query_rows =
19396 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19397 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19398 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19399 ) {
19400 // Include deleted hunks that are adjacent to the query range, because
19401 // otherwise they would be missed.
19402 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19403 if hunk.status().is_deleted() {
19404 intersects_range |= hunk.row_range.start == query_rows.end;
19405 intersects_range |= hunk.row_range.end == query_rows.start;
19406 }
19407 if intersects_range {
19408 if !processed_buffer_rows
19409 .entry(hunk.buffer_id)
19410 .or_default()
19411 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19412 {
19413 continue;
19414 }
19415 hunks.push(hunk);
19416 }
19417 }
19418 }
19419
19420 hunks
19421 }
19422
19423 fn display_diff_hunks_for_rows<'a>(
19424 &'a self,
19425 display_rows: Range<DisplayRow>,
19426 folded_buffers: &'a HashSet<BufferId>,
19427 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19428 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19429 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19430
19431 self.buffer_snapshot
19432 .diff_hunks_in_range(buffer_start..buffer_end)
19433 .filter_map(|hunk| {
19434 if folded_buffers.contains(&hunk.buffer_id) {
19435 return None;
19436 }
19437
19438 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19439 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19440
19441 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19442 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19443
19444 let display_hunk = if hunk_display_start.column() != 0 {
19445 DisplayDiffHunk::Folded {
19446 display_row: hunk_display_start.row(),
19447 }
19448 } else {
19449 let mut end_row = hunk_display_end.row();
19450 if hunk_display_end.column() > 0 {
19451 end_row.0 += 1;
19452 }
19453 let is_created_file = hunk.is_created_file();
19454 DisplayDiffHunk::Unfolded {
19455 status: hunk.status(),
19456 diff_base_byte_range: hunk.diff_base_byte_range,
19457 display_row_range: hunk_display_start.row()..end_row,
19458 multi_buffer_range: Anchor::range_in_buffer(
19459 hunk.excerpt_id,
19460 hunk.buffer_id,
19461 hunk.buffer_range,
19462 ),
19463 is_created_file,
19464 }
19465 };
19466
19467 Some(display_hunk)
19468 })
19469 }
19470
19471 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19472 self.display_snapshot.buffer_snapshot.language_at(position)
19473 }
19474
19475 pub fn is_focused(&self) -> bool {
19476 self.is_focused
19477 }
19478
19479 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19480 self.placeholder_text.as_ref()
19481 }
19482
19483 pub fn scroll_position(&self) -> gpui::Point<f32> {
19484 self.scroll_anchor.scroll_position(&self.display_snapshot)
19485 }
19486
19487 fn gutter_dimensions(
19488 &self,
19489 font_id: FontId,
19490 font_size: Pixels,
19491 max_line_number_width: Pixels,
19492 cx: &App,
19493 ) -> Option<GutterDimensions> {
19494 if !self.show_gutter {
19495 return None;
19496 }
19497
19498 let descent = cx.text_system().descent(font_id, font_size);
19499 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19500 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19501
19502 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19503 matches!(
19504 ProjectSettings::get_global(cx).git.git_gutter,
19505 Some(GitGutterSetting::TrackedFiles)
19506 )
19507 });
19508 let gutter_settings = EditorSettings::get_global(cx).gutter;
19509 let show_line_numbers = self
19510 .show_line_numbers
19511 .unwrap_or(gutter_settings.line_numbers);
19512 let line_gutter_width = if show_line_numbers {
19513 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19514 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19515 max_line_number_width.max(min_width_for_number_on_gutter)
19516 } else {
19517 0.0.into()
19518 };
19519
19520 let show_code_actions = self
19521 .show_code_actions
19522 .unwrap_or(gutter_settings.code_actions);
19523
19524 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19525 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19526
19527 let git_blame_entries_width =
19528 self.git_blame_gutter_max_author_length
19529 .map(|max_author_length| {
19530 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19531 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19532
19533 /// The number of characters to dedicate to gaps and margins.
19534 const SPACING_WIDTH: usize = 4;
19535
19536 let max_char_count = max_author_length.min(renderer.max_author_length())
19537 + ::git::SHORT_SHA_LENGTH
19538 + MAX_RELATIVE_TIMESTAMP.len()
19539 + SPACING_WIDTH;
19540
19541 em_advance * max_char_count
19542 });
19543
19544 let is_singleton = self.buffer_snapshot.is_singleton();
19545
19546 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19547 left_padding += if !is_singleton {
19548 em_width * 4.0
19549 } else if show_code_actions || show_runnables || show_breakpoints {
19550 em_width * 3.0
19551 } else if show_git_gutter && show_line_numbers {
19552 em_width * 2.0
19553 } else if show_git_gutter || show_line_numbers {
19554 em_width
19555 } else {
19556 px(0.)
19557 };
19558
19559 let shows_folds = is_singleton && gutter_settings.folds;
19560
19561 let right_padding = if shows_folds && show_line_numbers {
19562 em_width * 4.0
19563 } else if shows_folds || (!is_singleton && show_line_numbers) {
19564 em_width * 3.0
19565 } else if show_line_numbers {
19566 em_width
19567 } else {
19568 px(0.)
19569 };
19570
19571 Some(GutterDimensions {
19572 left_padding,
19573 right_padding,
19574 width: line_gutter_width + left_padding + right_padding,
19575 margin: -descent,
19576 git_blame_entries_width,
19577 })
19578 }
19579
19580 pub fn render_crease_toggle(
19581 &self,
19582 buffer_row: MultiBufferRow,
19583 row_contains_cursor: bool,
19584 editor: Entity<Editor>,
19585 window: &mut Window,
19586 cx: &mut App,
19587 ) -> Option<AnyElement> {
19588 let folded = self.is_line_folded(buffer_row);
19589 let mut is_foldable = false;
19590
19591 if let Some(crease) = self
19592 .crease_snapshot
19593 .query_row(buffer_row, &self.buffer_snapshot)
19594 {
19595 is_foldable = true;
19596 match crease {
19597 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19598 if let Some(render_toggle) = render_toggle {
19599 let toggle_callback =
19600 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19601 if folded {
19602 editor.update(cx, |editor, cx| {
19603 editor.fold_at(buffer_row, window, cx)
19604 });
19605 } else {
19606 editor.update(cx, |editor, cx| {
19607 editor.unfold_at(buffer_row, window, cx)
19608 });
19609 }
19610 });
19611 return Some((render_toggle)(
19612 buffer_row,
19613 folded,
19614 toggle_callback,
19615 window,
19616 cx,
19617 ));
19618 }
19619 }
19620 }
19621 }
19622
19623 is_foldable |= self.starts_indent(buffer_row);
19624
19625 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19626 Some(
19627 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19628 .toggle_state(folded)
19629 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19630 if folded {
19631 this.unfold_at(buffer_row, window, cx);
19632 } else {
19633 this.fold_at(buffer_row, window, cx);
19634 }
19635 }))
19636 .into_any_element(),
19637 )
19638 } else {
19639 None
19640 }
19641 }
19642
19643 pub fn render_crease_trailer(
19644 &self,
19645 buffer_row: MultiBufferRow,
19646 window: &mut Window,
19647 cx: &mut App,
19648 ) -> Option<AnyElement> {
19649 let folded = self.is_line_folded(buffer_row);
19650 if let Crease::Inline { render_trailer, .. } = self
19651 .crease_snapshot
19652 .query_row(buffer_row, &self.buffer_snapshot)?
19653 {
19654 let render_trailer = render_trailer.as_ref()?;
19655 Some(render_trailer(buffer_row, folded, window, cx))
19656 } else {
19657 None
19658 }
19659 }
19660}
19661
19662impl Deref for EditorSnapshot {
19663 type Target = DisplaySnapshot;
19664
19665 fn deref(&self) -> &Self::Target {
19666 &self.display_snapshot
19667 }
19668}
19669
19670#[derive(Clone, Debug, PartialEq, Eq)]
19671pub enum EditorEvent {
19672 InputIgnored {
19673 text: Arc<str>,
19674 },
19675 InputHandled {
19676 utf16_range_to_replace: Option<Range<isize>>,
19677 text: Arc<str>,
19678 },
19679 ExcerptsAdded {
19680 buffer: Entity<Buffer>,
19681 predecessor: ExcerptId,
19682 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19683 },
19684 ExcerptsRemoved {
19685 ids: Vec<ExcerptId>,
19686 },
19687 BufferFoldToggled {
19688 ids: Vec<ExcerptId>,
19689 folded: bool,
19690 },
19691 ExcerptsEdited {
19692 ids: Vec<ExcerptId>,
19693 },
19694 ExcerptsExpanded {
19695 ids: Vec<ExcerptId>,
19696 },
19697 BufferEdited,
19698 Edited {
19699 transaction_id: clock::Lamport,
19700 },
19701 Reparsed(BufferId),
19702 Focused,
19703 FocusedIn,
19704 Blurred,
19705 DirtyChanged,
19706 Saved,
19707 TitleChanged,
19708 DiffBaseChanged,
19709 SelectionsChanged {
19710 local: bool,
19711 },
19712 ScrollPositionChanged {
19713 local: bool,
19714 autoscroll: bool,
19715 },
19716 Closed,
19717 TransactionUndone {
19718 transaction_id: clock::Lamport,
19719 },
19720 TransactionBegun {
19721 transaction_id: clock::Lamport,
19722 },
19723 Reloaded,
19724 CursorShapeChanged,
19725 PushedToNavHistory {
19726 anchor: Anchor,
19727 is_deactivate: bool,
19728 },
19729}
19730
19731impl EventEmitter<EditorEvent> for Editor {}
19732
19733impl Focusable for Editor {
19734 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19735 self.focus_handle.clone()
19736 }
19737}
19738
19739impl Render for Editor {
19740 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19741 let settings = ThemeSettings::get_global(cx);
19742
19743 let mut text_style = match self.mode {
19744 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19745 color: cx.theme().colors().editor_foreground,
19746 font_family: settings.ui_font.family.clone(),
19747 font_features: settings.ui_font.features.clone(),
19748 font_fallbacks: settings.ui_font.fallbacks.clone(),
19749 font_size: rems(0.875).into(),
19750 font_weight: settings.ui_font.weight,
19751 line_height: relative(settings.buffer_line_height.value()),
19752 ..Default::default()
19753 },
19754 EditorMode::Full { .. } => TextStyle {
19755 color: cx.theme().colors().editor_foreground,
19756 font_family: settings.buffer_font.family.clone(),
19757 font_features: settings.buffer_font.features.clone(),
19758 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19759 font_size: settings.buffer_font_size(cx).into(),
19760 font_weight: settings.buffer_font.weight,
19761 line_height: relative(settings.buffer_line_height.value()),
19762 ..Default::default()
19763 },
19764 };
19765 if let Some(text_style_refinement) = &self.text_style_refinement {
19766 text_style.refine(text_style_refinement)
19767 }
19768
19769 let background = match self.mode {
19770 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19771 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19772 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19773 };
19774
19775 EditorElement::new(
19776 &cx.entity(),
19777 EditorStyle {
19778 background,
19779 local_player: cx.theme().players().local(),
19780 text: text_style,
19781 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19782 syntax: cx.theme().syntax().clone(),
19783 status: cx.theme().status().clone(),
19784 inlay_hints_style: make_inlay_hints_style(cx),
19785 inline_completion_styles: make_suggestion_styles(cx),
19786 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19787 },
19788 )
19789 }
19790}
19791
19792impl EntityInputHandler for Editor {
19793 fn text_for_range(
19794 &mut self,
19795 range_utf16: Range<usize>,
19796 adjusted_range: &mut Option<Range<usize>>,
19797 _: &mut Window,
19798 cx: &mut Context<Self>,
19799 ) -> Option<String> {
19800 let snapshot = self.buffer.read(cx).read(cx);
19801 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19802 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19803 if (start.0..end.0) != range_utf16 {
19804 adjusted_range.replace(start.0..end.0);
19805 }
19806 Some(snapshot.text_for_range(start..end).collect())
19807 }
19808
19809 fn selected_text_range(
19810 &mut self,
19811 ignore_disabled_input: bool,
19812 _: &mut Window,
19813 cx: &mut Context<Self>,
19814 ) -> Option<UTF16Selection> {
19815 // Prevent the IME menu from appearing when holding down an alphabetic key
19816 // while input is disabled.
19817 if !ignore_disabled_input && !self.input_enabled {
19818 return None;
19819 }
19820
19821 let selection = self.selections.newest::<OffsetUtf16>(cx);
19822 let range = selection.range();
19823
19824 Some(UTF16Selection {
19825 range: range.start.0..range.end.0,
19826 reversed: selection.reversed,
19827 })
19828 }
19829
19830 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19831 let snapshot = self.buffer.read(cx).read(cx);
19832 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19833 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19834 }
19835
19836 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19837 self.clear_highlights::<InputComposition>(cx);
19838 self.ime_transaction.take();
19839 }
19840
19841 fn replace_text_in_range(
19842 &mut self,
19843 range_utf16: Option<Range<usize>>,
19844 text: &str,
19845 window: &mut Window,
19846 cx: &mut Context<Self>,
19847 ) {
19848 if !self.input_enabled {
19849 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19850 return;
19851 }
19852
19853 self.transact(window, cx, |this, window, cx| {
19854 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19855 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19856 Some(this.selection_replacement_ranges(range_utf16, cx))
19857 } else {
19858 this.marked_text_ranges(cx)
19859 };
19860
19861 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19862 let newest_selection_id = this.selections.newest_anchor().id;
19863 this.selections
19864 .all::<OffsetUtf16>(cx)
19865 .iter()
19866 .zip(ranges_to_replace.iter())
19867 .find_map(|(selection, range)| {
19868 if selection.id == newest_selection_id {
19869 Some(
19870 (range.start.0 as isize - selection.head().0 as isize)
19871 ..(range.end.0 as isize - selection.head().0 as isize),
19872 )
19873 } else {
19874 None
19875 }
19876 })
19877 });
19878
19879 cx.emit(EditorEvent::InputHandled {
19880 utf16_range_to_replace: range_to_replace,
19881 text: text.into(),
19882 });
19883
19884 if let Some(new_selected_ranges) = new_selected_ranges {
19885 this.change_selections(None, window, cx, |selections| {
19886 selections.select_ranges(new_selected_ranges)
19887 });
19888 this.backspace(&Default::default(), window, cx);
19889 }
19890
19891 this.handle_input(text, window, cx);
19892 });
19893
19894 if let Some(transaction) = self.ime_transaction {
19895 self.buffer.update(cx, |buffer, cx| {
19896 buffer.group_until_transaction(transaction, cx);
19897 });
19898 }
19899
19900 self.unmark_text(window, cx);
19901 }
19902
19903 fn replace_and_mark_text_in_range(
19904 &mut self,
19905 range_utf16: Option<Range<usize>>,
19906 text: &str,
19907 new_selected_range_utf16: Option<Range<usize>>,
19908 window: &mut Window,
19909 cx: &mut Context<Self>,
19910 ) {
19911 if !self.input_enabled {
19912 return;
19913 }
19914
19915 let transaction = self.transact(window, cx, |this, window, cx| {
19916 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19917 let snapshot = this.buffer.read(cx).read(cx);
19918 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19919 for marked_range in &mut marked_ranges {
19920 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19921 marked_range.start.0 += relative_range_utf16.start;
19922 marked_range.start =
19923 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19924 marked_range.end =
19925 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19926 }
19927 }
19928 Some(marked_ranges)
19929 } else if let Some(range_utf16) = range_utf16 {
19930 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19931 Some(this.selection_replacement_ranges(range_utf16, cx))
19932 } else {
19933 None
19934 };
19935
19936 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19937 let newest_selection_id = this.selections.newest_anchor().id;
19938 this.selections
19939 .all::<OffsetUtf16>(cx)
19940 .iter()
19941 .zip(ranges_to_replace.iter())
19942 .find_map(|(selection, range)| {
19943 if selection.id == newest_selection_id {
19944 Some(
19945 (range.start.0 as isize - selection.head().0 as isize)
19946 ..(range.end.0 as isize - selection.head().0 as isize),
19947 )
19948 } else {
19949 None
19950 }
19951 })
19952 });
19953
19954 cx.emit(EditorEvent::InputHandled {
19955 utf16_range_to_replace: range_to_replace,
19956 text: text.into(),
19957 });
19958
19959 if let Some(ranges) = ranges_to_replace {
19960 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19961 }
19962
19963 let marked_ranges = {
19964 let snapshot = this.buffer.read(cx).read(cx);
19965 this.selections
19966 .disjoint_anchors()
19967 .iter()
19968 .map(|selection| {
19969 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19970 })
19971 .collect::<Vec<_>>()
19972 };
19973
19974 if text.is_empty() {
19975 this.unmark_text(window, cx);
19976 } else {
19977 this.highlight_text::<InputComposition>(
19978 marked_ranges.clone(),
19979 HighlightStyle {
19980 underline: Some(UnderlineStyle {
19981 thickness: px(1.),
19982 color: None,
19983 wavy: false,
19984 }),
19985 ..Default::default()
19986 },
19987 cx,
19988 );
19989 }
19990
19991 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19992 let use_autoclose = this.use_autoclose;
19993 let use_auto_surround = this.use_auto_surround;
19994 this.set_use_autoclose(false);
19995 this.set_use_auto_surround(false);
19996 this.handle_input(text, window, cx);
19997 this.set_use_autoclose(use_autoclose);
19998 this.set_use_auto_surround(use_auto_surround);
19999
20000 if let Some(new_selected_range) = new_selected_range_utf16 {
20001 let snapshot = this.buffer.read(cx).read(cx);
20002 let new_selected_ranges = marked_ranges
20003 .into_iter()
20004 .map(|marked_range| {
20005 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20006 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20007 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20008 snapshot.clip_offset_utf16(new_start, Bias::Left)
20009 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20010 })
20011 .collect::<Vec<_>>();
20012
20013 drop(snapshot);
20014 this.change_selections(None, window, cx, |selections| {
20015 selections.select_ranges(new_selected_ranges)
20016 });
20017 }
20018 });
20019
20020 self.ime_transaction = self.ime_transaction.or(transaction);
20021 if let Some(transaction) = self.ime_transaction {
20022 self.buffer.update(cx, |buffer, cx| {
20023 buffer.group_until_transaction(transaction, cx);
20024 });
20025 }
20026
20027 if self.text_highlights::<InputComposition>(cx).is_none() {
20028 self.ime_transaction.take();
20029 }
20030 }
20031
20032 fn bounds_for_range(
20033 &mut self,
20034 range_utf16: Range<usize>,
20035 element_bounds: gpui::Bounds<Pixels>,
20036 window: &mut Window,
20037 cx: &mut Context<Self>,
20038 ) -> Option<gpui::Bounds<Pixels>> {
20039 let text_layout_details = self.text_layout_details(window);
20040 let gpui::Size {
20041 width: em_width,
20042 height: line_height,
20043 } = self.character_size(window);
20044
20045 let snapshot = self.snapshot(window, cx);
20046 let scroll_position = snapshot.scroll_position();
20047 let scroll_left = scroll_position.x * em_width;
20048
20049 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20050 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20051 + self.gutter_dimensions.width
20052 + self.gutter_dimensions.margin;
20053 let y = line_height * (start.row().as_f32() - scroll_position.y);
20054
20055 Some(Bounds {
20056 origin: element_bounds.origin + point(x, y),
20057 size: size(em_width, line_height),
20058 })
20059 }
20060
20061 fn character_index_for_point(
20062 &mut self,
20063 point: gpui::Point<Pixels>,
20064 _window: &mut Window,
20065 _cx: &mut Context<Self>,
20066 ) -> Option<usize> {
20067 let position_map = self.last_position_map.as_ref()?;
20068 if !position_map.text_hitbox.contains(&point) {
20069 return None;
20070 }
20071 let display_point = position_map.point_for_position(point).previous_valid;
20072 let anchor = position_map
20073 .snapshot
20074 .display_point_to_anchor(display_point, Bias::Left);
20075 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20076 Some(utf16_offset.0)
20077 }
20078}
20079
20080trait SelectionExt {
20081 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20082 fn spanned_rows(
20083 &self,
20084 include_end_if_at_line_start: bool,
20085 map: &DisplaySnapshot,
20086 ) -> Range<MultiBufferRow>;
20087}
20088
20089impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20090 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20091 let start = self
20092 .start
20093 .to_point(&map.buffer_snapshot)
20094 .to_display_point(map);
20095 let end = self
20096 .end
20097 .to_point(&map.buffer_snapshot)
20098 .to_display_point(map);
20099 if self.reversed {
20100 end..start
20101 } else {
20102 start..end
20103 }
20104 }
20105
20106 fn spanned_rows(
20107 &self,
20108 include_end_if_at_line_start: bool,
20109 map: &DisplaySnapshot,
20110 ) -> Range<MultiBufferRow> {
20111 let start = self.start.to_point(&map.buffer_snapshot);
20112 let mut end = self.end.to_point(&map.buffer_snapshot);
20113 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20114 end.row -= 1;
20115 }
20116
20117 let buffer_start = map.prev_line_boundary(start).0;
20118 let buffer_end = map.next_line_boundary(end).0;
20119 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20120 }
20121}
20122
20123impl<T: InvalidationRegion> InvalidationStack<T> {
20124 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20125 where
20126 S: Clone + ToOffset,
20127 {
20128 while let Some(region) = self.last() {
20129 let all_selections_inside_invalidation_ranges =
20130 if selections.len() == region.ranges().len() {
20131 selections
20132 .iter()
20133 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20134 .all(|(selection, invalidation_range)| {
20135 let head = selection.head().to_offset(buffer);
20136 invalidation_range.start <= head && invalidation_range.end >= head
20137 })
20138 } else {
20139 false
20140 };
20141
20142 if all_selections_inside_invalidation_ranges {
20143 break;
20144 } else {
20145 self.pop();
20146 }
20147 }
20148 }
20149}
20150
20151impl<T> Default for InvalidationStack<T> {
20152 fn default() -> Self {
20153 Self(Default::default())
20154 }
20155}
20156
20157impl<T> Deref for InvalidationStack<T> {
20158 type Target = Vec<T>;
20159
20160 fn deref(&self) -> &Self::Target {
20161 &self.0
20162 }
20163}
20164
20165impl<T> DerefMut for InvalidationStack<T> {
20166 fn deref_mut(&mut self) -> &mut Self::Target {
20167 &mut self.0
20168 }
20169}
20170
20171impl InvalidationRegion for SnippetState {
20172 fn ranges(&self) -> &[Range<Anchor>] {
20173 &self.ranges[self.active_index]
20174 }
20175}
20176
20177fn inline_completion_edit_text(
20178 current_snapshot: &BufferSnapshot,
20179 edits: &[(Range<Anchor>, String)],
20180 edit_preview: &EditPreview,
20181 include_deletions: bool,
20182 cx: &App,
20183) -> HighlightedText {
20184 let edits = edits
20185 .iter()
20186 .map(|(anchor, text)| {
20187 (
20188 anchor.start.text_anchor..anchor.end.text_anchor,
20189 text.clone(),
20190 )
20191 })
20192 .collect::<Vec<_>>();
20193
20194 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20195}
20196
20197pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20198 match severity {
20199 DiagnosticSeverity::ERROR => colors.error,
20200 DiagnosticSeverity::WARNING => colors.warning,
20201 DiagnosticSeverity::INFORMATION => colors.info,
20202 DiagnosticSeverity::HINT => colors.info,
20203 _ => colors.ignored,
20204 }
20205}
20206
20207pub fn styled_runs_for_code_label<'a>(
20208 label: &'a CodeLabel,
20209 syntax_theme: &'a theme::SyntaxTheme,
20210) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20211 let fade_out = HighlightStyle {
20212 fade_out: Some(0.35),
20213 ..Default::default()
20214 };
20215
20216 let mut prev_end = label.filter_range.end;
20217 label
20218 .runs
20219 .iter()
20220 .enumerate()
20221 .flat_map(move |(ix, (range, highlight_id))| {
20222 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20223 style
20224 } else {
20225 return Default::default();
20226 };
20227 let mut muted_style = style;
20228 muted_style.highlight(fade_out);
20229
20230 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20231 if range.start >= label.filter_range.end {
20232 if range.start > prev_end {
20233 runs.push((prev_end..range.start, fade_out));
20234 }
20235 runs.push((range.clone(), muted_style));
20236 } else if range.end <= label.filter_range.end {
20237 runs.push((range.clone(), style));
20238 } else {
20239 runs.push((range.start..label.filter_range.end, style));
20240 runs.push((label.filter_range.end..range.end, muted_style));
20241 }
20242 prev_end = cmp::max(prev_end, range.end);
20243
20244 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20245 runs.push((prev_end..label.text.len(), fade_out));
20246 }
20247
20248 runs
20249 })
20250}
20251
20252pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20253 let mut prev_index = 0;
20254 let mut prev_codepoint: Option<char> = None;
20255 text.char_indices()
20256 .chain([(text.len(), '\0')])
20257 .filter_map(move |(index, codepoint)| {
20258 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20259 let is_boundary = index == text.len()
20260 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20261 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20262 if is_boundary {
20263 let chunk = &text[prev_index..index];
20264 prev_index = index;
20265 Some(chunk)
20266 } else {
20267 None
20268 }
20269 })
20270}
20271
20272pub trait RangeToAnchorExt: Sized {
20273 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20274
20275 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20276 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20277 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20278 }
20279}
20280
20281impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20282 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20283 let start_offset = self.start.to_offset(snapshot);
20284 let end_offset = self.end.to_offset(snapshot);
20285 if start_offset == end_offset {
20286 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20287 } else {
20288 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20289 }
20290 }
20291}
20292
20293pub trait RowExt {
20294 fn as_f32(&self) -> f32;
20295
20296 fn next_row(&self) -> Self;
20297
20298 fn previous_row(&self) -> Self;
20299
20300 fn minus(&self, other: Self) -> u32;
20301}
20302
20303impl RowExt for DisplayRow {
20304 fn as_f32(&self) -> f32 {
20305 self.0 as f32
20306 }
20307
20308 fn next_row(&self) -> Self {
20309 Self(self.0 + 1)
20310 }
20311
20312 fn previous_row(&self) -> Self {
20313 Self(self.0.saturating_sub(1))
20314 }
20315
20316 fn minus(&self, other: Self) -> u32 {
20317 self.0 - other.0
20318 }
20319}
20320
20321impl RowExt for MultiBufferRow {
20322 fn as_f32(&self) -> f32 {
20323 self.0 as f32
20324 }
20325
20326 fn next_row(&self) -> Self {
20327 Self(self.0 + 1)
20328 }
20329
20330 fn previous_row(&self) -> Self {
20331 Self(self.0.saturating_sub(1))
20332 }
20333
20334 fn minus(&self, other: Self) -> u32 {
20335 self.0 - other.0
20336 }
20337}
20338
20339trait RowRangeExt {
20340 type Row;
20341
20342 fn len(&self) -> usize;
20343
20344 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20345}
20346
20347impl RowRangeExt for Range<MultiBufferRow> {
20348 type Row = MultiBufferRow;
20349
20350 fn len(&self) -> usize {
20351 (self.end.0 - self.start.0) as usize
20352 }
20353
20354 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20355 (self.start.0..self.end.0).map(MultiBufferRow)
20356 }
20357}
20358
20359impl RowRangeExt for Range<DisplayRow> {
20360 type Row = DisplayRow;
20361
20362 fn len(&self) -> usize {
20363 (self.end.0 - self.start.0) as usize
20364 }
20365
20366 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20367 (self.start.0..self.end.0).map(DisplayRow)
20368 }
20369}
20370
20371/// If select range has more than one line, we
20372/// just point the cursor to range.start.
20373fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20374 if range.start.row == range.end.row {
20375 range
20376 } else {
20377 range.start..range.start
20378 }
20379}
20380pub struct KillRing(ClipboardItem);
20381impl Global for KillRing {}
20382
20383const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20384
20385enum BreakpointPromptEditAction {
20386 Log,
20387 Condition,
20388 HitCondition,
20389}
20390
20391struct BreakpointPromptEditor {
20392 pub(crate) prompt: Entity<Editor>,
20393 editor: WeakEntity<Editor>,
20394 breakpoint_anchor: Anchor,
20395 breakpoint: Breakpoint,
20396 edit_action: BreakpointPromptEditAction,
20397 block_ids: HashSet<CustomBlockId>,
20398 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20399 _subscriptions: Vec<Subscription>,
20400}
20401
20402impl BreakpointPromptEditor {
20403 const MAX_LINES: u8 = 4;
20404
20405 fn new(
20406 editor: WeakEntity<Editor>,
20407 breakpoint_anchor: Anchor,
20408 breakpoint: Breakpoint,
20409 edit_action: BreakpointPromptEditAction,
20410 window: &mut Window,
20411 cx: &mut Context<Self>,
20412 ) -> Self {
20413 let base_text = match edit_action {
20414 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20415 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20416 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20417 }
20418 .map(|msg| msg.to_string())
20419 .unwrap_or_default();
20420
20421 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20422 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20423
20424 let prompt = cx.new(|cx| {
20425 let mut prompt = Editor::new(
20426 EditorMode::AutoHeight {
20427 max_lines: Self::MAX_LINES as usize,
20428 },
20429 buffer,
20430 None,
20431 window,
20432 cx,
20433 );
20434 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20435 prompt.set_show_cursor_when_unfocused(false, cx);
20436 prompt.set_placeholder_text(
20437 match edit_action {
20438 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20439 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20440 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20441 },
20442 cx,
20443 );
20444
20445 prompt
20446 });
20447
20448 Self {
20449 prompt,
20450 editor,
20451 breakpoint_anchor,
20452 breakpoint,
20453 edit_action,
20454 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20455 block_ids: Default::default(),
20456 _subscriptions: vec![],
20457 }
20458 }
20459
20460 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20461 self.block_ids.extend(block_ids)
20462 }
20463
20464 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20465 if let Some(editor) = self.editor.upgrade() {
20466 let message = self
20467 .prompt
20468 .read(cx)
20469 .buffer
20470 .read(cx)
20471 .as_singleton()
20472 .expect("A multi buffer in breakpoint prompt isn't possible")
20473 .read(cx)
20474 .as_rope()
20475 .to_string();
20476
20477 editor.update(cx, |editor, cx| {
20478 editor.edit_breakpoint_at_anchor(
20479 self.breakpoint_anchor,
20480 self.breakpoint.clone(),
20481 match self.edit_action {
20482 BreakpointPromptEditAction::Log => {
20483 BreakpointEditAction::EditLogMessage(message.into())
20484 }
20485 BreakpointPromptEditAction::Condition => {
20486 BreakpointEditAction::EditCondition(message.into())
20487 }
20488 BreakpointPromptEditAction::HitCondition => {
20489 BreakpointEditAction::EditHitCondition(message.into())
20490 }
20491 },
20492 cx,
20493 );
20494
20495 editor.remove_blocks(self.block_ids.clone(), None, cx);
20496 cx.focus_self(window);
20497 });
20498 }
20499 }
20500
20501 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20502 self.editor
20503 .update(cx, |editor, cx| {
20504 editor.remove_blocks(self.block_ids.clone(), None, cx);
20505 window.focus(&editor.focus_handle);
20506 })
20507 .log_err();
20508 }
20509
20510 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20511 let settings = ThemeSettings::get_global(cx);
20512 let text_style = TextStyle {
20513 color: if self.prompt.read(cx).read_only(cx) {
20514 cx.theme().colors().text_disabled
20515 } else {
20516 cx.theme().colors().text
20517 },
20518 font_family: settings.buffer_font.family.clone(),
20519 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20520 font_size: settings.buffer_font_size(cx).into(),
20521 font_weight: settings.buffer_font.weight,
20522 line_height: relative(settings.buffer_line_height.value()),
20523 ..Default::default()
20524 };
20525 EditorElement::new(
20526 &self.prompt,
20527 EditorStyle {
20528 background: cx.theme().colors().editor_background,
20529 local_player: cx.theme().players().local(),
20530 text: text_style,
20531 ..Default::default()
20532 },
20533 )
20534 }
20535}
20536
20537impl Render for BreakpointPromptEditor {
20538 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20539 let gutter_dimensions = *self.gutter_dimensions.lock();
20540 h_flex()
20541 .key_context("Editor")
20542 .bg(cx.theme().colors().editor_background)
20543 .border_y_1()
20544 .border_color(cx.theme().status().info_border)
20545 .size_full()
20546 .py(window.line_height() / 2.5)
20547 .on_action(cx.listener(Self::confirm))
20548 .on_action(cx.listener(Self::cancel))
20549 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20550 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20551 }
20552}
20553
20554impl Focusable for BreakpointPromptEditor {
20555 fn focus_handle(&self, cx: &App) -> FocusHandle {
20556 self.prompt.focus_handle(cx)
20557 }
20558}
20559
20560fn all_edits_insertions_or_deletions(
20561 edits: &Vec<(Range<Anchor>, String)>,
20562 snapshot: &MultiBufferSnapshot,
20563) -> bool {
20564 let mut all_insertions = true;
20565 let mut all_deletions = true;
20566
20567 for (range, new_text) in edits.iter() {
20568 let range_is_empty = range.to_offset(&snapshot).is_empty();
20569 let text_is_empty = new_text.is_empty();
20570
20571 if range_is_empty != text_is_empty {
20572 if range_is_empty {
20573 all_deletions = false;
20574 } else {
20575 all_insertions = false;
20576 }
20577 } else {
20578 return false;
20579 }
20580
20581 if !all_insertions && !all_deletions {
20582 return false;
20583 }
20584 }
20585 all_insertions || all_deletions
20586}
20587
20588struct MissingEditPredictionKeybindingTooltip;
20589
20590impl Render for MissingEditPredictionKeybindingTooltip {
20591 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20592 ui::tooltip_container(window, cx, |container, _, cx| {
20593 container
20594 .flex_shrink_0()
20595 .max_w_80()
20596 .min_h(rems_from_px(124.))
20597 .justify_between()
20598 .child(
20599 v_flex()
20600 .flex_1()
20601 .text_ui_sm(cx)
20602 .child(Label::new("Conflict with Accept Keybinding"))
20603 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20604 )
20605 .child(
20606 h_flex()
20607 .pb_1()
20608 .gap_1()
20609 .items_end()
20610 .w_full()
20611 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20612 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20613 }))
20614 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20615 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20616 })),
20617 )
20618 })
20619 }
20620}
20621
20622#[derive(Debug, Clone, Copy, PartialEq)]
20623pub struct LineHighlight {
20624 pub background: Background,
20625 pub border: Option<gpui::Hsla>,
20626}
20627
20628impl From<Hsla> for LineHighlight {
20629 fn from(hsla: Hsla) -> Self {
20630 Self {
20631 background: hsla.into(),
20632 border: None,
20633 }
20634 }
20635}
20636
20637impl From<Background> for LineHighlight {
20638 fn from(background: Background) -> Self {
20639 Self {
20640 background,
20641 border: None,
20642 }
20643 }
20644}
20645
20646fn render_diff_hunk_controls(
20647 row: u32,
20648 status: &DiffHunkStatus,
20649 hunk_range: Range<Anchor>,
20650 is_created_file: bool,
20651 line_height: Pixels,
20652 editor: &Entity<Editor>,
20653 _window: &mut Window,
20654 cx: &mut App,
20655) -> AnyElement {
20656 h_flex()
20657 .h(line_height)
20658 .mr_1()
20659 .gap_1()
20660 .px_0p5()
20661 .pb_1()
20662 .border_x_1()
20663 .border_b_1()
20664 .border_color(cx.theme().colors().border_variant)
20665 .rounded_b_lg()
20666 .bg(cx.theme().colors().editor_background)
20667 .gap_1()
20668 .occlude()
20669 .shadow_md()
20670 .child(if status.has_secondary_hunk() {
20671 Button::new(("stage", row as u64), "Stage")
20672 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20673 .tooltip({
20674 let focus_handle = editor.focus_handle(cx);
20675 move |window, cx| {
20676 Tooltip::for_action_in(
20677 "Stage Hunk",
20678 &::git::ToggleStaged,
20679 &focus_handle,
20680 window,
20681 cx,
20682 )
20683 }
20684 })
20685 .on_click({
20686 let editor = editor.clone();
20687 move |_event, _window, cx| {
20688 editor.update(cx, |editor, cx| {
20689 editor.stage_or_unstage_diff_hunks(
20690 true,
20691 vec![hunk_range.start..hunk_range.start],
20692 cx,
20693 );
20694 });
20695 }
20696 })
20697 } else {
20698 Button::new(("unstage", row as u64), "Unstage")
20699 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20700 .tooltip({
20701 let focus_handle = editor.focus_handle(cx);
20702 move |window, cx| {
20703 Tooltip::for_action_in(
20704 "Unstage Hunk",
20705 &::git::ToggleStaged,
20706 &focus_handle,
20707 window,
20708 cx,
20709 )
20710 }
20711 })
20712 .on_click({
20713 let editor = editor.clone();
20714 move |_event, _window, cx| {
20715 editor.update(cx, |editor, cx| {
20716 editor.stage_or_unstage_diff_hunks(
20717 false,
20718 vec![hunk_range.start..hunk_range.start],
20719 cx,
20720 );
20721 });
20722 }
20723 })
20724 })
20725 .child(
20726 Button::new(("restore", row as u64), "Restore")
20727 .tooltip({
20728 let focus_handle = editor.focus_handle(cx);
20729 move |window, cx| {
20730 Tooltip::for_action_in(
20731 "Restore Hunk",
20732 &::git::Restore,
20733 &focus_handle,
20734 window,
20735 cx,
20736 )
20737 }
20738 })
20739 .on_click({
20740 let editor = editor.clone();
20741 move |_event, window, cx| {
20742 editor.update(cx, |editor, cx| {
20743 let snapshot = editor.snapshot(window, cx);
20744 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20745 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20746 });
20747 }
20748 })
20749 .disabled(is_created_file),
20750 )
20751 .when(
20752 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20753 |el| {
20754 el.child(
20755 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20756 .shape(IconButtonShape::Square)
20757 .icon_size(IconSize::Small)
20758 // .disabled(!has_multiple_hunks)
20759 .tooltip({
20760 let focus_handle = editor.focus_handle(cx);
20761 move |window, cx| {
20762 Tooltip::for_action_in(
20763 "Next Hunk",
20764 &GoToHunk,
20765 &focus_handle,
20766 window,
20767 cx,
20768 )
20769 }
20770 })
20771 .on_click({
20772 let editor = editor.clone();
20773 move |_event, window, cx| {
20774 editor.update(cx, |editor, cx| {
20775 let snapshot = editor.snapshot(window, cx);
20776 let position =
20777 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20778 editor.go_to_hunk_before_or_after_position(
20779 &snapshot,
20780 position,
20781 Direction::Next,
20782 window,
20783 cx,
20784 );
20785 editor.expand_selected_diff_hunks(cx);
20786 });
20787 }
20788 }),
20789 )
20790 .child(
20791 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20792 .shape(IconButtonShape::Square)
20793 .icon_size(IconSize::Small)
20794 // .disabled(!has_multiple_hunks)
20795 .tooltip({
20796 let focus_handle = editor.focus_handle(cx);
20797 move |window, cx| {
20798 Tooltip::for_action_in(
20799 "Previous Hunk",
20800 &GoToPreviousHunk,
20801 &focus_handle,
20802 window,
20803 cx,
20804 )
20805 }
20806 })
20807 .on_click({
20808 let editor = editor.clone();
20809 move |_event, window, cx| {
20810 editor.update(cx, |editor, cx| {
20811 let snapshot = editor.snapshot(window, cx);
20812 let point =
20813 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20814 editor.go_to_hunk_before_or_after_position(
20815 &snapshot,
20816 point,
20817 Direction::Prev,
20818 window,
20819 cx,
20820 );
20821 editor.expand_selected_diff_hunks(cx);
20822 });
20823 }
20824 }),
20825 )
20826 },
20827 )
20828 .into_any_element()
20829}