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 row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10159 if row_indent_size.len >= first_indent.len {
10160 trimmed_selections.push(
10161 Point::new(row, first_indent.len)
10162 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
10163 );
10164 } else {
10165 trimmed_selections.clear();
10166 trimmed_selections.push(start..end);
10167 break;
10168 }
10169 }
10170 }
10171 } else {
10172 trimmed_selections.push(start..end);
10173 }
10174
10175 for trimmed_range in trimmed_selections {
10176 if is_first {
10177 is_first = false;
10178 } else {
10179 text += "\n";
10180 }
10181 let mut len = 0;
10182 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10183 text.push_str(chunk);
10184 len += chunk.len();
10185 }
10186 clipboard_selections.push(ClipboardSelection {
10187 len,
10188 is_entire_line,
10189 first_line_indent: buffer
10190 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10191 .len,
10192 });
10193 }
10194 }
10195 }
10196
10197 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10198 text,
10199 clipboard_selections,
10200 ));
10201 }
10202
10203 pub fn do_paste(
10204 &mut self,
10205 text: &String,
10206 clipboard_selections: Option<Vec<ClipboardSelection>>,
10207 handle_entire_lines: bool,
10208 window: &mut Window,
10209 cx: &mut Context<Self>,
10210 ) {
10211 if self.read_only(cx) {
10212 return;
10213 }
10214
10215 let clipboard_text = Cow::Borrowed(text);
10216
10217 self.transact(window, cx, |this, window, cx| {
10218 if let Some(mut clipboard_selections) = clipboard_selections {
10219 let old_selections = this.selections.all::<usize>(cx);
10220 let all_selections_were_entire_line =
10221 clipboard_selections.iter().all(|s| s.is_entire_line);
10222 let first_selection_indent_column =
10223 clipboard_selections.first().map(|s| s.first_line_indent);
10224 if clipboard_selections.len() != old_selections.len() {
10225 clipboard_selections.drain(..);
10226 }
10227 let cursor_offset = this.selections.last::<usize>(cx).head();
10228 let mut auto_indent_on_paste = true;
10229
10230 this.buffer.update(cx, |buffer, cx| {
10231 let snapshot = buffer.read(cx);
10232 auto_indent_on_paste = snapshot
10233 .language_settings_at(cursor_offset, cx)
10234 .auto_indent_on_paste;
10235
10236 let mut start_offset = 0;
10237 let mut edits = Vec::new();
10238 let mut original_indent_columns = Vec::new();
10239 for (ix, selection) in old_selections.iter().enumerate() {
10240 let to_insert;
10241 let entire_line;
10242 let original_indent_column;
10243 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10244 let end_offset = start_offset + clipboard_selection.len;
10245 to_insert = &clipboard_text[start_offset..end_offset];
10246 entire_line = clipboard_selection.is_entire_line;
10247 start_offset = end_offset + 1;
10248 original_indent_column = Some(clipboard_selection.first_line_indent);
10249 } else {
10250 to_insert = clipboard_text.as_str();
10251 entire_line = all_selections_were_entire_line;
10252 original_indent_column = first_selection_indent_column
10253 }
10254
10255 // If the corresponding selection was empty when this slice of the
10256 // clipboard text was written, then the entire line containing the
10257 // selection was copied. If this selection is also currently empty,
10258 // then paste the line before the current line of the buffer.
10259 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10260 let column = selection.start.to_point(&snapshot).column as usize;
10261 let line_start = selection.start - column;
10262 line_start..line_start
10263 } else {
10264 selection.range()
10265 };
10266
10267 edits.push((range, to_insert));
10268 original_indent_columns.push(original_indent_column);
10269 }
10270 drop(snapshot);
10271
10272 buffer.edit(
10273 edits,
10274 if auto_indent_on_paste {
10275 Some(AutoindentMode::Block {
10276 original_indent_columns,
10277 })
10278 } else {
10279 None
10280 },
10281 cx,
10282 );
10283 });
10284
10285 let selections = this.selections.all::<usize>(cx);
10286 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10287 s.select(selections)
10288 });
10289 } else {
10290 this.insert(&clipboard_text, window, cx);
10291 }
10292 });
10293 }
10294
10295 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10296 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10297 if let Some(item) = cx.read_from_clipboard() {
10298 let entries = item.entries();
10299
10300 match entries.first() {
10301 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10302 // of all the pasted entries.
10303 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10304 .do_paste(
10305 clipboard_string.text(),
10306 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10307 true,
10308 window,
10309 cx,
10310 ),
10311 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10312 }
10313 }
10314 }
10315
10316 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10317 if self.read_only(cx) {
10318 return;
10319 }
10320
10321 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10322
10323 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10324 if let Some((selections, _)) =
10325 self.selection_history.transaction(transaction_id).cloned()
10326 {
10327 self.change_selections(None, window, cx, |s| {
10328 s.select_anchors(selections.to_vec());
10329 });
10330 } else {
10331 log::error!(
10332 "No entry in selection_history found for undo. \
10333 This may correspond to a bug where undo does not update the selection. \
10334 If this is occurring, please add details to \
10335 https://github.com/zed-industries/zed/issues/22692"
10336 );
10337 }
10338 self.request_autoscroll(Autoscroll::fit(), cx);
10339 self.unmark_text(window, cx);
10340 self.refresh_inline_completion(true, false, window, cx);
10341 cx.emit(EditorEvent::Edited { transaction_id });
10342 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10343 }
10344 }
10345
10346 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10347 if self.read_only(cx) {
10348 return;
10349 }
10350
10351 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10352
10353 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10354 if let Some((_, Some(selections))) =
10355 self.selection_history.transaction(transaction_id).cloned()
10356 {
10357 self.change_selections(None, window, cx, |s| {
10358 s.select_anchors(selections.to_vec());
10359 });
10360 } else {
10361 log::error!(
10362 "No entry in selection_history found for redo. \
10363 This may correspond to a bug where undo does not update the selection. \
10364 If this is occurring, please add details to \
10365 https://github.com/zed-industries/zed/issues/22692"
10366 );
10367 }
10368 self.request_autoscroll(Autoscroll::fit(), cx);
10369 self.unmark_text(window, cx);
10370 self.refresh_inline_completion(true, false, window, cx);
10371 cx.emit(EditorEvent::Edited { transaction_id });
10372 }
10373 }
10374
10375 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10376 self.buffer
10377 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10378 }
10379
10380 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10381 self.buffer
10382 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10383 }
10384
10385 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10386 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10387 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10388 s.move_with(|map, selection| {
10389 let cursor = if selection.is_empty() {
10390 movement::left(map, selection.start)
10391 } else {
10392 selection.start
10393 };
10394 selection.collapse_to(cursor, SelectionGoal::None);
10395 });
10396 })
10397 }
10398
10399 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10400 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10401 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10402 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10403 })
10404 }
10405
10406 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10407 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10408 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10409 s.move_with(|map, selection| {
10410 let cursor = if selection.is_empty() {
10411 movement::right(map, selection.end)
10412 } else {
10413 selection.end
10414 };
10415 selection.collapse_to(cursor, SelectionGoal::None)
10416 });
10417 })
10418 }
10419
10420 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10421 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10422 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10423 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10424 })
10425 }
10426
10427 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10428 if self.take_rename(true, window, cx).is_some() {
10429 return;
10430 }
10431
10432 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10433 cx.propagate();
10434 return;
10435 }
10436
10437 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10438
10439 let text_layout_details = &self.text_layout_details(window);
10440 let selection_count = self.selections.count();
10441 let first_selection = self.selections.first_anchor();
10442
10443 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10444 s.move_with(|map, selection| {
10445 if !selection.is_empty() {
10446 selection.goal = SelectionGoal::None;
10447 }
10448 let (cursor, goal) = movement::up(
10449 map,
10450 selection.start,
10451 selection.goal,
10452 false,
10453 text_layout_details,
10454 );
10455 selection.collapse_to(cursor, goal);
10456 });
10457 });
10458
10459 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10460 {
10461 cx.propagate();
10462 }
10463 }
10464
10465 pub fn move_up_by_lines(
10466 &mut self,
10467 action: &MoveUpByLines,
10468 window: &mut Window,
10469 cx: &mut Context<Self>,
10470 ) {
10471 if self.take_rename(true, window, cx).is_some() {
10472 return;
10473 }
10474
10475 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10476 cx.propagate();
10477 return;
10478 }
10479
10480 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10481
10482 let text_layout_details = &self.text_layout_details(window);
10483
10484 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10485 s.move_with(|map, selection| {
10486 if !selection.is_empty() {
10487 selection.goal = SelectionGoal::None;
10488 }
10489 let (cursor, goal) = movement::up_by_rows(
10490 map,
10491 selection.start,
10492 action.lines,
10493 selection.goal,
10494 false,
10495 text_layout_details,
10496 );
10497 selection.collapse_to(cursor, goal);
10498 });
10499 })
10500 }
10501
10502 pub fn move_down_by_lines(
10503 &mut self,
10504 action: &MoveDownByLines,
10505 window: &mut Window,
10506 cx: &mut Context<Self>,
10507 ) {
10508 if self.take_rename(true, window, cx).is_some() {
10509 return;
10510 }
10511
10512 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10513 cx.propagate();
10514 return;
10515 }
10516
10517 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10518
10519 let text_layout_details = &self.text_layout_details(window);
10520
10521 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10522 s.move_with(|map, selection| {
10523 if !selection.is_empty() {
10524 selection.goal = SelectionGoal::None;
10525 }
10526 let (cursor, goal) = movement::down_by_rows(
10527 map,
10528 selection.start,
10529 action.lines,
10530 selection.goal,
10531 false,
10532 text_layout_details,
10533 );
10534 selection.collapse_to(cursor, goal);
10535 });
10536 })
10537 }
10538
10539 pub fn select_down_by_lines(
10540 &mut self,
10541 action: &SelectDownByLines,
10542 window: &mut Window,
10543 cx: &mut Context<Self>,
10544 ) {
10545 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10546 let text_layout_details = &self.text_layout_details(window);
10547 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10548 s.move_heads_with(|map, head, goal| {
10549 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10550 })
10551 })
10552 }
10553
10554 pub fn select_up_by_lines(
10555 &mut self,
10556 action: &SelectUpByLines,
10557 window: &mut Window,
10558 cx: &mut Context<Self>,
10559 ) {
10560 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10561 let text_layout_details = &self.text_layout_details(window);
10562 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10563 s.move_heads_with(|map, head, goal| {
10564 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10565 })
10566 })
10567 }
10568
10569 pub fn select_page_up(
10570 &mut self,
10571 _: &SelectPageUp,
10572 window: &mut Window,
10573 cx: &mut Context<Self>,
10574 ) {
10575 let Some(row_count) = self.visible_row_count() else {
10576 return;
10577 };
10578
10579 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10580
10581 let text_layout_details = &self.text_layout_details(window);
10582
10583 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10584 s.move_heads_with(|map, head, goal| {
10585 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10586 })
10587 })
10588 }
10589
10590 pub fn move_page_up(
10591 &mut self,
10592 action: &MovePageUp,
10593 window: &mut Window,
10594 cx: &mut Context<Self>,
10595 ) {
10596 if self.take_rename(true, window, cx).is_some() {
10597 return;
10598 }
10599
10600 if self
10601 .context_menu
10602 .borrow_mut()
10603 .as_mut()
10604 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10605 .unwrap_or(false)
10606 {
10607 return;
10608 }
10609
10610 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10611 cx.propagate();
10612 return;
10613 }
10614
10615 let Some(row_count) = self.visible_row_count() else {
10616 return;
10617 };
10618
10619 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10620
10621 let autoscroll = if action.center_cursor {
10622 Autoscroll::center()
10623 } else {
10624 Autoscroll::fit()
10625 };
10626
10627 let text_layout_details = &self.text_layout_details(window);
10628
10629 self.change_selections(Some(autoscroll), window, cx, |s| {
10630 s.move_with(|map, selection| {
10631 if !selection.is_empty() {
10632 selection.goal = SelectionGoal::None;
10633 }
10634 let (cursor, goal) = movement::up_by_rows(
10635 map,
10636 selection.end,
10637 row_count,
10638 selection.goal,
10639 false,
10640 text_layout_details,
10641 );
10642 selection.collapse_to(cursor, goal);
10643 });
10644 });
10645 }
10646
10647 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10648 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10649 let text_layout_details = &self.text_layout_details(window);
10650 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10651 s.move_heads_with(|map, head, goal| {
10652 movement::up(map, head, goal, false, text_layout_details)
10653 })
10654 })
10655 }
10656
10657 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10658 self.take_rename(true, window, cx);
10659
10660 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10661 cx.propagate();
10662 return;
10663 }
10664
10665 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10666
10667 let text_layout_details = &self.text_layout_details(window);
10668 let selection_count = self.selections.count();
10669 let first_selection = self.selections.first_anchor();
10670
10671 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10672 s.move_with(|map, selection| {
10673 if !selection.is_empty() {
10674 selection.goal = SelectionGoal::None;
10675 }
10676 let (cursor, goal) = movement::down(
10677 map,
10678 selection.end,
10679 selection.goal,
10680 false,
10681 text_layout_details,
10682 );
10683 selection.collapse_to(cursor, goal);
10684 });
10685 });
10686
10687 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10688 {
10689 cx.propagate();
10690 }
10691 }
10692
10693 pub fn select_page_down(
10694 &mut self,
10695 _: &SelectPageDown,
10696 window: &mut Window,
10697 cx: &mut Context<Self>,
10698 ) {
10699 let Some(row_count) = self.visible_row_count() else {
10700 return;
10701 };
10702
10703 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10704
10705 let text_layout_details = &self.text_layout_details(window);
10706
10707 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10708 s.move_heads_with(|map, head, goal| {
10709 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10710 })
10711 })
10712 }
10713
10714 pub fn move_page_down(
10715 &mut self,
10716 action: &MovePageDown,
10717 window: &mut Window,
10718 cx: &mut Context<Self>,
10719 ) {
10720 if self.take_rename(true, window, cx).is_some() {
10721 return;
10722 }
10723
10724 if self
10725 .context_menu
10726 .borrow_mut()
10727 .as_mut()
10728 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10729 .unwrap_or(false)
10730 {
10731 return;
10732 }
10733
10734 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10735 cx.propagate();
10736 return;
10737 }
10738
10739 let Some(row_count) = self.visible_row_count() else {
10740 return;
10741 };
10742
10743 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10744
10745 let autoscroll = if action.center_cursor {
10746 Autoscroll::center()
10747 } else {
10748 Autoscroll::fit()
10749 };
10750
10751 let text_layout_details = &self.text_layout_details(window);
10752 self.change_selections(Some(autoscroll), window, cx, |s| {
10753 s.move_with(|map, selection| {
10754 if !selection.is_empty() {
10755 selection.goal = SelectionGoal::None;
10756 }
10757 let (cursor, goal) = movement::down_by_rows(
10758 map,
10759 selection.end,
10760 row_count,
10761 selection.goal,
10762 false,
10763 text_layout_details,
10764 );
10765 selection.collapse_to(cursor, goal);
10766 });
10767 });
10768 }
10769
10770 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10771 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10772 let text_layout_details = &self.text_layout_details(window);
10773 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10774 s.move_heads_with(|map, head, goal| {
10775 movement::down(map, head, goal, false, text_layout_details)
10776 })
10777 });
10778 }
10779
10780 pub fn context_menu_first(
10781 &mut self,
10782 _: &ContextMenuFirst,
10783 _window: &mut Window,
10784 cx: &mut Context<Self>,
10785 ) {
10786 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10787 context_menu.select_first(self.completion_provider.as_deref(), cx);
10788 }
10789 }
10790
10791 pub fn context_menu_prev(
10792 &mut self,
10793 _: &ContextMenuPrevious,
10794 _window: &mut Window,
10795 cx: &mut Context<Self>,
10796 ) {
10797 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10798 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10799 }
10800 }
10801
10802 pub fn context_menu_next(
10803 &mut self,
10804 _: &ContextMenuNext,
10805 _window: &mut Window,
10806 cx: &mut Context<Self>,
10807 ) {
10808 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10809 context_menu.select_next(self.completion_provider.as_deref(), cx);
10810 }
10811 }
10812
10813 pub fn context_menu_last(
10814 &mut self,
10815 _: &ContextMenuLast,
10816 _window: &mut Window,
10817 cx: &mut Context<Self>,
10818 ) {
10819 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10820 context_menu.select_last(self.completion_provider.as_deref(), cx);
10821 }
10822 }
10823
10824 pub fn move_to_previous_word_start(
10825 &mut self,
10826 _: &MoveToPreviousWordStart,
10827 window: &mut Window,
10828 cx: &mut Context<Self>,
10829 ) {
10830 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10831 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10832 s.move_cursors_with(|map, head, _| {
10833 (
10834 movement::previous_word_start(map, head),
10835 SelectionGoal::None,
10836 )
10837 });
10838 })
10839 }
10840
10841 pub fn move_to_previous_subword_start(
10842 &mut self,
10843 _: &MoveToPreviousSubwordStart,
10844 window: &mut Window,
10845 cx: &mut Context<Self>,
10846 ) {
10847 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10848 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10849 s.move_cursors_with(|map, head, _| {
10850 (
10851 movement::previous_subword_start(map, head),
10852 SelectionGoal::None,
10853 )
10854 });
10855 })
10856 }
10857
10858 pub fn select_to_previous_word_start(
10859 &mut self,
10860 _: &SelectToPreviousWordStart,
10861 window: &mut Window,
10862 cx: &mut Context<Self>,
10863 ) {
10864 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10865 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10866 s.move_heads_with(|map, head, _| {
10867 (
10868 movement::previous_word_start(map, head),
10869 SelectionGoal::None,
10870 )
10871 });
10872 })
10873 }
10874
10875 pub fn select_to_previous_subword_start(
10876 &mut self,
10877 _: &SelectToPreviousSubwordStart,
10878 window: &mut Window,
10879 cx: &mut Context<Self>,
10880 ) {
10881 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10882 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10883 s.move_heads_with(|map, head, _| {
10884 (
10885 movement::previous_subword_start(map, head),
10886 SelectionGoal::None,
10887 )
10888 });
10889 })
10890 }
10891
10892 pub fn delete_to_previous_word_start(
10893 &mut self,
10894 action: &DeleteToPreviousWordStart,
10895 window: &mut Window,
10896 cx: &mut Context<Self>,
10897 ) {
10898 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10899 self.transact(window, cx, |this, window, cx| {
10900 this.select_autoclose_pair(window, cx);
10901 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10902 s.move_with(|map, selection| {
10903 if selection.is_empty() {
10904 let cursor = if action.ignore_newlines {
10905 movement::previous_word_start(map, selection.head())
10906 } else {
10907 movement::previous_word_start_or_newline(map, selection.head())
10908 };
10909 selection.set_head(cursor, SelectionGoal::None);
10910 }
10911 });
10912 });
10913 this.insert("", window, cx);
10914 });
10915 }
10916
10917 pub fn delete_to_previous_subword_start(
10918 &mut self,
10919 _: &DeleteToPreviousSubwordStart,
10920 window: &mut Window,
10921 cx: &mut Context<Self>,
10922 ) {
10923 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10924 self.transact(window, cx, |this, window, cx| {
10925 this.select_autoclose_pair(window, cx);
10926 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10927 s.move_with(|map, selection| {
10928 if selection.is_empty() {
10929 let cursor = movement::previous_subword_start(map, selection.head());
10930 selection.set_head(cursor, SelectionGoal::None);
10931 }
10932 });
10933 });
10934 this.insert("", window, cx);
10935 });
10936 }
10937
10938 pub fn move_to_next_word_end(
10939 &mut self,
10940 _: &MoveToNextWordEnd,
10941 window: &mut Window,
10942 cx: &mut Context<Self>,
10943 ) {
10944 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10945 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10946 s.move_cursors_with(|map, head, _| {
10947 (movement::next_word_end(map, head), SelectionGoal::None)
10948 });
10949 })
10950 }
10951
10952 pub fn move_to_next_subword_end(
10953 &mut self,
10954 _: &MoveToNextSubwordEnd,
10955 window: &mut Window,
10956 cx: &mut Context<Self>,
10957 ) {
10958 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10959 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10960 s.move_cursors_with(|map, head, _| {
10961 (movement::next_subword_end(map, head), SelectionGoal::None)
10962 });
10963 })
10964 }
10965
10966 pub fn select_to_next_word_end(
10967 &mut self,
10968 _: &SelectToNextWordEnd,
10969 window: &mut Window,
10970 cx: &mut Context<Self>,
10971 ) {
10972 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10973 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10974 s.move_heads_with(|map, head, _| {
10975 (movement::next_word_end(map, head), SelectionGoal::None)
10976 });
10977 })
10978 }
10979
10980 pub fn select_to_next_subword_end(
10981 &mut self,
10982 _: &SelectToNextSubwordEnd,
10983 window: &mut Window,
10984 cx: &mut Context<Self>,
10985 ) {
10986 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10987 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10988 s.move_heads_with(|map, head, _| {
10989 (movement::next_subword_end(map, head), SelectionGoal::None)
10990 });
10991 })
10992 }
10993
10994 pub fn delete_to_next_word_end(
10995 &mut self,
10996 action: &DeleteToNextWordEnd,
10997 window: &mut Window,
10998 cx: &mut Context<Self>,
10999 ) {
11000 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11001 self.transact(window, cx, |this, window, cx| {
11002 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11003 s.move_with(|map, selection| {
11004 if selection.is_empty() {
11005 let cursor = if action.ignore_newlines {
11006 movement::next_word_end(map, selection.head())
11007 } else {
11008 movement::next_word_end_or_newline(map, selection.head())
11009 };
11010 selection.set_head(cursor, SelectionGoal::None);
11011 }
11012 });
11013 });
11014 this.insert("", window, cx);
11015 });
11016 }
11017
11018 pub fn delete_to_next_subword_end(
11019 &mut self,
11020 _: &DeleteToNextSubwordEnd,
11021 window: &mut Window,
11022 cx: &mut Context<Self>,
11023 ) {
11024 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11025 self.transact(window, cx, |this, window, cx| {
11026 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11027 s.move_with(|map, selection| {
11028 if selection.is_empty() {
11029 let cursor = movement::next_subword_end(map, selection.head());
11030 selection.set_head(cursor, SelectionGoal::None);
11031 }
11032 });
11033 });
11034 this.insert("", window, cx);
11035 });
11036 }
11037
11038 pub fn move_to_beginning_of_line(
11039 &mut self,
11040 action: &MoveToBeginningOfLine,
11041 window: &mut Window,
11042 cx: &mut Context<Self>,
11043 ) {
11044 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11045 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11046 s.move_cursors_with(|map, head, _| {
11047 (
11048 movement::indented_line_beginning(
11049 map,
11050 head,
11051 action.stop_at_soft_wraps,
11052 action.stop_at_indent,
11053 ),
11054 SelectionGoal::None,
11055 )
11056 });
11057 })
11058 }
11059
11060 pub fn select_to_beginning_of_line(
11061 &mut self,
11062 action: &SelectToBeginningOfLine,
11063 window: &mut Window,
11064 cx: &mut Context<Self>,
11065 ) {
11066 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11067 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11068 s.move_heads_with(|map, head, _| {
11069 (
11070 movement::indented_line_beginning(
11071 map,
11072 head,
11073 action.stop_at_soft_wraps,
11074 action.stop_at_indent,
11075 ),
11076 SelectionGoal::None,
11077 )
11078 });
11079 });
11080 }
11081
11082 pub fn delete_to_beginning_of_line(
11083 &mut self,
11084 action: &DeleteToBeginningOfLine,
11085 window: &mut Window,
11086 cx: &mut Context<Self>,
11087 ) {
11088 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11089 self.transact(window, cx, |this, window, cx| {
11090 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11091 s.move_with(|_, selection| {
11092 selection.reversed = true;
11093 });
11094 });
11095
11096 this.select_to_beginning_of_line(
11097 &SelectToBeginningOfLine {
11098 stop_at_soft_wraps: false,
11099 stop_at_indent: action.stop_at_indent,
11100 },
11101 window,
11102 cx,
11103 );
11104 this.backspace(&Backspace, window, cx);
11105 });
11106 }
11107
11108 pub fn move_to_end_of_line(
11109 &mut self,
11110 action: &MoveToEndOfLine,
11111 window: &mut Window,
11112 cx: &mut Context<Self>,
11113 ) {
11114 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11115 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11116 s.move_cursors_with(|map, head, _| {
11117 (
11118 movement::line_end(map, head, action.stop_at_soft_wraps),
11119 SelectionGoal::None,
11120 )
11121 });
11122 })
11123 }
11124
11125 pub fn select_to_end_of_line(
11126 &mut self,
11127 action: &SelectToEndOfLine,
11128 window: &mut Window,
11129 cx: &mut Context<Self>,
11130 ) {
11131 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11132 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11133 s.move_heads_with(|map, head, _| {
11134 (
11135 movement::line_end(map, head, action.stop_at_soft_wraps),
11136 SelectionGoal::None,
11137 )
11138 });
11139 })
11140 }
11141
11142 pub fn delete_to_end_of_line(
11143 &mut self,
11144 _: &DeleteToEndOfLine,
11145 window: &mut Window,
11146 cx: &mut Context<Self>,
11147 ) {
11148 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11149 self.transact(window, cx, |this, window, cx| {
11150 this.select_to_end_of_line(
11151 &SelectToEndOfLine {
11152 stop_at_soft_wraps: false,
11153 },
11154 window,
11155 cx,
11156 );
11157 this.delete(&Delete, window, cx);
11158 });
11159 }
11160
11161 pub fn cut_to_end_of_line(
11162 &mut self,
11163 _: &CutToEndOfLine,
11164 window: &mut Window,
11165 cx: &mut Context<Self>,
11166 ) {
11167 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11168 self.transact(window, cx, |this, window, cx| {
11169 this.select_to_end_of_line(
11170 &SelectToEndOfLine {
11171 stop_at_soft_wraps: false,
11172 },
11173 window,
11174 cx,
11175 );
11176 this.cut(&Cut, window, cx);
11177 });
11178 }
11179
11180 pub fn move_to_start_of_paragraph(
11181 &mut self,
11182 _: &MoveToStartOfParagraph,
11183 window: &mut Window,
11184 cx: &mut Context<Self>,
11185 ) {
11186 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11187 cx.propagate();
11188 return;
11189 }
11190 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11191 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11192 s.move_with(|map, selection| {
11193 selection.collapse_to(
11194 movement::start_of_paragraph(map, selection.head(), 1),
11195 SelectionGoal::None,
11196 )
11197 });
11198 })
11199 }
11200
11201 pub fn move_to_end_of_paragraph(
11202 &mut self,
11203 _: &MoveToEndOfParagraph,
11204 window: &mut Window,
11205 cx: &mut Context<Self>,
11206 ) {
11207 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11208 cx.propagate();
11209 return;
11210 }
11211 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11212 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11213 s.move_with(|map, selection| {
11214 selection.collapse_to(
11215 movement::end_of_paragraph(map, selection.head(), 1),
11216 SelectionGoal::None,
11217 )
11218 });
11219 })
11220 }
11221
11222 pub fn select_to_start_of_paragraph(
11223 &mut self,
11224 _: &SelectToStartOfParagraph,
11225 window: &mut Window,
11226 cx: &mut Context<Self>,
11227 ) {
11228 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11229 cx.propagate();
11230 return;
11231 }
11232 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11233 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11234 s.move_heads_with(|map, head, _| {
11235 (
11236 movement::start_of_paragraph(map, head, 1),
11237 SelectionGoal::None,
11238 )
11239 });
11240 })
11241 }
11242
11243 pub fn select_to_end_of_paragraph(
11244 &mut self,
11245 _: &SelectToEndOfParagraph,
11246 window: &mut Window,
11247 cx: &mut Context<Self>,
11248 ) {
11249 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11250 cx.propagate();
11251 return;
11252 }
11253 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11254 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11255 s.move_heads_with(|map, head, _| {
11256 (
11257 movement::end_of_paragraph(map, head, 1),
11258 SelectionGoal::None,
11259 )
11260 });
11261 })
11262 }
11263
11264 pub fn move_to_start_of_excerpt(
11265 &mut self,
11266 _: &MoveToStartOfExcerpt,
11267 window: &mut Window,
11268 cx: &mut Context<Self>,
11269 ) {
11270 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11271 cx.propagate();
11272 return;
11273 }
11274 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11275 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11276 s.move_with(|map, selection| {
11277 selection.collapse_to(
11278 movement::start_of_excerpt(
11279 map,
11280 selection.head(),
11281 workspace::searchable::Direction::Prev,
11282 ),
11283 SelectionGoal::None,
11284 )
11285 });
11286 })
11287 }
11288
11289 pub fn move_to_start_of_next_excerpt(
11290 &mut self,
11291 _: &MoveToStartOfNextExcerpt,
11292 window: &mut Window,
11293 cx: &mut Context<Self>,
11294 ) {
11295 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11296 cx.propagate();
11297 return;
11298 }
11299
11300 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11301 s.move_with(|map, selection| {
11302 selection.collapse_to(
11303 movement::start_of_excerpt(
11304 map,
11305 selection.head(),
11306 workspace::searchable::Direction::Next,
11307 ),
11308 SelectionGoal::None,
11309 )
11310 });
11311 })
11312 }
11313
11314 pub fn move_to_end_of_excerpt(
11315 &mut self,
11316 _: &MoveToEndOfExcerpt,
11317 window: &mut Window,
11318 cx: &mut Context<Self>,
11319 ) {
11320 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11321 cx.propagate();
11322 return;
11323 }
11324 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11325 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11326 s.move_with(|map, selection| {
11327 selection.collapse_to(
11328 movement::end_of_excerpt(
11329 map,
11330 selection.head(),
11331 workspace::searchable::Direction::Next,
11332 ),
11333 SelectionGoal::None,
11334 )
11335 });
11336 })
11337 }
11338
11339 pub fn move_to_end_of_previous_excerpt(
11340 &mut self,
11341 _: &MoveToEndOfPreviousExcerpt,
11342 window: &mut Window,
11343 cx: &mut Context<Self>,
11344 ) {
11345 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11346 cx.propagate();
11347 return;
11348 }
11349 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11350 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11351 s.move_with(|map, selection| {
11352 selection.collapse_to(
11353 movement::end_of_excerpt(
11354 map,
11355 selection.head(),
11356 workspace::searchable::Direction::Prev,
11357 ),
11358 SelectionGoal::None,
11359 )
11360 });
11361 })
11362 }
11363
11364 pub fn select_to_start_of_excerpt(
11365 &mut self,
11366 _: &SelectToStartOfExcerpt,
11367 window: &mut Window,
11368 cx: &mut Context<Self>,
11369 ) {
11370 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11371 cx.propagate();
11372 return;
11373 }
11374 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11375 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11376 s.move_heads_with(|map, head, _| {
11377 (
11378 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11379 SelectionGoal::None,
11380 )
11381 });
11382 })
11383 }
11384
11385 pub fn select_to_start_of_next_excerpt(
11386 &mut self,
11387 _: &SelectToStartOfNextExcerpt,
11388 window: &mut Window,
11389 cx: &mut Context<Self>,
11390 ) {
11391 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11392 cx.propagate();
11393 return;
11394 }
11395 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11396 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11397 s.move_heads_with(|map, head, _| {
11398 (
11399 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11400 SelectionGoal::None,
11401 )
11402 });
11403 })
11404 }
11405
11406 pub fn select_to_end_of_excerpt(
11407 &mut self,
11408 _: &SelectToEndOfExcerpt,
11409 window: &mut Window,
11410 cx: &mut Context<Self>,
11411 ) {
11412 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11413 cx.propagate();
11414 return;
11415 }
11416 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11417 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11418 s.move_heads_with(|map, head, _| {
11419 (
11420 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11421 SelectionGoal::None,
11422 )
11423 });
11424 })
11425 }
11426
11427 pub fn select_to_end_of_previous_excerpt(
11428 &mut self,
11429 _: &SelectToEndOfPreviousExcerpt,
11430 window: &mut Window,
11431 cx: &mut Context<Self>,
11432 ) {
11433 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11434 cx.propagate();
11435 return;
11436 }
11437 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11438 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11439 s.move_heads_with(|map, head, _| {
11440 (
11441 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11442 SelectionGoal::None,
11443 )
11444 });
11445 })
11446 }
11447
11448 pub fn move_to_beginning(
11449 &mut self,
11450 _: &MoveToBeginning,
11451 window: &mut Window,
11452 cx: &mut Context<Self>,
11453 ) {
11454 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11455 cx.propagate();
11456 return;
11457 }
11458 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11459 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11460 s.select_ranges(vec![0..0]);
11461 });
11462 }
11463
11464 pub fn select_to_beginning(
11465 &mut self,
11466 _: &SelectToBeginning,
11467 window: &mut Window,
11468 cx: &mut Context<Self>,
11469 ) {
11470 let mut selection = self.selections.last::<Point>(cx);
11471 selection.set_head(Point::zero(), SelectionGoal::None);
11472 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11473 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11474 s.select(vec![selection]);
11475 });
11476 }
11477
11478 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11479 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11480 cx.propagate();
11481 return;
11482 }
11483 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11484 let cursor = self.buffer.read(cx).read(cx).len();
11485 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11486 s.select_ranges(vec![cursor..cursor])
11487 });
11488 }
11489
11490 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11491 self.nav_history = nav_history;
11492 }
11493
11494 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11495 self.nav_history.as_ref()
11496 }
11497
11498 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11499 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11500 }
11501
11502 fn push_to_nav_history(
11503 &mut self,
11504 cursor_anchor: Anchor,
11505 new_position: Option<Point>,
11506 is_deactivate: bool,
11507 cx: &mut Context<Self>,
11508 ) {
11509 if let Some(nav_history) = self.nav_history.as_mut() {
11510 let buffer = self.buffer.read(cx).read(cx);
11511 let cursor_position = cursor_anchor.to_point(&buffer);
11512 let scroll_state = self.scroll_manager.anchor();
11513 let scroll_top_row = scroll_state.top_row(&buffer);
11514 drop(buffer);
11515
11516 if let Some(new_position) = new_position {
11517 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11518 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11519 return;
11520 }
11521 }
11522
11523 nav_history.push(
11524 Some(NavigationData {
11525 cursor_anchor,
11526 cursor_position,
11527 scroll_anchor: scroll_state,
11528 scroll_top_row,
11529 }),
11530 cx,
11531 );
11532 cx.emit(EditorEvent::PushedToNavHistory {
11533 anchor: cursor_anchor,
11534 is_deactivate,
11535 })
11536 }
11537 }
11538
11539 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11540 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11541 let buffer = self.buffer.read(cx).snapshot(cx);
11542 let mut selection = self.selections.first::<usize>(cx);
11543 selection.set_head(buffer.len(), SelectionGoal::None);
11544 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11545 s.select(vec![selection]);
11546 });
11547 }
11548
11549 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11550 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11551 let end = self.buffer.read(cx).read(cx).len();
11552 self.change_selections(None, window, cx, |s| {
11553 s.select_ranges(vec![0..end]);
11554 });
11555 }
11556
11557 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11558 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11559 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11560 let mut selections = self.selections.all::<Point>(cx);
11561 let max_point = display_map.buffer_snapshot.max_point();
11562 for selection in &mut selections {
11563 let rows = selection.spanned_rows(true, &display_map);
11564 selection.start = Point::new(rows.start.0, 0);
11565 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11566 selection.reversed = false;
11567 }
11568 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11569 s.select(selections);
11570 });
11571 }
11572
11573 pub fn split_selection_into_lines(
11574 &mut self,
11575 _: &SplitSelectionIntoLines,
11576 window: &mut Window,
11577 cx: &mut Context<Self>,
11578 ) {
11579 let selections = self
11580 .selections
11581 .all::<Point>(cx)
11582 .into_iter()
11583 .map(|selection| selection.start..selection.end)
11584 .collect::<Vec<_>>();
11585 self.unfold_ranges(&selections, true, true, cx);
11586
11587 let mut new_selection_ranges = Vec::new();
11588 {
11589 let buffer = self.buffer.read(cx).read(cx);
11590 for selection in selections {
11591 for row in selection.start.row..selection.end.row {
11592 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11593 new_selection_ranges.push(cursor..cursor);
11594 }
11595
11596 let is_multiline_selection = selection.start.row != selection.end.row;
11597 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11598 // so this action feels more ergonomic when paired with other selection operations
11599 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11600 if !should_skip_last {
11601 new_selection_ranges.push(selection.end..selection.end);
11602 }
11603 }
11604 }
11605 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11606 s.select_ranges(new_selection_ranges);
11607 });
11608 }
11609
11610 pub fn add_selection_above(
11611 &mut self,
11612 _: &AddSelectionAbove,
11613 window: &mut Window,
11614 cx: &mut Context<Self>,
11615 ) {
11616 self.add_selection(true, window, cx);
11617 }
11618
11619 pub fn add_selection_below(
11620 &mut self,
11621 _: &AddSelectionBelow,
11622 window: &mut Window,
11623 cx: &mut Context<Self>,
11624 ) {
11625 self.add_selection(false, window, cx);
11626 }
11627
11628 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11629 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11630
11631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11632 let mut selections = self.selections.all::<Point>(cx);
11633 let text_layout_details = self.text_layout_details(window);
11634 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11635 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11636 let range = oldest_selection.display_range(&display_map).sorted();
11637
11638 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11639 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11640 let positions = start_x.min(end_x)..start_x.max(end_x);
11641
11642 selections.clear();
11643 let mut stack = Vec::new();
11644 for row in range.start.row().0..=range.end.row().0 {
11645 if let Some(selection) = self.selections.build_columnar_selection(
11646 &display_map,
11647 DisplayRow(row),
11648 &positions,
11649 oldest_selection.reversed,
11650 &text_layout_details,
11651 ) {
11652 stack.push(selection.id);
11653 selections.push(selection);
11654 }
11655 }
11656
11657 if above {
11658 stack.reverse();
11659 }
11660
11661 AddSelectionsState { above, stack }
11662 });
11663
11664 let last_added_selection = *state.stack.last().unwrap();
11665 let mut new_selections = Vec::new();
11666 if above == state.above {
11667 let end_row = if above {
11668 DisplayRow(0)
11669 } else {
11670 display_map.max_point().row()
11671 };
11672
11673 'outer: for selection in selections {
11674 if selection.id == last_added_selection {
11675 let range = selection.display_range(&display_map).sorted();
11676 debug_assert_eq!(range.start.row(), range.end.row());
11677 let mut row = range.start.row();
11678 let positions =
11679 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11680 px(start)..px(end)
11681 } else {
11682 let start_x =
11683 display_map.x_for_display_point(range.start, &text_layout_details);
11684 let end_x =
11685 display_map.x_for_display_point(range.end, &text_layout_details);
11686 start_x.min(end_x)..start_x.max(end_x)
11687 };
11688
11689 while row != end_row {
11690 if above {
11691 row.0 -= 1;
11692 } else {
11693 row.0 += 1;
11694 }
11695
11696 if let Some(new_selection) = self.selections.build_columnar_selection(
11697 &display_map,
11698 row,
11699 &positions,
11700 selection.reversed,
11701 &text_layout_details,
11702 ) {
11703 state.stack.push(new_selection.id);
11704 if above {
11705 new_selections.push(new_selection);
11706 new_selections.push(selection);
11707 } else {
11708 new_selections.push(selection);
11709 new_selections.push(new_selection);
11710 }
11711
11712 continue 'outer;
11713 }
11714 }
11715 }
11716
11717 new_selections.push(selection);
11718 }
11719 } else {
11720 new_selections = selections;
11721 new_selections.retain(|s| s.id != last_added_selection);
11722 state.stack.pop();
11723 }
11724
11725 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11726 s.select(new_selections);
11727 });
11728 if state.stack.len() > 1 {
11729 self.add_selections_state = Some(state);
11730 }
11731 }
11732
11733 pub fn select_next_match_internal(
11734 &mut self,
11735 display_map: &DisplaySnapshot,
11736 replace_newest: bool,
11737 autoscroll: Option<Autoscroll>,
11738 window: &mut Window,
11739 cx: &mut Context<Self>,
11740 ) -> Result<()> {
11741 fn select_next_match_ranges(
11742 this: &mut Editor,
11743 range: Range<usize>,
11744 replace_newest: bool,
11745 auto_scroll: Option<Autoscroll>,
11746 window: &mut Window,
11747 cx: &mut Context<Editor>,
11748 ) {
11749 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11750 this.change_selections(auto_scroll, window, cx, |s| {
11751 if replace_newest {
11752 s.delete(s.newest_anchor().id);
11753 }
11754 s.insert_range(range.clone());
11755 });
11756 }
11757
11758 let buffer = &display_map.buffer_snapshot;
11759 let mut selections = self.selections.all::<usize>(cx);
11760 if let Some(mut select_next_state) = self.select_next_state.take() {
11761 let query = &select_next_state.query;
11762 if !select_next_state.done {
11763 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11764 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11765 let mut next_selected_range = None;
11766
11767 let bytes_after_last_selection =
11768 buffer.bytes_in_range(last_selection.end..buffer.len());
11769 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11770 let query_matches = query
11771 .stream_find_iter(bytes_after_last_selection)
11772 .map(|result| (last_selection.end, result))
11773 .chain(
11774 query
11775 .stream_find_iter(bytes_before_first_selection)
11776 .map(|result| (0, result)),
11777 );
11778
11779 for (start_offset, query_match) in query_matches {
11780 let query_match = query_match.unwrap(); // can only fail due to I/O
11781 let offset_range =
11782 start_offset + query_match.start()..start_offset + query_match.end();
11783 let display_range = offset_range.start.to_display_point(display_map)
11784 ..offset_range.end.to_display_point(display_map);
11785
11786 if !select_next_state.wordwise
11787 || (!movement::is_inside_word(display_map, display_range.start)
11788 && !movement::is_inside_word(display_map, display_range.end))
11789 {
11790 // TODO: This is n^2, because we might check all the selections
11791 if !selections
11792 .iter()
11793 .any(|selection| selection.range().overlaps(&offset_range))
11794 {
11795 next_selected_range = Some(offset_range);
11796 break;
11797 }
11798 }
11799 }
11800
11801 if let Some(next_selected_range) = next_selected_range {
11802 select_next_match_ranges(
11803 self,
11804 next_selected_range,
11805 replace_newest,
11806 autoscroll,
11807 window,
11808 cx,
11809 );
11810 } else {
11811 select_next_state.done = true;
11812 }
11813 }
11814
11815 self.select_next_state = Some(select_next_state);
11816 } else {
11817 let mut only_carets = true;
11818 let mut same_text_selected = true;
11819 let mut selected_text = None;
11820
11821 let mut selections_iter = selections.iter().peekable();
11822 while let Some(selection) = selections_iter.next() {
11823 if selection.start != selection.end {
11824 only_carets = false;
11825 }
11826
11827 if same_text_selected {
11828 if selected_text.is_none() {
11829 selected_text =
11830 Some(buffer.text_for_range(selection.range()).collect::<String>());
11831 }
11832
11833 if let Some(next_selection) = selections_iter.peek() {
11834 if next_selection.range().len() == selection.range().len() {
11835 let next_selected_text = buffer
11836 .text_for_range(next_selection.range())
11837 .collect::<String>();
11838 if Some(next_selected_text) != selected_text {
11839 same_text_selected = false;
11840 selected_text = None;
11841 }
11842 } else {
11843 same_text_selected = false;
11844 selected_text = None;
11845 }
11846 }
11847 }
11848 }
11849
11850 if only_carets {
11851 for selection in &mut selections {
11852 let word_range = movement::surrounding_word(
11853 display_map,
11854 selection.start.to_display_point(display_map),
11855 );
11856 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11857 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11858 selection.goal = SelectionGoal::None;
11859 selection.reversed = false;
11860 select_next_match_ranges(
11861 self,
11862 selection.start..selection.end,
11863 replace_newest,
11864 autoscroll,
11865 window,
11866 cx,
11867 );
11868 }
11869
11870 if selections.len() == 1 {
11871 let selection = selections
11872 .last()
11873 .expect("ensured that there's only one selection");
11874 let query = buffer
11875 .text_for_range(selection.start..selection.end)
11876 .collect::<String>();
11877 let is_empty = query.is_empty();
11878 let select_state = SelectNextState {
11879 query: AhoCorasick::new(&[query])?,
11880 wordwise: true,
11881 done: is_empty,
11882 };
11883 self.select_next_state = Some(select_state);
11884 } else {
11885 self.select_next_state = None;
11886 }
11887 } else if let Some(selected_text) = selected_text {
11888 self.select_next_state = Some(SelectNextState {
11889 query: AhoCorasick::new(&[selected_text])?,
11890 wordwise: false,
11891 done: false,
11892 });
11893 self.select_next_match_internal(
11894 display_map,
11895 replace_newest,
11896 autoscroll,
11897 window,
11898 cx,
11899 )?;
11900 }
11901 }
11902 Ok(())
11903 }
11904
11905 pub fn select_all_matches(
11906 &mut self,
11907 _action: &SelectAllMatches,
11908 window: &mut Window,
11909 cx: &mut Context<Self>,
11910 ) -> Result<()> {
11911 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11912
11913 self.push_to_selection_history();
11914 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11915
11916 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11917 let Some(select_next_state) = self.select_next_state.as_mut() else {
11918 return Ok(());
11919 };
11920 if select_next_state.done {
11921 return Ok(());
11922 }
11923
11924 let mut new_selections = Vec::new();
11925
11926 let reversed = self.selections.oldest::<usize>(cx).reversed;
11927 let buffer = &display_map.buffer_snapshot;
11928 let query_matches = select_next_state
11929 .query
11930 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11931
11932 for query_match in query_matches.into_iter() {
11933 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11934 let offset_range = if reversed {
11935 query_match.end()..query_match.start()
11936 } else {
11937 query_match.start()..query_match.end()
11938 };
11939 let display_range = offset_range.start.to_display_point(&display_map)
11940 ..offset_range.end.to_display_point(&display_map);
11941
11942 if !select_next_state.wordwise
11943 || (!movement::is_inside_word(&display_map, display_range.start)
11944 && !movement::is_inside_word(&display_map, display_range.end))
11945 {
11946 new_selections.push(offset_range.start..offset_range.end);
11947 }
11948 }
11949
11950 select_next_state.done = true;
11951 self.unfold_ranges(&new_selections.clone(), false, false, cx);
11952 self.change_selections(None, window, cx, |selections| {
11953 selections.select_ranges(new_selections)
11954 });
11955
11956 Ok(())
11957 }
11958
11959 pub fn select_next(
11960 &mut self,
11961 action: &SelectNext,
11962 window: &mut Window,
11963 cx: &mut Context<Self>,
11964 ) -> Result<()> {
11965 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11966 self.push_to_selection_history();
11967 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11968 self.select_next_match_internal(
11969 &display_map,
11970 action.replace_newest,
11971 Some(Autoscroll::newest()),
11972 window,
11973 cx,
11974 )?;
11975 Ok(())
11976 }
11977
11978 pub fn select_previous(
11979 &mut self,
11980 action: &SelectPrevious,
11981 window: &mut Window,
11982 cx: &mut Context<Self>,
11983 ) -> Result<()> {
11984 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11985 self.push_to_selection_history();
11986 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11987 let buffer = &display_map.buffer_snapshot;
11988 let mut selections = self.selections.all::<usize>(cx);
11989 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11990 let query = &select_prev_state.query;
11991 if !select_prev_state.done {
11992 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11993 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11994 let mut next_selected_range = None;
11995 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11996 let bytes_before_last_selection =
11997 buffer.reversed_bytes_in_range(0..last_selection.start);
11998 let bytes_after_first_selection =
11999 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12000 let query_matches = query
12001 .stream_find_iter(bytes_before_last_selection)
12002 .map(|result| (last_selection.start, result))
12003 .chain(
12004 query
12005 .stream_find_iter(bytes_after_first_selection)
12006 .map(|result| (buffer.len(), result)),
12007 );
12008 for (end_offset, query_match) in query_matches {
12009 let query_match = query_match.unwrap(); // can only fail due to I/O
12010 let offset_range =
12011 end_offset - query_match.end()..end_offset - query_match.start();
12012 let display_range = offset_range.start.to_display_point(&display_map)
12013 ..offset_range.end.to_display_point(&display_map);
12014
12015 if !select_prev_state.wordwise
12016 || (!movement::is_inside_word(&display_map, display_range.start)
12017 && !movement::is_inside_word(&display_map, display_range.end))
12018 {
12019 next_selected_range = Some(offset_range);
12020 break;
12021 }
12022 }
12023
12024 if let Some(next_selected_range) = next_selected_range {
12025 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12026 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12027 if action.replace_newest {
12028 s.delete(s.newest_anchor().id);
12029 }
12030 s.insert_range(next_selected_range);
12031 });
12032 } else {
12033 select_prev_state.done = true;
12034 }
12035 }
12036
12037 self.select_prev_state = Some(select_prev_state);
12038 } else {
12039 let mut only_carets = true;
12040 let mut same_text_selected = true;
12041 let mut selected_text = None;
12042
12043 let mut selections_iter = selections.iter().peekable();
12044 while let Some(selection) = selections_iter.next() {
12045 if selection.start != selection.end {
12046 only_carets = false;
12047 }
12048
12049 if same_text_selected {
12050 if selected_text.is_none() {
12051 selected_text =
12052 Some(buffer.text_for_range(selection.range()).collect::<String>());
12053 }
12054
12055 if let Some(next_selection) = selections_iter.peek() {
12056 if next_selection.range().len() == selection.range().len() {
12057 let next_selected_text = buffer
12058 .text_for_range(next_selection.range())
12059 .collect::<String>();
12060 if Some(next_selected_text) != selected_text {
12061 same_text_selected = false;
12062 selected_text = None;
12063 }
12064 } else {
12065 same_text_selected = false;
12066 selected_text = None;
12067 }
12068 }
12069 }
12070 }
12071
12072 if only_carets {
12073 for selection in &mut selections {
12074 let word_range = movement::surrounding_word(
12075 &display_map,
12076 selection.start.to_display_point(&display_map),
12077 );
12078 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12079 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12080 selection.goal = SelectionGoal::None;
12081 selection.reversed = false;
12082 }
12083 if selections.len() == 1 {
12084 let selection = selections
12085 .last()
12086 .expect("ensured that there's only one selection");
12087 let query = buffer
12088 .text_for_range(selection.start..selection.end)
12089 .collect::<String>();
12090 let is_empty = query.is_empty();
12091 let select_state = SelectNextState {
12092 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12093 wordwise: true,
12094 done: is_empty,
12095 };
12096 self.select_prev_state = Some(select_state);
12097 } else {
12098 self.select_prev_state = None;
12099 }
12100
12101 self.unfold_ranges(
12102 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12103 false,
12104 true,
12105 cx,
12106 );
12107 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12108 s.select(selections);
12109 });
12110 } else if let Some(selected_text) = selected_text {
12111 self.select_prev_state = Some(SelectNextState {
12112 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12113 wordwise: false,
12114 done: false,
12115 });
12116 self.select_previous(action, window, cx)?;
12117 }
12118 }
12119 Ok(())
12120 }
12121
12122 pub fn find_next_match(
12123 &mut self,
12124 _: &FindNextMatch,
12125 window: &mut Window,
12126 cx: &mut Context<Self>,
12127 ) -> Result<()> {
12128 let selections = self.selections.disjoint_anchors();
12129 match selections.first() {
12130 Some(first) if selections.len() >= 2 => {
12131 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12132 s.select_ranges([first.range()]);
12133 });
12134 }
12135 _ => self.select_next(
12136 &SelectNext {
12137 replace_newest: true,
12138 },
12139 window,
12140 cx,
12141 )?,
12142 }
12143 Ok(())
12144 }
12145
12146 pub fn find_previous_match(
12147 &mut self,
12148 _: &FindPreviousMatch,
12149 window: &mut Window,
12150 cx: &mut Context<Self>,
12151 ) -> Result<()> {
12152 let selections = self.selections.disjoint_anchors();
12153 match selections.last() {
12154 Some(last) if selections.len() >= 2 => {
12155 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12156 s.select_ranges([last.range()]);
12157 });
12158 }
12159 _ => self.select_previous(
12160 &SelectPrevious {
12161 replace_newest: true,
12162 },
12163 window,
12164 cx,
12165 )?,
12166 }
12167 Ok(())
12168 }
12169
12170 pub fn toggle_comments(
12171 &mut self,
12172 action: &ToggleComments,
12173 window: &mut Window,
12174 cx: &mut Context<Self>,
12175 ) {
12176 if self.read_only(cx) {
12177 return;
12178 }
12179 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12180 let text_layout_details = &self.text_layout_details(window);
12181 self.transact(window, cx, |this, window, cx| {
12182 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12183 let mut edits = Vec::new();
12184 let mut selection_edit_ranges = Vec::new();
12185 let mut last_toggled_row = None;
12186 let snapshot = this.buffer.read(cx).read(cx);
12187 let empty_str: Arc<str> = Arc::default();
12188 let mut suffixes_inserted = Vec::new();
12189 let ignore_indent = action.ignore_indent;
12190
12191 fn comment_prefix_range(
12192 snapshot: &MultiBufferSnapshot,
12193 row: MultiBufferRow,
12194 comment_prefix: &str,
12195 comment_prefix_whitespace: &str,
12196 ignore_indent: bool,
12197 ) -> Range<Point> {
12198 let indent_size = if ignore_indent {
12199 0
12200 } else {
12201 snapshot.indent_size_for_line(row).len
12202 };
12203
12204 let start = Point::new(row.0, indent_size);
12205
12206 let mut line_bytes = snapshot
12207 .bytes_in_range(start..snapshot.max_point())
12208 .flatten()
12209 .copied();
12210
12211 // If this line currently begins with the line comment prefix, then record
12212 // the range containing the prefix.
12213 if line_bytes
12214 .by_ref()
12215 .take(comment_prefix.len())
12216 .eq(comment_prefix.bytes())
12217 {
12218 // Include any whitespace that matches the comment prefix.
12219 let matching_whitespace_len = line_bytes
12220 .zip(comment_prefix_whitespace.bytes())
12221 .take_while(|(a, b)| a == b)
12222 .count() as u32;
12223 let end = Point::new(
12224 start.row,
12225 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12226 );
12227 start..end
12228 } else {
12229 start..start
12230 }
12231 }
12232
12233 fn comment_suffix_range(
12234 snapshot: &MultiBufferSnapshot,
12235 row: MultiBufferRow,
12236 comment_suffix: &str,
12237 comment_suffix_has_leading_space: bool,
12238 ) -> Range<Point> {
12239 let end = Point::new(row.0, snapshot.line_len(row));
12240 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12241
12242 let mut line_end_bytes = snapshot
12243 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12244 .flatten()
12245 .copied();
12246
12247 let leading_space_len = if suffix_start_column > 0
12248 && line_end_bytes.next() == Some(b' ')
12249 && comment_suffix_has_leading_space
12250 {
12251 1
12252 } else {
12253 0
12254 };
12255
12256 // If this line currently begins with the line comment prefix, then record
12257 // the range containing the prefix.
12258 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12259 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12260 start..end
12261 } else {
12262 end..end
12263 }
12264 }
12265
12266 // TODO: Handle selections that cross excerpts
12267 for selection in &mut selections {
12268 let start_column = snapshot
12269 .indent_size_for_line(MultiBufferRow(selection.start.row))
12270 .len;
12271 let language = if let Some(language) =
12272 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12273 {
12274 language
12275 } else {
12276 continue;
12277 };
12278
12279 selection_edit_ranges.clear();
12280
12281 // If multiple selections contain a given row, avoid processing that
12282 // row more than once.
12283 let mut start_row = MultiBufferRow(selection.start.row);
12284 if last_toggled_row == Some(start_row) {
12285 start_row = start_row.next_row();
12286 }
12287 let end_row =
12288 if selection.end.row > selection.start.row && selection.end.column == 0 {
12289 MultiBufferRow(selection.end.row - 1)
12290 } else {
12291 MultiBufferRow(selection.end.row)
12292 };
12293 last_toggled_row = Some(end_row);
12294
12295 if start_row > end_row {
12296 continue;
12297 }
12298
12299 // If the language has line comments, toggle those.
12300 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12301
12302 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12303 if ignore_indent {
12304 full_comment_prefixes = full_comment_prefixes
12305 .into_iter()
12306 .map(|s| Arc::from(s.trim_end()))
12307 .collect();
12308 }
12309
12310 if !full_comment_prefixes.is_empty() {
12311 let first_prefix = full_comment_prefixes
12312 .first()
12313 .expect("prefixes is non-empty");
12314 let prefix_trimmed_lengths = full_comment_prefixes
12315 .iter()
12316 .map(|p| p.trim_end_matches(' ').len())
12317 .collect::<SmallVec<[usize; 4]>>();
12318
12319 let mut all_selection_lines_are_comments = true;
12320
12321 for row in start_row.0..=end_row.0 {
12322 let row = MultiBufferRow(row);
12323 if start_row < end_row && snapshot.is_line_blank(row) {
12324 continue;
12325 }
12326
12327 let prefix_range = full_comment_prefixes
12328 .iter()
12329 .zip(prefix_trimmed_lengths.iter().copied())
12330 .map(|(prefix, trimmed_prefix_len)| {
12331 comment_prefix_range(
12332 snapshot.deref(),
12333 row,
12334 &prefix[..trimmed_prefix_len],
12335 &prefix[trimmed_prefix_len..],
12336 ignore_indent,
12337 )
12338 })
12339 .max_by_key(|range| range.end.column - range.start.column)
12340 .expect("prefixes is non-empty");
12341
12342 if prefix_range.is_empty() {
12343 all_selection_lines_are_comments = false;
12344 }
12345
12346 selection_edit_ranges.push(prefix_range);
12347 }
12348
12349 if all_selection_lines_are_comments {
12350 edits.extend(
12351 selection_edit_ranges
12352 .iter()
12353 .cloned()
12354 .map(|range| (range, empty_str.clone())),
12355 );
12356 } else {
12357 let min_column = selection_edit_ranges
12358 .iter()
12359 .map(|range| range.start.column)
12360 .min()
12361 .unwrap_or(0);
12362 edits.extend(selection_edit_ranges.iter().map(|range| {
12363 let position = Point::new(range.start.row, min_column);
12364 (position..position, first_prefix.clone())
12365 }));
12366 }
12367 } else if let Some((full_comment_prefix, comment_suffix)) =
12368 language.block_comment_delimiters()
12369 {
12370 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12371 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12372 let prefix_range = comment_prefix_range(
12373 snapshot.deref(),
12374 start_row,
12375 comment_prefix,
12376 comment_prefix_whitespace,
12377 ignore_indent,
12378 );
12379 let suffix_range = comment_suffix_range(
12380 snapshot.deref(),
12381 end_row,
12382 comment_suffix.trim_start_matches(' '),
12383 comment_suffix.starts_with(' '),
12384 );
12385
12386 if prefix_range.is_empty() || suffix_range.is_empty() {
12387 edits.push((
12388 prefix_range.start..prefix_range.start,
12389 full_comment_prefix.clone(),
12390 ));
12391 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12392 suffixes_inserted.push((end_row, comment_suffix.len()));
12393 } else {
12394 edits.push((prefix_range, empty_str.clone()));
12395 edits.push((suffix_range, empty_str.clone()));
12396 }
12397 } else {
12398 continue;
12399 }
12400 }
12401
12402 drop(snapshot);
12403 this.buffer.update(cx, |buffer, cx| {
12404 buffer.edit(edits, None, cx);
12405 });
12406
12407 // Adjust selections so that they end before any comment suffixes that
12408 // were inserted.
12409 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12410 let mut selections = this.selections.all::<Point>(cx);
12411 let snapshot = this.buffer.read(cx).read(cx);
12412 for selection in &mut selections {
12413 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12414 match row.cmp(&MultiBufferRow(selection.end.row)) {
12415 Ordering::Less => {
12416 suffixes_inserted.next();
12417 continue;
12418 }
12419 Ordering::Greater => break,
12420 Ordering::Equal => {
12421 if selection.end.column == snapshot.line_len(row) {
12422 if selection.is_empty() {
12423 selection.start.column -= suffix_len as u32;
12424 }
12425 selection.end.column -= suffix_len as u32;
12426 }
12427 break;
12428 }
12429 }
12430 }
12431 }
12432
12433 drop(snapshot);
12434 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12435 s.select(selections)
12436 });
12437
12438 let selections = this.selections.all::<Point>(cx);
12439 let selections_on_single_row = selections.windows(2).all(|selections| {
12440 selections[0].start.row == selections[1].start.row
12441 && selections[0].end.row == selections[1].end.row
12442 && selections[0].start.row == selections[0].end.row
12443 });
12444 let selections_selecting = selections
12445 .iter()
12446 .any(|selection| selection.start != selection.end);
12447 let advance_downwards = action.advance_downwards
12448 && selections_on_single_row
12449 && !selections_selecting
12450 && !matches!(this.mode, EditorMode::SingleLine { .. });
12451
12452 if advance_downwards {
12453 let snapshot = this.buffer.read(cx).snapshot(cx);
12454
12455 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12456 s.move_cursors_with(|display_snapshot, display_point, _| {
12457 let mut point = display_point.to_point(display_snapshot);
12458 point.row += 1;
12459 point = snapshot.clip_point(point, Bias::Left);
12460 let display_point = point.to_display_point(display_snapshot);
12461 let goal = SelectionGoal::HorizontalPosition(
12462 display_snapshot
12463 .x_for_display_point(display_point, text_layout_details)
12464 .into(),
12465 );
12466 (display_point, goal)
12467 })
12468 });
12469 }
12470 });
12471 }
12472
12473 pub fn select_enclosing_symbol(
12474 &mut self,
12475 _: &SelectEnclosingSymbol,
12476 window: &mut Window,
12477 cx: &mut Context<Self>,
12478 ) {
12479 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12480
12481 let buffer = self.buffer.read(cx).snapshot(cx);
12482 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12483
12484 fn update_selection(
12485 selection: &Selection<usize>,
12486 buffer_snap: &MultiBufferSnapshot,
12487 ) -> Option<Selection<usize>> {
12488 let cursor = selection.head();
12489 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12490 for symbol in symbols.iter().rev() {
12491 let start = symbol.range.start.to_offset(buffer_snap);
12492 let end = symbol.range.end.to_offset(buffer_snap);
12493 let new_range = start..end;
12494 if start < selection.start || end > selection.end {
12495 return Some(Selection {
12496 id: selection.id,
12497 start: new_range.start,
12498 end: new_range.end,
12499 goal: SelectionGoal::None,
12500 reversed: selection.reversed,
12501 });
12502 }
12503 }
12504 None
12505 }
12506
12507 let mut selected_larger_symbol = false;
12508 let new_selections = old_selections
12509 .iter()
12510 .map(|selection| match update_selection(selection, &buffer) {
12511 Some(new_selection) => {
12512 if new_selection.range() != selection.range() {
12513 selected_larger_symbol = true;
12514 }
12515 new_selection
12516 }
12517 None => selection.clone(),
12518 })
12519 .collect::<Vec<_>>();
12520
12521 if selected_larger_symbol {
12522 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12523 s.select(new_selections);
12524 });
12525 }
12526 }
12527
12528 pub fn select_larger_syntax_node(
12529 &mut self,
12530 _: &SelectLargerSyntaxNode,
12531 window: &mut Window,
12532 cx: &mut Context<Self>,
12533 ) {
12534 let Some(visible_row_count) = self.visible_row_count() else {
12535 return;
12536 };
12537 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12538 if old_selections.is_empty() {
12539 return;
12540 }
12541
12542 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12543
12544 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12545 let buffer = self.buffer.read(cx).snapshot(cx);
12546
12547 let mut selected_larger_node = false;
12548 let mut new_selections = old_selections
12549 .iter()
12550 .map(|selection| {
12551 let old_range = selection.start..selection.end;
12552
12553 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12554 // manually select word at selection
12555 if ["string_content", "inline"].contains(&node.kind()) {
12556 let word_range = {
12557 let display_point = buffer
12558 .offset_to_point(old_range.start)
12559 .to_display_point(&display_map);
12560 let Range { start, end } =
12561 movement::surrounding_word(&display_map, display_point);
12562 start.to_point(&display_map).to_offset(&buffer)
12563 ..end.to_point(&display_map).to_offset(&buffer)
12564 };
12565 // ignore if word is already selected
12566 if !word_range.is_empty() && old_range != word_range {
12567 let last_word_range = {
12568 let display_point = buffer
12569 .offset_to_point(old_range.end)
12570 .to_display_point(&display_map);
12571 let Range { start, end } =
12572 movement::surrounding_word(&display_map, display_point);
12573 start.to_point(&display_map).to_offset(&buffer)
12574 ..end.to_point(&display_map).to_offset(&buffer)
12575 };
12576 // only select word if start and end point belongs to same word
12577 if word_range == last_word_range {
12578 selected_larger_node = true;
12579 return Selection {
12580 id: selection.id,
12581 start: word_range.start,
12582 end: word_range.end,
12583 goal: SelectionGoal::None,
12584 reversed: selection.reversed,
12585 };
12586 }
12587 }
12588 }
12589 }
12590
12591 let mut new_range = old_range.clone();
12592 let mut new_node = None;
12593 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12594 {
12595 new_node = Some(node);
12596 new_range = match containing_range {
12597 MultiOrSingleBufferOffsetRange::Single(_) => break,
12598 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12599 };
12600 if !display_map.intersects_fold(new_range.start)
12601 && !display_map.intersects_fold(new_range.end)
12602 {
12603 break;
12604 }
12605 }
12606
12607 if let Some(node) = new_node {
12608 // Log the ancestor, to support using this action as a way to explore TreeSitter
12609 // nodes. Parent and grandparent are also logged because this operation will not
12610 // visit nodes that have the same range as their parent.
12611 log::info!("Node: {node:?}");
12612 let parent = node.parent();
12613 log::info!("Parent: {parent:?}");
12614 let grandparent = parent.and_then(|x| x.parent());
12615 log::info!("Grandparent: {grandparent:?}");
12616 }
12617
12618 selected_larger_node |= new_range != old_range;
12619 Selection {
12620 id: selection.id,
12621 start: new_range.start,
12622 end: new_range.end,
12623 goal: SelectionGoal::None,
12624 reversed: selection.reversed,
12625 }
12626 })
12627 .collect::<Vec<_>>();
12628
12629 if !selected_larger_node {
12630 return; // don't put this call in the history
12631 }
12632
12633 // scroll based on transformation done to the last selection created by the user
12634 let (last_old, last_new) = old_selections
12635 .last()
12636 .zip(new_selections.last().cloned())
12637 .expect("old_selections isn't empty");
12638
12639 // revert selection
12640 let is_selection_reversed = {
12641 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12642 new_selections.last_mut().expect("checked above").reversed =
12643 should_newest_selection_be_reversed;
12644 should_newest_selection_be_reversed
12645 };
12646
12647 if selected_larger_node {
12648 self.select_syntax_node_history.disable_clearing = true;
12649 self.change_selections(None, window, cx, |s| {
12650 s.select(new_selections.clone());
12651 });
12652 self.select_syntax_node_history.disable_clearing = false;
12653 }
12654
12655 let start_row = last_new.start.to_display_point(&display_map).row().0;
12656 let end_row = last_new.end.to_display_point(&display_map).row().0;
12657 let selection_height = end_row - start_row + 1;
12658 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12659
12660 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12661 let scroll_behavior = if fits_on_the_screen {
12662 self.request_autoscroll(Autoscroll::fit(), cx);
12663 SelectSyntaxNodeScrollBehavior::FitSelection
12664 } else if is_selection_reversed {
12665 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12666 SelectSyntaxNodeScrollBehavior::CursorTop
12667 } else {
12668 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12669 SelectSyntaxNodeScrollBehavior::CursorBottom
12670 };
12671
12672 self.select_syntax_node_history.push((
12673 old_selections,
12674 scroll_behavior,
12675 is_selection_reversed,
12676 ));
12677 }
12678
12679 pub fn select_smaller_syntax_node(
12680 &mut self,
12681 _: &SelectSmallerSyntaxNode,
12682 window: &mut Window,
12683 cx: &mut Context<Self>,
12684 ) {
12685 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12686
12687 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12688 self.select_syntax_node_history.pop()
12689 {
12690 if let Some(selection) = selections.last_mut() {
12691 selection.reversed = is_selection_reversed;
12692 }
12693
12694 self.select_syntax_node_history.disable_clearing = true;
12695 self.change_selections(None, window, cx, |s| {
12696 s.select(selections.to_vec());
12697 });
12698 self.select_syntax_node_history.disable_clearing = false;
12699
12700 match scroll_behavior {
12701 SelectSyntaxNodeScrollBehavior::CursorTop => {
12702 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12703 }
12704 SelectSyntaxNodeScrollBehavior::FitSelection => {
12705 self.request_autoscroll(Autoscroll::fit(), cx);
12706 }
12707 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12708 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12709 }
12710 }
12711 }
12712 }
12713
12714 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12715 if !EditorSettings::get_global(cx).gutter.runnables {
12716 self.clear_tasks();
12717 return Task::ready(());
12718 }
12719 let project = self.project.as_ref().map(Entity::downgrade);
12720 let task_sources = self.lsp_task_sources(cx);
12721 cx.spawn_in(window, async move |editor, cx| {
12722 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12723 let Some(project) = project.and_then(|p| p.upgrade()) else {
12724 return;
12725 };
12726 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12727 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12728 }) else {
12729 return;
12730 };
12731
12732 let hide_runnables = project
12733 .update(cx, |project, cx| {
12734 // Do not display any test indicators in non-dev server remote projects.
12735 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12736 })
12737 .unwrap_or(true);
12738 if hide_runnables {
12739 return;
12740 }
12741 let new_rows =
12742 cx.background_spawn({
12743 let snapshot = display_snapshot.clone();
12744 async move {
12745 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12746 }
12747 })
12748 .await;
12749 let Ok(lsp_tasks) =
12750 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12751 else {
12752 return;
12753 };
12754 let lsp_tasks = lsp_tasks.await;
12755
12756 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12757 lsp_tasks
12758 .into_iter()
12759 .flat_map(|(kind, tasks)| {
12760 tasks.into_iter().filter_map(move |(location, task)| {
12761 Some((kind.clone(), location?, task))
12762 })
12763 })
12764 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12765 let buffer = location.target.buffer;
12766 let buffer_snapshot = buffer.read(cx).snapshot();
12767 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12768 |(excerpt_id, snapshot, _)| {
12769 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12770 display_snapshot
12771 .buffer_snapshot
12772 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12773 } else {
12774 None
12775 }
12776 },
12777 );
12778 if let Some(offset) = offset {
12779 let task_buffer_range =
12780 location.target.range.to_point(&buffer_snapshot);
12781 let context_buffer_range =
12782 task_buffer_range.to_offset(&buffer_snapshot);
12783 let context_range = BufferOffset(context_buffer_range.start)
12784 ..BufferOffset(context_buffer_range.end);
12785
12786 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12787 .or_insert_with(|| RunnableTasks {
12788 templates: Vec::new(),
12789 offset,
12790 column: task_buffer_range.start.column,
12791 extra_variables: HashMap::default(),
12792 context_range,
12793 })
12794 .templates
12795 .push((kind, task.original_task().clone()));
12796 }
12797
12798 acc
12799 })
12800 }) else {
12801 return;
12802 };
12803
12804 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12805 editor
12806 .update(cx, |editor, _| {
12807 editor.clear_tasks();
12808 for (key, mut value) in rows {
12809 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12810 value.templates.extend(lsp_tasks.templates);
12811 }
12812
12813 editor.insert_tasks(key, value);
12814 }
12815 for (key, value) in lsp_tasks_by_rows {
12816 editor.insert_tasks(key, value);
12817 }
12818 })
12819 .ok();
12820 })
12821 }
12822 fn fetch_runnable_ranges(
12823 snapshot: &DisplaySnapshot,
12824 range: Range<Anchor>,
12825 ) -> Vec<language::RunnableRange> {
12826 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12827 }
12828
12829 fn runnable_rows(
12830 project: Entity<Project>,
12831 snapshot: DisplaySnapshot,
12832 runnable_ranges: Vec<RunnableRange>,
12833 mut cx: AsyncWindowContext,
12834 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12835 runnable_ranges
12836 .into_iter()
12837 .filter_map(|mut runnable| {
12838 let tasks = cx
12839 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12840 .ok()?;
12841 if tasks.is_empty() {
12842 return None;
12843 }
12844
12845 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12846
12847 let row = snapshot
12848 .buffer_snapshot
12849 .buffer_line_for_row(MultiBufferRow(point.row))?
12850 .1
12851 .start
12852 .row;
12853
12854 let context_range =
12855 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12856 Some((
12857 (runnable.buffer_id, row),
12858 RunnableTasks {
12859 templates: tasks,
12860 offset: snapshot
12861 .buffer_snapshot
12862 .anchor_before(runnable.run_range.start),
12863 context_range,
12864 column: point.column,
12865 extra_variables: runnable.extra_captures,
12866 },
12867 ))
12868 })
12869 .collect()
12870 }
12871
12872 fn templates_with_tags(
12873 project: &Entity<Project>,
12874 runnable: &mut Runnable,
12875 cx: &mut App,
12876 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12877 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12878 let (worktree_id, file) = project
12879 .buffer_for_id(runnable.buffer, cx)
12880 .and_then(|buffer| buffer.read(cx).file())
12881 .map(|file| (file.worktree_id(cx), file.clone()))
12882 .unzip();
12883
12884 (
12885 project.task_store().read(cx).task_inventory().cloned(),
12886 worktree_id,
12887 file,
12888 )
12889 });
12890
12891 let mut templates_with_tags = mem::take(&mut runnable.tags)
12892 .into_iter()
12893 .flat_map(|RunnableTag(tag)| {
12894 inventory
12895 .as_ref()
12896 .into_iter()
12897 .flat_map(|inventory| {
12898 inventory.read(cx).list_tasks(
12899 file.clone(),
12900 Some(runnable.language.clone()),
12901 worktree_id,
12902 cx,
12903 )
12904 })
12905 .filter(move |(_, template)| {
12906 template.tags.iter().any(|source_tag| source_tag == &tag)
12907 })
12908 })
12909 .sorted_by_key(|(kind, _)| kind.to_owned())
12910 .collect::<Vec<_>>();
12911 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12912 // Strongest source wins; if we have worktree tag binding, prefer that to
12913 // global and language bindings;
12914 // if we have a global binding, prefer that to language binding.
12915 let first_mismatch = templates_with_tags
12916 .iter()
12917 .position(|(tag_source, _)| tag_source != leading_tag_source);
12918 if let Some(index) = first_mismatch {
12919 templates_with_tags.truncate(index);
12920 }
12921 }
12922
12923 templates_with_tags
12924 }
12925
12926 pub fn move_to_enclosing_bracket(
12927 &mut self,
12928 _: &MoveToEnclosingBracket,
12929 window: &mut Window,
12930 cx: &mut Context<Self>,
12931 ) {
12932 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12933 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12934 s.move_offsets_with(|snapshot, selection| {
12935 let Some(enclosing_bracket_ranges) =
12936 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12937 else {
12938 return;
12939 };
12940
12941 let mut best_length = usize::MAX;
12942 let mut best_inside = false;
12943 let mut best_in_bracket_range = false;
12944 let mut best_destination = None;
12945 for (open, close) in enclosing_bracket_ranges {
12946 let close = close.to_inclusive();
12947 let length = close.end() - open.start;
12948 let inside = selection.start >= open.end && selection.end <= *close.start();
12949 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12950 || close.contains(&selection.head());
12951
12952 // If best is next to a bracket and current isn't, skip
12953 if !in_bracket_range && best_in_bracket_range {
12954 continue;
12955 }
12956
12957 // Prefer smaller lengths unless best is inside and current isn't
12958 if length > best_length && (best_inside || !inside) {
12959 continue;
12960 }
12961
12962 best_length = length;
12963 best_inside = inside;
12964 best_in_bracket_range = in_bracket_range;
12965 best_destination = Some(
12966 if close.contains(&selection.start) && close.contains(&selection.end) {
12967 if inside { open.end } else { open.start }
12968 } else if inside {
12969 *close.start()
12970 } else {
12971 *close.end()
12972 },
12973 );
12974 }
12975
12976 if let Some(destination) = best_destination {
12977 selection.collapse_to(destination, SelectionGoal::None);
12978 }
12979 })
12980 });
12981 }
12982
12983 pub fn undo_selection(
12984 &mut self,
12985 _: &UndoSelection,
12986 window: &mut Window,
12987 cx: &mut Context<Self>,
12988 ) {
12989 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12990 self.end_selection(window, cx);
12991 self.selection_history.mode = SelectionHistoryMode::Undoing;
12992 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12993 self.change_selections(None, window, cx, |s| {
12994 s.select_anchors(entry.selections.to_vec())
12995 });
12996 self.select_next_state = entry.select_next_state;
12997 self.select_prev_state = entry.select_prev_state;
12998 self.add_selections_state = entry.add_selections_state;
12999 self.request_autoscroll(Autoscroll::newest(), cx);
13000 }
13001 self.selection_history.mode = SelectionHistoryMode::Normal;
13002 }
13003
13004 pub fn redo_selection(
13005 &mut self,
13006 _: &RedoSelection,
13007 window: &mut Window,
13008 cx: &mut Context<Self>,
13009 ) {
13010 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13011 self.end_selection(window, cx);
13012 self.selection_history.mode = SelectionHistoryMode::Redoing;
13013 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13014 self.change_selections(None, window, cx, |s| {
13015 s.select_anchors(entry.selections.to_vec())
13016 });
13017 self.select_next_state = entry.select_next_state;
13018 self.select_prev_state = entry.select_prev_state;
13019 self.add_selections_state = entry.add_selections_state;
13020 self.request_autoscroll(Autoscroll::newest(), cx);
13021 }
13022 self.selection_history.mode = SelectionHistoryMode::Normal;
13023 }
13024
13025 pub fn expand_excerpts(
13026 &mut self,
13027 action: &ExpandExcerpts,
13028 _: &mut Window,
13029 cx: &mut Context<Self>,
13030 ) {
13031 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13032 }
13033
13034 pub fn expand_excerpts_down(
13035 &mut self,
13036 action: &ExpandExcerptsDown,
13037 _: &mut Window,
13038 cx: &mut Context<Self>,
13039 ) {
13040 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13041 }
13042
13043 pub fn expand_excerpts_up(
13044 &mut self,
13045 action: &ExpandExcerptsUp,
13046 _: &mut Window,
13047 cx: &mut Context<Self>,
13048 ) {
13049 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13050 }
13051
13052 pub fn expand_excerpts_for_direction(
13053 &mut self,
13054 lines: u32,
13055 direction: ExpandExcerptDirection,
13056
13057 cx: &mut Context<Self>,
13058 ) {
13059 let selections = self.selections.disjoint_anchors();
13060
13061 let lines = if lines == 0 {
13062 EditorSettings::get_global(cx).expand_excerpt_lines
13063 } else {
13064 lines
13065 };
13066
13067 self.buffer.update(cx, |buffer, cx| {
13068 let snapshot = buffer.snapshot(cx);
13069 let mut excerpt_ids = selections
13070 .iter()
13071 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13072 .collect::<Vec<_>>();
13073 excerpt_ids.sort();
13074 excerpt_ids.dedup();
13075 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13076 })
13077 }
13078
13079 pub fn expand_excerpt(
13080 &mut self,
13081 excerpt: ExcerptId,
13082 direction: ExpandExcerptDirection,
13083 window: &mut Window,
13084 cx: &mut Context<Self>,
13085 ) {
13086 let current_scroll_position = self.scroll_position(cx);
13087 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13088 let mut should_scroll_up = false;
13089
13090 if direction == ExpandExcerptDirection::Down {
13091 let multi_buffer = self.buffer.read(cx);
13092 let snapshot = multi_buffer.snapshot(cx);
13093 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13094 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13095 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13096 let buffer_snapshot = buffer.read(cx).snapshot();
13097 let excerpt_end_row =
13098 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13099 let last_row = buffer_snapshot.max_point().row;
13100 let lines_below = last_row.saturating_sub(excerpt_end_row);
13101 should_scroll_up = lines_below >= lines_to_expand;
13102 }
13103 }
13104 }
13105 }
13106
13107 self.buffer.update(cx, |buffer, cx| {
13108 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13109 });
13110
13111 if should_scroll_up {
13112 let new_scroll_position =
13113 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13114 self.set_scroll_position(new_scroll_position, window, cx);
13115 }
13116 }
13117
13118 pub fn go_to_singleton_buffer_point(
13119 &mut self,
13120 point: Point,
13121 window: &mut Window,
13122 cx: &mut Context<Self>,
13123 ) {
13124 self.go_to_singleton_buffer_range(point..point, window, cx);
13125 }
13126
13127 pub fn go_to_singleton_buffer_range(
13128 &mut self,
13129 range: Range<Point>,
13130 window: &mut Window,
13131 cx: &mut Context<Self>,
13132 ) {
13133 let multibuffer = self.buffer().read(cx);
13134 let Some(buffer) = multibuffer.as_singleton() else {
13135 return;
13136 };
13137 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13138 return;
13139 };
13140 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13141 return;
13142 };
13143 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13144 s.select_anchor_ranges([start..end])
13145 });
13146 }
13147
13148 pub fn go_to_diagnostic(
13149 &mut self,
13150 _: &GoToDiagnostic,
13151 window: &mut Window,
13152 cx: &mut Context<Self>,
13153 ) {
13154 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13155 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13156 }
13157
13158 pub fn go_to_prev_diagnostic(
13159 &mut self,
13160 _: &GoToPreviousDiagnostic,
13161 window: &mut Window,
13162 cx: &mut Context<Self>,
13163 ) {
13164 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13165 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13166 }
13167
13168 pub fn go_to_diagnostic_impl(
13169 &mut self,
13170 direction: Direction,
13171 window: &mut Window,
13172 cx: &mut Context<Self>,
13173 ) {
13174 let buffer = self.buffer.read(cx).snapshot(cx);
13175 let selection = self.selections.newest::<usize>(cx);
13176
13177 let mut active_group_id = None;
13178 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13179 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13180 active_group_id = Some(active_group.group_id);
13181 }
13182 }
13183
13184 fn filtered(
13185 snapshot: EditorSnapshot,
13186 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13187 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13188 diagnostics
13189 .filter(|entry| entry.range.start != entry.range.end)
13190 .filter(|entry| !entry.diagnostic.is_unnecessary)
13191 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13192 }
13193
13194 let snapshot = self.snapshot(window, cx);
13195 let before = filtered(
13196 snapshot.clone(),
13197 buffer
13198 .diagnostics_in_range(0..selection.start)
13199 .filter(|entry| entry.range.start <= selection.start),
13200 );
13201 let after = filtered(
13202 snapshot,
13203 buffer
13204 .diagnostics_in_range(selection.start..buffer.len())
13205 .filter(|entry| entry.range.start >= selection.start),
13206 );
13207
13208 let mut found: Option<DiagnosticEntry<usize>> = None;
13209 if direction == Direction::Prev {
13210 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13211 {
13212 for diagnostic in prev_diagnostics.into_iter().rev() {
13213 if diagnostic.range.start != selection.start
13214 || active_group_id
13215 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13216 {
13217 found = Some(diagnostic);
13218 break 'outer;
13219 }
13220 }
13221 }
13222 } else {
13223 for diagnostic in after.chain(before) {
13224 if diagnostic.range.start != selection.start
13225 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13226 {
13227 found = Some(diagnostic);
13228 break;
13229 }
13230 }
13231 }
13232 let Some(next_diagnostic) = found else {
13233 return;
13234 };
13235
13236 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13237 return;
13238 };
13239 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13240 s.select_ranges(vec![
13241 next_diagnostic.range.start..next_diagnostic.range.start,
13242 ])
13243 });
13244 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13245 self.refresh_inline_completion(false, true, window, cx);
13246 }
13247
13248 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13249 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13250 let snapshot = self.snapshot(window, cx);
13251 let selection = self.selections.newest::<Point>(cx);
13252 self.go_to_hunk_before_or_after_position(
13253 &snapshot,
13254 selection.head(),
13255 Direction::Next,
13256 window,
13257 cx,
13258 );
13259 }
13260
13261 pub fn go_to_hunk_before_or_after_position(
13262 &mut self,
13263 snapshot: &EditorSnapshot,
13264 position: Point,
13265 direction: Direction,
13266 window: &mut Window,
13267 cx: &mut Context<Editor>,
13268 ) {
13269 let row = if direction == Direction::Next {
13270 self.hunk_after_position(snapshot, position)
13271 .map(|hunk| hunk.row_range.start)
13272 } else {
13273 self.hunk_before_position(snapshot, position)
13274 };
13275
13276 if let Some(row) = row {
13277 let destination = Point::new(row.0, 0);
13278 let autoscroll = Autoscroll::center();
13279
13280 self.unfold_ranges(&[destination..destination], false, false, cx);
13281 self.change_selections(Some(autoscroll), window, cx, |s| {
13282 s.select_ranges([destination..destination]);
13283 });
13284 }
13285 }
13286
13287 fn hunk_after_position(
13288 &mut self,
13289 snapshot: &EditorSnapshot,
13290 position: Point,
13291 ) -> Option<MultiBufferDiffHunk> {
13292 snapshot
13293 .buffer_snapshot
13294 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13295 .find(|hunk| hunk.row_range.start.0 > position.row)
13296 .or_else(|| {
13297 snapshot
13298 .buffer_snapshot
13299 .diff_hunks_in_range(Point::zero()..position)
13300 .find(|hunk| hunk.row_range.end.0 < position.row)
13301 })
13302 }
13303
13304 fn go_to_prev_hunk(
13305 &mut self,
13306 _: &GoToPreviousHunk,
13307 window: &mut Window,
13308 cx: &mut Context<Self>,
13309 ) {
13310 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13311 let snapshot = self.snapshot(window, cx);
13312 let selection = self.selections.newest::<Point>(cx);
13313 self.go_to_hunk_before_or_after_position(
13314 &snapshot,
13315 selection.head(),
13316 Direction::Prev,
13317 window,
13318 cx,
13319 );
13320 }
13321
13322 fn hunk_before_position(
13323 &mut self,
13324 snapshot: &EditorSnapshot,
13325 position: Point,
13326 ) -> Option<MultiBufferRow> {
13327 snapshot
13328 .buffer_snapshot
13329 .diff_hunk_before(position)
13330 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13331 }
13332
13333 fn go_to_next_change(
13334 &mut self,
13335 _: &GoToNextChange,
13336 window: &mut Window,
13337 cx: &mut Context<Self>,
13338 ) {
13339 if let Some(selections) = self
13340 .change_list
13341 .next_change(1, Direction::Next)
13342 .map(|s| s.to_vec())
13343 {
13344 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13345 let map = s.display_map();
13346 s.select_display_ranges(selections.iter().map(|a| {
13347 let point = a.to_display_point(&map);
13348 point..point
13349 }))
13350 })
13351 }
13352 }
13353
13354 fn go_to_previous_change(
13355 &mut self,
13356 _: &GoToPreviousChange,
13357 window: &mut Window,
13358 cx: &mut Context<Self>,
13359 ) {
13360 if let Some(selections) = self
13361 .change_list
13362 .next_change(1, Direction::Prev)
13363 .map(|s| s.to_vec())
13364 {
13365 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13366 let map = s.display_map();
13367 s.select_display_ranges(selections.iter().map(|a| {
13368 let point = a.to_display_point(&map);
13369 point..point
13370 }))
13371 })
13372 }
13373 }
13374
13375 fn go_to_line<T: 'static>(
13376 &mut self,
13377 position: Anchor,
13378 highlight_color: Option<Hsla>,
13379 window: &mut Window,
13380 cx: &mut Context<Self>,
13381 ) {
13382 let snapshot = self.snapshot(window, cx).display_snapshot;
13383 let position = position.to_point(&snapshot.buffer_snapshot);
13384 let start = snapshot
13385 .buffer_snapshot
13386 .clip_point(Point::new(position.row, 0), Bias::Left);
13387 let end = start + Point::new(1, 0);
13388 let start = snapshot.buffer_snapshot.anchor_before(start);
13389 let end = snapshot.buffer_snapshot.anchor_before(end);
13390
13391 self.highlight_rows::<T>(
13392 start..end,
13393 highlight_color
13394 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13395 false,
13396 cx,
13397 );
13398 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13399 }
13400
13401 pub fn go_to_definition(
13402 &mut self,
13403 _: &GoToDefinition,
13404 window: &mut Window,
13405 cx: &mut Context<Self>,
13406 ) -> Task<Result<Navigated>> {
13407 let definition =
13408 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13409 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13410 cx.spawn_in(window, async move |editor, cx| {
13411 if definition.await? == Navigated::Yes {
13412 return Ok(Navigated::Yes);
13413 }
13414 match fallback_strategy {
13415 GoToDefinitionFallback::None => Ok(Navigated::No),
13416 GoToDefinitionFallback::FindAllReferences => {
13417 match editor.update_in(cx, |editor, window, cx| {
13418 editor.find_all_references(&FindAllReferences, window, cx)
13419 })? {
13420 Some(references) => references.await,
13421 None => Ok(Navigated::No),
13422 }
13423 }
13424 }
13425 })
13426 }
13427
13428 pub fn go_to_declaration(
13429 &mut self,
13430 _: &GoToDeclaration,
13431 window: &mut Window,
13432 cx: &mut Context<Self>,
13433 ) -> Task<Result<Navigated>> {
13434 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13435 }
13436
13437 pub fn go_to_declaration_split(
13438 &mut self,
13439 _: &GoToDeclaration,
13440 window: &mut Window,
13441 cx: &mut Context<Self>,
13442 ) -> Task<Result<Navigated>> {
13443 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13444 }
13445
13446 pub fn go_to_implementation(
13447 &mut self,
13448 _: &GoToImplementation,
13449 window: &mut Window,
13450 cx: &mut Context<Self>,
13451 ) -> Task<Result<Navigated>> {
13452 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13453 }
13454
13455 pub fn go_to_implementation_split(
13456 &mut self,
13457 _: &GoToImplementationSplit,
13458 window: &mut Window,
13459 cx: &mut Context<Self>,
13460 ) -> Task<Result<Navigated>> {
13461 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13462 }
13463
13464 pub fn go_to_type_definition(
13465 &mut self,
13466 _: &GoToTypeDefinition,
13467 window: &mut Window,
13468 cx: &mut Context<Self>,
13469 ) -> Task<Result<Navigated>> {
13470 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13471 }
13472
13473 pub fn go_to_definition_split(
13474 &mut self,
13475 _: &GoToDefinitionSplit,
13476 window: &mut Window,
13477 cx: &mut Context<Self>,
13478 ) -> Task<Result<Navigated>> {
13479 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13480 }
13481
13482 pub fn go_to_type_definition_split(
13483 &mut self,
13484 _: &GoToTypeDefinitionSplit,
13485 window: &mut Window,
13486 cx: &mut Context<Self>,
13487 ) -> Task<Result<Navigated>> {
13488 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13489 }
13490
13491 fn go_to_definition_of_kind(
13492 &mut self,
13493 kind: GotoDefinitionKind,
13494 split: bool,
13495 window: &mut Window,
13496 cx: &mut Context<Self>,
13497 ) -> Task<Result<Navigated>> {
13498 let Some(provider) = self.semantics_provider.clone() else {
13499 return Task::ready(Ok(Navigated::No));
13500 };
13501 let head = self.selections.newest::<usize>(cx).head();
13502 let buffer = self.buffer.read(cx);
13503 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13504 text_anchor
13505 } else {
13506 return Task::ready(Ok(Navigated::No));
13507 };
13508
13509 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13510 return Task::ready(Ok(Navigated::No));
13511 };
13512
13513 cx.spawn_in(window, async move |editor, cx| {
13514 let definitions = definitions.await?;
13515 let navigated = editor
13516 .update_in(cx, |editor, window, cx| {
13517 editor.navigate_to_hover_links(
13518 Some(kind),
13519 definitions
13520 .into_iter()
13521 .filter(|location| {
13522 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13523 })
13524 .map(HoverLink::Text)
13525 .collect::<Vec<_>>(),
13526 split,
13527 window,
13528 cx,
13529 )
13530 })?
13531 .await?;
13532 anyhow::Ok(navigated)
13533 })
13534 }
13535
13536 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13537 let selection = self.selections.newest_anchor();
13538 let head = selection.head();
13539 let tail = selection.tail();
13540
13541 let Some((buffer, start_position)) =
13542 self.buffer.read(cx).text_anchor_for_position(head, cx)
13543 else {
13544 return;
13545 };
13546
13547 let end_position = if head != tail {
13548 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13549 return;
13550 };
13551 Some(pos)
13552 } else {
13553 None
13554 };
13555
13556 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13557 let url = if let Some(end_pos) = end_position {
13558 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13559 } else {
13560 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13561 };
13562
13563 if let Some(url) = url {
13564 editor.update(cx, |_, cx| {
13565 cx.open_url(&url);
13566 })
13567 } else {
13568 Ok(())
13569 }
13570 });
13571
13572 url_finder.detach();
13573 }
13574
13575 pub fn open_selected_filename(
13576 &mut self,
13577 _: &OpenSelectedFilename,
13578 window: &mut Window,
13579 cx: &mut Context<Self>,
13580 ) {
13581 let Some(workspace) = self.workspace() else {
13582 return;
13583 };
13584
13585 let position = self.selections.newest_anchor().head();
13586
13587 let Some((buffer, buffer_position)) =
13588 self.buffer.read(cx).text_anchor_for_position(position, cx)
13589 else {
13590 return;
13591 };
13592
13593 let project = self.project.clone();
13594
13595 cx.spawn_in(window, async move |_, cx| {
13596 let result = find_file(&buffer, project, buffer_position, cx).await;
13597
13598 if let Some((_, path)) = result {
13599 workspace
13600 .update_in(cx, |workspace, window, cx| {
13601 workspace.open_resolved_path(path, window, cx)
13602 })?
13603 .await?;
13604 }
13605 anyhow::Ok(())
13606 })
13607 .detach();
13608 }
13609
13610 pub(crate) fn navigate_to_hover_links(
13611 &mut self,
13612 kind: Option<GotoDefinitionKind>,
13613 mut definitions: Vec<HoverLink>,
13614 split: bool,
13615 window: &mut Window,
13616 cx: &mut Context<Editor>,
13617 ) -> Task<Result<Navigated>> {
13618 // If there is one definition, just open it directly
13619 if definitions.len() == 1 {
13620 let definition = definitions.pop().unwrap();
13621
13622 enum TargetTaskResult {
13623 Location(Option<Location>),
13624 AlreadyNavigated,
13625 }
13626
13627 let target_task = match definition {
13628 HoverLink::Text(link) => {
13629 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13630 }
13631 HoverLink::InlayHint(lsp_location, server_id) => {
13632 let computation =
13633 self.compute_target_location(lsp_location, server_id, window, cx);
13634 cx.background_spawn(async move {
13635 let location = computation.await?;
13636 Ok(TargetTaskResult::Location(location))
13637 })
13638 }
13639 HoverLink::Url(url) => {
13640 cx.open_url(&url);
13641 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13642 }
13643 HoverLink::File(path) => {
13644 if let Some(workspace) = self.workspace() {
13645 cx.spawn_in(window, async move |_, cx| {
13646 workspace
13647 .update_in(cx, |workspace, window, cx| {
13648 workspace.open_resolved_path(path, window, cx)
13649 })?
13650 .await
13651 .map(|_| TargetTaskResult::AlreadyNavigated)
13652 })
13653 } else {
13654 Task::ready(Ok(TargetTaskResult::Location(None)))
13655 }
13656 }
13657 };
13658 cx.spawn_in(window, async move |editor, cx| {
13659 let target = match target_task.await.context("target resolution task")? {
13660 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13661 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13662 TargetTaskResult::Location(Some(target)) => target,
13663 };
13664
13665 editor.update_in(cx, |editor, window, cx| {
13666 let Some(workspace) = editor.workspace() else {
13667 return Navigated::No;
13668 };
13669 let pane = workspace.read(cx).active_pane().clone();
13670
13671 let range = target.range.to_point(target.buffer.read(cx));
13672 let range = editor.range_for_match(&range);
13673 let range = collapse_multiline_range(range);
13674
13675 if !split
13676 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13677 {
13678 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13679 } else {
13680 window.defer(cx, move |window, cx| {
13681 let target_editor: Entity<Self> =
13682 workspace.update(cx, |workspace, cx| {
13683 let pane = if split {
13684 workspace.adjacent_pane(window, cx)
13685 } else {
13686 workspace.active_pane().clone()
13687 };
13688
13689 workspace.open_project_item(
13690 pane,
13691 target.buffer.clone(),
13692 true,
13693 true,
13694 window,
13695 cx,
13696 )
13697 });
13698 target_editor.update(cx, |target_editor, cx| {
13699 // When selecting a definition in a different buffer, disable the nav history
13700 // to avoid creating a history entry at the previous cursor location.
13701 pane.update(cx, |pane, _| pane.disable_history());
13702 target_editor.go_to_singleton_buffer_range(range, window, cx);
13703 pane.update(cx, |pane, _| pane.enable_history());
13704 });
13705 });
13706 }
13707 Navigated::Yes
13708 })
13709 })
13710 } else if !definitions.is_empty() {
13711 cx.spawn_in(window, async move |editor, cx| {
13712 let (title, location_tasks, workspace) = editor
13713 .update_in(cx, |editor, window, cx| {
13714 let tab_kind = match kind {
13715 Some(GotoDefinitionKind::Implementation) => "Implementations",
13716 _ => "Definitions",
13717 };
13718 let title = definitions
13719 .iter()
13720 .find_map(|definition| match definition {
13721 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13722 let buffer = origin.buffer.read(cx);
13723 format!(
13724 "{} for {}",
13725 tab_kind,
13726 buffer
13727 .text_for_range(origin.range.clone())
13728 .collect::<String>()
13729 )
13730 }),
13731 HoverLink::InlayHint(_, _) => None,
13732 HoverLink::Url(_) => None,
13733 HoverLink::File(_) => None,
13734 })
13735 .unwrap_or(tab_kind.to_string());
13736 let location_tasks = definitions
13737 .into_iter()
13738 .map(|definition| match definition {
13739 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13740 HoverLink::InlayHint(lsp_location, server_id) => editor
13741 .compute_target_location(lsp_location, server_id, window, cx),
13742 HoverLink::Url(_) => Task::ready(Ok(None)),
13743 HoverLink::File(_) => Task::ready(Ok(None)),
13744 })
13745 .collect::<Vec<_>>();
13746 (title, location_tasks, editor.workspace().clone())
13747 })
13748 .context("location tasks preparation")?;
13749
13750 let locations = future::join_all(location_tasks)
13751 .await
13752 .into_iter()
13753 .filter_map(|location| location.transpose())
13754 .collect::<Result<_>>()
13755 .context("location tasks")?;
13756
13757 let Some(workspace) = workspace else {
13758 return Ok(Navigated::No);
13759 };
13760 let opened = workspace
13761 .update_in(cx, |workspace, window, cx| {
13762 Self::open_locations_in_multibuffer(
13763 workspace,
13764 locations,
13765 title,
13766 split,
13767 MultibufferSelectionMode::First,
13768 window,
13769 cx,
13770 )
13771 })
13772 .ok();
13773
13774 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13775 })
13776 } else {
13777 Task::ready(Ok(Navigated::No))
13778 }
13779 }
13780
13781 fn compute_target_location(
13782 &self,
13783 lsp_location: lsp::Location,
13784 server_id: LanguageServerId,
13785 window: &mut Window,
13786 cx: &mut Context<Self>,
13787 ) -> Task<anyhow::Result<Option<Location>>> {
13788 let Some(project) = self.project.clone() else {
13789 return Task::ready(Ok(None));
13790 };
13791
13792 cx.spawn_in(window, async move |editor, cx| {
13793 let location_task = editor.update(cx, |_, cx| {
13794 project.update(cx, |project, cx| {
13795 let language_server_name = project
13796 .language_server_statuses(cx)
13797 .find(|(id, _)| server_id == *id)
13798 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13799 language_server_name.map(|language_server_name| {
13800 project.open_local_buffer_via_lsp(
13801 lsp_location.uri.clone(),
13802 server_id,
13803 language_server_name,
13804 cx,
13805 )
13806 })
13807 })
13808 })?;
13809 let location = match location_task {
13810 Some(task) => Some({
13811 let target_buffer_handle = task.await.context("open local buffer")?;
13812 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13813 let target_start = target_buffer
13814 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13815 let target_end = target_buffer
13816 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13817 target_buffer.anchor_after(target_start)
13818 ..target_buffer.anchor_before(target_end)
13819 })?;
13820 Location {
13821 buffer: target_buffer_handle,
13822 range,
13823 }
13824 }),
13825 None => None,
13826 };
13827 Ok(location)
13828 })
13829 }
13830
13831 pub fn find_all_references(
13832 &mut self,
13833 _: &FindAllReferences,
13834 window: &mut Window,
13835 cx: &mut Context<Self>,
13836 ) -> Option<Task<Result<Navigated>>> {
13837 let selection = self.selections.newest::<usize>(cx);
13838 let multi_buffer = self.buffer.read(cx);
13839 let head = selection.head();
13840
13841 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13842 let head_anchor = multi_buffer_snapshot.anchor_at(
13843 head,
13844 if head < selection.tail() {
13845 Bias::Right
13846 } else {
13847 Bias::Left
13848 },
13849 );
13850
13851 match self
13852 .find_all_references_task_sources
13853 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13854 {
13855 Ok(_) => {
13856 log::info!(
13857 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13858 );
13859 return None;
13860 }
13861 Err(i) => {
13862 self.find_all_references_task_sources.insert(i, head_anchor);
13863 }
13864 }
13865
13866 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13867 let workspace = self.workspace()?;
13868 let project = workspace.read(cx).project().clone();
13869 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13870 Some(cx.spawn_in(window, async move |editor, cx| {
13871 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13872 if let Ok(i) = editor
13873 .find_all_references_task_sources
13874 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13875 {
13876 editor.find_all_references_task_sources.remove(i);
13877 }
13878 });
13879
13880 let locations = references.await?;
13881 if locations.is_empty() {
13882 return anyhow::Ok(Navigated::No);
13883 }
13884
13885 workspace.update_in(cx, |workspace, window, cx| {
13886 let title = locations
13887 .first()
13888 .as_ref()
13889 .map(|location| {
13890 let buffer = location.buffer.read(cx);
13891 format!(
13892 "References to `{}`",
13893 buffer
13894 .text_for_range(location.range.clone())
13895 .collect::<String>()
13896 )
13897 })
13898 .unwrap();
13899 Self::open_locations_in_multibuffer(
13900 workspace,
13901 locations,
13902 title,
13903 false,
13904 MultibufferSelectionMode::First,
13905 window,
13906 cx,
13907 );
13908 Navigated::Yes
13909 })
13910 }))
13911 }
13912
13913 /// Opens a multibuffer with the given project locations in it
13914 pub fn open_locations_in_multibuffer(
13915 workspace: &mut Workspace,
13916 mut locations: Vec<Location>,
13917 title: String,
13918 split: bool,
13919 multibuffer_selection_mode: MultibufferSelectionMode,
13920 window: &mut Window,
13921 cx: &mut Context<Workspace>,
13922 ) {
13923 // If there are multiple definitions, open them in a multibuffer
13924 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13925 let mut locations = locations.into_iter().peekable();
13926 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13927 let capability = workspace.project().read(cx).capability();
13928
13929 let excerpt_buffer = cx.new(|cx| {
13930 let mut multibuffer = MultiBuffer::new(capability);
13931 while let Some(location) = locations.next() {
13932 let buffer = location.buffer.read(cx);
13933 let mut ranges_for_buffer = Vec::new();
13934 let range = location.range.to_point(buffer);
13935 ranges_for_buffer.push(range.clone());
13936
13937 while let Some(next_location) = locations.peek() {
13938 if next_location.buffer == location.buffer {
13939 ranges_for_buffer.push(next_location.range.to_point(buffer));
13940 locations.next();
13941 } else {
13942 break;
13943 }
13944 }
13945
13946 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13947 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
13948 PathKey::for_buffer(&location.buffer, cx),
13949 location.buffer.clone(),
13950 ranges_for_buffer,
13951 DEFAULT_MULTIBUFFER_CONTEXT,
13952 cx,
13953 );
13954 ranges.extend(new_ranges)
13955 }
13956
13957 multibuffer.with_title(title)
13958 });
13959
13960 let editor = cx.new(|cx| {
13961 Editor::for_multibuffer(
13962 excerpt_buffer,
13963 Some(workspace.project().clone()),
13964 window,
13965 cx,
13966 )
13967 });
13968 editor.update(cx, |editor, cx| {
13969 match multibuffer_selection_mode {
13970 MultibufferSelectionMode::First => {
13971 if let Some(first_range) = ranges.first() {
13972 editor.change_selections(None, window, cx, |selections| {
13973 selections.clear_disjoint();
13974 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13975 });
13976 }
13977 editor.highlight_background::<Self>(
13978 &ranges,
13979 |theme| theme.editor_highlighted_line_background,
13980 cx,
13981 );
13982 }
13983 MultibufferSelectionMode::All => {
13984 editor.change_selections(None, window, cx, |selections| {
13985 selections.clear_disjoint();
13986 selections.select_anchor_ranges(ranges);
13987 });
13988 }
13989 }
13990 editor.register_buffers_with_language_servers(cx);
13991 });
13992
13993 let item = Box::new(editor);
13994 let item_id = item.item_id();
13995
13996 if split {
13997 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13998 } else {
13999 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14000 let (preview_item_id, preview_item_idx) =
14001 workspace.active_pane().update(cx, |pane, _| {
14002 (pane.preview_item_id(), pane.preview_item_idx())
14003 });
14004
14005 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14006
14007 if let Some(preview_item_id) = preview_item_id {
14008 workspace.active_pane().update(cx, |pane, cx| {
14009 pane.remove_item(preview_item_id, false, false, window, cx);
14010 });
14011 }
14012 } else {
14013 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14014 }
14015 }
14016 workspace.active_pane().update(cx, |pane, cx| {
14017 pane.set_preview_item_id(Some(item_id), cx);
14018 });
14019 }
14020
14021 pub fn rename(
14022 &mut self,
14023 _: &Rename,
14024 window: &mut Window,
14025 cx: &mut Context<Self>,
14026 ) -> Option<Task<Result<()>>> {
14027 use language::ToOffset as _;
14028
14029 let provider = self.semantics_provider.clone()?;
14030 let selection = self.selections.newest_anchor().clone();
14031 let (cursor_buffer, cursor_buffer_position) = self
14032 .buffer
14033 .read(cx)
14034 .text_anchor_for_position(selection.head(), cx)?;
14035 let (tail_buffer, cursor_buffer_position_end) = self
14036 .buffer
14037 .read(cx)
14038 .text_anchor_for_position(selection.tail(), cx)?;
14039 if tail_buffer != cursor_buffer {
14040 return None;
14041 }
14042
14043 let snapshot = cursor_buffer.read(cx).snapshot();
14044 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14045 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14046 let prepare_rename = provider
14047 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14048 .unwrap_or_else(|| Task::ready(Ok(None)));
14049 drop(snapshot);
14050
14051 Some(cx.spawn_in(window, async move |this, cx| {
14052 let rename_range = if let Some(range) = prepare_rename.await? {
14053 Some(range)
14054 } else {
14055 this.update(cx, |this, cx| {
14056 let buffer = this.buffer.read(cx).snapshot(cx);
14057 let mut buffer_highlights = this
14058 .document_highlights_for_position(selection.head(), &buffer)
14059 .filter(|highlight| {
14060 highlight.start.excerpt_id == selection.head().excerpt_id
14061 && highlight.end.excerpt_id == selection.head().excerpt_id
14062 });
14063 buffer_highlights
14064 .next()
14065 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14066 })?
14067 };
14068 if let Some(rename_range) = rename_range {
14069 this.update_in(cx, |this, window, cx| {
14070 let snapshot = cursor_buffer.read(cx).snapshot();
14071 let rename_buffer_range = rename_range.to_offset(&snapshot);
14072 let cursor_offset_in_rename_range =
14073 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14074 let cursor_offset_in_rename_range_end =
14075 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14076
14077 this.take_rename(false, window, cx);
14078 let buffer = this.buffer.read(cx).read(cx);
14079 let cursor_offset = selection.head().to_offset(&buffer);
14080 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14081 let rename_end = rename_start + rename_buffer_range.len();
14082 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14083 let mut old_highlight_id = None;
14084 let old_name: Arc<str> = buffer
14085 .chunks(rename_start..rename_end, true)
14086 .map(|chunk| {
14087 if old_highlight_id.is_none() {
14088 old_highlight_id = chunk.syntax_highlight_id;
14089 }
14090 chunk.text
14091 })
14092 .collect::<String>()
14093 .into();
14094
14095 drop(buffer);
14096
14097 // Position the selection in the rename editor so that it matches the current selection.
14098 this.show_local_selections = false;
14099 let rename_editor = cx.new(|cx| {
14100 let mut editor = Editor::single_line(window, cx);
14101 editor.buffer.update(cx, |buffer, cx| {
14102 buffer.edit([(0..0, old_name.clone())], None, cx)
14103 });
14104 let rename_selection_range = match cursor_offset_in_rename_range
14105 .cmp(&cursor_offset_in_rename_range_end)
14106 {
14107 Ordering::Equal => {
14108 editor.select_all(&SelectAll, window, cx);
14109 return editor;
14110 }
14111 Ordering::Less => {
14112 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14113 }
14114 Ordering::Greater => {
14115 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14116 }
14117 };
14118 if rename_selection_range.end > old_name.len() {
14119 editor.select_all(&SelectAll, window, cx);
14120 } else {
14121 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14122 s.select_ranges([rename_selection_range]);
14123 });
14124 }
14125 editor
14126 });
14127 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14128 if e == &EditorEvent::Focused {
14129 cx.emit(EditorEvent::FocusedIn)
14130 }
14131 })
14132 .detach();
14133
14134 let write_highlights =
14135 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14136 let read_highlights =
14137 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14138 let ranges = write_highlights
14139 .iter()
14140 .flat_map(|(_, ranges)| ranges.iter())
14141 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14142 .cloned()
14143 .collect();
14144
14145 this.highlight_text::<Rename>(
14146 ranges,
14147 HighlightStyle {
14148 fade_out: Some(0.6),
14149 ..Default::default()
14150 },
14151 cx,
14152 );
14153 let rename_focus_handle = rename_editor.focus_handle(cx);
14154 window.focus(&rename_focus_handle);
14155 let block_id = this.insert_blocks(
14156 [BlockProperties {
14157 style: BlockStyle::Flex,
14158 placement: BlockPlacement::Below(range.start),
14159 height: Some(1),
14160 render: Arc::new({
14161 let rename_editor = rename_editor.clone();
14162 move |cx: &mut BlockContext| {
14163 let mut text_style = cx.editor_style.text.clone();
14164 if let Some(highlight_style) = old_highlight_id
14165 .and_then(|h| h.style(&cx.editor_style.syntax))
14166 {
14167 text_style = text_style.highlight(highlight_style);
14168 }
14169 div()
14170 .block_mouse_down()
14171 .pl(cx.anchor_x)
14172 .child(EditorElement::new(
14173 &rename_editor,
14174 EditorStyle {
14175 background: cx.theme().system().transparent,
14176 local_player: cx.editor_style.local_player,
14177 text: text_style,
14178 scrollbar_width: cx.editor_style.scrollbar_width,
14179 syntax: cx.editor_style.syntax.clone(),
14180 status: cx.editor_style.status.clone(),
14181 inlay_hints_style: HighlightStyle {
14182 font_weight: Some(FontWeight::BOLD),
14183 ..make_inlay_hints_style(cx.app)
14184 },
14185 inline_completion_styles: make_suggestion_styles(
14186 cx.app,
14187 ),
14188 ..EditorStyle::default()
14189 },
14190 ))
14191 .into_any_element()
14192 }
14193 }),
14194 priority: 0,
14195 }],
14196 Some(Autoscroll::fit()),
14197 cx,
14198 )[0];
14199 this.pending_rename = Some(RenameState {
14200 range,
14201 old_name,
14202 editor: rename_editor,
14203 block_id,
14204 });
14205 })?;
14206 }
14207
14208 Ok(())
14209 }))
14210 }
14211
14212 pub fn confirm_rename(
14213 &mut self,
14214 _: &ConfirmRename,
14215 window: &mut Window,
14216 cx: &mut Context<Self>,
14217 ) -> Option<Task<Result<()>>> {
14218 let rename = self.take_rename(false, window, cx)?;
14219 let workspace = self.workspace()?.downgrade();
14220 let (buffer, start) = self
14221 .buffer
14222 .read(cx)
14223 .text_anchor_for_position(rename.range.start, cx)?;
14224 let (end_buffer, _) = self
14225 .buffer
14226 .read(cx)
14227 .text_anchor_for_position(rename.range.end, cx)?;
14228 if buffer != end_buffer {
14229 return None;
14230 }
14231
14232 let old_name = rename.old_name;
14233 let new_name = rename.editor.read(cx).text(cx);
14234
14235 let rename = self.semantics_provider.as_ref()?.perform_rename(
14236 &buffer,
14237 start,
14238 new_name.clone(),
14239 cx,
14240 )?;
14241
14242 Some(cx.spawn_in(window, async move |editor, cx| {
14243 let project_transaction = rename.await?;
14244 Self::open_project_transaction(
14245 &editor,
14246 workspace,
14247 project_transaction,
14248 format!("Rename: {} → {}", old_name, new_name),
14249 cx,
14250 )
14251 .await?;
14252
14253 editor.update(cx, |editor, cx| {
14254 editor.refresh_document_highlights(cx);
14255 })?;
14256 Ok(())
14257 }))
14258 }
14259
14260 fn take_rename(
14261 &mut self,
14262 moving_cursor: bool,
14263 window: &mut Window,
14264 cx: &mut Context<Self>,
14265 ) -> Option<RenameState> {
14266 let rename = self.pending_rename.take()?;
14267 if rename.editor.focus_handle(cx).is_focused(window) {
14268 window.focus(&self.focus_handle);
14269 }
14270
14271 self.remove_blocks(
14272 [rename.block_id].into_iter().collect(),
14273 Some(Autoscroll::fit()),
14274 cx,
14275 );
14276 self.clear_highlights::<Rename>(cx);
14277 self.show_local_selections = true;
14278
14279 if moving_cursor {
14280 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14281 editor.selections.newest::<usize>(cx).head()
14282 });
14283
14284 // Update the selection to match the position of the selection inside
14285 // the rename editor.
14286 let snapshot = self.buffer.read(cx).read(cx);
14287 let rename_range = rename.range.to_offset(&snapshot);
14288 let cursor_in_editor = snapshot
14289 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14290 .min(rename_range.end);
14291 drop(snapshot);
14292
14293 self.change_selections(None, window, cx, |s| {
14294 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14295 });
14296 } else {
14297 self.refresh_document_highlights(cx);
14298 }
14299
14300 Some(rename)
14301 }
14302
14303 pub fn pending_rename(&self) -> Option<&RenameState> {
14304 self.pending_rename.as_ref()
14305 }
14306
14307 fn format(
14308 &mut self,
14309 _: &Format,
14310 window: &mut Window,
14311 cx: &mut Context<Self>,
14312 ) -> Option<Task<Result<()>>> {
14313 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14314
14315 let project = match &self.project {
14316 Some(project) => project.clone(),
14317 None => return None,
14318 };
14319
14320 Some(self.perform_format(
14321 project,
14322 FormatTrigger::Manual,
14323 FormatTarget::Buffers,
14324 window,
14325 cx,
14326 ))
14327 }
14328
14329 fn format_selections(
14330 &mut self,
14331 _: &FormatSelections,
14332 window: &mut Window,
14333 cx: &mut Context<Self>,
14334 ) -> Option<Task<Result<()>>> {
14335 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14336
14337 let project = match &self.project {
14338 Some(project) => project.clone(),
14339 None => return None,
14340 };
14341
14342 let ranges = self
14343 .selections
14344 .all_adjusted(cx)
14345 .into_iter()
14346 .map(|selection| selection.range())
14347 .collect_vec();
14348
14349 Some(self.perform_format(
14350 project,
14351 FormatTrigger::Manual,
14352 FormatTarget::Ranges(ranges),
14353 window,
14354 cx,
14355 ))
14356 }
14357
14358 fn perform_format(
14359 &mut self,
14360 project: Entity<Project>,
14361 trigger: FormatTrigger,
14362 target: FormatTarget,
14363 window: &mut Window,
14364 cx: &mut Context<Self>,
14365 ) -> Task<Result<()>> {
14366 let buffer = self.buffer.clone();
14367 let (buffers, target) = match target {
14368 FormatTarget::Buffers => {
14369 let mut buffers = buffer.read(cx).all_buffers();
14370 if trigger == FormatTrigger::Save {
14371 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14372 }
14373 (buffers, LspFormatTarget::Buffers)
14374 }
14375 FormatTarget::Ranges(selection_ranges) => {
14376 let multi_buffer = buffer.read(cx);
14377 let snapshot = multi_buffer.read(cx);
14378 let mut buffers = HashSet::default();
14379 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14380 BTreeMap::new();
14381 for selection_range in selection_ranges {
14382 for (buffer, buffer_range, _) in
14383 snapshot.range_to_buffer_ranges(selection_range)
14384 {
14385 let buffer_id = buffer.remote_id();
14386 let start = buffer.anchor_before(buffer_range.start);
14387 let end = buffer.anchor_after(buffer_range.end);
14388 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14389 buffer_id_to_ranges
14390 .entry(buffer_id)
14391 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14392 .or_insert_with(|| vec![start..end]);
14393 }
14394 }
14395 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14396 }
14397 };
14398
14399 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14400 let selections_prev = transaction_id_prev
14401 .and_then(|transaction_id_prev| {
14402 // default to selections as they were after the last edit, if we have them,
14403 // instead of how they are now.
14404 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14405 // will take you back to where you made the last edit, instead of staying where you scrolled
14406 self.selection_history
14407 .transaction(transaction_id_prev)
14408 .map(|t| t.0.clone())
14409 })
14410 .unwrap_or_else(|| {
14411 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14412 self.selections.disjoint_anchors()
14413 });
14414
14415 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14416 let format = project.update(cx, |project, cx| {
14417 project.format(buffers, target, true, trigger, cx)
14418 });
14419
14420 cx.spawn_in(window, async move |editor, cx| {
14421 let transaction = futures::select_biased! {
14422 transaction = format.log_err().fuse() => transaction,
14423 () = timeout => {
14424 log::warn!("timed out waiting for formatting");
14425 None
14426 }
14427 };
14428
14429 buffer
14430 .update(cx, |buffer, cx| {
14431 if let Some(transaction) = transaction {
14432 if !buffer.is_singleton() {
14433 buffer.push_transaction(&transaction.0, cx);
14434 }
14435 }
14436 cx.notify();
14437 })
14438 .ok();
14439
14440 if let Some(transaction_id_now) =
14441 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14442 {
14443 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14444 if has_new_transaction {
14445 _ = editor.update(cx, |editor, _| {
14446 editor
14447 .selection_history
14448 .insert_transaction(transaction_id_now, selections_prev);
14449 });
14450 }
14451 }
14452
14453 Ok(())
14454 })
14455 }
14456
14457 fn organize_imports(
14458 &mut self,
14459 _: &OrganizeImports,
14460 window: &mut Window,
14461 cx: &mut Context<Self>,
14462 ) -> Option<Task<Result<()>>> {
14463 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14464 let project = match &self.project {
14465 Some(project) => project.clone(),
14466 None => return None,
14467 };
14468 Some(self.perform_code_action_kind(
14469 project,
14470 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14471 window,
14472 cx,
14473 ))
14474 }
14475
14476 fn perform_code_action_kind(
14477 &mut self,
14478 project: Entity<Project>,
14479 kind: CodeActionKind,
14480 window: &mut Window,
14481 cx: &mut Context<Self>,
14482 ) -> Task<Result<()>> {
14483 let buffer = self.buffer.clone();
14484 let buffers = buffer.read(cx).all_buffers();
14485 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14486 let apply_action = project.update(cx, |project, cx| {
14487 project.apply_code_action_kind(buffers, kind, true, cx)
14488 });
14489 cx.spawn_in(window, async move |_, cx| {
14490 let transaction = futures::select_biased! {
14491 () = timeout => {
14492 log::warn!("timed out waiting for executing code action");
14493 None
14494 }
14495 transaction = apply_action.log_err().fuse() => transaction,
14496 };
14497 buffer
14498 .update(cx, |buffer, cx| {
14499 // check if we need this
14500 if let Some(transaction) = transaction {
14501 if !buffer.is_singleton() {
14502 buffer.push_transaction(&transaction.0, cx);
14503 }
14504 }
14505 cx.notify();
14506 })
14507 .ok();
14508 Ok(())
14509 })
14510 }
14511
14512 fn restart_language_server(
14513 &mut self,
14514 _: &RestartLanguageServer,
14515 _: &mut Window,
14516 cx: &mut Context<Self>,
14517 ) {
14518 if let Some(project) = self.project.clone() {
14519 self.buffer.update(cx, |multi_buffer, cx| {
14520 project.update(cx, |project, cx| {
14521 project.restart_language_servers_for_buffers(
14522 multi_buffer.all_buffers().into_iter().collect(),
14523 cx,
14524 );
14525 });
14526 })
14527 }
14528 }
14529
14530 fn stop_language_server(
14531 &mut self,
14532 _: &StopLanguageServer,
14533 _: &mut Window,
14534 cx: &mut Context<Self>,
14535 ) {
14536 if let Some(project) = self.project.clone() {
14537 self.buffer.update(cx, |multi_buffer, cx| {
14538 project.update(cx, |project, cx| {
14539 project.stop_language_servers_for_buffers(
14540 multi_buffer.all_buffers().into_iter().collect(),
14541 cx,
14542 );
14543 cx.emit(project::Event::RefreshInlayHints);
14544 });
14545 });
14546 }
14547 }
14548
14549 fn cancel_language_server_work(
14550 workspace: &mut Workspace,
14551 _: &actions::CancelLanguageServerWork,
14552 _: &mut Window,
14553 cx: &mut Context<Workspace>,
14554 ) {
14555 let project = workspace.project();
14556 let buffers = workspace
14557 .active_item(cx)
14558 .and_then(|item| item.act_as::<Editor>(cx))
14559 .map_or(HashSet::default(), |editor| {
14560 editor.read(cx).buffer.read(cx).all_buffers()
14561 });
14562 project.update(cx, |project, cx| {
14563 project.cancel_language_server_work_for_buffers(buffers, cx);
14564 });
14565 }
14566
14567 fn show_character_palette(
14568 &mut self,
14569 _: &ShowCharacterPalette,
14570 window: &mut Window,
14571 _: &mut Context<Self>,
14572 ) {
14573 window.show_character_palette();
14574 }
14575
14576 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14577 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14578 let buffer = self.buffer.read(cx).snapshot(cx);
14579 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14580 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14581 let is_valid = buffer
14582 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14583 .any(|entry| {
14584 entry.diagnostic.is_primary
14585 && !entry.range.is_empty()
14586 && entry.range.start == primary_range_start
14587 && entry.diagnostic.message == active_diagnostics.active_message
14588 });
14589
14590 if !is_valid {
14591 self.dismiss_diagnostics(cx);
14592 }
14593 }
14594 }
14595
14596 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14597 match &self.active_diagnostics {
14598 ActiveDiagnostic::Group(group) => Some(group),
14599 _ => None,
14600 }
14601 }
14602
14603 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14604 self.dismiss_diagnostics(cx);
14605 self.active_diagnostics = ActiveDiagnostic::All;
14606 }
14607
14608 fn activate_diagnostics(
14609 &mut self,
14610 buffer_id: BufferId,
14611 diagnostic: DiagnosticEntry<usize>,
14612 window: &mut Window,
14613 cx: &mut Context<Self>,
14614 ) {
14615 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14616 return;
14617 }
14618 self.dismiss_diagnostics(cx);
14619 let snapshot = self.snapshot(window, cx);
14620 let Some(diagnostic_renderer) = cx
14621 .try_global::<GlobalDiagnosticRenderer>()
14622 .map(|g| g.0.clone())
14623 else {
14624 return;
14625 };
14626 let buffer = self.buffer.read(cx).snapshot(cx);
14627
14628 let diagnostic_group = buffer
14629 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14630 .collect::<Vec<_>>();
14631
14632 let blocks = diagnostic_renderer.render_group(
14633 diagnostic_group,
14634 buffer_id,
14635 snapshot,
14636 cx.weak_entity(),
14637 cx,
14638 );
14639
14640 let blocks = self.display_map.update(cx, |display_map, cx| {
14641 display_map.insert_blocks(blocks, cx).into_iter().collect()
14642 });
14643 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14644 active_range: buffer.anchor_before(diagnostic.range.start)
14645 ..buffer.anchor_after(diagnostic.range.end),
14646 active_message: diagnostic.diagnostic.message.clone(),
14647 group_id: diagnostic.diagnostic.group_id,
14648 blocks,
14649 });
14650 cx.notify();
14651 }
14652
14653 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14654 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14655 return;
14656 };
14657
14658 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14659 if let ActiveDiagnostic::Group(group) = prev {
14660 self.display_map.update(cx, |display_map, cx| {
14661 display_map.remove_blocks(group.blocks, cx);
14662 });
14663 cx.notify();
14664 }
14665 }
14666
14667 /// Disable inline diagnostics rendering for this editor.
14668 pub fn disable_inline_diagnostics(&mut self) {
14669 self.inline_diagnostics_enabled = false;
14670 self.inline_diagnostics_update = Task::ready(());
14671 self.inline_diagnostics.clear();
14672 }
14673
14674 pub fn inline_diagnostics_enabled(&self) -> bool {
14675 self.inline_diagnostics_enabled
14676 }
14677
14678 pub fn show_inline_diagnostics(&self) -> bool {
14679 self.show_inline_diagnostics
14680 }
14681
14682 pub fn toggle_inline_diagnostics(
14683 &mut self,
14684 _: &ToggleInlineDiagnostics,
14685 window: &mut Window,
14686 cx: &mut Context<Editor>,
14687 ) {
14688 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14689 self.refresh_inline_diagnostics(false, window, cx);
14690 }
14691
14692 fn refresh_inline_diagnostics(
14693 &mut self,
14694 debounce: bool,
14695 window: &mut Window,
14696 cx: &mut Context<Self>,
14697 ) {
14698 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14699 self.inline_diagnostics_update = Task::ready(());
14700 self.inline_diagnostics.clear();
14701 return;
14702 }
14703
14704 let debounce_ms = ProjectSettings::get_global(cx)
14705 .diagnostics
14706 .inline
14707 .update_debounce_ms;
14708 let debounce = if debounce && debounce_ms > 0 {
14709 Some(Duration::from_millis(debounce_ms))
14710 } else {
14711 None
14712 };
14713 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14714 let editor = editor.upgrade().unwrap();
14715
14716 if let Some(debounce) = debounce {
14717 cx.background_executor().timer(debounce).await;
14718 }
14719 let Some(snapshot) = editor
14720 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14721 .ok()
14722 else {
14723 return;
14724 };
14725
14726 let new_inline_diagnostics = cx
14727 .background_spawn(async move {
14728 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14729 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14730 let message = diagnostic_entry
14731 .diagnostic
14732 .message
14733 .split_once('\n')
14734 .map(|(line, _)| line)
14735 .map(SharedString::new)
14736 .unwrap_or_else(|| {
14737 SharedString::from(diagnostic_entry.diagnostic.message)
14738 });
14739 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14740 let (Ok(i) | Err(i)) = inline_diagnostics
14741 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14742 inline_diagnostics.insert(
14743 i,
14744 (
14745 start_anchor,
14746 InlineDiagnostic {
14747 message,
14748 group_id: diagnostic_entry.diagnostic.group_id,
14749 start: diagnostic_entry.range.start.to_point(&snapshot),
14750 is_primary: diagnostic_entry.diagnostic.is_primary,
14751 severity: diagnostic_entry.diagnostic.severity,
14752 },
14753 ),
14754 );
14755 }
14756 inline_diagnostics
14757 })
14758 .await;
14759
14760 editor
14761 .update(cx, |editor, cx| {
14762 editor.inline_diagnostics = new_inline_diagnostics;
14763 cx.notify();
14764 })
14765 .ok();
14766 });
14767 }
14768
14769 pub fn set_selections_from_remote(
14770 &mut self,
14771 selections: Vec<Selection<Anchor>>,
14772 pending_selection: Option<Selection<Anchor>>,
14773 window: &mut Window,
14774 cx: &mut Context<Self>,
14775 ) {
14776 let old_cursor_position = self.selections.newest_anchor().head();
14777 self.selections.change_with(cx, |s| {
14778 s.select_anchors(selections);
14779 if let Some(pending_selection) = pending_selection {
14780 s.set_pending(pending_selection, SelectMode::Character);
14781 } else {
14782 s.clear_pending();
14783 }
14784 });
14785 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14786 }
14787
14788 fn push_to_selection_history(&mut self) {
14789 self.selection_history.push(SelectionHistoryEntry {
14790 selections: self.selections.disjoint_anchors(),
14791 select_next_state: self.select_next_state.clone(),
14792 select_prev_state: self.select_prev_state.clone(),
14793 add_selections_state: self.add_selections_state.clone(),
14794 });
14795 }
14796
14797 pub fn transact(
14798 &mut self,
14799 window: &mut Window,
14800 cx: &mut Context<Self>,
14801 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14802 ) -> Option<TransactionId> {
14803 self.start_transaction_at(Instant::now(), window, cx);
14804 update(self, window, cx);
14805 self.end_transaction_at(Instant::now(), cx)
14806 }
14807
14808 pub fn start_transaction_at(
14809 &mut self,
14810 now: Instant,
14811 window: &mut Window,
14812 cx: &mut Context<Self>,
14813 ) {
14814 self.end_selection(window, cx);
14815 if let Some(tx_id) = self
14816 .buffer
14817 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14818 {
14819 self.selection_history
14820 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14821 cx.emit(EditorEvent::TransactionBegun {
14822 transaction_id: tx_id,
14823 })
14824 }
14825 }
14826
14827 pub fn end_transaction_at(
14828 &mut self,
14829 now: Instant,
14830 cx: &mut Context<Self>,
14831 ) -> Option<TransactionId> {
14832 if let Some(transaction_id) = self
14833 .buffer
14834 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14835 {
14836 if let Some((_, end_selections)) =
14837 self.selection_history.transaction_mut(transaction_id)
14838 {
14839 *end_selections = Some(self.selections.disjoint_anchors());
14840 } else {
14841 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14842 }
14843
14844 cx.emit(EditorEvent::Edited { transaction_id });
14845 Some(transaction_id)
14846 } else {
14847 None
14848 }
14849 }
14850
14851 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14852 if self.selection_mark_mode {
14853 self.change_selections(None, window, cx, |s| {
14854 s.move_with(|_, sel| {
14855 sel.collapse_to(sel.head(), SelectionGoal::None);
14856 });
14857 })
14858 }
14859 self.selection_mark_mode = true;
14860 cx.notify();
14861 }
14862
14863 pub fn swap_selection_ends(
14864 &mut self,
14865 _: &actions::SwapSelectionEnds,
14866 window: &mut Window,
14867 cx: &mut Context<Self>,
14868 ) {
14869 self.change_selections(None, window, cx, |s| {
14870 s.move_with(|_, sel| {
14871 if sel.start != sel.end {
14872 sel.reversed = !sel.reversed
14873 }
14874 });
14875 });
14876 self.request_autoscroll(Autoscroll::newest(), cx);
14877 cx.notify();
14878 }
14879
14880 pub fn toggle_fold(
14881 &mut self,
14882 _: &actions::ToggleFold,
14883 window: &mut Window,
14884 cx: &mut Context<Self>,
14885 ) {
14886 if self.is_singleton(cx) {
14887 let selection = self.selections.newest::<Point>(cx);
14888
14889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14890 let range = if selection.is_empty() {
14891 let point = selection.head().to_display_point(&display_map);
14892 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14893 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14894 .to_point(&display_map);
14895 start..end
14896 } else {
14897 selection.range()
14898 };
14899 if display_map.folds_in_range(range).next().is_some() {
14900 self.unfold_lines(&Default::default(), window, cx)
14901 } else {
14902 self.fold(&Default::default(), window, cx)
14903 }
14904 } else {
14905 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14906 let buffer_ids: HashSet<_> = self
14907 .selections
14908 .disjoint_anchor_ranges()
14909 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14910 .collect();
14911
14912 let should_unfold = buffer_ids
14913 .iter()
14914 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14915
14916 for buffer_id in buffer_ids {
14917 if should_unfold {
14918 self.unfold_buffer(buffer_id, cx);
14919 } else {
14920 self.fold_buffer(buffer_id, cx);
14921 }
14922 }
14923 }
14924 }
14925
14926 pub fn toggle_fold_recursive(
14927 &mut self,
14928 _: &actions::ToggleFoldRecursive,
14929 window: &mut Window,
14930 cx: &mut Context<Self>,
14931 ) {
14932 let selection = self.selections.newest::<Point>(cx);
14933
14934 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14935 let range = if selection.is_empty() {
14936 let point = selection.head().to_display_point(&display_map);
14937 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14938 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14939 .to_point(&display_map);
14940 start..end
14941 } else {
14942 selection.range()
14943 };
14944 if display_map.folds_in_range(range).next().is_some() {
14945 self.unfold_recursive(&Default::default(), window, cx)
14946 } else {
14947 self.fold_recursive(&Default::default(), window, cx)
14948 }
14949 }
14950
14951 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14952 if self.is_singleton(cx) {
14953 let mut to_fold = Vec::new();
14954 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14955 let selections = self.selections.all_adjusted(cx);
14956
14957 for selection in selections {
14958 let range = selection.range().sorted();
14959 let buffer_start_row = range.start.row;
14960
14961 if range.start.row != range.end.row {
14962 let mut found = false;
14963 let mut row = range.start.row;
14964 while row <= range.end.row {
14965 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14966 {
14967 found = true;
14968 row = crease.range().end.row + 1;
14969 to_fold.push(crease);
14970 } else {
14971 row += 1
14972 }
14973 }
14974 if found {
14975 continue;
14976 }
14977 }
14978
14979 for row in (0..=range.start.row).rev() {
14980 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14981 if crease.range().end.row >= buffer_start_row {
14982 to_fold.push(crease);
14983 if row <= range.start.row {
14984 break;
14985 }
14986 }
14987 }
14988 }
14989 }
14990
14991 self.fold_creases(to_fold, true, window, cx);
14992 } else {
14993 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14994 let buffer_ids = self
14995 .selections
14996 .disjoint_anchor_ranges()
14997 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14998 .collect::<HashSet<_>>();
14999 for buffer_id in buffer_ids {
15000 self.fold_buffer(buffer_id, cx);
15001 }
15002 }
15003 }
15004
15005 fn fold_at_level(
15006 &mut self,
15007 fold_at: &FoldAtLevel,
15008 window: &mut Window,
15009 cx: &mut Context<Self>,
15010 ) {
15011 if !self.buffer.read(cx).is_singleton() {
15012 return;
15013 }
15014
15015 let fold_at_level = fold_at.0;
15016 let snapshot = self.buffer.read(cx).snapshot(cx);
15017 let mut to_fold = Vec::new();
15018 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15019
15020 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15021 while start_row < end_row {
15022 match self
15023 .snapshot(window, cx)
15024 .crease_for_buffer_row(MultiBufferRow(start_row))
15025 {
15026 Some(crease) => {
15027 let nested_start_row = crease.range().start.row + 1;
15028 let nested_end_row = crease.range().end.row;
15029
15030 if current_level < fold_at_level {
15031 stack.push((nested_start_row, nested_end_row, current_level + 1));
15032 } else if current_level == fold_at_level {
15033 to_fold.push(crease);
15034 }
15035
15036 start_row = nested_end_row + 1;
15037 }
15038 None => start_row += 1,
15039 }
15040 }
15041 }
15042
15043 self.fold_creases(to_fold, true, window, cx);
15044 }
15045
15046 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15047 if self.buffer.read(cx).is_singleton() {
15048 let mut fold_ranges = Vec::new();
15049 let snapshot = self.buffer.read(cx).snapshot(cx);
15050
15051 for row in 0..snapshot.max_row().0 {
15052 if let Some(foldable_range) = self
15053 .snapshot(window, cx)
15054 .crease_for_buffer_row(MultiBufferRow(row))
15055 {
15056 fold_ranges.push(foldable_range);
15057 }
15058 }
15059
15060 self.fold_creases(fold_ranges, true, window, cx);
15061 } else {
15062 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15063 editor
15064 .update_in(cx, |editor, _, cx| {
15065 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15066 editor.fold_buffer(buffer_id, cx);
15067 }
15068 })
15069 .ok();
15070 });
15071 }
15072 }
15073
15074 pub fn fold_function_bodies(
15075 &mut self,
15076 _: &actions::FoldFunctionBodies,
15077 window: &mut Window,
15078 cx: &mut Context<Self>,
15079 ) {
15080 let snapshot = self.buffer.read(cx).snapshot(cx);
15081
15082 let ranges = snapshot
15083 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15084 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15085 .collect::<Vec<_>>();
15086
15087 let creases = ranges
15088 .into_iter()
15089 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15090 .collect();
15091
15092 self.fold_creases(creases, true, window, cx);
15093 }
15094
15095 pub fn fold_recursive(
15096 &mut self,
15097 _: &actions::FoldRecursive,
15098 window: &mut Window,
15099 cx: &mut Context<Self>,
15100 ) {
15101 let mut to_fold = Vec::new();
15102 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15103 let selections = self.selections.all_adjusted(cx);
15104
15105 for selection in selections {
15106 let range = selection.range().sorted();
15107 let buffer_start_row = range.start.row;
15108
15109 if range.start.row != range.end.row {
15110 let mut found = false;
15111 for row in range.start.row..=range.end.row {
15112 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15113 found = true;
15114 to_fold.push(crease);
15115 }
15116 }
15117 if found {
15118 continue;
15119 }
15120 }
15121
15122 for row in (0..=range.start.row).rev() {
15123 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15124 if crease.range().end.row >= buffer_start_row {
15125 to_fold.push(crease);
15126 } else {
15127 break;
15128 }
15129 }
15130 }
15131 }
15132
15133 self.fold_creases(to_fold, true, window, cx);
15134 }
15135
15136 pub fn fold_at(
15137 &mut self,
15138 buffer_row: MultiBufferRow,
15139 window: &mut Window,
15140 cx: &mut Context<Self>,
15141 ) {
15142 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15143
15144 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15145 let autoscroll = self
15146 .selections
15147 .all::<Point>(cx)
15148 .iter()
15149 .any(|selection| crease.range().overlaps(&selection.range()));
15150
15151 self.fold_creases(vec![crease], autoscroll, window, cx);
15152 }
15153 }
15154
15155 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15156 if self.is_singleton(cx) {
15157 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15158 let buffer = &display_map.buffer_snapshot;
15159 let selections = self.selections.all::<Point>(cx);
15160 let ranges = selections
15161 .iter()
15162 .map(|s| {
15163 let range = s.display_range(&display_map).sorted();
15164 let mut start = range.start.to_point(&display_map);
15165 let mut end = range.end.to_point(&display_map);
15166 start.column = 0;
15167 end.column = buffer.line_len(MultiBufferRow(end.row));
15168 start..end
15169 })
15170 .collect::<Vec<_>>();
15171
15172 self.unfold_ranges(&ranges, true, true, cx);
15173 } else {
15174 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15175 let buffer_ids = self
15176 .selections
15177 .disjoint_anchor_ranges()
15178 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15179 .collect::<HashSet<_>>();
15180 for buffer_id in buffer_ids {
15181 self.unfold_buffer(buffer_id, cx);
15182 }
15183 }
15184 }
15185
15186 pub fn unfold_recursive(
15187 &mut self,
15188 _: &UnfoldRecursive,
15189 _window: &mut Window,
15190 cx: &mut Context<Self>,
15191 ) {
15192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15193 let selections = self.selections.all::<Point>(cx);
15194 let ranges = selections
15195 .iter()
15196 .map(|s| {
15197 let mut range = s.display_range(&display_map).sorted();
15198 *range.start.column_mut() = 0;
15199 *range.end.column_mut() = display_map.line_len(range.end.row());
15200 let start = range.start.to_point(&display_map);
15201 let end = range.end.to_point(&display_map);
15202 start..end
15203 })
15204 .collect::<Vec<_>>();
15205
15206 self.unfold_ranges(&ranges, true, true, cx);
15207 }
15208
15209 pub fn unfold_at(
15210 &mut self,
15211 buffer_row: MultiBufferRow,
15212 _window: &mut Window,
15213 cx: &mut Context<Self>,
15214 ) {
15215 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15216
15217 let intersection_range = Point::new(buffer_row.0, 0)
15218 ..Point::new(
15219 buffer_row.0,
15220 display_map.buffer_snapshot.line_len(buffer_row),
15221 );
15222
15223 let autoscroll = self
15224 .selections
15225 .all::<Point>(cx)
15226 .iter()
15227 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15228
15229 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15230 }
15231
15232 pub fn unfold_all(
15233 &mut self,
15234 _: &actions::UnfoldAll,
15235 _window: &mut Window,
15236 cx: &mut Context<Self>,
15237 ) {
15238 if self.buffer.read(cx).is_singleton() {
15239 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15240 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15241 } else {
15242 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15243 editor
15244 .update(cx, |editor, cx| {
15245 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15246 editor.unfold_buffer(buffer_id, cx);
15247 }
15248 })
15249 .ok();
15250 });
15251 }
15252 }
15253
15254 pub fn fold_selected_ranges(
15255 &mut self,
15256 _: &FoldSelectedRanges,
15257 window: &mut Window,
15258 cx: &mut Context<Self>,
15259 ) {
15260 let selections = self.selections.all_adjusted(cx);
15261 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15262 let ranges = selections
15263 .into_iter()
15264 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15265 .collect::<Vec<_>>();
15266 self.fold_creases(ranges, true, window, cx);
15267 }
15268
15269 pub fn fold_ranges<T: ToOffset + Clone>(
15270 &mut self,
15271 ranges: Vec<Range<T>>,
15272 auto_scroll: bool,
15273 window: &mut Window,
15274 cx: &mut Context<Self>,
15275 ) {
15276 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15277 let ranges = ranges
15278 .into_iter()
15279 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15280 .collect::<Vec<_>>();
15281 self.fold_creases(ranges, auto_scroll, window, cx);
15282 }
15283
15284 pub fn fold_creases<T: ToOffset + Clone>(
15285 &mut self,
15286 creases: Vec<Crease<T>>,
15287 auto_scroll: bool,
15288 _window: &mut Window,
15289 cx: &mut Context<Self>,
15290 ) {
15291 if creases.is_empty() {
15292 return;
15293 }
15294
15295 let mut buffers_affected = HashSet::default();
15296 let multi_buffer = self.buffer().read(cx);
15297 for crease in &creases {
15298 if let Some((_, buffer, _)) =
15299 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15300 {
15301 buffers_affected.insert(buffer.read(cx).remote_id());
15302 };
15303 }
15304
15305 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15306
15307 if auto_scroll {
15308 self.request_autoscroll(Autoscroll::fit(), cx);
15309 }
15310
15311 cx.notify();
15312
15313 self.scrollbar_marker_state.dirty = true;
15314 self.folds_did_change(cx);
15315 }
15316
15317 /// Removes any folds whose ranges intersect any of the given ranges.
15318 pub fn unfold_ranges<T: ToOffset + Clone>(
15319 &mut self,
15320 ranges: &[Range<T>],
15321 inclusive: bool,
15322 auto_scroll: bool,
15323 cx: &mut Context<Self>,
15324 ) {
15325 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15326 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15327 });
15328 self.folds_did_change(cx);
15329 }
15330
15331 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15332 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15333 return;
15334 }
15335 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15336 self.display_map.update(cx, |display_map, cx| {
15337 display_map.fold_buffers([buffer_id], cx)
15338 });
15339 cx.emit(EditorEvent::BufferFoldToggled {
15340 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15341 folded: true,
15342 });
15343 cx.notify();
15344 }
15345
15346 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15347 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15348 return;
15349 }
15350 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15351 self.display_map.update(cx, |display_map, cx| {
15352 display_map.unfold_buffers([buffer_id], cx);
15353 });
15354 cx.emit(EditorEvent::BufferFoldToggled {
15355 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15356 folded: false,
15357 });
15358 cx.notify();
15359 }
15360
15361 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15362 self.display_map.read(cx).is_buffer_folded(buffer)
15363 }
15364
15365 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15366 self.display_map.read(cx).folded_buffers()
15367 }
15368
15369 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15370 self.display_map.update(cx, |display_map, cx| {
15371 display_map.disable_header_for_buffer(buffer_id, cx);
15372 });
15373 cx.notify();
15374 }
15375
15376 /// Removes any folds with the given ranges.
15377 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15378 &mut self,
15379 ranges: &[Range<T>],
15380 type_id: TypeId,
15381 auto_scroll: bool,
15382 cx: &mut Context<Self>,
15383 ) {
15384 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15385 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15386 });
15387 self.folds_did_change(cx);
15388 }
15389
15390 fn remove_folds_with<T: ToOffset + Clone>(
15391 &mut self,
15392 ranges: &[Range<T>],
15393 auto_scroll: bool,
15394 cx: &mut Context<Self>,
15395 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15396 ) {
15397 if ranges.is_empty() {
15398 return;
15399 }
15400
15401 let mut buffers_affected = HashSet::default();
15402 let multi_buffer = self.buffer().read(cx);
15403 for range in ranges {
15404 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15405 buffers_affected.insert(buffer.read(cx).remote_id());
15406 };
15407 }
15408
15409 self.display_map.update(cx, update);
15410
15411 if auto_scroll {
15412 self.request_autoscroll(Autoscroll::fit(), cx);
15413 }
15414
15415 cx.notify();
15416 self.scrollbar_marker_state.dirty = true;
15417 self.active_indent_guides_state.dirty = true;
15418 }
15419
15420 pub fn update_fold_widths(
15421 &mut self,
15422 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15423 cx: &mut Context<Self>,
15424 ) -> bool {
15425 self.display_map
15426 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15427 }
15428
15429 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15430 self.display_map.read(cx).fold_placeholder.clone()
15431 }
15432
15433 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15434 self.buffer.update(cx, |buffer, cx| {
15435 buffer.set_all_diff_hunks_expanded(cx);
15436 });
15437 }
15438
15439 pub fn expand_all_diff_hunks(
15440 &mut self,
15441 _: &ExpandAllDiffHunks,
15442 _window: &mut Window,
15443 cx: &mut Context<Self>,
15444 ) {
15445 self.buffer.update(cx, |buffer, cx| {
15446 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15447 });
15448 }
15449
15450 pub fn toggle_selected_diff_hunks(
15451 &mut self,
15452 _: &ToggleSelectedDiffHunks,
15453 _window: &mut Window,
15454 cx: &mut Context<Self>,
15455 ) {
15456 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15457 self.toggle_diff_hunks_in_ranges(ranges, cx);
15458 }
15459
15460 pub fn diff_hunks_in_ranges<'a>(
15461 &'a self,
15462 ranges: &'a [Range<Anchor>],
15463 buffer: &'a MultiBufferSnapshot,
15464 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15465 ranges.iter().flat_map(move |range| {
15466 let end_excerpt_id = range.end.excerpt_id;
15467 let range = range.to_point(buffer);
15468 let mut peek_end = range.end;
15469 if range.end.row < buffer.max_row().0 {
15470 peek_end = Point::new(range.end.row + 1, 0);
15471 }
15472 buffer
15473 .diff_hunks_in_range(range.start..peek_end)
15474 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15475 })
15476 }
15477
15478 pub fn has_stageable_diff_hunks_in_ranges(
15479 &self,
15480 ranges: &[Range<Anchor>],
15481 snapshot: &MultiBufferSnapshot,
15482 ) -> bool {
15483 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15484 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15485 }
15486
15487 pub fn toggle_staged_selected_diff_hunks(
15488 &mut self,
15489 _: &::git::ToggleStaged,
15490 _: &mut Window,
15491 cx: &mut Context<Self>,
15492 ) {
15493 let snapshot = self.buffer.read(cx).snapshot(cx);
15494 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15495 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15496 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15497 }
15498
15499 pub fn set_render_diff_hunk_controls(
15500 &mut self,
15501 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15502 cx: &mut Context<Self>,
15503 ) {
15504 self.render_diff_hunk_controls = render_diff_hunk_controls;
15505 cx.notify();
15506 }
15507
15508 pub fn stage_and_next(
15509 &mut self,
15510 _: &::git::StageAndNext,
15511 window: &mut Window,
15512 cx: &mut Context<Self>,
15513 ) {
15514 self.do_stage_or_unstage_and_next(true, window, cx);
15515 }
15516
15517 pub fn unstage_and_next(
15518 &mut self,
15519 _: &::git::UnstageAndNext,
15520 window: &mut Window,
15521 cx: &mut Context<Self>,
15522 ) {
15523 self.do_stage_or_unstage_and_next(false, window, cx);
15524 }
15525
15526 pub fn stage_or_unstage_diff_hunks(
15527 &mut self,
15528 stage: bool,
15529 ranges: Vec<Range<Anchor>>,
15530 cx: &mut Context<Self>,
15531 ) {
15532 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15533 cx.spawn(async move |this, cx| {
15534 task.await?;
15535 this.update(cx, |this, cx| {
15536 let snapshot = this.buffer.read(cx).snapshot(cx);
15537 let chunk_by = this
15538 .diff_hunks_in_ranges(&ranges, &snapshot)
15539 .chunk_by(|hunk| hunk.buffer_id);
15540 for (buffer_id, hunks) in &chunk_by {
15541 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15542 }
15543 })
15544 })
15545 .detach_and_log_err(cx);
15546 }
15547
15548 fn save_buffers_for_ranges_if_needed(
15549 &mut self,
15550 ranges: &[Range<Anchor>],
15551 cx: &mut Context<Editor>,
15552 ) -> Task<Result<()>> {
15553 let multibuffer = self.buffer.read(cx);
15554 let snapshot = multibuffer.read(cx);
15555 let buffer_ids: HashSet<_> = ranges
15556 .iter()
15557 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15558 .collect();
15559 drop(snapshot);
15560
15561 let mut buffers = HashSet::default();
15562 for buffer_id in buffer_ids {
15563 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15564 let buffer = buffer_entity.read(cx);
15565 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15566 {
15567 buffers.insert(buffer_entity);
15568 }
15569 }
15570 }
15571
15572 if let Some(project) = &self.project {
15573 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15574 } else {
15575 Task::ready(Ok(()))
15576 }
15577 }
15578
15579 fn do_stage_or_unstage_and_next(
15580 &mut self,
15581 stage: bool,
15582 window: &mut Window,
15583 cx: &mut Context<Self>,
15584 ) {
15585 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15586
15587 if ranges.iter().any(|range| range.start != range.end) {
15588 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15589 return;
15590 }
15591
15592 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15593 let snapshot = self.snapshot(window, cx);
15594 let position = self.selections.newest::<Point>(cx).head();
15595 let mut row = snapshot
15596 .buffer_snapshot
15597 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15598 .find(|hunk| hunk.row_range.start.0 > position.row)
15599 .map(|hunk| hunk.row_range.start);
15600
15601 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15602 // Outside of the project diff editor, wrap around to the beginning.
15603 if !all_diff_hunks_expanded {
15604 row = row.or_else(|| {
15605 snapshot
15606 .buffer_snapshot
15607 .diff_hunks_in_range(Point::zero()..position)
15608 .find(|hunk| hunk.row_range.end.0 < position.row)
15609 .map(|hunk| hunk.row_range.start)
15610 });
15611 }
15612
15613 if let Some(row) = row {
15614 let destination = Point::new(row.0, 0);
15615 let autoscroll = Autoscroll::center();
15616
15617 self.unfold_ranges(&[destination..destination], false, false, cx);
15618 self.change_selections(Some(autoscroll), window, cx, |s| {
15619 s.select_ranges([destination..destination]);
15620 });
15621 }
15622 }
15623
15624 fn do_stage_or_unstage(
15625 &self,
15626 stage: bool,
15627 buffer_id: BufferId,
15628 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15629 cx: &mut App,
15630 ) -> Option<()> {
15631 let project = self.project.as_ref()?;
15632 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15633 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15634 let buffer_snapshot = buffer.read(cx).snapshot();
15635 let file_exists = buffer_snapshot
15636 .file()
15637 .is_some_and(|file| file.disk_state().exists());
15638 diff.update(cx, |diff, cx| {
15639 diff.stage_or_unstage_hunks(
15640 stage,
15641 &hunks
15642 .map(|hunk| buffer_diff::DiffHunk {
15643 buffer_range: hunk.buffer_range,
15644 diff_base_byte_range: hunk.diff_base_byte_range,
15645 secondary_status: hunk.secondary_status,
15646 range: Point::zero()..Point::zero(), // unused
15647 })
15648 .collect::<Vec<_>>(),
15649 &buffer_snapshot,
15650 file_exists,
15651 cx,
15652 )
15653 });
15654 None
15655 }
15656
15657 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15658 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15659 self.buffer
15660 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15661 }
15662
15663 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15664 self.buffer.update(cx, |buffer, cx| {
15665 let ranges = vec![Anchor::min()..Anchor::max()];
15666 if !buffer.all_diff_hunks_expanded()
15667 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15668 {
15669 buffer.collapse_diff_hunks(ranges, cx);
15670 true
15671 } else {
15672 false
15673 }
15674 })
15675 }
15676
15677 fn toggle_diff_hunks_in_ranges(
15678 &mut self,
15679 ranges: Vec<Range<Anchor>>,
15680 cx: &mut Context<Editor>,
15681 ) {
15682 self.buffer.update(cx, |buffer, cx| {
15683 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15684 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15685 })
15686 }
15687
15688 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15689 self.buffer.update(cx, |buffer, cx| {
15690 let snapshot = buffer.snapshot(cx);
15691 let excerpt_id = range.end.excerpt_id;
15692 let point_range = range.to_point(&snapshot);
15693 let expand = !buffer.single_hunk_is_expanded(range, cx);
15694 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15695 })
15696 }
15697
15698 pub(crate) fn apply_all_diff_hunks(
15699 &mut self,
15700 _: &ApplyAllDiffHunks,
15701 window: &mut Window,
15702 cx: &mut Context<Self>,
15703 ) {
15704 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15705
15706 let buffers = self.buffer.read(cx).all_buffers();
15707 for branch_buffer in buffers {
15708 branch_buffer.update(cx, |branch_buffer, cx| {
15709 branch_buffer.merge_into_base(Vec::new(), cx);
15710 });
15711 }
15712
15713 if let Some(project) = self.project.clone() {
15714 self.save(true, project, window, cx).detach_and_log_err(cx);
15715 }
15716 }
15717
15718 pub(crate) fn apply_selected_diff_hunks(
15719 &mut self,
15720 _: &ApplyDiffHunk,
15721 window: &mut Window,
15722 cx: &mut Context<Self>,
15723 ) {
15724 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15725 let snapshot = self.snapshot(window, cx);
15726 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15727 let mut ranges_by_buffer = HashMap::default();
15728 self.transact(window, cx, |editor, _window, cx| {
15729 for hunk in hunks {
15730 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15731 ranges_by_buffer
15732 .entry(buffer.clone())
15733 .or_insert_with(Vec::new)
15734 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15735 }
15736 }
15737
15738 for (buffer, ranges) in ranges_by_buffer {
15739 buffer.update(cx, |buffer, cx| {
15740 buffer.merge_into_base(ranges, cx);
15741 });
15742 }
15743 });
15744
15745 if let Some(project) = self.project.clone() {
15746 self.save(true, project, window, cx).detach_and_log_err(cx);
15747 }
15748 }
15749
15750 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15751 if hovered != self.gutter_hovered {
15752 self.gutter_hovered = hovered;
15753 cx.notify();
15754 }
15755 }
15756
15757 pub fn insert_blocks(
15758 &mut self,
15759 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15760 autoscroll: Option<Autoscroll>,
15761 cx: &mut Context<Self>,
15762 ) -> Vec<CustomBlockId> {
15763 let blocks = self
15764 .display_map
15765 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15766 if let Some(autoscroll) = autoscroll {
15767 self.request_autoscroll(autoscroll, cx);
15768 }
15769 cx.notify();
15770 blocks
15771 }
15772
15773 pub fn resize_blocks(
15774 &mut self,
15775 heights: HashMap<CustomBlockId, u32>,
15776 autoscroll: Option<Autoscroll>,
15777 cx: &mut Context<Self>,
15778 ) {
15779 self.display_map
15780 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15781 if let Some(autoscroll) = autoscroll {
15782 self.request_autoscroll(autoscroll, cx);
15783 }
15784 cx.notify();
15785 }
15786
15787 pub fn replace_blocks(
15788 &mut self,
15789 renderers: HashMap<CustomBlockId, RenderBlock>,
15790 autoscroll: Option<Autoscroll>,
15791 cx: &mut Context<Self>,
15792 ) {
15793 self.display_map
15794 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15795 if let Some(autoscroll) = autoscroll {
15796 self.request_autoscroll(autoscroll, cx);
15797 }
15798 cx.notify();
15799 }
15800
15801 pub fn remove_blocks(
15802 &mut self,
15803 block_ids: HashSet<CustomBlockId>,
15804 autoscroll: Option<Autoscroll>,
15805 cx: &mut Context<Self>,
15806 ) {
15807 self.display_map.update(cx, |display_map, cx| {
15808 display_map.remove_blocks(block_ids, cx)
15809 });
15810 if let Some(autoscroll) = autoscroll {
15811 self.request_autoscroll(autoscroll, cx);
15812 }
15813 cx.notify();
15814 }
15815
15816 pub fn row_for_block(
15817 &self,
15818 block_id: CustomBlockId,
15819 cx: &mut Context<Self>,
15820 ) -> Option<DisplayRow> {
15821 self.display_map
15822 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15823 }
15824
15825 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15826 self.focused_block = Some(focused_block);
15827 }
15828
15829 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15830 self.focused_block.take()
15831 }
15832
15833 pub fn insert_creases(
15834 &mut self,
15835 creases: impl IntoIterator<Item = Crease<Anchor>>,
15836 cx: &mut Context<Self>,
15837 ) -> Vec<CreaseId> {
15838 self.display_map
15839 .update(cx, |map, cx| map.insert_creases(creases, cx))
15840 }
15841
15842 pub fn remove_creases(
15843 &mut self,
15844 ids: impl IntoIterator<Item = CreaseId>,
15845 cx: &mut Context<Self>,
15846 ) {
15847 self.display_map
15848 .update(cx, |map, cx| map.remove_creases(ids, cx));
15849 }
15850
15851 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15852 self.display_map
15853 .update(cx, |map, cx| map.snapshot(cx))
15854 .longest_row()
15855 }
15856
15857 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15858 self.display_map
15859 .update(cx, |map, cx| map.snapshot(cx))
15860 .max_point()
15861 }
15862
15863 pub fn text(&self, cx: &App) -> String {
15864 self.buffer.read(cx).read(cx).text()
15865 }
15866
15867 pub fn is_empty(&self, cx: &App) -> bool {
15868 self.buffer.read(cx).read(cx).is_empty()
15869 }
15870
15871 pub fn text_option(&self, cx: &App) -> Option<String> {
15872 let text = self.text(cx);
15873 let text = text.trim();
15874
15875 if text.is_empty() {
15876 return None;
15877 }
15878
15879 Some(text.to_string())
15880 }
15881
15882 pub fn set_text(
15883 &mut self,
15884 text: impl Into<Arc<str>>,
15885 window: &mut Window,
15886 cx: &mut Context<Self>,
15887 ) {
15888 self.transact(window, cx, |this, _, cx| {
15889 this.buffer
15890 .read(cx)
15891 .as_singleton()
15892 .expect("you can only call set_text on editors for singleton buffers")
15893 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15894 });
15895 }
15896
15897 pub fn display_text(&self, cx: &mut App) -> String {
15898 self.display_map
15899 .update(cx, |map, cx| map.snapshot(cx))
15900 .text()
15901 }
15902
15903 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15904 let mut wrap_guides = smallvec::smallvec![];
15905
15906 if self.show_wrap_guides == Some(false) {
15907 return wrap_guides;
15908 }
15909
15910 let settings = self.buffer.read(cx).language_settings(cx);
15911 if settings.show_wrap_guides {
15912 match self.soft_wrap_mode(cx) {
15913 SoftWrap::Column(soft_wrap) => {
15914 wrap_guides.push((soft_wrap as usize, true));
15915 }
15916 SoftWrap::Bounded(soft_wrap) => {
15917 wrap_guides.push((soft_wrap as usize, true));
15918 }
15919 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15920 }
15921 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15922 }
15923
15924 wrap_guides
15925 }
15926
15927 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15928 let settings = self.buffer.read(cx).language_settings(cx);
15929 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15930 match mode {
15931 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15932 SoftWrap::None
15933 }
15934 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15935 language_settings::SoftWrap::PreferredLineLength => {
15936 SoftWrap::Column(settings.preferred_line_length)
15937 }
15938 language_settings::SoftWrap::Bounded => {
15939 SoftWrap::Bounded(settings.preferred_line_length)
15940 }
15941 }
15942 }
15943
15944 pub fn set_soft_wrap_mode(
15945 &mut self,
15946 mode: language_settings::SoftWrap,
15947
15948 cx: &mut Context<Self>,
15949 ) {
15950 self.soft_wrap_mode_override = Some(mode);
15951 cx.notify();
15952 }
15953
15954 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15955 self.hard_wrap = hard_wrap;
15956 cx.notify();
15957 }
15958
15959 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15960 self.text_style_refinement = Some(style);
15961 }
15962
15963 /// called by the Element so we know what style we were most recently rendered with.
15964 pub(crate) fn set_style(
15965 &mut self,
15966 style: EditorStyle,
15967 window: &mut Window,
15968 cx: &mut Context<Self>,
15969 ) {
15970 let rem_size = window.rem_size();
15971 self.display_map.update(cx, |map, cx| {
15972 map.set_font(
15973 style.text.font(),
15974 style.text.font_size.to_pixels(rem_size),
15975 cx,
15976 )
15977 });
15978 self.style = Some(style);
15979 }
15980
15981 pub fn style(&self) -> Option<&EditorStyle> {
15982 self.style.as_ref()
15983 }
15984
15985 // Called by the element. This method is not designed to be called outside of the editor
15986 // element's layout code because it does not notify when rewrapping is computed synchronously.
15987 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15988 self.display_map
15989 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15990 }
15991
15992 pub fn set_soft_wrap(&mut self) {
15993 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15994 }
15995
15996 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15997 if self.soft_wrap_mode_override.is_some() {
15998 self.soft_wrap_mode_override.take();
15999 } else {
16000 let soft_wrap = match self.soft_wrap_mode(cx) {
16001 SoftWrap::GitDiff => return,
16002 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16003 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16004 language_settings::SoftWrap::None
16005 }
16006 };
16007 self.soft_wrap_mode_override = Some(soft_wrap);
16008 }
16009 cx.notify();
16010 }
16011
16012 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16013 let Some(workspace) = self.workspace() else {
16014 return;
16015 };
16016 let fs = workspace.read(cx).app_state().fs.clone();
16017 let current_show = TabBarSettings::get_global(cx).show;
16018 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16019 setting.show = Some(!current_show);
16020 });
16021 }
16022
16023 pub fn toggle_indent_guides(
16024 &mut self,
16025 _: &ToggleIndentGuides,
16026 _: &mut Window,
16027 cx: &mut Context<Self>,
16028 ) {
16029 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16030 self.buffer
16031 .read(cx)
16032 .language_settings(cx)
16033 .indent_guides
16034 .enabled
16035 });
16036 self.show_indent_guides = Some(!currently_enabled);
16037 cx.notify();
16038 }
16039
16040 fn should_show_indent_guides(&self) -> Option<bool> {
16041 self.show_indent_guides
16042 }
16043
16044 pub fn toggle_line_numbers(
16045 &mut self,
16046 _: &ToggleLineNumbers,
16047 _: &mut Window,
16048 cx: &mut Context<Self>,
16049 ) {
16050 let mut editor_settings = EditorSettings::get_global(cx).clone();
16051 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16052 EditorSettings::override_global(editor_settings, cx);
16053 }
16054
16055 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16056 if let Some(show_line_numbers) = self.show_line_numbers {
16057 return show_line_numbers;
16058 }
16059 EditorSettings::get_global(cx).gutter.line_numbers
16060 }
16061
16062 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16063 self.use_relative_line_numbers
16064 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16065 }
16066
16067 pub fn toggle_relative_line_numbers(
16068 &mut self,
16069 _: &ToggleRelativeLineNumbers,
16070 _: &mut Window,
16071 cx: &mut Context<Self>,
16072 ) {
16073 let is_relative = self.should_use_relative_line_numbers(cx);
16074 self.set_relative_line_number(Some(!is_relative), cx)
16075 }
16076
16077 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16078 self.use_relative_line_numbers = is_relative;
16079 cx.notify();
16080 }
16081
16082 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16083 self.show_gutter = show_gutter;
16084 cx.notify();
16085 }
16086
16087 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16088 self.show_scrollbars = show_scrollbars;
16089 cx.notify();
16090 }
16091
16092 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16093 self.show_line_numbers = Some(show_line_numbers);
16094 cx.notify();
16095 }
16096
16097 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16098 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16099 cx.notify();
16100 }
16101
16102 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16103 self.show_code_actions = Some(show_code_actions);
16104 cx.notify();
16105 }
16106
16107 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16108 self.show_runnables = Some(show_runnables);
16109 cx.notify();
16110 }
16111
16112 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16113 self.show_breakpoints = Some(show_breakpoints);
16114 cx.notify();
16115 }
16116
16117 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16118 if self.display_map.read(cx).masked != masked {
16119 self.display_map.update(cx, |map, _| map.masked = masked);
16120 }
16121 cx.notify()
16122 }
16123
16124 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16125 self.show_wrap_guides = Some(show_wrap_guides);
16126 cx.notify();
16127 }
16128
16129 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16130 self.show_indent_guides = Some(show_indent_guides);
16131 cx.notify();
16132 }
16133
16134 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16135 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16136 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16137 if let Some(dir) = file.abs_path(cx).parent() {
16138 return Some(dir.to_owned());
16139 }
16140 }
16141
16142 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16143 return Some(project_path.path.to_path_buf());
16144 }
16145 }
16146
16147 None
16148 }
16149
16150 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16151 self.active_excerpt(cx)?
16152 .1
16153 .read(cx)
16154 .file()
16155 .and_then(|f| f.as_local())
16156 }
16157
16158 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16159 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16160 let buffer = buffer.read(cx);
16161 if let Some(project_path) = buffer.project_path(cx) {
16162 let project = self.project.as_ref()?.read(cx);
16163 project.absolute_path(&project_path, cx)
16164 } else {
16165 buffer
16166 .file()
16167 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16168 }
16169 })
16170 }
16171
16172 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16173 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16174 let project_path = buffer.read(cx).project_path(cx)?;
16175 let project = self.project.as_ref()?.read(cx);
16176 let entry = project.entry_for_path(&project_path, cx)?;
16177 let path = entry.path.to_path_buf();
16178 Some(path)
16179 })
16180 }
16181
16182 pub fn reveal_in_finder(
16183 &mut self,
16184 _: &RevealInFileManager,
16185 _window: &mut Window,
16186 cx: &mut Context<Self>,
16187 ) {
16188 if let Some(target) = self.target_file(cx) {
16189 cx.reveal_path(&target.abs_path(cx));
16190 }
16191 }
16192
16193 pub fn copy_path(
16194 &mut self,
16195 _: &zed_actions::workspace::CopyPath,
16196 _window: &mut Window,
16197 cx: &mut Context<Self>,
16198 ) {
16199 if let Some(path) = self.target_file_abs_path(cx) {
16200 if let Some(path) = path.to_str() {
16201 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16202 }
16203 }
16204 }
16205
16206 pub fn copy_relative_path(
16207 &mut self,
16208 _: &zed_actions::workspace::CopyRelativePath,
16209 _window: &mut Window,
16210 cx: &mut Context<Self>,
16211 ) {
16212 if let Some(path) = self.target_file_path(cx) {
16213 if let Some(path) = path.to_str() {
16214 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16215 }
16216 }
16217 }
16218
16219 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16220 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16221 buffer.read(cx).project_path(cx)
16222 } else {
16223 None
16224 }
16225 }
16226
16227 // Returns true if the editor handled a go-to-line request
16228 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16229 maybe!({
16230 let breakpoint_store = self.breakpoint_store.as_ref()?;
16231
16232 let Some((_, _, active_position)) =
16233 breakpoint_store.read(cx).active_position().cloned()
16234 else {
16235 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16236 return None;
16237 };
16238
16239 let snapshot = self
16240 .project
16241 .as_ref()?
16242 .read(cx)
16243 .buffer_for_id(active_position.buffer_id?, cx)?
16244 .read(cx)
16245 .snapshot();
16246
16247 let mut handled = false;
16248 for (id, ExcerptRange { context, .. }) in self
16249 .buffer
16250 .read(cx)
16251 .excerpts_for_buffer(active_position.buffer_id?, cx)
16252 {
16253 if context.start.cmp(&active_position, &snapshot).is_ge()
16254 || context.end.cmp(&active_position, &snapshot).is_lt()
16255 {
16256 continue;
16257 }
16258 let snapshot = self.buffer.read(cx).snapshot(cx);
16259 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16260
16261 handled = true;
16262 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16263 self.go_to_line::<DebugCurrentRowHighlight>(
16264 multibuffer_anchor,
16265 Some(cx.theme().colors().editor_debugger_active_line_background),
16266 window,
16267 cx,
16268 );
16269
16270 cx.notify();
16271 }
16272 handled.then_some(())
16273 })
16274 .is_some()
16275 }
16276
16277 pub fn copy_file_name_without_extension(
16278 &mut self,
16279 _: &CopyFileNameWithoutExtension,
16280 _: &mut Window,
16281 cx: &mut Context<Self>,
16282 ) {
16283 if let Some(file) = self.target_file(cx) {
16284 if let Some(file_stem) = file.path().file_stem() {
16285 if let Some(name) = file_stem.to_str() {
16286 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16287 }
16288 }
16289 }
16290 }
16291
16292 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16293 if let Some(file) = self.target_file(cx) {
16294 if let Some(file_name) = file.path().file_name() {
16295 if let Some(name) = file_name.to_str() {
16296 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16297 }
16298 }
16299 }
16300 }
16301
16302 pub fn toggle_git_blame(
16303 &mut self,
16304 _: &::git::Blame,
16305 window: &mut Window,
16306 cx: &mut Context<Self>,
16307 ) {
16308 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16309
16310 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16311 self.start_git_blame(true, window, cx);
16312 }
16313
16314 cx.notify();
16315 }
16316
16317 pub fn toggle_git_blame_inline(
16318 &mut self,
16319 _: &ToggleGitBlameInline,
16320 window: &mut Window,
16321 cx: &mut Context<Self>,
16322 ) {
16323 self.toggle_git_blame_inline_internal(true, window, cx);
16324 cx.notify();
16325 }
16326
16327 pub fn open_git_blame_commit(
16328 &mut self,
16329 _: &OpenGitBlameCommit,
16330 window: &mut Window,
16331 cx: &mut Context<Self>,
16332 ) {
16333 self.open_git_blame_commit_internal(window, cx);
16334 }
16335
16336 fn open_git_blame_commit_internal(
16337 &mut self,
16338 window: &mut Window,
16339 cx: &mut Context<Self>,
16340 ) -> Option<()> {
16341 let blame = self.blame.as_ref()?;
16342 let snapshot = self.snapshot(window, cx);
16343 let cursor = self.selections.newest::<Point>(cx).head();
16344 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16345 let blame_entry = blame
16346 .update(cx, |blame, cx| {
16347 blame
16348 .blame_for_rows(
16349 &[RowInfo {
16350 buffer_id: Some(buffer.remote_id()),
16351 buffer_row: Some(point.row),
16352 ..Default::default()
16353 }],
16354 cx,
16355 )
16356 .next()
16357 })
16358 .flatten()?;
16359 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16360 let repo = blame.read(cx).repository(cx)?;
16361 let workspace = self.workspace()?.downgrade();
16362 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16363 None
16364 }
16365
16366 pub fn git_blame_inline_enabled(&self) -> bool {
16367 self.git_blame_inline_enabled
16368 }
16369
16370 pub fn toggle_selection_menu(
16371 &mut self,
16372 _: &ToggleSelectionMenu,
16373 _: &mut Window,
16374 cx: &mut Context<Self>,
16375 ) {
16376 self.show_selection_menu = self
16377 .show_selection_menu
16378 .map(|show_selections_menu| !show_selections_menu)
16379 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16380
16381 cx.notify();
16382 }
16383
16384 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16385 self.show_selection_menu
16386 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16387 }
16388
16389 fn start_git_blame(
16390 &mut self,
16391 user_triggered: bool,
16392 window: &mut Window,
16393 cx: &mut Context<Self>,
16394 ) {
16395 if let Some(project) = self.project.as_ref() {
16396 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16397 return;
16398 };
16399
16400 if buffer.read(cx).file().is_none() {
16401 return;
16402 }
16403
16404 let focused = self.focus_handle(cx).contains_focused(window, cx);
16405
16406 let project = project.clone();
16407 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16408 self.blame_subscription =
16409 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16410 self.blame = Some(blame);
16411 }
16412 }
16413
16414 fn toggle_git_blame_inline_internal(
16415 &mut self,
16416 user_triggered: bool,
16417 window: &mut Window,
16418 cx: &mut Context<Self>,
16419 ) {
16420 if self.git_blame_inline_enabled {
16421 self.git_blame_inline_enabled = false;
16422 self.show_git_blame_inline = false;
16423 self.show_git_blame_inline_delay_task.take();
16424 } else {
16425 self.git_blame_inline_enabled = true;
16426 self.start_git_blame_inline(user_triggered, window, cx);
16427 }
16428
16429 cx.notify();
16430 }
16431
16432 fn start_git_blame_inline(
16433 &mut self,
16434 user_triggered: bool,
16435 window: &mut Window,
16436 cx: &mut Context<Self>,
16437 ) {
16438 self.start_git_blame(user_triggered, window, cx);
16439
16440 if ProjectSettings::get_global(cx)
16441 .git
16442 .inline_blame_delay()
16443 .is_some()
16444 {
16445 self.start_inline_blame_timer(window, cx);
16446 } else {
16447 self.show_git_blame_inline = true
16448 }
16449 }
16450
16451 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16452 self.blame.as_ref()
16453 }
16454
16455 pub fn show_git_blame_gutter(&self) -> bool {
16456 self.show_git_blame_gutter
16457 }
16458
16459 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16460 self.show_git_blame_gutter && self.has_blame_entries(cx)
16461 }
16462
16463 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16464 self.show_git_blame_inline
16465 && (self.focus_handle.is_focused(window)
16466 || self
16467 .git_blame_inline_tooltip
16468 .as_ref()
16469 .and_then(|t| t.upgrade())
16470 .is_some())
16471 && !self.newest_selection_head_on_empty_line(cx)
16472 && self.has_blame_entries(cx)
16473 }
16474
16475 fn has_blame_entries(&self, cx: &App) -> bool {
16476 self.blame()
16477 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16478 }
16479
16480 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16481 let cursor_anchor = self.selections.newest_anchor().head();
16482
16483 let snapshot = self.buffer.read(cx).snapshot(cx);
16484 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16485
16486 snapshot.line_len(buffer_row) == 0
16487 }
16488
16489 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16490 let buffer_and_selection = maybe!({
16491 let selection = self.selections.newest::<Point>(cx);
16492 let selection_range = selection.range();
16493
16494 let multi_buffer = self.buffer().read(cx);
16495 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16496 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16497
16498 let (buffer, range, _) = if selection.reversed {
16499 buffer_ranges.first()
16500 } else {
16501 buffer_ranges.last()
16502 }?;
16503
16504 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16505 ..text::ToPoint::to_point(&range.end, &buffer).row;
16506 Some((
16507 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16508 selection,
16509 ))
16510 });
16511
16512 let Some((buffer, selection)) = buffer_and_selection else {
16513 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16514 };
16515
16516 let Some(project) = self.project.as_ref() else {
16517 return Task::ready(Err(anyhow!("editor does not have project")));
16518 };
16519
16520 project.update(cx, |project, cx| {
16521 project.get_permalink_to_line(&buffer, selection, cx)
16522 })
16523 }
16524
16525 pub fn copy_permalink_to_line(
16526 &mut self,
16527 _: &CopyPermalinkToLine,
16528 window: &mut Window,
16529 cx: &mut Context<Self>,
16530 ) {
16531 let permalink_task = self.get_permalink_to_line(cx);
16532 let workspace = self.workspace();
16533
16534 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16535 Ok(permalink) => {
16536 cx.update(|_, cx| {
16537 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16538 })
16539 .ok();
16540 }
16541 Err(err) => {
16542 let message = format!("Failed to copy permalink: {err}");
16543
16544 Err::<(), anyhow::Error>(err).log_err();
16545
16546 if let Some(workspace) = workspace {
16547 workspace
16548 .update_in(cx, |workspace, _, cx| {
16549 struct CopyPermalinkToLine;
16550
16551 workspace.show_toast(
16552 Toast::new(
16553 NotificationId::unique::<CopyPermalinkToLine>(),
16554 message,
16555 ),
16556 cx,
16557 )
16558 })
16559 .ok();
16560 }
16561 }
16562 })
16563 .detach();
16564 }
16565
16566 pub fn copy_file_location(
16567 &mut self,
16568 _: &CopyFileLocation,
16569 _: &mut Window,
16570 cx: &mut Context<Self>,
16571 ) {
16572 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16573 if let Some(file) = self.target_file(cx) {
16574 if let Some(path) = file.path().to_str() {
16575 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16576 }
16577 }
16578 }
16579
16580 pub fn open_permalink_to_line(
16581 &mut self,
16582 _: &OpenPermalinkToLine,
16583 window: &mut Window,
16584 cx: &mut Context<Self>,
16585 ) {
16586 let permalink_task = self.get_permalink_to_line(cx);
16587 let workspace = self.workspace();
16588
16589 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16590 Ok(permalink) => {
16591 cx.update(|_, cx| {
16592 cx.open_url(permalink.as_ref());
16593 })
16594 .ok();
16595 }
16596 Err(err) => {
16597 let message = format!("Failed to open permalink: {err}");
16598
16599 Err::<(), anyhow::Error>(err).log_err();
16600
16601 if let Some(workspace) = workspace {
16602 workspace
16603 .update(cx, |workspace, cx| {
16604 struct OpenPermalinkToLine;
16605
16606 workspace.show_toast(
16607 Toast::new(
16608 NotificationId::unique::<OpenPermalinkToLine>(),
16609 message,
16610 ),
16611 cx,
16612 )
16613 })
16614 .ok();
16615 }
16616 }
16617 })
16618 .detach();
16619 }
16620
16621 pub fn insert_uuid_v4(
16622 &mut self,
16623 _: &InsertUuidV4,
16624 window: &mut Window,
16625 cx: &mut Context<Self>,
16626 ) {
16627 self.insert_uuid(UuidVersion::V4, window, cx);
16628 }
16629
16630 pub fn insert_uuid_v7(
16631 &mut self,
16632 _: &InsertUuidV7,
16633 window: &mut Window,
16634 cx: &mut Context<Self>,
16635 ) {
16636 self.insert_uuid(UuidVersion::V7, window, cx);
16637 }
16638
16639 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16640 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16641 self.transact(window, cx, |this, window, cx| {
16642 let edits = this
16643 .selections
16644 .all::<Point>(cx)
16645 .into_iter()
16646 .map(|selection| {
16647 let uuid = match version {
16648 UuidVersion::V4 => uuid::Uuid::new_v4(),
16649 UuidVersion::V7 => uuid::Uuid::now_v7(),
16650 };
16651
16652 (selection.range(), uuid.to_string())
16653 });
16654 this.edit(edits, cx);
16655 this.refresh_inline_completion(true, false, window, cx);
16656 });
16657 }
16658
16659 pub fn open_selections_in_multibuffer(
16660 &mut self,
16661 _: &OpenSelectionsInMultibuffer,
16662 window: &mut Window,
16663 cx: &mut Context<Self>,
16664 ) {
16665 let multibuffer = self.buffer.read(cx);
16666
16667 let Some(buffer) = multibuffer.as_singleton() else {
16668 return;
16669 };
16670
16671 let Some(workspace) = self.workspace() else {
16672 return;
16673 };
16674
16675 let locations = self
16676 .selections
16677 .disjoint_anchors()
16678 .iter()
16679 .map(|range| Location {
16680 buffer: buffer.clone(),
16681 range: range.start.text_anchor..range.end.text_anchor,
16682 })
16683 .collect::<Vec<_>>();
16684
16685 let title = multibuffer.title(cx).to_string();
16686
16687 cx.spawn_in(window, async move |_, cx| {
16688 workspace.update_in(cx, |workspace, window, cx| {
16689 Self::open_locations_in_multibuffer(
16690 workspace,
16691 locations,
16692 format!("Selections for '{title}'"),
16693 false,
16694 MultibufferSelectionMode::All,
16695 window,
16696 cx,
16697 );
16698 })
16699 })
16700 .detach();
16701 }
16702
16703 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16704 /// last highlight added will be used.
16705 ///
16706 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16707 pub fn highlight_rows<T: 'static>(
16708 &mut self,
16709 range: Range<Anchor>,
16710 color: Hsla,
16711 should_autoscroll: bool,
16712 cx: &mut Context<Self>,
16713 ) {
16714 let snapshot = self.buffer().read(cx).snapshot(cx);
16715 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16716 let ix = row_highlights.binary_search_by(|highlight| {
16717 Ordering::Equal
16718 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16719 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16720 });
16721
16722 if let Err(mut ix) = ix {
16723 let index = post_inc(&mut self.highlight_order);
16724
16725 // If this range intersects with the preceding highlight, then merge it with
16726 // the preceding highlight. Otherwise insert a new highlight.
16727 let mut merged = false;
16728 if ix > 0 {
16729 let prev_highlight = &mut row_highlights[ix - 1];
16730 if prev_highlight
16731 .range
16732 .end
16733 .cmp(&range.start, &snapshot)
16734 .is_ge()
16735 {
16736 ix -= 1;
16737 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16738 prev_highlight.range.end = range.end;
16739 }
16740 merged = true;
16741 prev_highlight.index = index;
16742 prev_highlight.color = color;
16743 prev_highlight.should_autoscroll = should_autoscroll;
16744 }
16745 }
16746
16747 if !merged {
16748 row_highlights.insert(
16749 ix,
16750 RowHighlight {
16751 range: range.clone(),
16752 index,
16753 color,
16754 should_autoscroll,
16755 },
16756 );
16757 }
16758
16759 // If any of the following highlights intersect with this one, merge them.
16760 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16761 let highlight = &row_highlights[ix];
16762 if next_highlight
16763 .range
16764 .start
16765 .cmp(&highlight.range.end, &snapshot)
16766 .is_le()
16767 {
16768 if next_highlight
16769 .range
16770 .end
16771 .cmp(&highlight.range.end, &snapshot)
16772 .is_gt()
16773 {
16774 row_highlights[ix].range.end = next_highlight.range.end;
16775 }
16776 row_highlights.remove(ix + 1);
16777 } else {
16778 break;
16779 }
16780 }
16781 }
16782 }
16783
16784 /// Remove any highlighted row ranges of the given type that intersect the
16785 /// given ranges.
16786 pub fn remove_highlighted_rows<T: 'static>(
16787 &mut self,
16788 ranges_to_remove: Vec<Range<Anchor>>,
16789 cx: &mut Context<Self>,
16790 ) {
16791 let snapshot = self.buffer().read(cx).snapshot(cx);
16792 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16793 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16794 row_highlights.retain(|highlight| {
16795 while let Some(range_to_remove) = ranges_to_remove.peek() {
16796 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16797 Ordering::Less | Ordering::Equal => {
16798 ranges_to_remove.next();
16799 }
16800 Ordering::Greater => {
16801 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16802 Ordering::Less | Ordering::Equal => {
16803 return false;
16804 }
16805 Ordering::Greater => break,
16806 }
16807 }
16808 }
16809 }
16810
16811 true
16812 })
16813 }
16814
16815 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16816 pub fn clear_row_highlights<T: 'static>(&mut self) {
16817 self.highlighted_rows.remove(&TypeId::of::<T>());
16818 }
16819
16820 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16821 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16822 self.highlighted_rows
16823 .get(&TypeId::of::<T>())
16824 .map_or(&[] as &[_], |vec| vec.as_slice())
16825 .iter()
16826 .map(|highlight| (highlight.range.clone(), highlight.color))
16827 }
16828
16829 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16830 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16831 /// Allows to ignore certain kinds of highlights.
16832 pub fn highlighted_display_rows(
16833 &self,
16834 window: &mut Window,
16835 cx: &mut App,
16836 ) -> BTreeMap<DisplayRow, LineHighlight> {
16837 let snapshot = self.snapshot(window, cx);
16838 let mut used_highlight_orders = HashMap::default();
16839 self.highlighted_rows
16840 .iter()
16841 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16842 .fold(
16843 BTreeMap::<DisplayRow, LineHighlight>::new(),
16844 |mut unique_rows, highlight| {
16845 let start = highlight.range.start.to_display_point(&snapshot);
16846 let end = highlight.range.end.to_display_point(&snapshot);
16847 let start_row = start.row().0;
16848 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16849 && end.column() == 0
16850 {
16851 end.row().0.saturating_sub(1)
16852 } else {
16853 end.row().0
16854 };
16855 for row in start_row..=end_row {
16856 let used_index =
16857 used_highlight_orders.entry(row).or_insert(highlight.index);
16858 if highlight.index >= *used_index {
16859 *used_index = highlight.index;
16860 unique_rows.insert(DisplayRow(row), highlight.color.into());
16861 }
16862 }
16863 unique_rows
16864 },
16865 )
16866 }
16867
16868 pub fn highlighted_display_row_for_autoscroll(
16869 &self,
16870 snapshot: &DisplaySnapshot,
16871 ) -> Option<DisplayRow> {
16872 self.highlighted_rows
16873 .values()
16874 .flat_map(|highlighted_rows| highlighted_rows.iter())
16875 .filter_map(|highlight| {
16876 if highlight.should_autoscroll {
16877 Some(highlight.range.start.to_display_point(snapshot).row())
16878 } else {
16879 None
16880 }
16881 })
16882 .min()
16883 }
16884
16885 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16886 self.highlight_background::<SearchWithinRange>(
16887 ranges,
16888 |colors| colors.editor_document_highlight_read_background,
16889 cx,
16890 )
16891 }
16892
16893 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16894 self.breadcrumb_header = Some(new_header);
16895 }
16896
16897 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16898 self.clear_background_highlights::<SearchWithinRange>(cx);
16899 }
16900
16901 pub fn highlight_background<T: 'static>(
16902 &mut self,
16903 ranges: &[Range<Anchor>],
16904 color_fetcher: fn(&ThemeColors) -> Hsla,
16905 cx: &mut Context<Self>,
16906 ) {
16907 self.background_highlights
16908 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16909 self.scrollbar_marker_state.dirty = true;
16910 cx.notify();
16911 }
16912
16913 pub fn clear_background_highlights<T: 'static>(
16914 &mut self,
16915 cx: &mut Context<Self>,
16916 ) -> Option<BackgroundHighlight> {
16917 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16918 if !text_highlights.1.is_empty() {
16919 self.scrollbar_marker_state.dirty = true;
16920 cx.notify();
16921 }
16922 Some(text_highlights)
16923 }
16924
16925 pub fn highlight_gutter<T: 'static>(
16926 &mut self,
16927 ranges: &[Range<Anchor>],
16928 color_fetcher: fn(&App) -> Hsla,
16929 cx: &mut Context<Self>,
16930 ) {
16931 self.gutter_highlights
16932 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16933 cx.notify();
16934 }
16935
16936 pub fn clear_gutter_highlights<T: 'static>(
16937 &mut self,
16938 cx: &mut Context<Self>,
16939 ) -> Option<GutterHighlight> {
16940 cx.notify();
16941 self.gutter_highlights.remove(&TypeId::of::<T>())
16942 }
16943
16944 #[cfg(feature = "test-support")]
16945 pub fn all_text_background_highlights(
16946 &self,
16947 window: &mut Window,
16948 cx: &mut Context<Self>,
16949 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16950 let snapshot = self.snapshot(window, cx);
16951 let buffer = &snapshot.buffer_snapshot;
16952 let start = buffer.anchor_before(0);
16953 let end = buffer.anchor_after(buffer.len());
16954 let theme = cx.theme().colors();
16955 self.background_highlights_in_range(start..end, &snapshot, theme)
16956 }
16957
16958 #[cfg(feature = "test-support")]
16959 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16960 let snapshot = self.buffer().read(cx).snapshot(cx);
16961
16962 let highlights = self
16963 .background_highlights
16964 .get(&TypeId::of::<items::BufferSearchHighlights>());
16965
16966 if let Some((_color, ranges)) = highlights {
16967 ranges
16968 .iter()
16969 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16970 .collect_vec()
16971 } else {
16972 vec![]
16973 }
16974 }
16975
16976 fn document_highlights_for_position<'a>(
16977 &'a self,
16978 position: Anchor,
16979 buffer: &'a MultiBufferSnapshot,
16980 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16981 let read_highlights = self
16982 .background_highlights
16983 .get(&TypeId::of::<DocumentHighlightRead>())
16984 .map(|h| &h.1);
16985 let write_highlights = self
16986 .background_highlights
16987 .get(&TypeId::of::<DocumentHighlightWrite>())
16988 .map(|h| &h.1);
16989 let left_position = position.bias_left(buffer);
16990 let right_position = position.bias_right(buffer);
16991 read_highlights
16992 .into_iter()
16993 .chain(write_highlights)
16994 .flat_map(move |ranges| {
16995 let start_ix = match ranges.binary_search_by(|probe| {
16996 let cmp = probe.end.cmp(&left_position, buffer);
16997 if cmp.is_ge() {
16998 Ordering::Greater
16999 } else {
17000 Ordering::Less
17001 }
17002 }) {
17003 Ok(i) | Err(i) => i,
17004 };
17005
17006 ranges[start_ix..]
17007 .iter()
17008 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17009 })
17010 }
17011
17012 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17013 self.background_highlights
17014 .get(&TypeId::of::<T>())
17015 .map_or(false, |(_, highlights)| !highlights.is_empty())
17016 }
17017
17018 pub fn background_highlights_in_range(
17019 &self,
17020 search_range: Range<Anchor>,
17021 display_snapshot: &DisplaySnapshot,
17022 theme: &ThemeColors,
17023 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17024 let mut results = Vec::new();
17025 for (color_fetcher, ranges) in self.background_highlights.values() {
17026 let color = color_fetcher(theme);
17027 let start_ix = match ranges.binary_search_by(|probe| {
17028 let cmp = probe
17029 .end
17030 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17031 if cmp.is_gt() {
17032 Ordering::Greater
17033 } else {
17034 Ordering::Less
17035 }
17036 }) {
17037 Ok(i) | Err(i) => i,
17038 };
17039 for range in &ranges[start_ix..] {
17040 if range
17041 .start
17042 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17043 .is_ge()
17044 {
17045 break;
17046 }
17047
17048 let start = range.start.to_display_point(display_snapshot);
17049 let end = range.end.to_display_point(display_snapshot);
17050 results.push((start..end, color))
17051 }
17052 }
17053 results
17054 }
17055
17056 pub fn background_highlight_row_ranges<T: 'static>(
17057 &self,
17058 search_range: Range<Anchor>,
17059 display_snapshot: &DisplaySnapshot,
17060 count: usize,
17061 ) -> Vec<RangeInclusive<DisplayPoint>> {
17062 let mut results = Vec::new();
17063 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17064 return vec![];
17065 };
17066
17067 let start_ix = match ranges.binary_search_by(|probe| {
17068 let cmp = probe
17069 .end
17070 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17071 if cmp.is_gt() {
17072 Ordering::Greater
17073 } else {
17074 Ordering::Less
17075 }
17076 }) {
17077 Ok(i) | Err(i) => i,
17078 };
17079 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17080 if let (Some(start_display), Some(end_display)) = (start, end) {
17081 results.push(
17082 start_display.to_display_point(display_snapshot)
17083 ..=end_display.to_display_point(display_snapshot),
17084 );
17085 }
17086 };
17087 let mut start_row: Option<Point> = None;
17088 let mut end_row: Option<Point> = None;
17089 if ranges.len() > count {
17090 return Vec::new();
17091 }
17092 for range in &ranges[start_ix..] {
17093 if range
17094 .start
17095 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17096 .is_ge()
17097 {
17098 break;
17099 }
17100 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17101 if let Some(current_row) = &end_row {
17102 if end.row == current_row.row {
17103 continue;
17104 }
17105 }
17106 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17107 if start_row.is_none() {
17108 assert_eq!(end_row, None);
17109 start_row = Some(start);
17110 end_row = Some(end);
17111 continue;
17112 }
17113 if let Some(current_end) = end_row.as_mut() {
17114 if start.row > current_end.row + 1 {
17115 push_region(start_row, end_row);
17116 start_row = Some(start);
17117 end_row = Some(end);
17118 } else {
17119 // Merge two hunks.
17120 *current_end = end;
17121 }
17122 } else {
17123 unreachable!();
17124 }
17125 }
17126 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17127 push_region(start_row, end_row);
17128 results
17129 }
17130
17131 pub fn gutter_highlights_in_range(
17132 &self,
17133 search_range: Range<Anchor>,
17134 display_snapshot: &DisplaySnapshot,
17135 cx: &App,
17136 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17137 let mut results = Vec::new();
17138 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17139 let color = color_fetcher(cx);
17140 let start_ix = match ranges.binary_search_by(|probe| {
17141 let cmp = probe
17142 .end
17143 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17144 if cmp.is_gt() {
17145 Ordering::Greater
17146 } else {
17147 Ordering::Less
17148 }
17149 }) {
17150 Ok(i) | Err(i) => i,
17151 };
17152 for range in &ranges[start_ix..] {
17153 if range
17154 .start
17155 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17156 .is_ge()
17157 {
17158 break;
17159 }
17160
17161 let start = range.start.to_display_point(display_snapshot);
17162 let end = range.end.to_display_point(display_snapshot);
17163 results.push((start..end, color))
17164 }
17165 }
17166 results
17167 }
17168
17169 /// Get the text ranges corresponding to the redaction query
17170 pub fn redacted_ranges(
17171 &self,
17172 search_range: Range<Anchor>,
17173 display_snapshot: &DisplaySnapshot,
17174 cx: &App,
17175 ) -> Vec<Range<DisplayPoint>> {
17176 display_snapshot
17177 .buffer_snapshot
17178 .redacted_ranges(search_range, |file| {
17179 if let Some(file) = file {
17180 file.is_private()
17181 && EditorSettings::get(
17182 Some(SettingsLocation {
17183 worktree_id: file.worktree_id(cx),
17184 path: file.path().as_ref(),
17185 }),
17186 cx,
17187 )
17188 .redact_private_values
17189 } else {
17190 false
17191 }
17192 })
17193 .map(|range| {
17194 range.start.to_display_point(display_snapshot)
17195 ..range.end.to_display_point(display_snapshot)
17196 })
17197 .collect()
17198 }
17199
17200 pub fn highlight_text<T: 'static>(
17201 &mut self,
17202 ranges: Vec<Range<Anchor>>,
17203 style: HighlightStyle,
17204 cx: &mut Context<Self>,
17205 ) {
17206 self.display_map.update(cx, |map, _| {
17207 map.highlight_text(TypeId::of::<T>(), ranges, style)
17208 });
17209 cx.notify();
17210 }
17211
17212 pub(crate) fn highlight_inlays<T: 'static>(
17213 &mut self,
17214 highlights: Vec<InlayHighlight>,
17215 style: HighlightStyle,
17216 cx: &mut Context<Self>,
17217 ) {
17218 self.display_map.update(cx, |map, _| {
17219 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17220 });
17221 cx.notify();
17222 }
17223
17224 pub fn text_highlights<'a, T: 'static>(
17225 &'a self,
17226 cx: &'a App,
17227 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17228 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17229 }
17230
17231 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17232 let cleared = self
17233 .display_map
17234 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17235 if cleared {
17236 cx.notify();
17237 }
17238 }
17239
17240 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17241 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17242 && self.focus_handle.is_focused(window)
17243 }
17244
17245 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17246 self.show_cursor_when_unfocused = is_enabled;
17247 cx.notify();
17248 }
17249
17250 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17251 cx.notify();
17252 }
17253
17254 fn on_buffer_event(
17255 &mut self,
17256 multibuffer: &Entity<MultiBuffer>,
17257 event: &multi_buffer::Event,
17258 window: &mut Window,
17259 cx: &mut Context<Self>,
17260 ) {
17261 match event {
17262 multi_buffer::Event::Edited {
17263 singleton_buffer_edited,
17264 edited_buffer: buffer_edited,
17265 } => {
17266 self.scrollbar_marker_state.dirty = true;
17267 self.active_indent_guides_state.dirty = true;
17268 self.refresh_active_diagnostics(cx);
17269 self.refresh_code_actions(window, cx);
17270 if self.has_active_inline_completion() {
17271 self.update_visible_inline_completion(window, cx);
17272 }
17273 if let Some(buffer) = buffer_edited {
17274 let buffer_id = buffer.read(cx).remote_id();
17275 if !self.registered_buffers.contains_key(&buffer_id) {
17276 if let Some(project) = self.project.as_ref() {
17277 project.update(cx, |project, cx| {
17278 self.registered_buffers.insert(
17279 buffer_id,
17280 project.register_buffer_with_language_servers(&buffer, cx),
17281 );
17282 })
17283 }
17284 }
17285 }
17286 cx.emit(EditorEvent::BufferEdited);
17287 cx.emit(SearchEvent::MatchesInvalidated);
17288 if *singleton_buffer_edited {
17289 if let Some(project) = &self.project {
17290 #[allow(clippy::mutable_key_type)]
17291 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17292 multibuffer
17293 .all_buffers()
17294 .into_iter()
17295 .filter_map(|buffer| {
17296 buffer.update(cx, |buffer, cx| {
17297 let language = buffer.language()?;
17298 let should_discard = project.update(cx, |project, cx| {
17299 project.is_local()
17300 && !project.has_language_servers_for(buffer, cx)
17301 });
17302 should_discard.not().then_some(language.clone())
17303 })
17304 })
17305 .collect::<HashSet<_>>()
17306 });
17307 if !languages_affected.is_empty() {
17308 self.refresh_inlay_hints(
17309 InlayHintRefreshReason::BufferEdited(languages_affected),
17310 cx,
17311 );
17312 }
17313 }
17314 }
17315
17316 let Some(project) = &self.project else { return };
17317 let (telemetry, is_via_ssh) = {
17318 let project = project.read(cx);
17319 let telemetry = project.client().telemetry().clone();
17320 let is_via_ssh = project.is_via_ssh();
17321 (telemetry, is_via_ssh)
17322 };
17323 refresh_linked_ranges(self, window, cx);
17324 telemetry.log_edit_event("editor", is_via_ssh);
17325 }
17326 multi_buffer::Event::ExcerptsAdded {
17327 buffer,
17328 predecessor,
17329 excerpts,
17330 } => {
17331 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17332 let buffer_id = buffer.read(cx).remote_id();
17333 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17334 if let Some(project) = &self.project {
17335 get_uncommitted_diff_for_buffer(
17336 project,
17337 [buffer.clone()],
17338 self.buffer.clone(),
17339 cx,
17340 )
17341 .detach();
17342 }
17343 }
17344 cx.emit(EditorEvent::ExcerptsAdded {
17345 buffer: buffer.clone(),
17346 predecessor: *predecessor,
17347 excerpts: excerpts.clone(),
17348 });
17349 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17350 }
17351 multi_buffer::Event::ExcerptsRemoved { ids } => {
17352 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17353 let buffer = self.buffer.read(cx);
17354 self.registered_buffers
17355 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17356 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17357 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17358 }
17359 multi_buffer::Event::ExcerptsEdited {
17360 excerpt_ids,
17361 buffer_ids,
17362 } => {
17363 self.display_map.update(cx, |map, cx| {
17364 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17365 });
17366 cx.emit(EditorEvent::ExcerptsEdited {
17367 ids: excerpt_ids.clone(),
17368 })
17369 }
17370 multi_buffer::Event::ExcerptsExpanded { ids } => {
17371 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17372 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17373 }
17374 multi_buffer::Event::Reparsed(buffer_id) => {
17375 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17376 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17377
17378 cx.emit(EditorEvent::Reparsed(*buffer_id));
17379 }
17380 multi_buffer::Event::DiffHunksToggled => {
17381 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17382 }
17383 multi_buffer::Event::LanguageChanged(buffer_id) => {
17384 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17385 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17386 cx.emit(EditorEvent::Reparsed(*buffer_id));
17387 cx.notify();
17388 }
17389 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17390 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17391 multi_buffer::Event::FileHandleChanged
17392 | multi_buffer::Event::Reloaded
17393 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17394 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17395 multi_buffer::Event::DiagnosticsUpdated => {
17396 self.refresh_active_diagnostics(cx);
17397 self.refresh_inline_diagnostics(true, window, cx);
17398 self.scrollbar_marker_state.dirty = true;
17399 cx.notify();
17400 }
17401 _ => {}
17402 };
17403 }
17404
17405 fn on_display_map_changed(
17406 &mut self,
17407 _: Entity<DisplayMap>,
17408 _: &mut Window,
17409 cx: &mut Context<Self>,
17410 ) {
17411 cx.notify();
17412 }
17413
17414 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17415 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17416 self.update_edit_prediction_settings(cx);
17417 self.refresh_inline_completion(true, false, window, cx);
17418 self.refresh_inlay_hints(
17419 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17420 self.selections.newest_anchor().head(),
17421 &self.buffer.read(cx).snapshot(cx),
17422 cx,
17423 )),
17424 cx,
17425 );
17426
17427 let old_cursor_shape = self.cursor_shape;
17428
17429 {
17430 let editor_settings = EditorSettings::get_global(cx);
17431 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17432 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17433 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17434 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17435 }
17436
17437 if old_cursor_shape != self.cursor_shape {
17438 cx.emit(EditorEvent::CursorShapeChanged);
17439 }
17440
17441 let project_settings = ProjectSettings::get_global(cx);
17442 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17443
17444 if self.mode.is_full() {
17445 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17446 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17447 if self.show_inline_diagnostics != show_inline_diagnostics {
17448 self.show_inline_diagnostics = show_inline_diagnostics;
17449 self.refresh_inline_diagnostics(false, window, cx);
17450 }
17451
17452 if self.git_blame_inline_enabled != inline_blame_enabled {
17453 self.toggle_git_blame_inline_internal(false, window, cx);
17454 }
17455 }
17456
17457 cx.notify();
17458 }
17459
17460 pub fn set_searchable(&mut self, searchable: bool) {
17461 self.searchable = searchable;
17462 }
17463
17464 pub fn searchable(&self) -> bool {
17465 self.searchable
17466 }
17467
17468 fn open_proposed_changes_editor(
17469 &mut self,
17470 _: &OpenProposedChangesEditor,
17471 window: &mut Window,
17472 cx: &mut Context<Self>,
17473 ) {
17474 let Some(workspace) = self.workspace() else {
17475 cx.propagate();
17476 return;
17477 };
17478
17479 let selections = self.selections.all::<usize>(cx);
17480 let multi_buffer = self.buffer.read(cx);
17481 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17482 let mut new_selections_by_buffer = HashMap::default();
17483 for selection in selections {
17484 for (buffer, range, _) in
17485 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17486 {
17487 let mut range = range.to_point(buffer);
17488 range.start.column = 0;
17489 range.end.column = buffer.line_len(range.end.row);
17490 new_selections_by_buffer
17491 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17492 .or_insert(Vec::new())
17493 .push(range)
17494 }
17495 }
17496
17497 let proposed_changes_buffers = new_selections_by_buffer
17498 .into_iter()
17499 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17500 .collect::<Vec<_>>();
17501 let proposed_changes_editor = cx.new(|cx| {
17502 ProposedChangesEditor::new(
17503 "Proposed changes",
17504 proposed_changes_buffers,
17505 self.project.clone(),
17506 window,
17507 cx,
17508 )
17509 });
17510
17511 window.defer(cx, move |window, cx| {
17512 workspace.update(cx, |workspace, cx| {
17513 workspace.active_pane().update(cx, |pane, cx| {
17514 pane.add_item(
17515 Box::new(proposed_changes_editor),
17516 true,
17517 true,
17518 None,
17519 window,
17520 cx,
17521 );
17522 });
17523 });
17524 });
17525 }
17526
17527 pub fn open_excerpts_in_split(
17528 &mut self,
17529 _: &OpenExcerptsSplit,
17530 window: &mut Window,
17531 cx: &mut Context<Self>,
17532 ) {
17533 self.open_excerpts_common(None, true, window, cx)
17534 }
17535
17536 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17537 self.open_excerpts_common(None, false, window, cx)
17538 }
17539
17540 fn open_excerpts_common(
17541 &mut self,
17542 jump_data: Option<JumpData>,
17543 split: bool,
17544 window: &mut Window,
17545 cx: &mut Context<Self>,
17546 ) {
17547 let Some(workspace) = self.workspace() else {
17548 cx.propagate();
17549 return;
17550 };
17551
17552 if self.buffer.read(cx).is_singleton() {
17553 cx.propagate();
17554 return;
17555 }
17556
17557 let mut new_selections_by_buffer = HashMap::default();
17558 match &jump_data {
17559 Some(JumpData::MultiBufferPoint {
17560 excerpt_id,
17561 position,
17562 anchor,
17563 line_offset_from_top,
17564 }) => {
17565 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17566 if let Some(buffer) = multi_buffer_snapshot
17567 .buffer_id_for_excerpt(*excerpt_id)
17568 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17569 {
17570 let buffer_snapshot = buffer.read(cx).snapshot();
17571 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17572 language::ToPoint::to_point(anchor, &buffer_snapshot)
17573 } else {
17574 buffer_snapshot.clip_point(*position, Bias::Left)
17575 };
17576 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17577 new_selections_by_buffer.insert(
17578 buffer,
17579 (
17580 vec![jump_to_offset..jump_to_offset],
17581 Some(*line_offset_from_top),
17582 ),
17583 );
17584 }
17585 }
17586 Some(JumpData::MultiBufferRow {
17587 row,
17588 line_offset_from_top,
17589 }) => {
17590 let point = MultiBufferPoint::new(row.0, 0);
17591 if let Some((buffer, buffer_point, _)) =
17592 self.buffer.read(cx).point_to_buffer_point(point, cx)
17593 {
17594 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17595 new_selections_by_buffer
17596 .entry(buffer)
17597 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17598 .0
17599 .push(buffer_offset..buffer_offset)
17600 }
17601 }
17602 None => {
17603 let selections = self.selections.all::<usize>(cx);
17604 let multi_buffer = self.buffer.read(cx);
17605 for selection in selections {
17606 for (snapshot, range, _, anchor) in multi_buffer
17607 .snapshot(cx)
17608 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17609 {
17610 if let Some(anchor) = anchor {
17611 // selection is in a deleted hunk
17612 let Some(buffer_id) = anchor.buffer_id else {
17613 continue;
17614 };
17615 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17616 continue;
17617 };
17618 let offset = text::ToOffset::to_offset(
17619 &anchor.text_anchor,
17620 &buffer_handle.read(cx).snapshot(),
17621 );
17622 let range = offset..offset;
17623 new_selections_by_buffer
17624 .entry(buffer_handle)
17625 .or_insert((Vec::new(), None))
17626 .0
17627 .push(range)
17628 } else {
17629 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17630 else {
17631 continue;
17632 };
17633 new_selections_by_buffer
17634 .entry(buffer_handle)
17635 .or_insert((Vec::new(), None))
17636 .0
17637 .push(range)
17638 }
17639 }
17640 }
17641 }
17642 }
17643
17644 new_selections_by_buffer
17645 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17646
17647 if new_selections_by_buffer.is_empty() {
17648 return;
17649 }
17650
17651 // We defer the pane interaction because we ourselves are a workspace item
17652 // and activating a new item causes the pane to call a method on us reentrantly,
17653 // which panics if we're on the stack.
17654 window.defer(cx, move |window, cx| {
17655 workspace.update(cx, |workspace, cx| {
17656 let pane = if split {
17657 workspace.adjacent_pane(window, cx)
17658 } else {
17659 workspace.active_pane().clone()
17660 };
17661
17662 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17663 let editor = buffer
17664 .read(cx)
17665 .file()
17666 .is_none()
17667 .then(|| {
17668 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17669 // so `workspace.open_project_item` will never find them, always opening a new editor.
17670 // Instead, we try to activate the existing editor in the pane first.
17671 let (editor, pane_item_index) =
17672 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17673 let editor = item.downcast::<Editor>()?;
17674 let singleton_buffer =
17675 editor.read(cx).buffer().read(cx).as_singleton()?;
17676 if singleton_buffer == buffer {
17677 Some((editor, i))
17678 } else {
17679 None
17680 }
17681 })?;
17682 pane.update(cx, |pane, cx| {
17683 pane.activate_item(pane_item_index, true, true, window, cx)
17684 });
17685 Some(editor)
17686 })
17687 .flatten()
17688 .unwrap_or_else(|| {
17689 workspace.open_project_item::<Self>(
17690 pane.clone(),
17691 buffer,
17692 true,
17693 true,
17694 window,
17695 cx,
17696 )
17697 });
17698
17699 editor.update(cx, |editor, cx| {
17700 let autoscroll = match scroll_offset {
17701 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17702 None => Autoscroll::newest(),
17703 };
17704 let nav_history = editor.nav_history.take();
17705 editor.change_selections(Some(autoscroll), window, cx, |s| {
17706 s.select_ranges(ranges);
17707 });
17708 editor.nav_history = nav_history;
17709 });
17710 }
17711 })
17712 });
17713 }
17714
17715 // For now, don't allow opening excerpts in buffers that aren't backed by
17716 // regular project files.
17717 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17718 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17719 }
17720
17721 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17722 let snapshot = self.buffer.read(cx).read(cx);
17723 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17724 Some(
17725 ranges
17726 .iter()
17727 .map(move |range| {
17728 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17729 })
17730 .collect(),
17731 )
17732 }
17733
17734 fn selection_replacement_ranges(
17735 &self,
17736 range: Range<OffsetUtf16>,
17737 cx: &mut App,
17738 ) -> Vec<Range<OffsetUtf16>> {
17739 let selections = self.selections.all::<OffsetUtf16>(cx);
17740 let newest_selection = selections
17741 .iter()
17742 .max_by_key(|selection| selection.id)
17743 .unwrap();
17744 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17745 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17746 let snapshot = self.buffer.read(cx).read(cx);
17747 selections
17748 .into_iter()
17749 .map(|mut selection| {
17750 selection.start.0 =
17751 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17752 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17753 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17754 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17755 })
17756 .collect()
17757 }
17758
17759 fn report_editor_event(
17760 &self,
17761 event_type: &'static str,
17762 file_extension: Option<String>,
17763 cx: &App,
17764 ) {
17765 if cfg!(any(test, feature = "test-support")) {
17766 return;
17767 }
17768
17769 let Some(project) = &self.project else { return };
17770
17771 // If None, we are in a file without an extension
17772 let file = self
17773 .buffer
17774 .read(cx)
17775 .as_singleton()
17776 .and_then(|b| b.read(cx).file());
17777 let file_extension = file_extension.or(file
17778 .as_ref()
17779 .and_then(|file| Path::new(file.file_name(cx)).extension())
17780 .and_then(|e| e.to_str())
17781 .map(|a| a.to_string()));
17782
17783 let vim_mode = vim_enabled(cx);
17784
17785 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17786 let copilot_enabled = edit_predictions_provider
17787 == language::language_settings::EditPredictionProvider::Copilot;
17788 let copilot_enabled_for_language = self
17789 .buffer
17790 .read(cx)
17791 .language_settings(cx)
17792 .show_edit_predictions;
17793
17794 let project = project.read(cx);
17795 telemetry::event!(
17796 event_type,
17797 file_extension,
17798 vim_mode,
17799 copilot_enabled,
17800 copilot_enabled_for_language,
17801 edit_predictions_provider,
17802 is_via_ssh = project.is_via_ssh(),
17803 );
17804 }
17805
17806 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17807 /// with each line being an array of {text, highlight} objects.
17808 fn copy_highlight_json(
17809 &mut self,
17810 _: &CopyHighlightJson,
17811 window: &mut Window,
17812 cx: &mut Context<Self>,
17813 ) {
17814 #[derive(Serialize)]
17815 struct Chunk<'a> {
17816 text: String,
17817 highlight: Option<&'a str>,
17818 }
17819
17820 let snapshot = self.buffer.read(cx).snapshot(cx);
17821 let range = self
17822 .selected_text_range(false, window, cx)
17823 .and_then(|selection| {
17824 if selection.range.is_empty() {
17825 None
17826 } else {
17827 Some(selection.range)
17828 }
17829 })
17830 .unwrap_or_else(|| 0..snapshot.len());
17831
17832 let chunks = snapshot.chunks(range, true);
17833 let mut lines = Vec::new();
17834 let mut line: VecDeque<Chunk> = VecDeque::new();
17835
17836 let Some(style) = self.style.as_ref() else {
17837 return;
17838 };
17839
17840 for chunk in chunks {
17841 let highlight = chunk
17842 .syntax_highlight_id
17843 .and_then(|id| id.name(&style.syntax));
17844 let mut chunk_lines = chunk.text.split('\n').peekable();
17845 while let Some(text) = chunk_lines.next() {
17846 let mut merged_with_last_token = false;
17847 if let Some(last_token) = line.back_mut() {
17848 if last_token.highlight == highlight {
17849 last_token.text.push_str(text);
17850 merged_with_last_token = true;
17851 }
17852 }
17853
17854 if !merged_with_last_token {
17855 line.push_back(Chunk {
17856 text: text.into(),
17857 highlight,
17858 });
17859 }
17860
17861 if chunk_lines.peek().is_some() {
17862 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17863 line.pop_front();
17864 }
17865 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17866 line.pop_back();
17867 }
17868
17869 lines.push(mem::take(&mut line));
17870 }
17871 }
17872 }
17873
17874 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17875 return;
17876 };
17877 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17878 }
17879
17880 pub fn open_context_menu(
17881 &mut self,
17882 _: &OpenContextMenu,
17883 window: &mut Window,
17884 cx: &mut Context<Self>,
17885 ) {
17886 self.request_autoscroll(Autoscroll::newest(), cx);
17887 let position = self.selections.newest_display(cx).start;
17888 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17889 }
17890
17891 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17892 &self.inlay_hint_cache
17893 }
17894
17895 pub fn replay_insert_event(
17896 &mut self,
17897 text: &str,
17898 relative_utf16_range: Option<Range<isize>>,
17899 window: &mut Window,
17900 cx: &mut Context<Self>,
17901 ) {
17902 if !self.input_enabled {
17903 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17904 return;
17905 }
17906 if let Some(relative_utf16_range) = relative_utf16_range {
17907 let selections = self.selections.all::<OffsetUtf16>(cx);
17908 self.change_selections(None, window, cx, |s| {
17909 let new_ranges = selections.into_iter().map(|range| {
17910 let start = OffsetUtf16(
17911 range
17912 .head()
17913 .0
17914 .saturating_add_signed(relative_utf16_range.start),
17915 );
17916 let end = OffsetUtf16(
17917 range
17918 .head()
17919 .0
17920 .saturating_add_signed(relative_utf16_range.end),
17921 );
17922 start..end
17923 });
17924 s.select_ranges(new_ranges);
17925 });
17926 }
17927
17928 self.handle_input(text, window, cx);
17929 }
17930
17931 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17932 let Some(provider) = self.semantics_provider.as_ref() else {
17933 return false;
17934 };
17935
17936 let mut supports = false;
17937 self.buffer().update(cx, |this, cx| {
17938 this.for_each_buffer(|buffer| {
17939 supports |= provider.supports_inlay_hints(buffer, cx);
17940 });
17941 });
17942
17943 supports
17944 }
17945
17946 pub fn is_focused(&self, window: &Window) -> bool {
17947 self.focus_handle.is_focused(window)
17948 }
17949
17950 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17951 cx.emit(EditorEvent::Focused);
17952
17953 if let Some(descendant) = self
17954 .last_focused_descendant
17955 .take()
17956 .and_then(|descendant| descendant.upgrade())
17957 {
17958 window.focus(&descendant);
17959 } else {
17960 if let Some(blame) = self.blame.as_ref() {
17961 blame.update(cx, GitBlame::focus)
17962 }
17963
17964 self.blink_manager.update(cx, BlinkManager::enable);
17965 self.show_cursor_names(window, cx);
17966 self.buffer.update(cx, |buffer, cx| {
17967 buffer.finalize_last_transaction(cx);
17968 if self.leader_peer_id.is_none() {
17969 buffer.set_active_selections(
17970 &self.selections.disjoint_anchors(),
17971 self.selections.line_mode,
17972 self.cursor_shape,
17973 cx,
17974 );
17975 }
17976 });
17977 }
17978 }
17979
17980 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17981 cx.emit(EditorEvent::FocusedIn)
17982 }
17983
17984 fn handle_focus_out(
17985 &mut self,
17986 event: FocusOutEvent,
17987 _window: &mut Window,
17988 cx: &mut Context<Self>,
17989 ) {
17990 if event.blurred != self.focus_handle {
17991 self.last_focused_descendant = Some(event.blurred);
17992 }
17993 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17994 }
17995
17996 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17997 self.blink_manager.update(cx, BlinkManager::disable);
17998 self.buffer
17999 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18000
18001 if let Some(blame) = self.blame.as_ref() {
18002 blame.update(cx, GitBlame::blur)
18003 }
18004 if !self.hover_state.focused(window, cx) {
18005 hide_hover(self, cx);
18006 }
18007 if !self
18008 .context_menu
18009 .borrow()
18010 .as_ref()
18011 .is_some_and(|context_menu| context_menu.focused(window, cx))
18012 {
18013 self.hide_context_menu(window, cx);
18014 }
18015 self.discard_inline_completion(false, cx);
18016 cx.emit(EditorEvent::Blurred);
18017 cx.notify();
18018 }
18019
18020 pub fn register_action<A: Action>(
18021 &mut self,
18022 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18023 ) -> Subscription {
18024 let id = self.next_editor_action_id.post_inc();
18025 let listener = Arc::new(listener);
18026 self.editor_actions.borrow_mut().insert(
18027 id,
18028 Box::new(move |window, _| {
18029 let listener = listener.clone();
18030 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18031 let action = action.downcast_ref().unwrap();
18032 if phase == DispatchPhase::Bubble {
18033 listener(action, window, cx)
18034 }
18035 })
18036 }),
18037 );
18038
18039 let editor_actions = self.editor_actions.clone();
18040 Subscription::new(move || {
18041 editor_actions.borrow_mut().remove(&id);
18042 })
18043 }
18044
18045 pub fn file_header_size(&self) -> u32 {
18046 FILE_HEADER_HEIGHT
18047 }
18048
18049 pub fn restore(
18050 &mut self,
18051 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18052 window: &mut Window,
18053 cx: &mut Context<Self>,
18054 ) {
18055 let workspace = self.workspace();
18056 let project = self.project.as_ref();
18057 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18058 let mut tasks = Vec::new();
18059 for (buffer_id, changes) in revert_changes {
18060 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18061 buffer.update(cx, |buffer, cx| {
18062 buffer.edit(
18063 changes
18064 .into_iter()
18065 .map(|(range, text)| (range, text.to_string())),
18066 None,
18067 cx,
18068 );
18069 });
18070
18071 if let Some(project) =
18072 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18073 {
18074 project.update(cx, |project, cx| {
18075 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18076 })
18077 }
18078 }
18079 }
18080 tasks
18081 });
18082 cx.spawn_in(window, async move |_, cx| {
18083 for (buffer, task) in save_tasks {
18084 let result = task.await;
18085 if result.is_err() {
18086 let Some(path) = buffer
18087 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18088 .ok()
18089 else {
18090 continue;
18091 };
18092 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18093 let Some(task) = cx
18094 .update_window_entity(&workspace, |workspace, window, cx| {
18095 workspace
18096 .open_path_preview(path, None, false, false, false, window, cx)
18097 })
18098 .ok()
18099 else {
18100 continue;
18101 };
18102 task.await.log_err();
18103 }
18104 }
18105 }
18106 })
18107 .detach();
18108 self.change_selections(None, window, cx, |selections| selections.refresh());
18109 }
18110
18111 pub fn to_pixel_point(
18112 &self,
18113 source: multi_buffer::Anchor,
18114 editor_snapshot: &EditorSnapshot,
18115 window: &mut Window,
18116 ) -> Option<gpui::Point<Pixels>> {
18117 let source_point = source.to_display_point(editor_snapshot);
18118 self.display_to_pixel_point(source_point, editor_snapshot, window)
18119 }
18120
18121 pub fn display_to_pixel_point(
18122 &self,
18123 source: DisplayPoint,
18124 editor_snapshot: &EditorSnapshot,
18125 window: &mut Window,
18126 ) -> Option<gpui::Point<Pixels>> {
18127 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18128 let text_layout_details = self.text_layout_details(window);
18129 let scroll_top = text_layout_details
18130 .scroll_anchor
18131 .scroll_position(editor_snapshot)
18132 .y;
18133
18134 if source.row().as_f32() < scroll_top.floor() {
18135 return None;
18136 }
18137 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18138 let source_y = line_height * (source.row().as_f32() - scroll_top);
18139 Some(gpui::Point::new(source_x, source_y))
18140 }
18141
18142 pub fn has_visible_completions_menu(&self) -> bool {
18143 !self.edit_prediction_preview_is_active()
18144 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18145 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18146 })
18147 }
18148
18149 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18150 self.addons
18151 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18152 }
18153
18154 pub fn unregister_addon<T: Addon>(&mut self) {
18155 self.addons.remove(&std::any::TypeId::of::<T>());
18156 }
18157
18158 pub fn addon<T: Addon>(&self) -> Option<&T> {
18159 let type_id = std::any::TypeId::of::<T>();
18160 self.addons
18161 .get(&type_id)
18162 .and_then(|item| item.to_any().downcast_ref::<T>())
18163 }
18164
18165 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18166 let text_layout_details = self.text_layout_details(window);
18167 let style = &text_layout_details.editor_style;
18168 let font_id = window.text_system().resolve_font(&style.text.font());
18169 let font_size = style.text.font_size.to_pixels(window.rem_size());
18170 let line_height = style.text.line_height_in_pixels(window.rem_size());
18171 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18172
18173 gpui::Size::new(em_width, line_height)
18174 }
18175
18176 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18177 self.load_diff_task.clone()
18178 }
18179
18180 fn read_metadata_from_db(
18181 &mut self,
18182 item_id: u64,
18183 workspace_id: WorkspaceId,
18184 window: &mut Window,
18185 cx: &mut Context<Editor>,
18186 ) {
18187 if self.is_singleton(cx)
18188 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18189 {
18190 let buffer_snapshot = OnceCell::new();
18191
18192 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18193 if !folds.is_empty() {
18194 let snapshot =
18195 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18196 self.fold_ranges(
18197 folds
18198 .into_iter()
18199 .map(|(start, end)| {
18200 snapshot.clip_offset(start, Bias::Left)
18201 ..snapshot.clip_offset(end, Bias::Right)
18202 })
18203 .collect(),
18204 false,
18205 window,
18206 cx,
18207 );
18208 }
18209 }
18210
18211 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18212 if !selections.is_empty() {
18213 let snapshot =
18214 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18215 self.change_selections(None, window, cx, |s| {
18216 s.select_ranges(selections.into_iter().map(|(start, end)| {
18217 snapshot.clip_offset(start, Bias::Left)
18218 ..snapshot.clip_offset(end, Bias::Right)
18219 }));
18220 });
18221 }
18222 };
18223 }
18224
18225 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18226 }
18227}
18228
18229fn vim_enabled(cx: &App) -> bool {
18230 cx.global::<SettingsStore>()
18231 .raw_user_settings()
18232 .get("vim_mode")
18233 == Some(&serde_json::Value::Bool(true))
18234}
18235
18236// Consider user intent and default settings
18237fn choose_completion_range(
18238 completion: &Completion,
18239 intent: CompletionIntent,
18240 buffer: &Entity<Buffer>,
18241 cx: &mut Context<Editor>,
18242) -> Range<usize> {
18243 fn should_replace(
18244 completion: &Completion,
18245 insert_range: &Range<text::Anchor>,
18246 intent: CompletionIntent,
18247 completion_mode_setting: LspInsertMode,
18248 buffer: &Buffer,
18249 ) -> bool {
18250 // specific actions take precedence over settings
18251 match intent {
18252 CompletionIntent::CompleteWithInsert => return false,
18253 CompletionIntent::CompleteWithReplace => return true,
18254 CompletionIntent::Complete | CompletionIntent::Compose => {}
18255 }
18256
18257 match completion_mode_setting {
18258 LspInsertMode::Insert => false,
18259 LspInsertMode::Replace => true,
18260 LspInsertMode::ReplaceSubsequence => {
18261 let mut text_to_replace = buffer.chars_for_range(
18262 buffer.anchor_before(completion.replace_range.start)
18263 ..buffer.anchor_after(completion.replace_range.end),
18264 );
18265 let mut completion_text = completion.new_text.chars();
18266
18267 // is `text_to_replace` a subsequence of `completion_text`
18268 text_to_replace
18269 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18270 }
18271 LspInsertMode::ReplaceSuffix => {
18272 let range_after_cursor = insert_range.end..completion.replace_range.end;
18273
18274 let text_after_cursor = buffer
18275 .text_for_range(
18276 buffer.anchor_before(range_after_cursor.start)
18277 ..buffer.anchor_after(range_after_cursor.end),
18278 )
18279 .collect::<String>();
18280 completion.new_text.ends_with(&text_after_cursor)
18281 }
18282 }
18283 }
18284
18285 let buffer = buffer.read(cx);
18286
18287 if let CompletionSource::Lsp {
18288 insert_range: Some(insert_range),
18289 ..
18290 } = &completion.source
18291 {
18292 let completion_mode_setting =
18293 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18294 .completions
18295 .lsp_insert_mode;
18296
18297 if !should_replace(
18298 completion,
18299 &insert_range,
18300 intent,
18301 completion_mode_setting,
18302 buffer,
18303 ) {
18304 return insert_range.to_offset(buffer);
18305 }
18306 }
18307
18308 completion.replace_range.to_offset(buffer)
18309}
18310
18311fn insert_extra_newline_brackets(
18312 buffer: &MultiBufferSnapshot,
18313 range: Range<usize>,
18314 language: &language::LanguageScope,
18315) -> bool {
18316 let leading_whitespace_len = buffer
18317 .reversed_chars_at(range.start)
18318 .take_while(|c| c.is_whitespace() && *c != '\n')
18319 .map(|c| c.len_utf8())
18320 .sum::<usize>();
18321 let trailing_whitespace_len = buffer
18322 .chars_at(range.end)
18323 .take_while(|c| c.is_whitespace() && *c != '\n')
18324 .map(|c| c.len_utf8())
18325 .sum::<usize>();
18326 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18327
18328 language.brackets().any(|(pair, enabled)| {
18329 let pair_start = pair.start.trim_end();
18330 let pair_end = pair.end.trim_start();
18331
18332 enabled
18333 && pair.newline
18334 && buffer.contains_str_at(range.end, pair_end)
18335 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18336 })
18337}
18338
18339fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18340 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18341 [(buffer, range, _)] => (*buffer, range.clone()),
18342 _ => return false,
18343 };
18344 let pair = {
18345 let mut result: Option<BracketMatch> = None;
18346
18347 for pair in buffer
18348 .all_bracket_ranges(range.clone())
18349 .filter(move |pair| {
18350 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18351 })
18352 {
18353 let len = pair.close_range.end - pair.open_range.start;
18354
18355 if let Some(existing) = &result {
18356 let existing_len = existing.close_range.end - existing.open_range.start;
18357 if len > existing_len {
18358 continue;
18359 }
18360 }
18361
18362 result = Some(pair);
18363 }
18364
18365 result
18366 };
18367 let Some(pair) = pair else {
18368 return false;
18369 };
18370 pair.newline_only
18371 && buffer
18372 .chars_for_range(pair.open_range.end..range.start)
18373 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18374 .all(|c| c.is_whitespace() && c != '\n')
18375}
18376
18377fn get_uncommitted_diff_for_buffer(
18378 project: &Entity<Project>,
18379 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18380 buffer: Entity<MultiBuffer>,
18381 cx: &mut App,
18382) -> Task<()> {
18383 let mut tasks = Vec::new();
18384 project.update(cx, |project, cx| {
18385 for buffer in buffers {
18386 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18387 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18388 }
18389 }
18390 });
18391 cx.spawn(async move |cx| {
18392 let diffs = future::join_all(tasks).await;
18393 buffer
18394 .update(cx, |buffer, cx| {
18395 for diff in diffs.into_iter().flatten() {
18396 buffer.add_diff(diff, cx);
18397 }
18398 })
18399 .ok();
18400 })
18401}
18402
18403fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18404 let tab_size = tab_size.get() as usize;
18405 let mut width = offset;
18406
18407 for ch in text.chars() {
18408 width += if ch == '\t' {
18409 tab_size - (width % tab_size)
18410 } else {
18411 1
18412 };
18413 }
18414
18415 width - offset
18416}
18417
18418#[cfg(test)]
18419mod tests {
18420 use super::*;
18421
18422 #[test]
18423 fn test_string_size_with_expanded_tabs() {
18424 let nz = |val| NonZeroU32::new(val).unwrap();
18425 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18426 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18427 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18428 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18429 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18430 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18431 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18432 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18433 }
18434}
18435
18436/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18437struct WordBreakingTokenizer<'a> {
18438 input: &'a str,
18439}
18440
18441impl<'a> WordBreakingTokenizer<'a> {
18442 fn new(input: &'a str) -> Self {
18443 Self { input }
18444 }
18445}
18446
18447fn is_char_ideographic(ch: char) -> bool {
18448 use unicode_script::Script::*;
18449 use unicode_script::UnicodeScript;
18450 matches!(ch.script(), Han | Tangut | Yi)
18451}
18452
18453fn is_grapheme_ideographic(text: &str) -> bool {
18454 text.chars().any(is_char_ideographic)
18455}
18456
18457fn is_grapheme_whitespace(text: &str) -> bool {
18458 text.chars().any(|x| x.is_whitespace())
18459}
18460
18461fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18462 text.chars().next().map_or(false, |ch| {
18463 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18464 })
18465}
18466
18467#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18468enum WordBreakToken<'a> {
18469 Word { token: &'a str, grapheme_len: usize },
18470 InlineWhitespace { token: &'a str, grapheme_len: usize },
18471 Newline,
18472}
18473
18474impl<'a> Iterator for WordBreakingTokenizer<'a> {
18475 /// Yields a span, the count of graphemes in the token, and whether it was
18476 /// whitespace. Note that it also breaks at word boundaries.
18477 type Item = WordBreakToken<'a>;
18478
18479 fn next(&mut self) -> Option<Self::Item> {
18480 use unicode_segmentation::UnicodeSegmentation;
18481 if self.input.is_empty() {
18482 return None;
18483 }
18484
18485 let mut iter = self.input.graphemes(true).peekable();
18486 let mut offset = 0;
18487 let mut grapheme_len = 0;
18488 if let Some(first_grapheme) = iter.next() {
18489 let is_newline = first_grapheme == "\n";
18490 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18491 offset += first_grapheme.len();
18492 grapheme_len += 1;
18493 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18494 if let Some(grapheme) = iter.peek().copied() {
18495 if should_stay_with_preceding_ideograph(grapheme) {
18496 offset += grapheme.len();
18497 grapheme_len += 1;
18498 }
18499 }
18500 } else {
18501 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18502 let mut next_word_bound = words.peek().copied();
18503 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18504 next_word_bound = words.next();
18505 }
18506 while let Some(grapheme) = iter.peek().copied() {
18507 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18508 break;
18509 };
18510 if is_grapheme_whitespace(grapheme) != is_whitespace
18511 || (grapheme == "\n") != is_newline
18512 {
18513 break;
18514 };
18515 offset += grapheme.len();
18516 grapheme_len += 1;
18517 iter.next();
18518 }
18519 }
18520 let token = &self.input[..offset];
18521 self.input = &self.input[offset..];
18522 if token == "\n" {
18523 Some(WordBreakToken::Newline)
18524 } else if is_whitespace {
18525 Some(WordBreakToken::InlineWhitespace {
18526 token,
18527 grapheme_len,
18528 })
18529 } else {
18530 Some(WordBreakToken::Word {
18531 token,
18532 grapheme_len,
18533 })
18534 }
18535 } else {
18536 None
18537 }
18538 }
18539}
18540
18541#[test]
18542fn test_word_breaking_tokenizer() {
18543 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18544 ("", &[]),
18545 (" ", &[whitespace(" ", 2)]),
18546 ("Ʒ", &[word("Ʒ", 1)]),
18547 ("Ǽ", &[word("Ǽ", 1)]),
18548 ("⋑", &[word("⋑", 1)]),
18549 ("⋑⋑", &[word("⋑⋑", 2)]),
18550 (
18551 "原理,进而",
18552 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18553 ),
18554 (
18555 "hello world",
18556 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18557 ),
18558 (
18559 "hello, world",
18560 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18561 ),
18562 (
18563 " hello world",
18564 &[
18565 whitespace(" ", 2),
18566 word("hello", 5),
18567 whitespace(" ", 1),
18568 word("world", 5),
18569 ],
18570 ),
18571 (
18572 "这是什么 \n 钢笔",
18573 &[
18574 word("这", 1),
18575 word("是", 1),
18576 word("什", 1),
18577 word("么", 1),
18578 whitespace(" ", 1),
18579 newline(),
18580 whitespace(" ", 1),
18581 word("钢", 1),
18582 word("笔", 1),
18583 ],
18584 ),
18585 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18586 ];
18587
18588 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18589 WordBreakToken::Word {
18590 token,
18591 grapheme_len,
18592 }
18593 }
18594
18595 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18596 WordBreakToken::InlineWhitespace {
18597 token,
18598 grapheme_len,
18599 }
18600 }
18601
18602 fn newline() -> WordBreakToken<'static> {
18603 WordBreakToken::Newline
18604 }
18605
18606 for (input, result) in tests {
18607 assert_eq!(
18608 WordBreakingTokenizer::new(input)
18609 .collect::<Vec<_>>()
18610 .as_slice(),
18611 *result,
18612 );
18613 }
18614}
18615
18616fn wrap_with_prefix(
18617 line_prefix: String,
18618 unwrapped_text: String,
18619 wrap_column: usize,
18620 tab_size: NonZeroU32,
18621 preserve_existing_whitespace: bool,
18622) -> String {
18623 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18624 let mut wrapped_text = String::new();
18625 let mut current_line = line_prefix.clone();
18626
18627 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18628 let mut current_line_len = line_prefix_len;
18629 let mut in_whitespace = false;
18630 for token in tokenizer {
18631 let have_preceding_whitespace = in_whitespace;
18632 match token {
18633 WordBreakToken::Word {
18634 token,
18635 grapheme_len,
18636 } => {
18637 in_whitespace = false;
18638 if current_line_len + grapheme_len > wrap_column
18639 && current_line_len != line_prefix_len
18640 {
18641 wrapped_text.push_str(current_line.trim_end());
18642 wrapped_text.push('\n');
18643 current_line.truncate(line_prefix.len());
18644 current_line_len = line_prefix_len;
18645 }
18646 current_line.push_str(token);
18647 current_line_len += grapheme_len;
18648 }
18649 WordBreakToken::InlineWhitespace {
18650 mut token,
18651 mut grapheme_len,
18652 } => {
18653 in_whitespace = true;
18654 if have_preceding_whitespace && !preserve_existing_whitespace {
18655 continue;
18656 }
18657 if !preserve_existing_whitespace {
18658 token = " ";
18659 grapheme_len = 1;
18660 }
18661 if current_line_len + grapheme_len > wrap_column {
18662 wrapped_text.push_str(current_line.trim_end());
18663 wrapped_text.push('\n');
18664 current_line.truncate(line_prefix.len());
18665 current_line_len = line_prefix_len;
18666 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18667 current_line.push_str(token);
18668 current_line_len += grapheme_len;
18669 }
18670 }
18671 WordBreakToken::Newline => {
18672 in_whitespace = true;
18673 if preserve_existing_whitespace {
18674 wrapped_text.push_str(current_line.trim_end());
18675 wrapped_text.push('\n');
18676 current_line.truncate(line_prefix.len());
18677 current_line_len = line_prefix_len;
18678 } else if have_preceding_whitespace {
18679 continue;
18680 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18681 {
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 current_line_len != line_prefix_len {
18687 current_line.push(' ');
18688 current_line_len += 1;
18689 }
18690 }
18691 }
18692 }
18693
18694 if !current_line.is_empty() {
18695 wrapped_text.push_str(¤t_line);
18696 }
18697 wrapped_text
18698}
18699
18700#[test]
18701fn test_wrap_with_prefix() {
18702 assert_eq!(
18703 wrap_with_prefix(
18704 "# ".to_string(),
18705 "abcdefg".to_string(),
18706 4,
18707 NonZeroU32::new(4).unwrap(),
18708 false,
18709 ),
18710 "# abcdefg"
18711 );
18712 assert_eq!(
18713 wrap_with_prefix(
18714 "".to_string(),
18715 "\thello world".to_string(),
18716 8,
18717 NonZeroU32::new(4).unwrap(),
18718 false,
18719 ),
18720 "hello\nworld"
18721 );
18722 assert_eq!(
18723 wrap_with_prefix(
18724 "// ".to_string(),
18725 "xx \nyy zz aa bb cc".to_string(),
18726 12,
18727 NonZeroU32::new(4).unwrap(),
18728 false,
18729 ),
18730 "// xx yy zz\n// aa bb cc"
18731 );
18732 assert_eq!(
18733 wrap_with_prefix(
18734 String::new(),
18735 "这是什么 \n 钢笔".to_string(),
18736 3,
18737 NonZeroU32::new(4).unwrap(),
18738 false,
18739 ),
18740 "这是什\n么 钢\n笔"
18741 );
18742}
18743
18744pub trait CollaborationHub {
18745 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18746 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18747 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18748}
18749
18750impl CollaborationHub for Entity<Project> {
18751 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18752 self.read(cx).collaborators()
18753 }
18754
18755 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18756 self.read(cx).user_store().read(cx).participant_indices()
18757 }
18758
18759 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18760 let this = self.read(cx);
18761 let user_ids = this.collaborators().values().map(|c| c.user_id);
18762 this.user_store().read_with(cx, |user_store, cx| {
18763 user_store.participant_names(user_ids, cx)
18764 })
18765 }
18766}
18767
18768pub trait SemanticsProvider {
18769 fn hover(
18770 &self,
18771 buffer: &Entity<Buffer>,
18772 position: text::Anchor,
18773 cx: &mut App,
18774 ) -> Option<Task<Vec<project::Hover>>>;
18775
18776 fn inlay_hints(
18777 &self,
18778 buffer_handle: Entity<Buffer>,
18779 range: Range<text::Anchor>,
18780 cx: &mut App,
18781 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18782
18783 fn resolve_inlay_hint(
18784 &self,
18785 hint: InlayHint,
18786 buffer_handle: Entity<Buffer>,
18787 server_id: LanguageServerId,
18788 cx: &mut App,
18789 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18790
18791 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18792
18793 fn document_highlights(
18794 &self,
18795 buffer: &Entity<Buffer>,
18796 position: text::Anchor,
18797 cx: &mut App,
18798 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18799
18800 fn definitions(
18801 &self,
18802 buffer: &Entity<Buffer>,
18803 position: text::Anchor,
18804 kind: GotoDefinitionKind,
18805 cx: &mut App,
18806 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18807
18808 fn range_for_rename(
18809 &self,
18810 buffer: &Entity<Buffer>,
18811 position: text::Anchor,
18812 cx: &mut App,
18813 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18814
18815 fn perform_rename(
18816 &self,
18817 buffer: &Entity<Buffer>,
18818 position: text::Anchor,
18819 new_name: String,
18820 cx: &mut App,
18821 ) -> Option<Task<Result<ProjectTransaction>>>;
18822}
18823
18824pub trait CompletionProvider {
18825 fn completions(
18826 &self,
18827 excerpt_id: ExcerptId,
18828 buffer: &Entity<Buffer>,
18829 buffer_position: text::Anchor,
18830 trigger: CompletionContext,
18831 window: &mut Window,
18832 cx: &mut Context<Editor>,
18833 ) -> Task<Result<Option<Vec<Completion>>>>;
18834
18835 fn resolve_completions(
18836 &self,
18837 buffer: Entity<Buffer>,
18838 completion_indices: Vec<usize>,
18839 completions: Rc<RefCell<Box<[Completion]>>>,
18840 cx: &mut Context<Editor>,
18841 ) -> Task<Result<bool>>;
18842
18843 fn apply_additional_edits_for_completion(
18844 &self,
18845 _buffer: Entity<Buffer>,
18846 _completions: Rc<RefCell<Box<[Completion]>>>,
18847 _completion_index: usize,
18848 _push_to_history: bool,
18849 _cx: &mut Context<Editor>,
18850 ) -> Task<Result<Option<language::Transaction>>> {
18851 Task::ready(Ok(None))
18852 }
18853
18854 fn is_completion_trigger(
18855 &self,
18856 buffer: &Entity<Buffer>,
18857 position: language::Anchor,
18858 text: &str,
18859 trigger_in_words: bool,
18860 cx: &mut Context<Editor>,
18861 ) -> bool;
18862
18863 fn sort_completions(&self) -> bool {
18864 true
18865 }
18866
18867 fn filter_completions(&self) -> bool {
18868 true
18869 }
18870}
18871
18872pub trait CodeActionProvider {
18873 fn id(&self) -> Arc<str>;
18874
18875 fn code_actions(
18876 &self,
18877 buffer: &Entity<Buffer>,
18878 range: Range<text::Anchor>,
18879 window: &mut Window,
18880 cx: &mut App,
18881 ) -> Task<Result<Vec<CodeAction>>>;
18882
18883 fn apply_code_action(
18884 &self,
18885 buffer_handle: Entity<Buffer>,
18886 action: CodeAction,
18887 excerpt_id: ExcerptId,
18888 push_to_history: bool,
18889 window: &mut Window,
18890 cx: &mut App,
18891 ) -> Task<Result<ProjectTransaction>>;
18892}
18893
18894impl CodeActionProvider for Entity<Project> {
18895 fn id(&self) -> Arc<str> {
18896 "project".into()
18897 }
18898
18899 fn code_actions(
18900 &self,
18901 buffer: &Entity<Buffer>,
18902 range: Range<text::Anchor>,
18903 _window: &mut Window,
18904 cx: &mut App,
18905 ) -> Task<Result<Vec<CodeAction>>> {
18906 self.update(cx, |project, cx| {
18907 let code_lens = project.code_lens(buffer, range.clone(), cx);
18908 let code_actions = project.code_actions(buffer, range, None, cx);
18909 cx.background_spawn(async move {
18910 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18911 Ok(code_lens
18912 .context("code lens fetch")?
18913 .into_iter()
18914 .chain(code_actions.context("code action fetch")?)
18915 .collect())
18916 })
18917 })
18918 }
18919
18920 fn apply_code_action(
18921 &self,
18922 buffer_handle: Entity<Buffer>,
18923 action: CodeAction,
18924 _excerpt_id: ExcerptId,
18925 push_to_history: bool,
18926 _window: &mut Window,
18927 cx: &mut App,
18928 ) -> Task<Result<ProjectTransaction>> {
18929 self.update(cx, |project, cx| {
18930 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18931 })
18932 }
18933}
18934
18935fn snippet_completions(
18936 project: &Project,
18937 buffer: &Entity<Buffer>,
18938 buffer_position: text::Anchor,
18939 cx: &mut App,
18940) -> Task<Result<Vec<Completion>>> {
18941 let languages = buffer.read(cx).languages_at(buffer_position);
18942 let snippet_store = project.snippets().read(cx);
18943
18944 let scopes: Vec<_> = languages
18945 .iter()
18946 .filter_map(|language| {
18947 let language_name = language.lsp_id();
18948 let snippets = snippet_store.snippets_for(Some(language_name), cx);
18949
18950 if snippets.is_empty() {
18951 None
18952 } else {
18953 Some((language.default_scope(), snippets))
18954 }
18955 })
18956 .collect();
18957
18958 if scopes.is_empty() {
18959 return Task::ready(Ok(vec![]));
18960 }
18961
18962 let snapshot = buffer.read(cx).text_snapshot();
18963 let chars: String = snapshot
18964 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18965 .collect();
18966 let executor = cx.background_executor().clone();
18967
18968 cx.background_spawn(async move {
18969 let mut all_results: Vec<Completion> = Vec::new();
18970 for (scope, snippets) in scopes.into_iter() {
18971 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
18972 let mut last_word = chars
18973 .chars()
18974 .take_while(|c| classifier.is_word(*c))
18975 .collect::<String>();
18976 last_word = last_word.chars().rev().collect();
18977
18978 if last_word.is_empty() {
18979 return Ok(vec![]);
18980 }
18981
18982 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18983 let to_lsp = |point: &text::Anchor| {
18984 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18985 point_to_lsp(end)
18986 };
18987 let lsp_end = to_lsp(&buffer_position);
18988
18989 let candidates = snippets
18990 .iter()
18991 .enumerate()
18992 .flat_map(|(ix, snippet)| {
18993 snippet
18994 .prefix
18995 .iter()
18996 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18997 })
18998 .collect::<Vec<StringMatchCandidate>>();
18999
19000 let mut matches = fuzzy::match_strings(
19001 &candidates,
19002 &last_word,
19003 last_word.chars().any(|c| c.is_uppercase()),
19004 100,
19005 &Default::default(),
19006 executor.clone(),
19007 )
19008 .await;
19009
19010 // Remove all candidates where the query's start does not match the start of any word in the candidate
19011 if let Some(query_start) = last_word.chars().next() {
19012 matches.retain(|string_match| {
19013 split_words(&string_match.string).any(|word| {
19014 // Check that the first codepoint of the word as lowercase matches the first
19015 // codepoint of the query as lowercase
19016 word.chars()
19017 .flat_map(|codepoint| codepoint.to_lowercase())
19018 .zip(query_start.to_lowercase())
19019 .all(|(word_cp, query_cp)| word_cp == query_cp)
19020 })
19021 });
19022 }
19023
19024 let matched_strings = matches
19025 .into_iter()
19026 .map(|m| m.string)
19027 .collect::<HashSet<_>>();
19028
19029 let mut result: Vec<Completion> = snippets
19030 .iter()
19031 .filter_map(|snippet| {
19032 let matching_prefix = snippet
19033 .prefix
19034 .iter()
19035 .find(|prefix| matched_strings.contains(*prefix))?;
19036 let start = as_offset - last_word.len();
19037 let start = snapshot.anchor_before(start);
19038 let range = start..buffer_position;
19039 let lsp_start = to_lsp(&start);
19040 let lsp_range = lsp::Range {
19041 start: lsp_start,
19042 end: lsp_end,
19043 };
19044 Some(Completion {
19045 replace_range: range,
19046 new_text: snippet.body.clone(),
19047 source: CompletionSource::Lsp {
19048 insert_range: None,
19049 server_id: LanguageServerId(usize::MAX),
19050 resolved: true,
19051 lsp_completion: Box::new(lsp::CompletionItem {
19052 label: snippet.prefix.first().unwrap().clone(),
19053 kind: Some(CompletionItemKind::SNIPPET),
19054 label_details: snippet.description.as_ref().map(|description| {
19055 lsp::CompletionItemLabelDetails {
19056 detail: Some(description.clone()),
19057 description: None,
19058 }
19059 }),
19060 insert_text_format: Some(InsertTextFormat::SNIPPET),
19061 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19062 lsp::InsertReplaceEdit {
19063 new_text: snippet.body.clone(),
19064 insert: lsp_range,
19065 replace: lsp_range,
19066 },
19067 )),
19068 filter_text: Some(snippet.body.clone()),
19069 sort_text: Some(char::MAX.to_string()),
19070 ..lsp::CompletionItem::default()
19071 }),
19072 lsp_defaults: None,
19073 },
19074 label: CodeLabel {
19075 text: matching_prefix.clone(),
19076 runs: Vec::new(),
19077 filter_range: 0..matching_prefix.len(),
19078 },
19079 icon_path: None,
19080 documentation: snippet.description.clone().map(|description| {
19081 CompletionDocumentation::SingleLine(description.into())
19082 }),
19083 insert_text_mode: None,
19084 confirm: None,
19085 })
19086 })
19087 .collect();
19088
19089 all_results.append(&mut result);
19090 }
19091
19092 Ok(all_results)
19093 })
19094}
19095
19096impl CompletionProvider for Entity<Project> {
19097 fn completions(
19098 &self,
19099 _excerpt_id: ExcerptId,
19100 buffer: &Entity<Buffer>,
19101 buffer_position: text::Anchor,
19102 options: CompletionContext,
19103 _window: &mut Window,
19104 cx: &mut Context<Editor>,
19105 ) -> Task<Result<Option<Vec<Completion>>>> {
19106 self.update(cx, |project, cx| {
19107 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19108 let project_completions = project.completions(buffer, buffer_position, options, cx);
19109 cx.background_spawn(async move {
19110 let snippets_completions = snippets.await?;
19111 match project_completions.await? {
19112 Some(mut completions) => {
19113 completions.extend(snippets_completions);
19114 Ok(Some(completions))
19115 }
19116 None => {
19117 if snippets_completions.is_empty() {
19118 Ok(None)
19119 } else {
19120 Ok(Some(snippets_completions))
19121 }
19122 }
19123 }
19124 })
19125 })
19126 }
19127
19128 fn resolve_completions(
19129 &self,
19130 buffer: Entity<Buffer>,
19131 completion_indices: Vec<usize>,
19132 completions: Rc<RefCell<Box<[Completion]>>>,
19133 cx: &mut Context<Editor>,
19134 ) -> Task<Result<bool>> {
19135 self.update(cx, |project, cx| {
19136 project.lsp_store().update(cx, |lsp_store, cx| {
19137 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19138 })
19139 })
19140 }
19141
19142 fn apply_additional_edits_for_completion(
19143 &self,
19144 buffer: Entity<Buffer>,
19145 completions: Rc<RefCell<Box<[Completion]>>>,
19146 completion_index: usize,
19147 push_to_history: bool,
19148 cx: &mut Context<Editor>,
19149 ) -> Task<Result<Option<language::Transaction>>> {
19150 self.update(cx, |project, cx| {
19151 project.lsp_store().update(cx, |lsp_store, cx| {
19152 lsp_store.apply_additional_edits_for_completion(
19153 buffer,
19154 completions,
19155 completion_index,
19156 push_to_history,
19157 cx,
19158 )
19159 })
19160 })
19161 }
19162
19163 fn is_completion_trigger(
19164 &self,
19165 buffer: &Entity<Buffer>,
19166 position: language::Anchor,
19167 text: &str,
19168 trigger_in_words: bool,
19169 cx: &mut Context<Editor>,
19170 ) -> bool {
19171 let mut chars = text.chars();
19172 let char = if let Some(char) = chars.next() {
19173 char
19174 } else {
19175 return false;
19176 };
19177 if chars.next().is_some() {
19178 return false;
19179 }
19180
19181 let buffer = buffer.read(cx);
19182 let snapshot = buffer.snapshot();
19183 if !snapshot.settings_at(position, cx).show_completions_on_input {
19184 return false;
19185 }
19186 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19187 if trigger_in_words && classifier.is_word(char) {
19188 return true;
19189 }
19190
19191 buffer.completion_triggers().contains(text)
19192 }
19193}
19194
19195impl SemanticsProvider for Entity<Project> {
19196 fn hover(
19197 &self,
19198 buffer: &Entity<Buffer>,
19199 position: text::Anchor,
19200 cx: &mut App,
19201 ) -> Option<Task<Vec<project::Hover>>> {
19202 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19203 }
19204
19205 fn document_highlights(
19206 &self,
19207 buffer: &Entity<Buffer>,
19208 position: text::Anchor,
19209 cx: &mut App,
19210 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19211 Some(self.update(cx, |project, cx| {
19212 project.document_highlights(buffer, position, cx)
19213 }))
19214 }
19215
19216 fn definitions(
19217 &self,
19218 buffer: &Entity<Buffer>,
19219 position: text::Anchor,
19220 kind: GotoDefinitionKind,
19221 cx: &mut App,
19222 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19223 Some(self.update(cx, |project, cx| match kind {
19224 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19225 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19226 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19227 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19228 }))
19229 }
19230
19231 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19232 // TODO: make this work for remote projects
19233 self.update(cx, |this, cx| {
19234 buffer.update(cx, |buffer, cx| {
19235 this.any_language_server_supports_inlay_hints(buffer, cx)
19236 })
19237 })
19238 }
19239
19240 fn inlay_hints(
19241 &self,
19242 buffer_handle: Entity<Buffer>,
19243 range: Range<text::Anchor>,
19244 cx: &mut App,
19245 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19246 Some(self.update(cx, |project, cx| {
19247 project.inlay_hints(buffer_handle, range, cx)
19248 }))
19249 }
19250
19251 fn resolve_inlay_hint(
19252 &self,
19253 hint: InlayHint,
19254 buffer_handle: Entity<Buffer>,
19255 server_id: LanguageServerId,
19256 cx: &mut App,
19257 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19258 Some(self.update(cx, |project, cx| {
19259 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19260 }))
19261 }
19262
19263 fn range_for_rename(
19264 &self,
19265 buffer: &Entity<Buffer>,
19266 position: text::Anchor,
19267 cx: &mut App,
19268 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19269 Some(self.update(cx, |project, cx| {
19270 let buffer = buffer.clone();
19271 let task = project.prepare_rename(buffer.clone(), position, cx);
19272 cx.spawn(async move |_, cx| {
19273 Ok(match task.await? {
19274 PrepareRenameResponse::Success(range) => Some(range),
19275 PrepareRenameResponse::InvalidPosition => None,
19276 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19277 // Fallback on using TreeSitter info to determine identifier range
19278 buffer.update(cx, |buffer, _| {
19279 let snapshot = buffer.snapshot();
19280 let (range, kind) = snapshot.surrounding_word(position);
19281 if kind != Some(CharKind::Word) {
19282 return None;
19283 }
19284 Some(
19285 snapshot.anchor_before(range.start)
19286 ..snapshot.anchor_after(range.end),
19287 )
19288 })?
19289 }
19290 })
19291 })
19292 }))
19293 }
19294
19295 fn perform_rename(
19296 &self,
19297 buffer: &Entity<Buffer>,
19298 position: text::Anchor,
19299 new_name: String,
19300 cx: &mut App,
19301 ) -> Option<Task<Result<ProjectTransaction>>> {
19302 Some(self.update(cx, |project, cx| {
19303 project.perform_rename(buffer.clone(), position, new_name, cx)
19304 }))
19305 }
19306}
19307
19308fn inlay_hint_settings(
19309 location: Anchor,
19310 snapshot: &MultiBufferSnapshot,
19311 cx: &mut Context<Editor>,
19312) -> InlayHintSettings {
19313 let file = snapshot.file_at(location);
19314 let language = snapshot.language_at(location).map(|l| l.name());
19315 language_settings(language, file, cx).inlay_hints
19316}
19317
19318fn consume_contiguous_rows(
19319 contiguous_row_selections: &mut Vec<Selection<Point>>,
19320 selection: &Selection<Point>,
19321 display_map: &DisplaySnapshot,
19322 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19323) -> (MultiBufferRow, MultiBufferRow) {
19324 contiguous_row_selections.push(selection.clone());
19325 let start_row = MultiBufferRow(selection.start.row);
19326 let mut end_row = ending_row(selection, display_map);
19327
19328 while let Some(next_selection) = selections.peek() {
19329 if next_selection.start.row <= end_row.0 {
19330 end_row = ending_row(next_selection, display_map);
19331 contiguous_row_selections.push(selections.next().unwrap().clone());
19332 } else {
19333 break;
19334 }
19335 }
19336 (start_row, end_row)
19337}
19338
19339fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19340 if next_selection.end.column > 0 || next_selection.is_empty() {
19341 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19342 } else {
19343 MultiBufferRow(next_selection.end.row)
19344 }
19345}
19346
19347impl EditorSnapshot {
19348 pub fn remote_selections_in_range<'a>(
19349 &'a self,
19350 range: &'a Range<Anchor>,
19351 collaboration_hub: &dyn CollaborationHub,
19352 cx: &'a App,
19353 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19354 let participant_names = collaboration_hub.user_names(cx);
19355 let participant_indices = collaboration_hub.user_participant_indices(cx);
19356 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19357 let collaborators_by_replica_id = collaborators_by_peer_id
19358 .iter()
19359 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19360 .collect::<HashMap<_, _>>();
19361 self.buffer_snapshot
19362 .selections_in_range(range, false)
19363 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19364 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19365 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19366 let user_name = participant_names.get(&collaborator.user_id).cloned();
19367 Some(RemoteSelection {
19368 replica_id,
19369 selection,
19370 cursor_shape,
19371 line_mode,
19372 participant_index,
19373 peer_id: collaborator.peer_id,
19374 user_name,
19375 })
19376 })
19377 }
19378
19379 pub fn hunks_for_ranges(
19380 &self,
19381 ranges: impl IntoIterator<Item = Range<Point>>,
19382 ) -> Vec<MultiBufferDiffHunk> {
19383 let mut hunks = Vec::new();
19384 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19385 HashMap::default();
19386 for query_range in ranges {
19387 let query_rows =
19388 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19389 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19390 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19391 ) {
19392 // Include deleted hunks that are adjacent to the query range, because
19393 // otherwise they would be missed.
19394 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19395 if hunk.status().is_deleted() {
19396 intersects_range |= hunk.row_range.start == query_rows.end;
19397 intersects_range |= hunk.row_range.end == query_rows.start;
19398 }
19399 if intersects_range {
19400 if !processed_buffer_rows
19401 .entry(hunk.buffer_id)
19402 .or_default()
19403 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19404 {
19405 continue;
19406 }
19407 hunks.push(hunk);
19408 }
19409 }
19410 }
19411
19412 hunks
19413 }
19414
19415 fn display_diff_hunks_for_rows<'a>(
19416 &'a self,
19417 display_rows: Range<DisplayRow>,
19418 folded_buffers: &'a HashSet<BufferId>,
19419 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19420 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19421 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19422
19423 self.buffer_snapshot
19424 .diff_hunks_in_range(buffer_start..buffer_end)
19425 .filter_map(|hunk| {
19426 if folded_buffers.contains(&hunk.buffer_id) {
19427 return None;
19428 }
19429
19430 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19431 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19432
19433 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19434 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19435
19436 let display_hunk = if hunk_display_start.column() != 0 {
19437 DisplayDiffHunk::Folded {
19438 display_row: hunk_display_start.row(),
19439 }
19440 } else {
19441 let mut end_row = hunk_display_end.row();
19442 if hunk_display_end.column() > 0 {
19443 end_row.0 += 1;
19444 }
19445 let is_created_file = hunk.is_created_file();
19446 DisplayDiffHunk::Unfolded {
19447 status: hunk.status(),
19448 diff_base_byte_range: hunk.diff_base_byte_range,
19449 display_row_range: hunk_display_start.row()..end_row,
19450 multi_buffer_range: Anchor::range_in_buffer(
19451 hunk.excerpt_id,
19452 hunk.buffer_id,
19453 hunk.buffer_range,
19454 ),
19455 is_created_file,
19456 }
19457 };
19458
19459 Some(display_hunk)
19460 })
19461 }
19462
19463 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19464 self.display_snapshot.buffer_snapshot.language_at(position)
19465 }
19466
19467 pub fn is_focused(&self) -> bool {
19468 self.is_focused
19469 }
19470
19471 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19472 self.placeholder_text.as_ref()
19473 }
19474
19475 pub fn scroll_position(&self) -> gpui::Point<f32> {
19476 self.scroll_anchor.scroll_position(&self.display_snapshot)
19477 }
19478
19479 fn gutter_dimensions(
19480 &self,
19481 font_id: FontId,
19482 font_size: Pixels,
19483 max_line_number_width: Pixels,
19484 cx: &App,
19485 ) -> Option<GutterDimensions> {
19486 if !self.show_gutter {
19487 return None;
19488 }
19489
19490 let descent = cx.text_system().descent(font_id, font_size);
19491 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19492 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19493
19494 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19495 matches!(
19496 ProjectSettings::get_global(cx).git.git_gutter,
19497 Some(GitGutterSetting::TrackedFiles)
19498 )
19499 });
19500 let gutter_settings = EditorSettings::get_global(cx).gutter;
19501 let show_line_numbers = self
19502 .show_line_numbers
19503 .unwrap_or(gutter_settings.line_numbers);
19504 let line_gutter_width = if show_line_numbers {
19505 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19506 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19507 max_line_number_width.max(min_width_for_number_on_gutter)
19508 } else {
19509 0.0.into()
19510 };
19511
19512 let show_code_actions = self
19513 .show_code_actions
19514 .unwrap_or(gutter_settings.code_actions);
19515
19516 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19517 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19518
19519 let git_blame_entries_width =
19520 self.git_blame_gutter_max_author_length
19521 .map(|max_author_length| {
19522 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19523 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19524
19525 /// The number of characters to dedicate to gaps and margins.
19526 const SPACING_WIDTH: usize = 4;
19527
19528 let max_char_count = max_author_length.min(renderer.max_author_length())
19529 + ::git::SHORT_SHA_LENGTH
19530 + MAX_RELATIVE_TIMESTAMP.len()
19531 + SPACING_WIDTH;
19532
19533 em_advance * max_char_count
19534 });
19535
19536 let is_singleton = self.buffer_snapshot.is_singleton();
19537
19538 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19539 left_padding += if !is_singleton {
19540 em_width * 4.0
19541 } else if show_code_actions || show_runnables || show_breakpoints {
19542 em_width * 3.0
19543 } else if show_git_gutter && show_line_numbers {
19544 em_width * 2.0
19545 } else if show_git_gutter || show_line_numbers {
19546 em_width
19547 } else {
19548 px(0.)
19549 };
19550
19551 let shows_folds = is_singleton && gutter_settings.folds;
19552
19553 let right_padding = if shows_folds && show_line_numbers {
19554 em_width * 4.0
19555 } else if shows_folds || (!is_singleton && show_line_numbers) {
19556 em_width * 3.0
19557 } else if show_line_numbers {
19558 em_width
19559 } else {
19560 px(0.)
19561 };
19562
19563 Some(GutterDimensions {
19564 left_padding,
19565 right_padding,
19566 width: line_gutter_width + left_padding + right_padding,
19567 margin: -descent,
19568 git_blame_entries_width,
19569 })
19570 }
19571
19572 pub fn render_crease_toggle(
19573 &self,
19574 buffer_row: MultiBufferRow,
19575 row_contains_cursor: bool,
19576 editor: Entity<Editor>,
19577 window: &mut Window,
19578 cx: &mut App,
19579 ) -> Option<AnyElement> {
19580 let folded = self.is_line_folded(buffer_row);
19581 let mut is_foldable = false;
19582
19583 if let Some(crease) = self
19584 .crease_snapshot
19585 .query_row(buffer_row, &self.buffer_snapshot)
19586 {
19587 is_foldable = true;
19588 match crease {
19589 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19590 if let Some(render_toggle) = render_toggle {
19591 let toggle_callback =
19592 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19593 if folded {
19594 editor.update(cx, |editor, cx| {
19595 editor.fold_at(buffer_row, window, cx)
19596 });
19597 } else {
19598 editor.update(cx, |editor, cx| {
19599 editor.unfold_at(buffer_row, window, cx)
19600 });
19601 }
19602 });
19603 return Some((render_toggle)(
19604 buffer_row,
19605 folded,
19606 toggle_callback,
19607 window,
19608 cx,
19609 ));
19610 }
19611 }
19612 }
19613 }
19614
19615 is_foldable |= self.starts_indent(buffer_row);
19616
19617 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19618 Some(
19619 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19620 .toggle_state(folded)
19621 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19622 if folded {
19623 this.unfold_at(buffer_row, window, cx);
19624 } else {
19625 this.fold_at(buffer_row, window, cx);
19626 }
19627 }))
19628 .into_any_element(),
19629 )
19630 } else {
19631 None
19632 }
19633 }
19634
19635 pub fn render_crease_trailer(
19636 &self,
19637 buffer_row: MultiBufferRow,
19638 window: &mut Window,
19639 cx: &mut App,
19640 ) -> Option<AnyElement> {
19641 let folded = self.is_line_folded(buffer_row);
19642 if let Crease::Inline { render_trailer, .. } = self
19643 .crease_snapshot
19644 .query_row(buffer_row, &self.buffer_snapshot)?
19645 {
19646 let render_trailer = render_trailer.as_ref()?;
19647 Some(render_trailer(buffer_row, folded, window, cx))
19648 } else {
19649 None
19650 }
19651 }
19652}
19653
19654impl Deref for EditorSnapshot {
19655 type Target = DisplaySnapshot;
19656
19657 fn deref(&self) -> &Self::Target {
19658 &self.display_snapshot
19659 }
19660}
19661
19662#[derive(Clone, Debug, PartialEq, Eq)]
19663pub enum EditorEvent {
19664 InputIgnored {
19665 text: Arc<str>,
19666 },
19667 InputHandled {
19668 utf16_range_to_replace: Option<Range<isize>>,
19669 text: Arc<str>,
19670 },
19671 ExcerptsAdded {
19672 buffer: Entity<Buffer>,
19673 predecessor: ExcerptId,
19674 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19675 },
19676 ExcerptsRemoved {
19677 ids: Vec<ExcerptId>,
19678 },
19679 BufferFoldToggled {
19680 ids: Vec<ExcerptId>,
19681 folded: bool,
19682 },
19683 ExcerptsEdited {
19684 ids: Vec<ExcerptId>,
19685 },
19686 ExcerptsExpanded {
19687 ids: Vec<ExcerptId>,
19688 },
19689 BufferEdited,
19690 Edited {
19691 transaction_id: clock::Lamport,
19692 },
19693 Reparsed(BufferId),
19694 Focused,
19695 FocusedIn,
19696 Blurred,
19697 DirtyChanged,
19698 Saved,
19699 TitleChanged,
19700 DiffBaseChanged,
19701 SelectionsChanged {
19702 local: bool,
19703 },
19704 ScrollPositionChanged {
19705 local: bool,
19706 autoscroll: bool,
19707 },
19708 Closed,
19709 TransactionUndone {
19710 transaction_id: clock::Lamport,
19711 },
19712 TransactionBegun {
19713 transaction_id: clock::Lamport,
19714 },
19715 Reloaded,
19716 CursorShapeChanged,
19717 PushedToNavHistory {
19718 anchor: Anchor,
19719 is_deactivate: bool,
19720 },
19721}
19722
19723impl EventEmitter<EditorEvent> for Editor {}
19724
19725impl Focusable for Editor {
19726 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19727 self.focus_handle.clone()
19728 }
19729}
19730
19731impl Render for Editor {
19732 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19733 let settings = ThemeSettings::get_global(cx);
19734
19735 let mut text_style = match self.mode {
19736 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19737 color: cx.theme().colors().editor_foreground,
19738 font_family: settings.ui_font.family.clone(),
19739 font_features: settings.ui_font.features.clone(),
19740 font_fallbacks: settings.ui_font.fallbacks.clone(),
19741 font_size: rems(0.875).into(),
19742 font_weight: settings.ui_font.weight,
19743 line_height: relative(settings.buffer_line_height.value()),
19744 ..Default::default()
19745 },
19746 EditorMode::Full { .. } => TextStyle {
19747 color: cx.theme().colors().editor_foreground,
19748 font_family: settings.buffer_font.family.clone(),
19749 font_features: settings.buffer_font.features.clone(),
19750 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19751 font_size: settings.buffer_font_size(cx).into(),
19752 font_weight: settings.buffer_font.weight,
19753 line_height: relative(settings.buffer_line_height.value()),
19754 ..Default::default()
19755 },
19756 };
19757 if let Some(text_style_refinement) = &self.text_style_refinement {
19758 text_style.refine(text_style_refinement)
19759 }
19760
19761 let background = match self.mode {
19762 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19763 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19764 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19765 };
19766
19767 EditorElement::new(
19768 &cx.entity(),
19769 EditorStyle {
19770 background,
19771 local_player: cx.theme().players().local(),
19772 text: text_style,
19773 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19774 syntax: cx.theme().syntax().clone(),
19775 status: cx.theme().status().clone(),
19776 inlay_hints_style: make_inlay_hints_style(cx),
19777 inline_completion_styles: make_suggestion_styles(cx),
19778 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19779 },
19780 )
19781 }
19782}
19783
19784impl EntityInputHandler for Editor {
19785 fn text_for_range(
19786 &mut self,
19787 range_utf16: Range<usize>,
19788 adjusted_range: &mut Option<Range<usize>>,
19789 _: &mut Window,
19790 cx: &mut Context<Self>,
19791 ) -> Option<String> {
19792 let snapshot = self.buffer.read(cx).read(cx);
19793 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19794 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19795 if (start.0..end.0) != range_utf16 {
19796 adjusted_range.replace(start.0..end.0);
19797 }
19798 Some(snapshot.text_for_range(start..end).collect())
19799 }
19800
19801 fn selected_text_range(
19802 &mut self,
19803 ignore_disabled_input: bool,
19804 _: &mut Window,
19805 cx: &mut Context<Self>,
19806 ) -> Option<UTF16Selection> {
19807 // Prevent the IME menu from appearing when holding down an alphabetic key
19808 // while input is disabled.
19809 if !ignore_disabled_input && !self.input_enabled {
19810 return None;
19811 }
19812
19813 let selection = self.selections.newest::<OffsetUtf16>(cx);
19814 let range = selection.range();
19815
19816 Some(UTF16Selection {
19817 range: range.start.0..range.end.0,
19818 reversed: selection.reversed,
19819 })
19820 }
19821
19822 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19823 let snapshot = self.buffer.read(cx).read(cx);
19824 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19825 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19826 }
19827
19828 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19829 self.clear_highlights::<InputComposition>(cx);
19830 self.ime_transaction.take();
19831 }
19832
19833 fn replace_text_in_range(
19834 &mut self,
19835 range_utf16: Option<Range<usize>>,
19836 text: &str,
19837 window: &mut Window,
19838 cx: &mut Context<Self>,
19839 ) {
19840 if !self.input_enabled {
19841 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19842 return;
19843 }
19844
19845 self.transact(window, cx, |this, window, cx| {
19846 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19847 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19848 Some(this.selection_replacement_ranges(range_utf16, cx))
19849 } else {
19850 this.marked_text_ranges(cx)
19851 };
19852
19853 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19854 let newest_selection_id = this.selections.newest_anchor().id;
19855 this.selections
19856 .all::<OffsetUtf16>(cx)
19857 .iter()
19858 .zip(ranges_to_replace.iter())
19859 .find_map(|(selection, range)| {
19860 if selection.id == newest_selection_id {
19861 Some(
19862 (range.start.0 as isize - selection.head().0 as isize)
19863 ..(range.end.0 as isize - selection.head().0 as isize),
19864 )
19865 } else {
19866 None
19867 }
19868 })
19869 });
19870
19871 cx.emit(EditorEvent::InputHandled {
19872 utf16_range_to_replace: range_to_replace,
19873 text: text.into(),
19874 });
19875
19876 if let Some(new_selected_ranges) = new_selected_ranges {
19877 this.change_selections(None, window, cx, |selections| {
19878 selections.select_ranges(new_selected_ranges)
19879 });
19880 this.backspace(&Default::default(), window, cx);
19881 }
19882
19883 this.handle_input(text, window, cx);
19884 });
19885
19886 if let Some(transaction) = self.ime_transaction {
19887 self.buffer.update(cx, |buffer, cx| {
19888 buffer.group_until_transaction(transaction, cx);
19889 });
19890 }
19891
19892 self.unmark_text(window, cx);
19893 }
19894
19895 fn replace_and_mark_text_in_range(
19896 &mut self,
19897 range_utf16: Option<Range<usize>>,
19898 text: &str,
19899 new_selected_range_utf16: Option<Range<usize>>,
19900 window: &mut Window,
19901 cx: &mut Context<Self>,
19902 ) {
19903 if !self.input_enabled {
19904 return;
19905 }
19906
19907 let transaction = self.transact(window, cx, |this, window, cx| {
19908 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19909 let snapshot = this.buffer.read(cx).read(cx);
19910 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19911 for marked_range in &mut marked_ranges {
19912 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19913 marked_range.start.0 += relative_range_utf16.start;
19914 marked_range.start =
19915 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19916 marked_range.end =
19917 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19918 }
19919 }
19920 Some(marked_ranges)
19921 } else if let Some(range_utf16) = range_utf16 {
19922 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19923 Some(this.selection_replacement_ranges(range_utf16, cx))
19924 } else {
19925 None
19926 };
19927
19928 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19929 let newest_selection_id = this.selections.newest_anchor().id;
19930 this.selections
19931 .all::<OffsetUtf16>(cx)
19932 .iter()
19933 .zip(ranges_to_replace.iter())
19934 .find_map(|(selection, range)| {
19935 if selection.id == newest_selection_id {
19936 Some(
19937 (range.start.0 as isize - selection.head().0 as isize)
19938 ..(range.end.0 as isize - selection.head().0 as isize),
19939 )
19940 } else {
19941 None
19942 }
19943 })
19944 });
19945
19946 cx.emit(EditorEvent::InputHandled {
19947 utf16_range_to_replace: range_to_replace,
19948 text: text.into(),
19949 });
19950
19951 if let Some(ranges) = ranges_to_replace {
19952 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19953 }
19954
19955 let marked_ranges = {
19956 let snapshot = this.buffer.read(cx).read(cx);
19957 this.selections
19958 .disjoint_anchors()
19959 .iter()
19960 .map(|selection| {
19961 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19962 })
19963 .collect::<Vec<_>>()
19964 };
19965
19966 if text.is_empty() {
19967 this.unmark_text(window, cx);
19968 } else {
19969 this.highlight_text::<InputComposition>(
19970 marked_ranges.clone(),
19971 HighlightStyle {
19972 underline: Some(UnderlineStyle {
19973 thickness: px(1.),
19974 color: None,
19975 wavy: false,
19976 }),
19977 ..Default::default()
19978 },
19979 cx,
19980 );
19981 }
19982
19983 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19984 let use_autoclose = this.use_autoclose;
19985 let use_auto_surround = this.use_auto_surround;
19986 this.set_use_autoclose(false);
19987 this.set_use_auto_surround(false);
19988 this.handle_input(text, window, cx);
19989 this.set_use_autoclose(use_autoclose);
19990 this.set_use_auto_surround(use_auto_surround);
19991
19992 if let Some(new_selected_range) = new_selected_range_utf16 {
19993 let snapshot = this.buffer.read(cx).read(cx);
19994 let new_selected_ranges = marked_ranges
19995 .into_iter()
19996 .map(|marked_range| {
19997 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19998 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19999 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20000 snapshot.clip_offset_utf16(new_start, Bias::Left)
20001 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20002 })
20003 .collect::<Vec<_>>();
20004
20005 drop(snapshot);
20006 this.change_selections(None, window, cx, |selections| {
20007 selections.select_ranges(new_selected_ranges)
20008 });
20009 }
20010 });
20011
20012 self.ime_transaction = self.ime_transaction.or(transaction);
20013 if let Some(transaction) = self.ime_transaction {
20014 self.buffer.update(cx, |buffer, cx| {
20015 buffer.group_until_transaction(transaction, cx);
20016 });
20017 }
20018
20019 if self.text_highlights::<InputComposition>(cx).is_none() {
20020 self.ime_transaction.take();
20021 }
20022 }
20023
20024 fn bounds_for_range(
20025 &mut self,
20026 range_utf16: Range<usize>,
20027 element_bounds: gpui::Bounds<Pixels>,
20028 window: &mut Window,
20029 cx: &mut Context<Self>,
20030 ) -> Option<gpui::Bounds<Pixels>> {
20031 let text_layout_details = self.text_layout_details(window);
20032 let gpui::Size {
20033 width: em_width,
20034 height: line_height,
20035 } = self.character_size(window);
20036
20037 let snapshot = self.snapshot(window, cx);
20038 let scroll_position = snapshot.scroll_position();
20039 let scroll_left = scroll_position.x * em_width;
20040
20041 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20042 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20043 + self.gutter_dimensions.width
20044 + self.gutter_dimensions.margin;
20045 let y = line_height * (start.row().as_f32() - scroll_position.y);
20046
20047 Some(Bounds {
20048 origin: element_bounds.origin + point(x, y),
20049 size: size(em_width, line_height),
20050 })
20051 }
20052
20053 fn character_index_for_point(
20054 &mut self,
20055 point: gpui::Point<Pixels>,
20056 _window: &mut Window,
20057 _cx: &mut Context<Self>,
20058 ) -> Option<usize> {
20059 let position_map = self.last_position_map.as_ref()?;
20060 if !position_map.text_hitbox.contains(&point) {
20061 return None;
20062 }
20063 let display_point = position_map.point_for_position(point).previous_valid;
20064 let anchor = position_map
20065 .snapshot
20066 .display_point_to_anchor(display_point, Bias::Left);
20067 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20068 Some(utf16_offset.0)
20069 }
20070}
20071
20072trait SelectionExt {
20073 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20074 fn spanned_rows(
20075 &self,
20076 include_end_if_at_line_start: bool,
20077 map: &DisplaySnapshot,
20078 ) -> Range<MultiBufferRow>;
20079}
20080
20081impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20082 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20083 let start = self
20084 .start
20085 .to_point(&map.buffer_snapshot)
20086 .to_display_point(map);
20087 let end = self
20088 .end
20089 .to_point(&map.buffer_snapshot)
20090 .to_display_point(map);
20091 if self.reversed {
20092 end..start
20093 } else {
20094 start..end
20095 }
20096 }
20097
20098 fn spanned_rows(
20099 &self,
20100 include_end_if_at_line_start: bool,
20101 map: &DisplaySnapshot,
20102 ) -> Range<MultiBufferRow> {
20103 let start = self.start.to_point(&map.buffer_snapshot);
20104 let mut end = self.end.to_point(&map.buffer_snapshot);
20105 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20106 end.row -= 1;
20107 }
20108
20109 let buffer_start = map.prev_line_boundary(start).0;
20110 let buffer_end = map.next_line_boundary(end).0;
20111 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20112 }
20113}
20114
20115impl<T: InvalidationRegion> InvalidationStack<T> {
20116 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20117 where
20118 S: Clone + ToOffset,
20119 {
20120 while let Some(region) = self.last() {
20121 let all_selections_inside_invalidation_ranges =
20122 if selections.len() == region.ranges().len() {
20123 selections
20124 .iter()
20125 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20126 .all(|(selection, invalidation_range)| {
20127 let head = selection.head().to_offset(buffer);
20128 invalidation_range.start <= head && invalidation_range.end >= head
20129 })
20130 } else {
20131 false
20132 };
20133
20134 if all_selections_inside_invalidation_ranges {
20135 break;
20136 } else {
20137 self.pop();
20138 }
20139 }
20140 }
20141}
20142
20143impl<T> Default for InvalidationStack<T> {
20144 fn default() -> Self {
20145 Self(Default::default())
20146 }
20147}
20148
20149impl<T> Deref for InvalidationStack<T> {
20150 type Target = Vec<T>;
20151
20152 fn deref(&self) -> &Self::Target {
20153 &self.0
20154 }
20155}
20156
20157impl<T> DerefMut for InvalidationStack<T> {
20158 fn deref_mut(&mut self) -> &mut Self::Target {
20159 &mut self.0
20160 }
20161}
20162
20163impl InvalidationRegion for SnippetState {
20164 fn ranges(&self) -> &[Range<Anchor>] {
20165 &self.ranges[self.active_index]
20166 }
20167}
20168
20169fn inline_completion_edit_text(
20170 current_snapshot: &BufferSnapshot,
20171 edits: &[(Range<Anchor>, String)],
20172 edit_preview: &EditPreview,
20173 include_deletions: bool,
20174 cx: &App,
20175) -> HighlightedText {
20176 let edits = edits
20177 .iter()
20178 .map(|(anchor, text)| {
20179 (
20180 anchor.start.text_anchor..anchor.end.text_anchor,
20181 text.clone(),
20182 )
20183 })
20184 .collect::<Vec<_>>();
20185
20186 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20187}
20188
20189pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20190 match severity {
20191 DiagnosticSeverity::ERROR => colors.error,
20192 DiagnosticSeverity::WARNING => colors.warning,
20193 DiagnosticSeverity::INFORMATION => colors.info,
20194 DiagnosticSeverity::HINT => colors.info,
20195 _ => colors.ignored,
20196 }
20197}
20198
20199pub fn styled_runs_for_code_label<'a>(
20200 label: &'a CodeLabel,
20201 syntax_theme: &'a theme::SyntaxTheme,
20202) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20203 let fade_out = HighlightStyle {
20204 fade_out: Some(0.35),
20205 ..Default::default()
20206 };
20207
20208 let mut prev_end = label.filter_range.end;
20209 label
20210 .runs
20211 .iter()
20212 .enumerate()
20213 .flat_map(move |(ix, (range, highlight_id))| {
20214 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20215 style
20216 } else {
20217 return Default::default();
20218 };
20219 let mut muted_style = style;
20220 muted_style.highlight(fade_out);
20221
20222 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20223 if range.start >= label.filter_range.end {
20224 if range.start > prev_end {
20225 runs.push((prev_end..range.start, fade_out));
20226 }
20227 runs.push((range.clone(), muted_style));
20228 } else if range.end <= label.filter_range.end {
20229 runs.push((range.clone(), style));
20230 } else {
20231 runs.push((range.start..label.filter_range.end, style));
20232 runs.push((label.filter_range.end..range.end, muted_style));
20233 }
20234 prev_end = cmp::max(prev_end, range.end);
20235
20236 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20237 runs.push((prev_end..label.text.len(), fade_out));
20238 }
20239
20240 runs
20241 })
20242}
20243
20244pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20245 let mut prev_index = 0;
20246 let mut prev_codepoint: Option<char> = None;
20247 text.char_indices()
20248 .chain([(text.len(), '\0')])
20249 .filter_map(move |(index, codepoint)| {
20250 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20251 let is_boundary = index == text.len()
20252 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20253 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20254 if is_boundary {
20255 let chunk = &text[prev_index..index];
20256 prev_index = index;
20257 Some(chunk)
20258 } else {
20259 None
20260 }
20261 })
20262}
20263
20264pub trait RangeToAnchorExt: Sized {
20265 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20266
20267 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20268 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20269 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20270 }
20271}
20272
20273impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20274 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20275 let start_offset = self.start.to_offset(snapshot);
20276 let end_offset = self.end.to_offset(snapshot);
20277 if start_offset == end_offset {
20278 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20279 } else {
20280 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20281 }
20282 }
20283}
20284
20285pub trait RowExt {
20286 fn as_f32(&self) -> f32;
20287
20288 fn next_row(&self) -> Self;
20289
20290 fn previous_row(&self) -> Self;
20291
20292 fn minus(&self, other: Self) -> u32;
20293}
20294
20295impl RowExt for DisplayRow {
20296 fn as_f32(&self) -> f32 {
20297 self.0 as f32
20298 }
20299
20300 fn next_row(&self) -> Self {
20301 Self(self.0 + 1)
20302 }
20303
20304 fn previous_row(&self) -> Self {
20305 Self(self.0.saturating_sub(1))
20306 }
20307
20308 fn minus(&self, other: Self) -> u32 {
20309 self.0 - other.0
20310 }
20311}
20312
20313impl RowExt for MultiBufferRow {
20314 fn as_f32(&self) -> f32 {
20315 self.0 as f32
20316 }
20317
20318 fn next_row(&self) -> Self {
20319 Self(self.0 + 1)
20320 }
20321
20322 fn previous_row(&self) -> Self {
20323 Self(self.0.saturating_sub(1))
20324 }
20325
20326 fn minus(&self, other: Self) -> u32 {
20327 self.0 - other.0
20328 }
20329}
20330
20331trait RowRangeExt {
20332 type Row;
20333
20334 fn len(&self) -> usize;
20335
20336 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20337}
20338
20339impl RowRangeExt for Range<MultiBufferRow> {
20340 type Row = MultiBufferRow;
20341
20342 fn len(&self) -> usize {
20343 (self.end.0 - self.start.0) as usize
20344 }
20345
20346 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20347 (self.start.0..self.end.0).map(MultiBufferRow)
20348 }
20349}
20350
20351impl RowRangeExt for Range<DisplayRow> {
20352 type Row = DisplayRow;
20353
20354 fn len(&self) -> usize {
20355 (self.end.0 - self.start.0) as usize
20356 }
20357
20358 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20359 (self.start.0..self.end.0).map(DisplayRow)
20360 }
20361}
20362
20363/// If select range has more than one line, we
20364/// just point the cursor to range.start.
20365fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20366 if range.start.row == range.end.row {
20367 range
20368 } else {
20369 range.start..range.start
20370 }
20371}
20372pub struct KillRing(ClipboardItem);
20373impl Global for KillRing {}
20374
20375const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20376
20377enum BreakpointPromptEditAction {
20378 Log,
20379 Condition,
20380 HitCondition,
20381}
20382
20383struct BreakpointPromptEditor {
20384 pub(crate) prompt: Entity<Editor>,
20385 editor: WeakEntity<Editor>,
20386 breakpoint_anchor: Anchor,
20387 breakpoint: Breakpoint,
20388 edit_action: BreakpointPromptEditAction,
20389 block_ids: HashSet<CustomBlockId>,
20390 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20391 _subscriptions: Vec<Subscription>,
20392}
20393
20394impl BreakpointPromptEditor {
20395 const MAX_LINES: u8 = 4;
20396
20397 fn new(
20398 editor: WeakEntity<Editor>,
20399 breakpoint_anchor: Anchor,
20400 breakpoint: Breakpoint,
20401 edit_action: BreakpointPromptEditAction,
20402 window: &mut Window,
20403 cx: &mut Context<Self>,
20404 ) -> Self {
20405 let base_text = match edit_action {
20406 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20407 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20408 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20409 }
20410 .map(|msg| msg.to_string())
20411 .unwrap_or_default();
20412
20413 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20414 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20415
20416 let prompt = cx.new(|cx| {
20417 let mut prompt = Editor::new(
20418 EditorMode::AutoHeight {
20419 max_lines: Self::MAX_LINES as usize,
20420 },
20421 buffer,
20422 None,
20423 window,
20424 cx,
20425 );
20426 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20427 prompt.set_show_cursor_when_unfocused(false, cx);
20428 prompt.set_placeholder_text(
20429 match edit_action {
20430 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20431 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20432 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20433 },
20434 cx,
20435 );
20436
20437 prompt
20438 });
20439
20440 Self {
20441 prompt,
20442 editor,
20443 breakpoint_anchor,
20444 breakpoint,
20445 edit_action,
20446 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20447 block_ids: Default::default(),
20448 _subscriptions: vec![],
20449 }
20450 }
20451
20452 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20453 self.block_ids.extend(block_ids)
20454 }
20455
20456 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20457 if let Some(editor) = self.editor.upgrade() {
20458 let message = self
20459 .prompt
20460 .read(cx)
20461 .buffer
20462 .read(cx)
20463 .as_singleton()
20464 .expect("A multi buffer in breakpoint prompt isn't possible")
20465 .read(cx)
20466 .as_rope()
20467 .to_string();
20468
20469 editor.update(cx, |editor, cx| {
20470 editor.edit_breakpoint_at_anchor(
20471 self.breakpoint_anchor,
20472 self.breakpoint.clone(),
20473 match self.edit_action {
20474 BreakpointPromptEditAction::Log => {
20475 BreakpointEditAction::EditLogMessage(message.into())
20476 }
20477 BreakpointPromptEditAction::Condition => {
20478 BreakpointEditAction::EditCondition(message.into())
20479 }
20480 BreakpointPromptEditAction::HitCondition => {
20481 BreakpointEditAction::EditHitCondition(message.into())
20482 }
20483 },
20484 cx,
20485 );
20486
20487 editor.remove_blocks(self.block_ids.clone(), None, cx);
20488 cx.focus_self(window);
20489 });
20490 }
20491 }
20492
20493 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20494 self.editor
20495 .update(cx, |editor, cx| {
20496 editor.remove_blocks(self.block_ids.clone(), None, cx);
20497 window.focus(&editor.focus_handle);
20498 })
20499 .log_err();
20500 }
20501
20502 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20503 let settings = ThemeSettings::get_global(cx);
20504 let text_style = TextStyle {
20505 color: if self.prompt.read(cx).read_only(cx) {
20506 cx.theme().colors().text_disabled
20507 } else {
20508 cx.theme().colors().text
20509 },
20510 font_family: settings.buffer_font.family.clone(),
20511 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20512 font_size: settings.buffer_font_size(cx).into(),
20513 font_weight: settings.buffer_font.weight,
20514 line_height: relative(settings.buffer_line_height.value()),
20515 ..Default::default()
20516 };
20517 EditorElement::new(
20518 &self.prompt,
20519 EditorStyle {
20520 background: cx.theme().colors().editor_background,
20521 local_player: cx.theme().players().local(),
20522 text: text_style,
20523 ..Default::default()
20524 },
20525 )
20526 }
20527}
20528
20529impl Render for BreakpointPromptEditor {
20530 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20531 let gutter_dimensions = *self.gutter_dimensions.lock();
20532 h_flex()
20533 .key_context("Editor")
20534 .bg(cx.theme().colors().editor_background)
20535 .border_y_1()
20536 .border_color(cx.theme().status().info_border)
20537 .size_full()
20538 .py(window.line_height() / 2.5)
20539 .on_action(cx.listener(Self::confirm))
20540 .on_action(cx.listener(Self::cancel))
20541 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20542 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20543 }
20544}
20545
20546impl Focusable for BreakpointPromptEditor {
20547 fn focus_handle(&self, cx: &App) -> FocusHandle {
20548 self.prompt.focus_handle(cx)
20549 }
20550}
20551
20552fn all_edits_insertions_or_deletions(
20553 edits: &Vec<(Range<Anchor>, String)>,
20554 snapshot: &MultiBufferSnapshot,
20555) -> bool {
20556 let mut all_insertions = true;
20557 let mut all_deletions = true;
20558
20559 for (range, new_text) in edits.iter() {
20560 let range_is_empty = range.to_offset(&snapshot).is_empty();
20561 let text_is_empty = new_text.is_empty();
20562
20563 if range_is_empty != text_is_empty {
20564 if range_is_empty {
20565 all_deletions = false;
20566 } else {
20567 all_insertions = false;
20568 }
20569 } else {
20570 return false;
20571 }
20572
20573 if !all_insertions && !all_deletions {
20574 return false;
20575 }
20576 }
20577 all_insertions || all_deletions
20578}
20579
20580struct MissingEditPredictionKeybindingTooltip;
20581
20582impl Render for MissingEditPredictionKeybindingTooltip {
20583 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20584 ui::tooltip_container(window, cx, |container, _, cx| {
20585 container
20586 .flex_shrink_0()
20587 .max_w_80()
20588 .min_h(rems_from_px(124.))
20589 .justify_between()
20590 .child(
20591 v_flex()
20592 .flex_1()
20593 .text_ui_sm(cx)
20594 .child(Label::new("Conflict with Accept Keybinding"))
20595 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20596 )
20597 .child(
20598 h_flex()
20599 .pb_1()
20600 .gap_1()
20601 .items_end()
20602 .w_full()
20603 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20604 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20605 }))
20606 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20607 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20608 })),
20609 )
20610 })
20611 }
20612}
20613
20614#[derive(Debug, Clone, Copy, PartialEq)]
20615pub struct LineHighlight {
20616 pub background: Background,
20617 pub border: Option<gpui::Hsla>,
20618}
20619
20620impl From<Hsla> for LineHighlight {
20621 fn from(hsla: Hsla) -> Self {
20622 Self {
20623 background: hsla.into(),
20624 border: None,
20625 }
20626 }
20627}
20628
20629impl From<Background> for LineHighlight {
20630 fn from(background: Background) -> Self {
20631 Self {
20632 background,
20633 border: None,
20634 }
20635 }
20636}
20637
20638fn render_diff_hunk_controls(
20639 row: u32,
20640 status: &DiffHunkStatus,
20641 hunk_range: Range<Anchor>,
20642 is_created_file: bool,
20643 line_height: Pixels,
20644 editor: &Entity<Editor>,
20645 _window: &mut Window,
20646 cx: &mut App,
20647) -> AnyElement {
20648 h_flex()
20649 .h(line_height)
20650 .mr_1()
20651 .gap_1()
20652 .px_0p5()
20653 .pb_1()
20654 .border_x_1()
20655 .border_b_1()
20656 .border_color(cx.theme().colors().border_variant)
20657 .rounded_b_lg()
20658 .bg(cx.theme().colors().editor_background)
20659 .gap_1()
20660 .occlude()
20661 .shadow_md()
20662 .child(if status.has_secondary_hunk() {
20663 Button::new(("stage", row as u64), "Stage")
20664 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20665 .tooltip({
20666 let focus_handle = editor.focus_handle(cx);
20667 move |window, cx| {
20668 Tooltip::for_action_in(
20669 "Stage Hunk",
20670 &::git::ToggleStaged,
20671 &focus_handle,
20672 window,
20673 cx,
20674 )
20675 }
20676 })
20677 .on_click({
20678 let editor = editor.clone();
20679 move |_event, _window, cx| {
20680 editor.update(cx, |editor, cx| {
20681 editor.stage_or_unstage_diff_hunks(
20682 true,
20683 vec![hunk_range.start..hunk_range.start],
20684 cx,
20685 );
20686 });
20687 }
20688 })
20689 } else {
20690 Button::new(("unstage", row as u64), "Unstage")
20691 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20692 .tooltip({
20693 let focus_handle = editor.focus_handle(cx);
20694 move |window, cx| {
20695 Tooltip::for_action_in(
20696 "Unstage Hunk",
20697 &::git::ToggleStaged,
20698 &focus_handle,
20699 window,
20700 cx,
20701 )
20702 }
20703 })
20704 .on_click({
20705 let editor = editor.clone();
20706 move |_event, _window, cx| {
20707 editor.update(cx, |editor, cx| {
20708 editor.stage_or_unstage_diff_hunks(
20709 false,
20710 vec![hunk_range.start..hunk_range.start],
20711 cx,
20712 );
20713 });
20714 }
20715 })
20716 })
20717 .child(
20718 Button::new(("restore", row as u64), "Restore")
20719 .tooltip({
20720 let focus_handle = editor.focus_handle(cx);
20721 move |window, cx| {
20722 Tooltip::for_action_in(
20723 "Restore Hunk",
20724 &::git::Restore,
20725 &focus_handle,
20726 window,
20727 cx,
20728 )
20729 }
20730 })
20731 .on_click({
20732 let editor = editor.clone();
20733 move |_event, window, cx| {
20734 editor.update(cx, |editor, cx| {
20735 let snapshot = editor.snapshot(window, cx);
20736 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20737 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20738 });
20739 }
20740 })
20741 .disabled(is_created_file),
20742 )
20743 .when(
20744 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20745 |el| {
20746 el.child(
20747 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20748 .shape(IconButtonShape::Square)
20749 .icon_size(IconSize::Small)
20750 // .disabled(!has_multiple_hunks)
20751 .tooltip({
20752 let focus_handle = editor.focus_handle(cx);
20753 move |window, cx| {
20754 Tooltip::for_action_in(
20755 "Next Hunk",
20756 &GoToHunk,
20757 &focus_handle,
20758 window,
20759 cx,
20760 )
20761 }
20762 })
20763 .on_click({
20764 let editor = editor.clone();
20765 move |_event, window, cx| {
20766 editor.update(cx, |editor, cx| {
20767 let snapshot = editor.snapshot(window, cx);
20768 let position =
20769 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20770 editor.go_to_hunk_before_or_after_position(
20771 &snapshot,
20772 position,
20773 Direction::Next,
20774 window,
20775 cx,
20776 );
20777 editor.expand_selected_diff_hunks(cx);
20778 });
20779 }
20780 }),
20781 )
20782 .child(
20783 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20784 .shape(IconButtonShape::Square)
20785 .icon_size(IconSize::Small)
20786 // .disabled(!has_multiple_hunks)
20787 .tooltip({
20788 let focus_handle = editor.focus_handle(cx);
20789 move |window, cx| {
20790 Tooltip::for_action_in(
20791 "Previous Hunk",
20792 &GoToPreviousHunk,
20793 &focus_handle,
20794 window,
20795 cx,
20796 )
20797 }
20798 })
20799 .on_click({
20800 let editor = editor.clone();
20801 move |_event, window, cx| {
20802 editor.update(cx, |editor, cx| {
20803 let snapshot = editor.snapshot(window, cx);
20804 let point =
20805 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20806 editor.go_to_hunk_before_or_after_position(
20807 &snapshot,
20808 point,
20809 Direction::Prev,
20810 window,
20811 cx,
20812 );
20813 editor.expand_selected_diff_hunks(cx);
20814 });
20815 }
20816 }),
20817 )
20818 },
20819 )
20820 .into_any_element()
20821}