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 commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod jsx_tag_auto_close;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51pub(crate) use actions::*;
52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use buffer_diff::DiffHunkStatus;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use feature_flags::{Debugger, FeatureFlagAppExt};
72use futures::{
73 future::{self, join, Shared},
74 FutureExt,
75};
76use fuzzy::StringMatchCandidate;
77
78use ::git::Restore;
79use code_context_menus::{
80 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
81 CompletionsMenu, ContextMenuOrigin,
82};
83use git::blame::GitBlame;
84use gpui::{
85 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
86 AnimationExt, AnyElement, App, AppContext, AsyncWindowContext, AvailableSpace, Background,
87 Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
88 EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
89 Global, HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
90 ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
91 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
92 WeakEntity, WeakFocusHandle, Window,
93};
94use highlight_matching_bracket::refresh_matching_bracket_highlights;
95use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
96use hover_popover::{hide_hover, HoverState};
97use indent_guides::ActiveIndentGuidesState;
98use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
99pub use inline_completion::Direction;
100use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
101pub use items::MAX_TAB_TITLE_LEN;
102use itertools::Itertools;
103use language::{
104 language_settings::{
105 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
106 WordsCompletionMode,
107 },
108 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
109 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
110 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
111 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
112};
113use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
114use linked_editing_ranges::refresh_linked_ranges;
115use mouse_context_menu::MouseContextMenu;
116use persistence::DB;
117use project::{
118 debugger::breakpoint_store::{BreakpointEditAction, BreakpointStore, BreakpointStoreEvent},
119 ProjectPath,
120};
121
122pub use proposed_changes_editor::{
123 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
124};
125use smallvec::smallvec;
126use std::{cell::OnceCell, iter::Peekable};
127use task::{ResolvedTask, TaskTemplate, TaskVariables};
128
129pub use lsp::CompletionContext;
130use lsp::{
131 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
132 InsertTextFormat, LanguageServerId, LanguageServerName,
133};
134
135use language::BufferSnapshot;
136use movement::TextLayoutDetails;
137pub use multi_buffer::{
138 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
139 ToOffset, ToPoint,
140};
141use multi_buffer::{
142 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
143 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
144};
145use parking_lot::Mutex;
146use project::{
147 debugger::breakpoint_store::{Breakpoint, BreakpointKind},
148 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
149 project_settings::{GitGutterSetting, ProjectSettings},
150 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
151 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
152 TaskSourceKind,
153};
154use rand::prelude::*;
155use rpc::{proto::*, ErrorExt};
156use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
157use selections_collection::{
158 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
159};
160use serde::{Deserialize, Serialize};
161use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
162use smallvec::SmallVec;
163use snippet::Snippet;
164use std::sync::Arc;
165use std::{
166 any::TypeId,
167 borrow::Cow,
168 cell::RefCell,
169 cmp::{self, Ordering, Reverse},
170 mem,
171 num::NonZeroU32,
172 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
173 path::{Path, PathBuf},
174 rc::Rc,
175 time::{Duration, Instant},
176};
177pub use sum_tree::Bias;
178use sum_tree::TreeMap;
179use text::{BufferId, OffsetUtf16, Rope};
180use theme::{
181 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
182 ThemeColors, ThemeSettings,
183};
184use ui::{
185 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
186 Tooltip,
187};
188use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
189use workspace::{
190 item::{ItemHandle, PreviewTabsSettings},
191 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
192 searchable::SearchEvent,
193 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
194 RestoreOnStartupBehavior, SplitDirection, TabBarSettings, Toast, ViewId, Workspace,
195 WorkspaceId, WorkspaceSettings, SERIALIZATION_THROTTLE_TIME,
196};
197
198use crate::hover_links::{find_url, find_url_from_range};
199use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
200
201pub const FILE_HEADER_HEIGHT: u32 = 2;
202pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
203pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
204const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
205const MAX_LINE_LEN: usize = 1024;
206const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
207const MAX_SELECTION_HISTORY_LEN: usize = 1024;
208pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
209#[doc(hidden)]
210pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
211
212pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
213pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
214pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
215
216pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
217pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
218pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
219
220const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
221 alt: true,
222 shift: true,
223 control: false,
224 platform: false,
225 function: false,
226};
227
228#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
229pub enum InlayId {
230 InlineCompletion(usize),
231 Hint(usize),
232}
233
234impl InlayId {
235 fn id(&self) -> usize {
236 match self {
237 Self::InlineCompletion(id) => *id,
238 Self::Hint(id) => *id,
239 }
240 }
241}
242
243pub enum DebugCurrentRowHighlight {}
244enum DocumentHighlightRead {}
245enum DocumentHighlightWrite {}
246enum InputComposition {}
247enum SelectedTextHighlight {}
248
249#[derive(Debug, Copy, Clone, PartialEq, Eq)]
250pub enum Navigated {
251 Yes,
252 No,
253}
254
255impl Navigated {
256 pub fn from_bool(yes: bool) -> Navigated {
257 if yes {
258 Navigated::Yes
259 } else {
260 Navigated::No
261 }
262 }
263}
264
265#[derive(Debug, Clone, PartialEq, Eq)]
266enum DisplayDiffHunk {
267 Folded {
268 display_row: DisplayRow,
269 },
270 Unfolded {
271 is_created_file: bool,
272 diff_base_byte_range: Range<usize>,
273 display_row_range: Range<DisplayRow>,
274 multi_buffer_range: Range<Anchor>,
275 status: DiffHunkStatus,
276 },
277}
278
279pub fn init_settings(cx: &mut App) {
280 EditorSettings::register(cx);
281}
282
283pub fn init(cx: &mut App) {
284 init_settings(cx);
285
286 workspace::register_project_item::<Editor>(cx);
287 workspace::FollowableViewRegistry::register::<Editor>(cx);
288 workspace::register_serializable_item::<Editor>(cx);
289
290 cx.observe_new(
291 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
292 workspace.register_action(Editor::new_file);
293 workspace.register_action(Editor::new_file_vertical);
294 workspace.register_action(Editor::new_file_horizontal);
295 workspace.register_action(Editor::cancel_language_server_work);
296 },
297 )
298 .detach();
299
300 cx.on_action(move |_: &workspace::NewFile, cx| {
301 let app_state = workspace::AppState::global(cx);
302 if let Some(app_state) = app_state.upgrade() {
303 workspace::open_new(
304 Default::default(),
305 app_state,
306 cx,
307 |workspace, window, cx| {
308 Editor::new_file(workspace, &Default::default(), window, cx)
309 },
310 )
311 .detach();
312 }
313 });
314 cx.on_action(move |_: &workspace::NewWindow, cx| {
315 let app_state = workspace::AppState::global(cx);
316 if let Some(app_state) = app_state.upgrade() {
317 workspace::open_new(
318 Default::default(),
319 app_state,
320 cx,
321 |workspace, window, cx| {
322 cx.activate(true);
323 Editor::new_file(workspace, &Default::default(), window, cx)
324 },
325 )
326 .detach();
327 }
328 });
329}
330
331pub struct SearchWithinRange;
332
333trait InvalidationRegion {
334 fn ranges(&self) -> &[Range<Anchor>];
335}
336
337#[derive(Clone, Debug, PartialEq)]
338pub enum SelectPhase {
339 Begin {
340 position: DisplayPoint,
341 add: bool,
342 click_count: usize,
343 },
344 BeginColumnar {
345 position: DisplayPoint,
346 reset: bool,
347 goal_column: u32,
348 },
349 Extend {
350 position: DisplayPoint,
351 click_count: usize,
352 },
353 Update {
354 position: DisplayPoint,
355 goal_column: u32,
356 scroll_delta: gpui::Point<f32>,
357 },
358 End,
359}
360
361#[derive(Clone, Debug)]
362pub enum SelectMode {
363 Character,
364 Word(Range<Anchor>),
365 Line(Range<Anchor>),
366 All,
367}
368
369#[derive(Copy, Clone, PartialEq, Eq, Debug)]
370pub enum EditorMode {
371 SingleLine { auto_width: bool },
372 AutoHeight { max_lines: usize },
373 Full,
374}
375
376#[derive(Copy, Clone, Debug)]
377pub enum SoftWrap {
378 /// Prefer not to wrap at all.
379 ///
380 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
381 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
382 GitDiff,
383 /// Prefer a single line generally, unless an overly long line is encountered.
384 None,
385 /// Soft wrap lines that exceed the editor width.
386 EditorWidth,
387 /// Soft wrap lines at the preferred line length.
388 Column(u32),
389 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
390 Bounded(u32),
391}
392
393#[derive(Clone)]
394pub struct EditorStyle {
395 pub background: Hsla,
396 pub local_player: PlayerColor,
397 pub text: TextStyle,
398 pub scrollbar_width: Pixels,
399 pub syntax: Arc<SyntaxTheme>,
400 pub status: StatusColors,
401 pub inlay_hints_style: HighlightStyle,
402 pub inline_completion_styles: InlineCompletionStyles,
403 pub unnecessary_code_fade: f32,
404}
405
406impl Default for EditorStyle {
407 fn default() -> Self {
408 Self {
409 background: Hsla::default(),
410 local_player: PlayerColor::default(),
411 text: TextStyle::default(),
412 scrollbar_width: Pixels::default(),
413 syntax: Default::default(),
414 // HACK: Status colors don't have a real default.
415 // We should look into removing the status colors from the editor
416 // style and retrieve them directly from the theme.
417 status: StatusColors::dark(),
418 inlay_hints_style: HighlightStyle::default(),
419 inline_completion_styles: InlineCompletionStyles {
420 insertion: HighlightStyle::default(),
421 whitespace: HighlightStyle::default(),
422 },
423 unnecessary_code_fade: Default::default(),
424 }
425 }
426}
427
428pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
429 let show_background = language_settings::language_settings(None, None, cx)
430 .inlay_hints
431 .show_background;
432
433 HighlightStyle {
434 color: Some(cx.theme().status().hint),
435 background_color: show_background.then(|| cx.theme().status().hint_background),
436 ..HighlightStyle::default()
437 }
438}
439
440pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
441 InlineCompletionStyles {
442 insertion: HighlightStyle {
443 color: Some(cx.theme().status().predictive),
444 ..HighlightStyle::default()
445 },
446 whitespace: HighlightStyle {
447 background_color: Some(cx.theme().status().created_background),
448 ..HighlightStyle::default()
449 },
450 }
451}
452
453type CompletionId = usize;
454
455pub(crate) enum EditDisplayMode {
456 TabAccept,
457 DiffPopover,
458 Inline,
459}
460
461enum InlineCompletion {
462 Edit {
463 edits: Vec<(Range<Anchor>, String)>,
464 edit_preview: Option<EditPreview>,
465 display_mode: EditDisplayMode,
466 snapshot: BufferSnapshot,
467 },
468 Move {
469 target: Anchor,
470 snapshot: BufferSnapshot,
471 },
472}
473
474struct InlineCompletionState {
475 inlay_ids: Vec<InlayId>,
476 completion: InlineCompletion,
477 completion_id: Option<SharedString>,
478 invalidation_range: Range<Anchor>,
479}
480
481enum EditPredictionSettings {
482 Disabled,
483 Enabled {
484 show_in_menu: bool,
485 preview_requires_modifier: bool,
486 },
487}
488
489enum InlineCompletionHighlight {}
490
491#[derive(Debug, Clone)]
492struct InlineDiagnostic {
493 message: SharedString,
494 group_id: usize,
495 is_primary: bool,
496 start: Point,
497 severity: DiagnosticSeverity,
498}
499
500pub enum MenuInlineCompletionsPolicy {
501 Never,
502 ByProvider,
503}
504
505pub enum EditPredictionPreview {
506 /// Modifier is not pressed
507 Inactive { released_too_fast: bool },
508 /// Modifier pressed
509 Active {
510 since: Instant,
511 previous_scroll_position: Option<ScrollAnchor>,
512 },
513}
514
515impl EditPredictionPreview {
516 pub fn released_too_fast(&self) -> bool {
517 match self {
518 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
519 EditPredictionPreview::Active { .. } => false,
520 }
521 }
522
523 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
524 if let EditPredictionPreview::Active {
525 previous_scroll_position,
526 ..
527 } = self
528 {
529 *previous_scroll_position = scroll_position;
530 }
531 }
532}
533
534pub struct ContextMenuOptions {
535 pub min_entries_visible: usize,
536 pub max_entries_visible: usize,
537 pub placement: Option<ContextMenuPlacement>,
538}
539
540#[derive(Debug, Clone, PartialEq, Eq)]
541pub enum ContextMenuPlacement {
542 Above,
543 Below,
544}
545
546#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
547struct EditorActionId(usize);
548
549impl EditorActionId {
550 pub fn post_inc(&mut self) -> Self {
551 let answer = self.0;
552
553 *self = Self(answer + 1);
554
555 Self(answer)
556 }
557}
558
559// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
560// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
561
562type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
563type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
564
565#[derive(Default)]
566struct ScrollbarMarkerState {
567 scrollbar_size: Size<Pixels>,
568 dirty: bool,
569 markers: Arc<[PaintQuad]>,
570 pending_refresh: Option<Task<Result<()>>>,
571}
572
573impl ScrollbarMarkerState {
574 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
575 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
576 }
577}
578
579#[derive(Clone, Debug)]
580struct RunnableTasks {
581 templates: Vec<(TaskSourceKind, TaskTemplate)>,
582 offset: multi_buffer::Anchor,
583 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
584 column: u32,
585 // Values of all named captures, including those starting with '_'
586 extra_variables: HashMap<String, String>,
587 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
588 context_range: Range<BufferOffset>,
589}
590
591impl RunnableTasks {
592 fn resolve<'a>(
593 &'a self,
594 cx: &'a task::TaskContext,
595 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
596 self.templates.iter().filter_map(|(kind, template)| {
597 template
598 .resolve_task(&kind.to_id_base(), cx)
599 .map(|task| (kind.clone(), task))
600 })
601 }
602}
603
604#[derive(Clone)]
605struct ResolvedTasks {
606 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
607 position: Anchor,
608}
609
610#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
611struct BufferOffset(usize);
612
613// Addons allow storing per-editor state in other crates (e.g. Vim)
614pub trait Addon: 'static {
615 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
616
617 fn render_buffer_header_controls(
618 &self,
619 _: &ExcerptInfo,
620 _: &Window,
621 _: &App,
622 ) -> Option<AnyElement> {
623 None
624 }
625
626 fn to_any(&self) -> &dyn std::any::Any;
627}
628
629/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
630///
631/// See the [module level documentation](self) for more information.
632pub struct Editor {
633 focus_handle: FocusHandle,
634 last_focused_descendant: Option<WeakFocusHandle>,
635 /// The text buffer being edited
636 buffer: Entity<MultiBuffer>,
637 /// Map of how text in the buffer should be displayed.
638 /// Handles soft wraps, folds, fake inlay text insertions, etc.
639 pub display_map: Entity<DisplayMap>,
640 pub selections: SelectionsCollection,
641 pub scroll_manager: ScrollManager,
642 /// When inline assist editors are linked, they all render cursors because
643 /// typing enters text into each of them, even the ones that aren't focused.
644 pub(crate) show_cursor_when_unfocused: bool,
645 columnar_selection_tail: Option<Anchor>,
646 add_selections_state: Option<AddSelectionsState>,
647 select_next_state: Option<SelectNextState>,
648 select_prev_state: Option<SelectNextState>,
649 selection_history: SelectionHistory,
650 autoclose_regions: Vec<AutocloseRegion>,
651 snippet_stack: InvalidationStack<SnippetState>,
652 select_syntax_node_history: SelectSyntaxNodeHistory,
653 ime_transaction: Option<TransactionId>,
654 active_diagnostics: Option<ActiveDiagnosticGroup>,
655 show_inline_diagnostics: bool,
656 inline_diagnostics_update: Task<()>,
657 inline_diagnostics_enabled: bool,
658 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
659 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
660 hard_wrap: Option<usize>,
661
662 // TODO: make this a access method
663 pub project: Option<Entity<Project>>,
664 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
665 completion_provider: Option<Box<dyn CompletionProvider>>,
666 collaboration_hub: Option<Box<dyn CollaborationHub>>,
667 blink_manager: Entity<BlinkManager>,
668 show_cursor_names: bool,
669 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
670 pub show_local_selections: bool,
671 mode: EditorMode,
672 show_breadcrumbs: bool,
673 show_gutter: bool,
674 show_scrollbars: bool,
675 show_line_numbers: Option<bool>,
676 use_relative_line_numbers: Option<bool>,
677 show_git_diff_gutter: Option<bool>,
678 show_code_actions: Option<bool>,
679 show_runnables: Option<bool>,
680 show_breakpoints: Option<bool>,
681 show_wrap_guides: Option<bool>,
682 show_indent_guides: Option<bool>,
683 placeholder_text: Option<Arc<str>>,
684 highlight_order: usize,
685 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
686 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
687 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
688 scrollbar_marker_state: ScrollbarMarkerState,
689 active_indent_guides_state: ActiveIndentGuidesState,
690 nav_history: Option<ItemNavHistory>,
691 context_menu: RefCell<Option<CodeContextMenu>>,
692 context_menu_options: Option<ContextMenuOptions>,
693 mouse_context_menu: Option<MouseContextMenu>,
694 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
695 signature_help_state: SignatureHelpState,
696 auto_signature_help: Option<bool>,
697 find_all_references_task_sources: Vec<Anchor>,
698 next_completion_id: CompletionId,
699 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
700 code_actions_task: Option<Task<Result<()>>>,
701 selection_highlight_task: Option<Task<()>>,
702 document_highlights_task: Option<Task<()>>,
703 linked_editing_range_task: Option<Task<Option<()>>>,
704 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
705 pending_rename: Option<RenameState>,
706 searchable: bool,
707 cursor_shape: CursorShape,
708 current_line_highlight: Option<CurrentLineHighlight>,
709 collapse_matches: bool,
710 autoindent_mode: Option<AutoindentMode>,
711 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
712 input_enabled: bool,
713 use_modal_editing: bool,
714 read_only: bool,
715 leader_peer_id: Option<PeerId>,
716 remote_id: Option<ViewId>,
717 hover_state: HoverState,
718 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
719 gutter_hovered: bool,
720 hovered_link_state: Option<HoveredLinkState>,
721 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
722 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
723 active_inline_completion: Option<InlineCompletionState>,
724 /// Used to prevent flickering as the user types while the menu is open
725 stale_inline_completion_in_menu: Option<InlineCompletionState>,
726 edit_prediction_settings: EditPredictionSettings,
727 inline_completions_hidden_for_vim_mode: bool,
728 show_inline_completions_override: Option<bool>,
729 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
730 edit_prediction_preview: EditPredictionPreview,
731 edit_prediction_indent_conflict: bool,
732 edit_prediction_requires_modifier_in_indent_conflict: bool,
733 inlay_hint_cache: InlayHintCache,
734 next_inlay_id: usize,
735 _subscriptions: Vec<Subscription>,
736 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
737 gutter_dimensions: GutterDimensions,
738 style: Option<EditorStyle>,
739 text_style_refinement: Option<TextStyleRefinement>,
740 next_editor_action_id: EditorActionId,
741 editor_actions:
742 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
743 use_autoclose: bool,
744 use_auto_surround: bool,
745 auto_replace_emoji_shortcode: bool,
746 jsx_tag_auto_close_enabled_in_any_buffer: bool,
747 show_git_blame_gutter: bool,
748 show_git_blame_inline: bool,
749 show_git_blame_inline_delay_task: Option<Task<()>>,
750 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
751 git_blame_inline_enabled: bool,
752 serialize_dirty_buffers: bool,
753 show_selection_menu: Option<bool>,
754 blame: Option<Entity<GitBlame>>,
755 blame_subscription: Option<Subscription>,
756 custom_context_menu: Option<
757 Box<
758 dyn 'static
759 + Fn(
760 &mut Self,
761 DisplayPoint,
762 &mut Window,
763 &mut Context<Self>,
764 ) -> Option<Entity<ui::ContextMenu>>,
765 >,
766 >,
767 last_bounds: Option<Bounds<Pixels>>,
768 last_position_map: Option<Rc<PositionMap>>,
769 expect_bounds_change: Option<Bounds<Pixels>>,
770 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
771 tasks_update_task: Option<Task<()>>,
772 pub breakpoint_store: Option<Entity<BreakpointStore>>,
773 /// Allow's a user to create a breakpoint by selecting this indicator
774 /// It should be None while a user is not hovering over the gutter
775 /// Otherwise it represents the point that the breakpoint will be shown
776 pub gutter_breakpoint_indicator: Option<DisplayPoint>,
777 in_project_search: bool,
778 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
779 breadcrumb_header: Option<String>,
780 focused_block: Option<FocusedBlock>,
781 next_scroll_position: NextScrollCursorCenterTopBottom,
782 addons: HashMap<TypeId, Box<dyn Addon>>,
783 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
784 load_diff_task: Option<Shared<Task<()>>>,
785 selection_mark_mode: bool,
786 toggle_fold_multiple_buffers: Task<()>,
787 _scroll_cursor_center_top_bottom_task: Task<()>,
788 serialize_selections: Task<()>,
789 serialize_folds: Task<()>,
790}
791
792#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
793enum NextScrollCursorCenterTopBottom {
794 #[default]
795 Center,
796 Top,
797 Bottom,
798}
799
800impl NextScrollCursorCenterTopBottom {
801 fn next(&self) -> Self {
802 match self {
803 Self::Center => Self::Top,
804 Self::Top => Self::Bottom,
805 Self::Bottom => Self::Center,
806 }
807 }
808}
809
810#[derive(Clone)]
811pub struct EditorSnapshot {
812 pub mode: EditorMode,
813 show_gutter: bool,
814 show_line_numbers: Option<bool>,
815 show_git_diff_gutter: Option<bool>,
816 show_code_actions: Option<bool>,
817 show_runnables: Option<bool>,
818 show_breakpoints: Option<bool>,
819 git_blame_gutter_max_author_length: Option<usize>,
820 pub display_snapshot: DisplaySnapshot,
821 pub placeholder_text: Option<Arc<str>>,
822 is_focused: bool,
823 scroll_anchor: ScrollAnchor,
824 ongoing_scroll: OngoingScroll,
825 current_line_highlight: CurrentLineHighlight,
826 gutter_hovered: bool,
827}
828
829const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
830
831#[derive(Default, Debug, Clone, Copy)]
832pub struct GutterDimensions {
833 pub left_padding: Pixels,
834 pub right_padding: Pixels,
835 pub width: Pixels,
836 pub margin: Pixels,
837 pub git_blame_entries_width: Option<Pixels>,
838}
839
840impl GutterDimensions {
841 /// The full width of the space taken up by the gutter.
842 pub fn full_width(&self) -> Pixels {
843 self.margin + self.width
844 }
845
846 /// The width of the space reserved for the fold indicators,
847 /// use alongside 'justify_end' and `gutter_width` to
848 /// right align content with the line numbers
849 pub fn fold_area_width(&self) -> Pixels {
850 self.margin + self.right_padding
851 }
852}
853
854#[derive(Debug)]
855pub struct RemoteSelection {
856 pub replica_id: ReplicaId,
857 pub selection: Selection<Anchor>,
858 pub cursor_shape: CursorShape,
859 pub peer_id: PeerId,
860 pub line_mode: bool,
861 pub participant_index: Option<ParticipantIndex>,
862 pub user_name: Option<SharedString>,
863}
864
865#[derive(Clone, Debug)]
866struct SelectionHistoryEntry {
867 selections: Arc<[Selection<Anchor>]>,
868 select_next_state: Option<SelectNextState>,
869 select_prev_state: Option<SelectNextState>,
870 add_selections_state: Option<AddSelectionsState>,
871}
872
873enum SelectionHistoryMode {
874 Normal,
875 Undoing,
876 Redoing,
877}
878
879#[derive(Clone, PartialEq, Eq, Hash)]
880struct HoveredCursor {
881 replica_id: u16,
882 selection_id: usize,
883}
884
885impl Default for SelectionHistoryMode {
886 fn default() -> Self {
887 Self::Normal
888 }
889}
890
891#[derive(Default)]
892struct SelectionHistory {
893 #[allow(clippy::type_complexity)]
894 selections_by_transaction:
895 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
896 mode: SelectionHistoryMode,
897 undo_stack: VecDeque<SelectionHistoryEntry>,
898 redo_stack: VecDeque<SelectionHistoryEntry>,
899}
900
901impl SelectionHistory {
902 fn insert_transaction(
903 &mut self,
904 transaction_id: TransactionId,
905 selections: Arc<[Selection<Anchor>]>,
906 ) {
907 self.selections_by_transaction
908 .insert(transaction_id, (selections, None));
909 }
910
911 #[allow(clippy::type_complexity)]
912 fn transaction(
913 &self,
914 transaction_id: TransactionId,
915 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
916 self.selections_by_transaction.get(&transaction_id)
917 }
918
919 #[allow(clippy::type_complexity)]
920 fn transaction_mut(
921 &mut self,
922 transaction_id: TransactionId,
923 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
924 self.selections_by_transaction.get_mut(&transaction_id)
925 }
926
927 fn push(&mut self, entry: SelectionHistoryEntry) {
928 if !entry.selections.is_empty() {
929 match self.mode {
930 SelectionHistoryMode::Normal => {
931 self.push_undo(entry);
932 self.redo_stack.clear();
933 }
934 SelectionHistoryMode::Undoing => self.push_redo(entry),
935 SelectionHistoryMode::Redoing => self.push_undo(entry),
936 }
937 }
938 }
939
940 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
941 if self
942 .undo_stack
943 .back()
944 .map_or(true, |e| e.selections != entry.selections)
945 {
946 self.undo_stack.push_back(entry);
947 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
948 self.undo_stack.pop_front();
949 }
950 }
951 }
952
953 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
954 if self
955 .redo_stack
956 .back()
957 .map_or(true, |e| e.selections != entry.selections)
958 {
959 self.redo_stack.push_back(entry);
960 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
961 self.redo_stack.pop_front();
962 }
963 }
964 }
965}
966
967struct RowHighlight {
968 index: usize,
969 range: Range<Anchor>,
970 color: Hsla,
971 should_autoscroll: bool,
972}
973
974#[derive(Clone, Debug)]
975struct AddSelectionsState {
976 above: bool,
977 stack: Vec<usize>,
978}
979
980#[derive(Clone)]
981struct SelectNextState {
982 query: AhoCorasick,
983 wordwise: bool,
984 done: bool,
985}
986
987impl std::fmt::Debug for SelectNextState {
988 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
989 f.debug_struct(std::any::type_name::<Self>())
990 .field("wordwise", &self.wordwise)
991 .field("done", &self.done)
992 .finish()
993 }
994}
995
996#[derive(Debug)]
997struct AutocloseRegion {
998 selection_id: usize,
999 range: Range<Anchor>,
1000 pair: BracketPair,
1001}
1002
1003#[derive(Debug)]
1004struct SnippetState {
1005 ranges: Vec<Vec<Range<Anchor>>>,
1006 active_index: usize,
1007 choices: Vec<Option<Vec<String>>>,
1008}
1009
1010#[doc(hidden)]
1011pub struct RenameState {
1012 pub range: Range<Anchor>,
1013 pub old_name: Arc<str>,
1014 pub editor: Entity<Editor>,
1015 block_id: CustomBlockId,
1016}
1017
1018struct InvalidationStack<T>(Vec<T>);
1019
1020struct RegisteredInlineCompletionProvider {
1021 provider: Arc<dyn InlineCompletionProviderHandle>,
1022 _subscription: Subscription,
1023}
1024
1025#[derive(Debug, PartialEq, Eq)]
1026struct ActiveDiagnosticGroup {
1027 primary_range: Range<Anchor>,
1028 primary_message: String,
1029 group_id: usize,
1030 blocks: HashMap<CustomBlockId, Diagnostic>,
1031 is_valid: bool,
1032}
1033
1034#[derive(Serialize, Deserialize, Clone, Debug)]
1035pub struct ClipboardSelection {
1036 /// The number of bytes in this selection.
1037 pub len: usize,
1038 /// Whether this was a full-line selection.
1039 pub is_entire_line: bool,
1040 /// The indentation of the first line when this content was originally copied.
1041 pub first_line_indent: u32,
1042}
1043
1044// selections, scroll behavior, was newest selection reversed
1045type SelectSyntaxNodeHistoryState = (
1046 Box<[Selection<usize>]>,
1047 SelectSyntaxNodeScrollBehavior,
1048 bool,
1049);
1050
1051#[derive(Default)]
1052struct SelectSyntaxNodeHistory {
1053 stack: Vec<SelectSyntaxNodeHistoryState>,
1054 // disable temporarily to allow changing selections without losing the stack
1055 pub disable_clearing: bool,
1056}
1057
1058impl SelectSyntaxNodeHistory {
1059 pub fn try_clear(&mut self) {
1060 if !self.disable_clearing {
1061 self.stack.clear();
1062 }
1063 }
1064
1065 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1066 self.stack.push(selection);
1067 }
1068
1069 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1070 self.stack.pop()
1071 }
1072}
1073
1074enum SelectSyntaxNodeScrollBehavior {
1075 CursorTop,
1076 CenterSelection,
1077 CursorBottom,
1078}
1079
1080#[derive(Debug)]
1081pub(crate) struct NavigationData {
1082 cursor_anchor: Anchor,
1083 cursor_position: Point,
1084 scroll_anchor: ScrollAnchor,
1085 scroll_top_row: u32,
1086}
1087
1088#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1089pub enum GotoDefinitionKind {
1090 Symbol,
1091 Declaration,
1092 Type,
1093 Implementation,
1094}
1095
1096#[derive(Debug, Clone)]
1097enum InlayHintRefreshReason {
1098 ModifiersChanged(bool),
1099 Toggle(bool),
1100 SettingsChange(InlayHintSettings),
1101 NewLinesShown,
1102 BufferEdited(HashSet<Arc<Language>>),
1103 RefreshRequested,
1104 ExcerptsRemoved(Vec<ExcerptId>),
1105}
1106
1107impl InlayHintRefreshReason {
1108 fn description(&self) -> &'static str {
1109 match self {
1110 Self::ModifiersChanged(_) => "modifiers changed",
1111 Self::Toggle(_) => "toggle",
1112 Self::SettingsChange(_) => "settings change",
1113 Self::NewLinesShown => "new lines shown",
1114 Self::BufferEdited(_) => "buffer edited",
1115 Self::RefreshRequested => "refresh requested",
1116 Self::ExcerptsRemoved(_) => "excerpts removed",
1117 }
1118 }
1119}
1120
1121pub enum FormatTarget {
1122 Buffers,
1123 Ranges(Vec<Range<MultiBufferPoint>>),
1124}
1125
1126pub(crate) struct FocusedBlock {
1127 id: BlockId,
1128 focus_handle: WeakFocusHandle,
1129}
1130
1131#[derive(Clone)]
1132enum JumpData {
1133 MultiBufferRow {
1134 row: MultiBufferRow,
1135 line_offset_from_top: u32,
1136 },
1137 MultiBufferPoint {
1138 excerpt_id: ExcerptId,
1139 position: Point,
1140 anchor: text::Anchor,
1141 line_offset_from_top: u32,
1142 },
1143}
1144
1145pub enum MultibufferSelectionMode {
1146 First,
1147 All,
1148}
1149
1150#[derive(Clone, Copy, Debug, Default)]
1151pub struct RewrapOptions {
1152 pub override_language_settings: bool,
1153 pub preserve_existing_whitespace: bool,
1154}
1155
1156impl Editor {
1157 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1158 let buffer = cx.new(|cx| Buffer::local("", cx));
1159 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1160 Self::new(
1161 EditorMode::SingleLine { auto_width: false },
1162 buffer,
1163 None,
1164 window,
1165 cx,
1166 )
1167 }
1168
1169 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1170 let buffer = cx.new(|cx| Buffer::local("", cx));
1171 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1172 Self::new(EditorMode::Full, buffer, None, window, cx)
1173 }
1174
1175 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1176 let buffer = cx.new(|cx| Buffer::local("", cx));
1177 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1178 Self::new(
1179 EditorMode::SingleLine { auto_width: true },
1180 buffer,
1181 None,
1182 window,
1183 cx,
1184 )
1185 }
1186
1187 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1188 let buffer = cx.new(|cx| Buffer::local("", cx));
1189 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1190 Self::new(
1191 EditorMode::AutoHeight { max_lines },
1192 buffer,
1193 None,
1194 window,
1195 cx,
1196 )
1197 }
1198
1199 pub fn for_buffer(
1200 buffer: Entity<Buffer>,
1201 project: Option<Entity<Project>>,
1202 window: &mut Window,
1203 cx: &mut Context<Self>,
1204 ) -> Self {
1205 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1206 Self::new(EditorMode::Full, buffer, project, window, cx)
1207 }
1208
1209 pub fn for_multibuffer(
1210 buffer: Entity<MultiBuffer>,
1211 project: Option<Entity<Project>>,
1212 window: &mut Window,
1213 cx: &mut Context<Self>,
1214 ) -> Self {
1215 Self::new(EditorMode::Full, buffer, project, window, cx)
1216 }
1217
1218 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1219 let mut clone = Self::new(
1220 self.mode,
1221 self.buffer.clone(),
1222 self.project.clone(),
1223 window,
1224 cx,
1225 );
1226 self.display_map.update(cx, |display_map, cx| {
1227 let snapshot = display_map.snapshot(cx);
1228 clone.display_map.update(cx, |display_map, cx| {
1229 display_map.set_state(&snapshot, cx);
1230 });
1231 });
1232 clone.folds_did_change(cx);
1233 clone.selections.clone_state(&self.selections);
1234 clone.scroll_manager.clone_state(&self.scroll_manager);
1235 clone.searchable = self.searchable;
1236 clone
1237 }
1238
1239 pub fn new(
1240 mode: EditorMode,
1241 buffer: Entity<MultiBuffer>,
1242 project: Option<Entity<Project>>,
1243 window: &mut Window,
1244 cx: &mut Context<Self>,
1245 ) -> Self {
1246 let style = window.text_style();
1247 let font_size = style.font_size.to_pixels(window.rem_size());
1248 let editor = cx.entity().downgrade();
1249 let fold_placeholder = FoldPlaceholder {
1250 constrain_width: true,
1251 render: Arc::new(move |fold_id, fold_range, cx| {
1252 let editor = editor.clone();
1253 div()
1254 .id(fold_id)
1255 .bg(cx.theme().colors().ghost_element_background)
1256 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1257 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1258 .rounded_xs()
1259 .size_full()
1260 .cursor_pointer()
1261 .child("⋯")
1262 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1263 .on_click(move |_, _window, cx| {
1264 editor
1265 .update(cx, |editor, cx| {
1266 editor.unfold_ranges(
1267 &[fold_range.start..fold_range.end],
1268 true,
1269 false,
1270 cx,
1271 );
1272 cx.stop_propagation();
1273 })
1274 .ok();
1275 })
1276 .into_any()
1277 }),
1278 merge_adjacent: true,
1279 ..Default::default()
1280 };
1281 let display_map = cx.new(|cx| {
1282 DisplayMap::new(
1283 buffer.clone(),
1284 style.font(),
1285 font_size,
1286 None,
1287 FILE_HEADER_HEIGHT,
1288 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1289 fold_placeholder,
1290 cx,
1291 )
1292 });
1293
1294 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1295
1296 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1297
1298 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1299 .then(|| language_settings::SoftWrap::None);
1300
1301 let mut project_subscriptions = Vec::new();
1302 if mode == EditorMode::Full {
1303 if let Some(project) = project.as_ref() {
1304 project_subscriptions.push(cx.subscribe_in(
1305 project,
1306 window,
1307 |editor, _, event, window, cx| match event {
1308 project::Event::RefreshCodeLens => {
1309 // we always query lens with actions, without storing them, always refreshing them
1310 }
1311 project::Event::RefreshInlayHints => {
1312 editor
1313 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1314 }
1315 project::Event::SnippetEdit(id, snippet_edits) => {
1316 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1317 let focus_handle = editor.focus_handle(cx);
1318 if focus_handle.is_focused(window) {
1319 let snapshot = buffer.read(cx).snapshot();
1320 for (range, snippet) in snippet_edits {
1321 let editor_range =
1322 language::range_from_lsp(*range).to_offset(&snapshot);
1323 editor
1324 .insert_snippet(
1325 &[editor_range],
1326 snippet.clone(),
1327 window,
1328 cx,
1329 )
1330 .ok();
1331 }
1332 }
1333 }
1334 }
1335 _ => {}
1336 },
1337 ));
1338 if let Some(task_inventory) = project
1339 .read(cx)
1340 .task_store()
1341 .read(cx)
1342 .task_inventory()
1343 .cloned()
1344 {
1345 project_subscriptions.push(cx.observe_in(
1346 &task_inventory,
1347 window,
1348 |editor, _, window, cx| {
1349 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1350 },
1351 ));
1352 };
1353
1354 project_subscriptions.push(cx.subscribe_in(
1355 &project.read(cx).breakpoint_store(),
1356 window,
1357 |editor, _, event, window, cx| match event {
1358 BreakpointStoreEvent::ActiveDebugLineChanged => {
1359 editor.go_to_active_debug_line(window, cx);
1360 }
1361 _ => {}
1362 },
1363 ));
1364 }
1365 }
1366
1367 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1368
1369 let inlay_hint_settings =
1370 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1371 let focus_handle = cx.focus_handle();
1372 cx.on_focus(&focus_handle, window, Self::handle_focus)
1373 .detach();
1374 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1375 .detach();
1376 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1377 .detach();
1378 cx.on_blur(&focus_handle, window, Self::handle_blur)
1379 .detach();
1380
1381 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1382 Some(false)
1383 } else {
1384 None
1385 };
1386
1387 let breakpoint_store = match (mode, project.as_ref()) {
1388 (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
1389 _ => None,
1390 };
1391
1392 let mut code_action_providers = Vec::new();
1393 let mut load_uncommitted_diff = None;
1394 if let Some(project) = project.clone() {
1395 load_uncommitted_diff = Some(
1396 get_uncommitted_diff_for_buffer(
1397 &project,
1398 buffer.read(cx).all_buffers(),
1399 buffer.clone(),
1400 cx,
1401 )
1402 .shared(),
1403 );
1404 code_action_providers.push(Rc::new(project) as Rc<_>);
1405 }
1406
1407 let mut this = Self {
1408 focus_handle,
1409 show_cursor_when_unfocused: false,
1410 last_focused_descendant: None,
1411 buffer: buffer.clone(),
1412 display_map: display_map.clone(),
1413 selections,
1414 scroll_manager: ScrollManager::new(cx),
1415 columnar_selection_tail: None,
1416 add_selections_state: None,
1417 select_next_state: None,
1418 select_prev_state: None,
1419 selection_history: Default::default(),
1420 autoclose_regions: Default::default(),
1421 snippet_stack: Default::default(),
1422 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1423 ime_transaction: Default::default(),
1424 active_diagnostics: None,
1425 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1426 inline_diagnostics_update: Task::ready(()),
1427 inline_diagnostics: Vec::new(),
1428 soft_wrap_mode_override,
1429 hard_wrap: None,
1430 completion_provider: project.clone().map(|project| Box::new(project) as _),
1431 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1432 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1433 project,
1434 blink_manager: blink_manager.clone(),
1435 show_local_selections: true,
1436 show_scrollbars: true,
1437 mode,
1438 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1439 show_gutter: mode == EditorMode::Full,
1440 show_line_numbers: None,
1441 use_relative_line_numbers: None,
1442 show_git_diff_gutter: None,
1443 show_code_actions: None,
1444 show_runnables: None,
1445 show_breakpoints: None,
1446 show_wrap_guides: None,
1447 show_indent_guides,
1448 placeholder_text: None,
1449 highlight_order: 0,
1450 highlighted_rows: HashMap::default(),
1451 background_highlights: Default::default(),
1452 gutter_highlights: TreeMap::default(),
1453 scrollbar_marker_state: ScrollbarMarkerState::default(),
1454 active_indent_guides_state: ActiveIndentGuidesState::default(),
1455 nav_history: None,
1456 context_menu: RefCell::new(None),
1457 context_menu_options: None,
1458 mouse_context_menu: None,
1459 completion_tasks: Default::default(),
1460 signature_help_state: SignatureHelpState::default(),
1461 auto_signature_help: None,
1462 find_all_references_task_sources: Vec::new(),
1463 next_completion_id: 0,
1464 next_inlay_id: 0,
1465 code_action_providers,
1466 available_code_actions: Default::default(),
1467 code_actions_task: Default::default(),
1468 selection_highlight_task: Default::default(),
1469 document_highlights_task: Default::default(),
1470 linked_editing_range_task: Default::default(),
1471 pending_rename: Default::default(),
1472 searchable: true,
1473 cursor_shape: EditorSettings::get_global(cx)
1474 .cursor_shape
1475 .unwrap_or_default(),
1476 current_line_highlight: None,
1477 autoindent_mode: Some(AutoindentMode::EachLine),
1478 collapse_matches: false,
1479 workspace: None,
1480 input_enabled: true,
1481 use_modal_editing: mode == EditorMode::Full,
1482 read_only: false,
1483 use_autoclose: true,
1484 use_auto_surround: true,
1485 auto_replace_emoji_shortcode: false,
1486 jsx_tag_auto_close_enabled_in_any_buffer: false,
1487 leader_peer_id: None,
1488 remote_id: None,
1489 hover_state: Default::default(),
1490 pending_mouse_down: None,
1491 hovered_link_state: Default::default(),
1492 edit_prediction_provider: None,
1493 active_inline_completion: None,
1494 stale_inline_completion_in_menu: None,
1495 edit_prediction_preview: EditPredictionPreview::Inactive {
1496 released_too_fast: false,
1497 },
1498 inline_diagnostics_enabled: mode == EditorMode::Full,
1499 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1500
1501 gutter_hovered: false,
1502 pixel_position_of_newest_cursor: None,
1503 last_bounds: None,
1504 last_position_map: None,
1505 expect_bounds_change: None,
1506 gutter_dimensions: GutterDimensions::default(),
1507 style: None,
1508 show_cursor_names: false,
1509 hovered_cursors: Default::default(),
1510 next_editor_action_id: EditorActionId::default(),
1511 editor_actions: Rc::default(),
1512 inline_completions_hidden_for_vim_mode: false,
1513 show_inline_completions_override: None,
1514 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1515 edit_prediction_settings: EditPredictionSettings::Disabled,
1516 edit_prediction_indent_conflict: false,
1517 edit_prediction_requires_modifier_in_indent_conflict: true,
1518 custom_context_menu: None,
1519 show_git_blame_gutter: false,
1520 show_git_blame_inline: false,
1521 show_selection_menu: None,
1522 show_git_blame_inline_delay_task: None,
1523 git_blame_inline_tooltip: None,
1524 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1525 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1526 .session
1527 .restore_unsaved_buffers,
1528 blame: None,
1529 blame_subscription: None,
1530 tasks: Default::default(),
1531
1532 breakpoint_store,
1533 gutter_breakpoint_indicator: None,
1534 _subscriptions: vec![
1535 cx.observe(&buffer, Self::on_buffer_changed),
1536 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1537 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1538 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1539 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1540 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1541 cx.observe_window_activation(window, |editor, window, cx| {
1542 let active = window.is_window_active();
1543 editor.blink_manager.update(cx, |blink_manager, cx| {
1544 if active {
1545 blink_manager.enable(cx);
1546 } else {
1547 blink_manager.disable(cx);
1548 }
1549 });
1550 }),
1551 ],
1552 tasks_update_task: None,
1553 linked_edit_ranges: Default::default(),
1554 in_project_search: false,
1555 previous_search_ranges: None,
1556 breadcrumb_header: None,
1557 focused_block: None,
1558 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1559 addons: HashMap::default(),
1560 registered_buffers: HashMap::default(),
1561 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1562 selection_mark_mode: false,
1563 toggle_fold_multiple_buffers: Task::ready(()),
1564 serialize_selections: Task::ready(()),
1565 serialize_folds: Task::ready(()),
1566 text_style_refinement: None,
1567 load_diff_task: load_uncommitted_diff,
1568 };
1569 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1570 this._subscriptions
1571 .push(cx.observe(breakpoints, |_, _, cx| {
1572 cx.notify();
1573 }));
1574 }
1575 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1576 this._subscriptions.extend(project_subscriptions);
1577
1578 this.end_selection(window, cx);
1579 this.scroll_manager.show_scrollbar(window, cx);
1580 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1581
1582 if mode == EditorMode::Full {
1583 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1584 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1585
1586 if this.git_blame_inline_enabled {
1587 this.git_blame_inline_enabled = true;
1588 this.start_git_blame_inline(false, window, cx);
1589 }
1590
1591 this.go_to_active_debug_line(window, cx);
1592
1593 if let Some(buffer) = buffer.read(cx).as_singleton() {
1594 if let Some(project) = this.project.as_ref() {
1595 let handle = project.update(cx, |project, cx| {
1596 project.register_buffer_with_language_servers(&buffer, cx)
1597 });
1598 this.registered_buffers
1599 .insert(buffer.read(cx).remote_id(), handle);
1600 }
1601 }
1602 }
1603
1604 this.report_editor_event("Editor Opened", None, cx);
1605 this
1606 }
1607
1608 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1609 self.mouse_context_menu
1610 .as_ref()
1611 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1612 }
1613
1614 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1615 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1616 }
1617
1618 fn key_context_internal(
1619 &self,
1620 has_active_edit_prediction: bool,
1621 window: &Window,
1622 cx: &App,
1623 ) -> KeyContext {
1624 let mut key_context = KeyContext::new_with_defaults();
1625 key_context.add("Editor");
1626 let mode = match self.mode {
1627 EditorMode::SingleLine { .. } => "single_line",
1628 EditorMode::AutoHeight { .. } => "auto_height",
1629 EditorMode::Full => "full",
1630 };
1631
1632 if EditorSettings::jupyter_enabled(cx) {
1633 key_context.add("jupyter");
1634 }
1635
1636 key_context.set("mode", mode);
1637 if self.pending_rename.is_some() {
1638 key_context.add("renaming");
1639 }
1640
1641 match self.context_menu.borrow().as_ref() {
1642 Some(CodeContextMenu::Completions(_)) => {
1643 key_context.add("menu");
1644 key_context.add("showing_completions");
1645 }
1646 Some(CodeContextMenu::CodeActions(_)) => {
1647 key_context.add("menu");
1648 key_context.add("showing_code_actions")
1649 }
1650 None => {}
1651 }
1652
1653 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1654 if !self.focus_handle(cx).contains_focused(window, cx)
1655 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1656 {
1657 for addon in self.addons.values() {
1658 addon.extend_key_context(&mut key_context, cx)
1659 }
1660 }
1661
1662 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1663 if let Some(extension) = singleton_buffer
1664 .read(cx)
1665 .file()
1666 .and_then(|file| file.path().extension()?.to_str())
1667 {
1668 key_context.set("extension", extension.to_string());
1669 }
1670 } else {
1671 key_context.add("multibuffer");
1672 }
1673
1674 if has_active_edit_prediction {
1675 if self.edit_prediction_in_conflict() {
1676 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1677 } else {
1678 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1679 key_context.add("copilot_suggestion");
1680 }
1681 }
1682
1683 if self.selection_mark_mode {
1684 key_context.add("selection_mode");
1685 }
1686
1687 key_context
1688 }
1689
1690 pub fn edit_prediction_in_conflict(&self) -> bool {
1691 if !self.show_edit_predictions_in_menu() {
1692 return false;
1693 }
1694
1695 let showing_completions = self
1696 .context_menu
1697 .borrow()
1698 .as_ref()
1699 .map_or(false, |context| {
1700 matches!(context, CodeContextMenu::Completions(_))
1701 });
1702
1703 showing_completions
1704 || self.edit_prediction_requires_modifier()
1705 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1706 // bindings to insert tab characters.
1707 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1708 }
1709
1710 pub fn accept_edit_prediction_keybind(
1711 &self,
1712 window: &Window,
1713 cx: &App,
1714 ) -> AcceptEditPredictionBinding {
1715 let key_context = self.key_context_internal(true, window, cx);
1716 let in_conflict = self.edit_prediction_in_conflict();
1717
1718 AcceptEditPredictionBinding(
1719 window
1720 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1721 .into_iter()
1722 .filter(|binding| {
1723 !in_conflict
1724 || binding
1725 .keystrokes()
1726 .first()
1727 .map_or(false, |keystroke| keystroke.modifiers.modified())
1728 })
1729 .rev()
1730 .min_by_key(|binding| {
1731 binding
1732 .keystrokes()
1733 .first()
1734 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1735 }),
1736 )
1737 }
1738
1739 pub fn new_file(
1740 workspace: &mut Workspace,
1741 _: &workspace::NewFile,
1742 window: &mut Window,
1743 cx: &mut Context<Workspace>,
1744 ) {
1745 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1746 "Failed to create buffer",
1747 window,
1748 cx,
1749 |e, _, _| match e.error_code() {
1750 ErrorCode::RemoteUpgradeRequired => Some(format!(
1751 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1752 e.error_tag("required").unwrap_or("the latest version")
1753 )),
1754 _ => None,
1755 },
1756 );
1757 }
1758
1759 pub fn new_in_workspace(
1760 workspace: &mut Workspace,
1761 window: &mut Window,
1762 cx: &mut Context<Workspace>,
1763 ) -> Task<Result<Entity<Editor>>> {
1764 let project = workspace.project().clone();
1765 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1766
1767 cx.spawn_in(window, async move |workspace, cx| {
1768 let buffer = create.await?;
1769 workspace.update_in(cx, |workspace, window, cx| {
1770 let editor =
1771 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1772 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1773 editor
1774 })
1775 })
1776 }
1777
1778 fn new_file_vertical(
1779 workspace: &mut Workspace,
1780 _: &workspace::NewFileSplitVertical,
1781 window: &mut Window,
1782 cx: &mut Context<Workspace>,
1783 ) {
1784 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1785 }
1786
1787 fn new_file_horizontal(
1788 workspace: &mut Workspace,
1789 _: &workspace::NewFileSplitHorizontal,
1790 window: &mut Window,
1791 cx: &mut Context<Workspace>,
1792 ) {
1793 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1794 }
1795
1796 fn new_file_in_direction(
1797 workspace: &mut Workspace,
1798 direction: SplitDirection,
1799 window: &mut Window,
1800 cx: &mut Context<Workspace>,
1801 ) {
1802 let project = workspace.project().clone();
1803 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1804
1805 cx.spawn_in(window, async move |workspace, cx| {
1806 let buffer = create.await?;
1807 workspace.update_in(cx, move |workspace, window, cx| {
1808 workspace.split_item(
1809 direction,
1810 Box::new(
1811 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1812 ),
1813 window,
1814 cx,
1815 )
1816 })?;
1817 anyhow::Ok(())
1818 })
1819 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1820 match e.error_code() {
1821 ErrorCode::RemoteUpgradeRequired => Some(format!(
1822 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1823 e.error_tag("required").unwrap_or("the latest version")
1824 )),
1825 _ => None,
1826 }
1827 });
1828 }
1829
1830 pub fn leader_peer_id(&self) -> Option<PeerId> {
1831 self.leader_peer_id
1832 }
1833
1834 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1835 &self.buffer
1836 }
1837
1838 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1839 self.workspace.as_ref()?.0.upgrade()
1840 }
1841
1842 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1843 self.buffer().read(cx).title(cx)
1844 }
1845
1846 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1847 let git_blame_gutter_max_author_length = self
1848 .render_git_blame_gutter(cx)
1849 .then(|| {
1850 if let Some(blame) = self.blame.as_ref() {
1851 let max_author_length =
1852 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1853 Some(max_author_length)
1854 } else {
1855 None
1856 }
1857 })
1858 .flatten();
1859
1860 EditorSnapshot {
1861 mode: self.mode,
1862 show_gutter: self.show_gutter,
1863 show_line_numbers: self.show_line_numbers,
1864 show_git_diff_gutter: self.show_git_diff_gutter,
1865 show_code_actions: self.show_code_actions,
1866 show_runnables: self.show_runnables,
1867 show_breakpoints: self.show_breakpoints,
1868 git_blame_gutter_max_author_length,
1869 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1870 scroll_anchor: self.scroll_manager.anchor(),
1871 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1872 placeholder_text: self.placeholder_text.clone(),
1873 is_focused: self.focus_handle.is_focused(window),
1874 current_line_highlight: self
1875 .current_line_highlight
1876 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1877 gutter_hovered: self.gutter_hovered,
1878 }
1879 }
1880
1881 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1882 self.buffer.read(cx).language_at(point, cx)
1883 }
1884
1885 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1886 self.buffer.read(cx).read(cx).file_at(point).cloned()
1887 }
1888
1889 pub fn active_excerpt(
1890 &self,
1891 cx: &App,
1892 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1893 self.buffer
1894 .read(cx)
1895 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1896 }
1897
1898 pub fn mode(&self) -> EditorMode {
1899 self.mode
1900 }
1901
1902 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1903 self.collaboration_hub.as_deref()
1904 }
1905
1906 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1907 self.collaboration_hub = Some(hub);
1908 }
1909
1910 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1911 self.in_project_search = in_project_search;
1912 }
1913
1914 pub fn set_custom_context_menu(
1915 &mut self,
1916 f: impl 'static
1917 + Fn(
1918 &mut Self,
1919 DisplayPoint,
1920 &mut Window,
1921 &mut Context<Self>,
1922 ) -> Option<Entity<ui::ContextMenu>>,
1923 ) {
1924 self.custom_context_menu = Some(Box::new(f))
1925 }
1926
1927 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1928 self.completion_provider = provider;
1929 }
1930
1931 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1932 self.semantics_provider.clone()
1933 }
1934
1935 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1936 self.semantics_provider = provider;
1937 }
1938
1939 pub fn set_edit_prediction_provider<T>(
1940 &mut self,
1941 provider: Option<Entity<T>>,
1942 window: &mut Window,
1943 cx: &mut Context<Self>,
1944 ) where
1945 T: EditPredictionProvider,
1946 {
1947 self.edit_prediction_provider =
1948 provider.map(|provider| RegisteredInlineCompletionProvider {
1949 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1950 if this.focus_handle.is_focused(window) {
1951 this.update_visible_inline_completion(window, cx);
1952 }
1953 }),
1954 provider: Arc::new(provider),
1955 });
1956 self.update_edit_prediction_settings(cx);
1957 self.refresh_inline_completion(false, false, window, cx);
1958 }
1959
1960 pub fn placeholder_text(&self) -> Option<&str> {
1961 self.placeholder_text.as_deref()
1962 }
1963
1964 pub fn set_placeholder_text(
1965 &mut self,
1966 placeholder_text: impl Into<Arc<str>>,
1967 cx: &mut Context<Self>,
1968 ) {
1969 let placeholder_text = Some(placeholder_text.into());
1970 if self.placeholder_text != placeholder_text {
1971 self.placeholder_text = placeholder_text;
1972 cx.notify();
1973 }
1974 }
1975
1976 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1977 self.cursor_shape = cursor_shape;
1978
1979 // Disrupt blink for immediate user feedback that the cursor shape has changed
1980 self.blink_manager.update(cx, BlinkManager::show_cursor);
1981
1982 cx.notify();
1983 }
1984
1985 pub fn set_current_line_highlight(
1986 &mut self,
1987 current_line_highlight: Option<CurrentLineHighlight>,
1988 ) {
1989 self.current_line_highlight = current_line_highlight;
1990 }
1991
1992 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1993 self.collapse_matches = collapse_matches;
1994 }
1995
1996 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1997 let buffers = self.buffer.read(cx).all_buffers();
1998 let Some(project) = self.project.as_ref() else {
1999 return;
2000 };
2001 project.update(cx, |project, cx| {
2002 for buffer in buffers {
2003 self.registered_buffers
2004 .entry(buffer.read(cx).remote_id())
2005 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2006 }
2007 })
2008 }
2009
2010 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2011 if self.collapse_matches {
2012 return range.start..range.start;
2013 }
2014 range.clone()
2015 }
2016
2017 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2018 if self.display_map.read(cx).clip_at_line_ends != clip {
2019 self.display_map
2020 .update(cx, |map, _| map.clip_at_line_ends = clip);
2021 }
2022 }
2023
2024 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2025 self.input_enabled = input_enabled;
2026 }
2027
2028 pub fn set_inline_completions_hidden_for_vim_mode(
2029 &mut self,
2030 hidden: bool,
2031 window: &mut Window,
2032 cx: &mut Context<Self>,
2033 ) {
2034 if hidden != self.inline_completions_hidden_for_vim_mode {
2035 self.inline_completions_hidden_for_vim_mode = hidden;
2036 if hidden {
2037 self.update_visible_inline_completion(window, cx);
2038 } else {
2039 self.refresh_inline_completion(true, false, window, cx);
2040 }
2041 }
2042 }
2043
2044 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2045 self.menu_inline_completions_policy = value;
2046 }
2047
2048 pub fn set_autoindent(&mut self, autoindent: bool) {
2049 if autoindent {
2050 self.autoindent_mode = Some(AutoindentMode::EachLine);
2051 } else {
2052 self.autoindent_mode = None;
2053 }
2054 }
2055
2056 pub fn read_only(&self, cx: &App) -> bool {
2057 self.read_only || self.buffer.read(cx).read_only()
2058 }
2059
2060 pub fn set_read_only(&mut self, read_only: bool) {
2061 self.read_only = read_only;
2062 }
2063
2064 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2065 self.use_autoclose = autoclose;
2066 }
2067
2068 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2069 self.use_auto_surround = auto_surround;
2070 }
2071
2072 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2073 self.auto_replace_emoji_shortcode = auto_replace;
2074 }
2075
2076 pub fn toggle_edit_predictions(
2077 &mut self,
2078 _: &ToggleEditPrediction,
2079 window: &mut Window,
2080 cx: &mut Context<Self>,
2081 ) {
2082 if self.show_inline_completions_override.is_some() {
2083 self.set_show_edit_predictions(None, window, cx);
2084 } else {
2085 let show_edit_predictions = !self.edit_predictions_enabled();
2086 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2087 }
2088 }
2089
2090 pub fn set_show_edit_predictions(
2091 &mut self,
2092 show_edit_predictions: Option<bool>,
2093 window: &mut Window,
2094 cx: &mut Context<Self>,
2095 ) {
2096 self.show_inline_completions_override = show_edit_predictions;
2097 self.update_edit_prediction_settings(cx);
2098
2099 if let Some(false) = show_edit_predictions {
2100 self.discard_inline_completion(false, cx);
2101 } else {
2102 self.refresh_inline_completion(false, true, window, cx);
2103 }
2104 }
2105
2106 fn inline_completions_disabled_in_scope(
2107 &self,
2108 buffer: &Entity<Buffer>,
2109 buffer_position: language::Anchor,
2110 cx: &App,
2111 ) -> bool {
2112 let snapshot = buffer.read(cx).snapshot();
2113 let settings = snapshot.settings_at(buffer_position, cx);
2114
2115 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2116 return false;
2117 };
2118
2119 scope.override_name().map_or(false, |scope_name| {
2120 settings
2121 .edit_predictions_disabled_in
2122 .iter()
2123 .any(|s| s == scope_name)
2124 })
2125 }
2126
2127 pub fn set_use_modal_editing(&mut self, to: bool) {
2128 self.use_modal_editing = to;
2129 }
2130
2131 pub fn use_modal_editing(&self) -> bool {
2132 self.use_modal_editing
2133 }
2134
2135 fn selections_did_change(
2136 &mut self,
2137 local: bool,
2138 old_cursor_position: &Anchor,
2139 show_completions: bool,
2140 window: &mut Window,
2141 cx: &mut Context<Self>,
2142 ) {
2143 window.invalidate_character_coordinates();
2144
2145 // Copy selections to primary selection buffer
2146 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2147 if local {
2148 let selections = self.selections.all::<usize>(cx);
2149 let buffer_handle = self.buffer.read(cx).read(cx);
2150
2151 let mut text = String::new();
2152 for (index, selection) in selections.iter().enumerate() {
2153 let text_for_selection = buffer_handle
2154 .text_for_range(selection.start..selection.end)
2155 .collect::<String>();
2156
2157 text.push_str(&text_for_selection);
2158 if index != selections.len() - 1 {
2159 text.push('\n');
2160 }
2161 }
2162
2163 if !text.is_empty() {
2164 cx.write_to_primary(ClipboardItem::new_string(text));
2165 }
2166 }
2167
2168 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2169 self.buffer.update(cx, |buffer, cx| {
2170 buffer.set_active_selections(
2171 &self.selections.disjoint_anchors(),
2172 self.selections.line_mode,
2173 self.cursor_shape,
2174 cx,
2175 )
2176 });
2177 }
2178 let display_map = self
2179 .display_map
2180 .update(cx, |display_map, cx| display_map.snapshot(cx));
2181 let buffer = &display_map.buffer_snapshot;
2182 self.add_selections_state = None;
2183 self.select_next_state = None;
2184 self.select_prev_state = None;
2185 self.select_syntax_node_history.try_clear();
2186 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2187 self.snippet_stack
2188 .invalidate(&self.selections.disjoint_anchors(), buffer);
2189 self.take_rename(false, window, cx);
2190
2191 let new_cursor_position = self.selections.newest_anchor().head();
2192
2193 self.push_to_nav_history(
2194 *old_cursor_position,
2195 Some(new_cursor_position.to_point(buffer)),
2196 false,
2197 cx,
2198 );
2199
2200 if local {
2201 let new_cursor_position = self.selections.newest_anchor().head();
2202 let mut context_menu = self.context_menu.borrow_mut();
2203 let completion_menu = match context_menu.as_ref() {
2204 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2205 _ => {
2206 *context_menu = None;
2207 None
2208 }
2209 };
2210 if let Some(buffer_id) = new_cursor_position.buffer_id {
2211 if !self.registered_buffers.contains_key(&buffer_id) {
2212 if let Some(project) = self.project.as_ref() {
2213 project.update(cx, |project, cx| {
2214 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2215 return;
2216 };
2217 self.registered_buffers.insert(
2218 buffer_id,
2219 project.register_buffer_with_language_servers(&buffer, cx),
2220 );
2221 })
2222 }
2223 }
2224 }
2225
2226 if let Some(completion_menu) = completion_menu {
2227 let cursor_position = new_cursor_position.to_offset(buffer);
2228 let (word_range, kind) =
2229 buffer.surrounding_word(completion_menu.initial_position, true);
2230 if kind == Some(CharKind::Word)
2231 && word_range.to_inclusive().contains(&cursor_position)
2232 {
2233 let mut completion_menu = completion_menu.clone();
2234 drop(context_menu);
2235
2236 let query = Self::completion_query(buffer, cursor_position);
2237 cx.spawn(async move |this, cx| {
2238 completion_menu
2239 .filter(query.as_deref(), cx.background_executor().clone())
2240 .await;
2241
2242 this.update(cx, |this, cx| {
2243 let mut context_menu = this.context_menu.borrow_mut();
2244 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2245 else {
2246 return;
2247 };
2248
2249 if menu.id > completion_menu.id {
2250 return;
2251 }
2252
2253 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2254 drop(context_menu);
2255 cx.notify();
2256 })
2257 })
2258 .detach();
2259
2260 if show_completions {
2261 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2262 }
2263 } else {
2264 drop(context_menu);
2265 self.hide_context_menu(window, cx);
2266 }
2267 } else {
2268 drop(context_menu);
2269 }
2270
2271 hide_hover(self, cx);
2272
2273 if old_cursor_position.to_display_point(&display_map).row()
2274 != new_cursor_position.to_display_point(&display_map).row()
2275 {
2276 self.available_code_actions.take();
2277 }
2278 self.refresh_code_actions(window, cx);
2279 self.refresh_document_highlights(cx);
2280 self.refresh_selected_text_highlights(window, cx);
2281 refresh_matching_bracket_highlights(self, window, cx);
2282 self.update_visible_inline_completion(window, cx);
2283 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2284 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2285 if self.git_blame_inline_enabled {
2286 self.start_inline_blame_timer(window, cx);
2287 }
2288 }
2289
2290 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2291 cx.emit(EditorEvent::SelectionsChanged { local });
2292
2293 let selections = &self.selections.disjoint;
2294 if selections.len() == 1 {
2295 cx.emit(SearchEvent::ActiveMatchChanged)
2296 }
2297 if local
2298 && self.is_singleton(cx)
2299 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2300 {
2301 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2302 let background_executor = cx.background_executor().clone();
2303 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2304 let snapshot = self.buffer().read(cx).snapshot(cx);
2305 let selections = selections.clone();
2306 self.serialize_selections = cx.background_spawn(async move {
2307 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2308 let selections = selections
2309 .iter()
2310 .map(|selection| {
2311 (
2312 selection.start.to_offset(&snapshot),
2313 selection.end.to_offset(&snapshot),
2314 )
2315 })
2316 .collect();
2317
2318 DB.save_editor_selections(editor_id, workspace_id, selections)
2319 .await
2320 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2321 .log_err();
2322 });
2323 }
2324 }
2325
2326 cx.notify();
2327 }
2328
2329 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2330 if !self.is_singleton(cx)
2331 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
2332 {
2333 return;
2334 }
2335
2336 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2337 return;
2338 };
2339 let background_executor = cx.background_executor().clone();
2340 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2341 let snapshot = self.buffer().read(cx).snapshot(cx);
2342 let folds = self.display_map.update(cx, |display_map, cx| {
2343 display_map
2344 .snapshot(cx)
2345 .folds_in_range(0..snapshot.len())
2346 .map(|fold| {
2347 (
2348 fold.range.start.to_offset(&snapshot),
2349 fold.range.end.to_offset(&snapshot),
2350 )
2351 })
2352 .collect()
2353 });
2354 self.serialize_folds = cx.background_spawn(async move {
2355 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2356 DB.save_editor_folds(editor_id, workspace_id, folds)
2357 .await
2358 .with_context(|| format!("persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"))
2359 .log_err();
2360 });
2361 }
2362
2363 pub fn sync_selections(
2364 &mut self,
2365 other: Entity<Editor>,
2366 cx: &mut Context<Self>,
2367 ) -> gpui::Subscription {
2368 let other_selections = other.read(cx).selections.disjoint.to_vec();
2369 self.selections.change_with(cx, |selections| {
2370 selections.select_anchors(other_selections);
2371 });
2372
2373 let other_subscription =
2374 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2375 EditorEvent::SelectionsChanged { local: true } => {
2376 let other_selections = other.read(cx).selections.disjoint.to_vec();
2377 if other_selections.is_empty() {
2378 return;
2379 }
2380 this.selections.change_with(cx, |selections| {
2381 selections.select_anchors(other_selections);
2382 });
2383 }
2384 _ => {}
2385 });
2386
2387 let this_subscription =
2388 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2389 EditorEvent::SelectionsChanged { local: true } => {
2390 let these_selections = this.selections.disjoint.to_vec();
2391 if these_selections.is_empty() {
2392 return;
2393 }
2394 other.update(cx, |other_editor, cx| {
2395 other_editor.selections.change_with(cx, |selections| {
2396 selections.select_anchors(these_selections);
2397 })
2398 });
2399 }
2400 _ => {}
2401 });
2402
2403 Subscription::join(other_subscription, this_subscription)
2404 }
2405
2406 pub fn change_selections<R>(
2407 &mut self,
2408 autoscroll: Option<Autoscroll>,
2409 window: &mut Window,
2410 cx: &mut Context<Self>,
2411 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2412 ) -> R {
2413 self.change_selections_inner(autoscroll, true, window, cx, change)
2414 }
2415
2416 fn change_selections_inner<R>(
2417 &mut self,
2418 autoscroll: Option<Autoscroll>,
2419 request_completions: bool,
2420 window: &mut Window,
2421 cx: &mut Context<Self>,
2422 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2423 ) -> R {
2424 let old_cursor_position = self.selections.newest_anchor().head();
2425 self.push_to_selection_history();
2426
2427 let (changed, result) = self.selections.change_with(cx, change);
2428
2429 if changed {
2430 if let Some(autoscroll) = autoscroll {
2431 self.request_autoscroll(autoscroll, cx);
2432 }
2433 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2434
2435 if self.should_open_signature_help_automatically(
2436 &old_cursor_position,
2437 self.signature_help_state.backspace_pressed(),
2438 cx,
2439 ) {
2440 self.show_signature_help(&ShowSignatureHelp, window, cx);
2441 }
2442 self.signature_help_state.set_backspace_pressed(false);
2443 }
2444
2445 result
2446 }
2447
2448 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2449 where
2450 I: IntoIterator<Item = (Range<S>, T)>,
2451 S: ToOffset,
2452 T: Into<Arc<str>>,
2453 {
2454 if self.read_only(cx) {
2455 return;
2456 }
2457
2458 self.buffer
2459 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2460 }
2461
2462 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2463 where
2464 I: IntoIterator<Item = (Range<S>, T)>,
2465 S: ToOffset,
2466 T: Into<Arc<str>>,
2467 {
2468 if self.read_only(cx) {
2469 return;
2470 }
2471
2472 self.buffer.update(cx, |buffer, cx| {
2473 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2474 });
2475 }
2476
2477 pub fn edit_with_block_indent<I, S, T>(
2478 &mut self,
2479 edits: I,
2480 original_indent_columns: Vec<Option<u32>>,
2481 cx: &mut Context<Self>,
2482 ) where
2483 I: IntoIterator<Item = (Range<S>, T)>,
2484 S: ToOffset,
2485 T: Into<Arc<str>>,
2486 {
2487 if self.read_only(cx) {
2488 return;
2489 }
2490
2491 self.buffer.update(cx, |buffer, cx| {
2492 buffer.edit(
2493 edits,
2494 Some(AutoindentMode::Block {
2495 original_indent_columns,
2496 }),
2497 cx,
2498 )
2499 });
2500 }
2501
2502 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2503 self.hide_context_menu(window, cx);
2504
2505 match phase {
2506 SelectPhase::Begin {
2507 position,
2508 add,
2509 click_count,
2510 } => self.begin_selection(position, add, click_count, window, cx),
2511 SelectPhase::BeginColumnar {
2512 position,
2513 goal_column,
2514 reset,
2515 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2516 SelectPhase::Extend {
2517 position,
2518 click_count,
2519 } => self.extend_selection(position, click_count, window, cx),
2520 SelectPhase::Update {
2521 position,
2522 goal_column,
2523 scroll_delta,
2524 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2525 SelectPhase::End => self.end_selection(window, cx),
2526 }
2527 }
2528
2529 fn extend_selection(
2530 &mut self,
2531 position: DisplayPoint,
2532 click_count: usize,
2533 window: &mut Window,
2534 cx: &mut Context<Self>,
2535 ) {
2536 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2537 let tail = self.selections.newest::<usize>(cx).tail();
2538 self.begin_selection(position, false, click_count, window, cx);
2539
2540 let position = position.to_offset(&display_map, Bias::Left);
2541 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2542
2543 let mut pending_selection = self
2544 .selections
2545 .pending_anchor()
2546 .expect("extend_selection not called with pending selection");
2547 if position >= tail {
2548 pending_selection.start = tail_anchor;
2549 } else {
2550 pending_selection.end = tail_anchor;
2551 pending_selection.reversed = true;
2552 }
2553
2554 let mut pending_mode = self.selections.pending_mode().unwrap();
2555 match &mut pending_mode {
2556 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2557 _ => {}
2558 }
2559
2560 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2561 s.set_pending(pending_selection, pending_mode)
2562 });
2563 }
2564
2565 fn begin_selection(
2566 &mut self,
2567 position: DisplayPoint,
2568 add: bool,
2569 click_count: usize,
2570 window: &mut Window,
2571 cx: &mut Context<Self>,
2572 ) {
2573 if !self.focus_handle.is_focused(window) {
2574 self.last_focused_descendant = None;
2575 window.focus(&self.focus_handle);
2576 }
2577
2578 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2579 let buffer = &display_map.buffer_snapshot;
2580 let newest_selection = self.selections.newest_anchor().clone();
2581 let position = display_map.clip_point(position, Bias::Left);
2582
2583 let start;
2584 let end;
2585 let mode;
2586 let mut auto_scroll;
2587 match click_count {
2588 1 => {
2589 start = buffer.anchor_before(position.to_point(&display_map));
2590 end = start;
2591 mode = SelectMode::Character;
2592 auto_scroll = true;
2593 }
2594 2 => {
2595 let range = movement::surrounding_word(&display_map, position);
2596 start = buffer.anchor_before(range.start.to_point(&display_map));
2597 end = buffer.anchor_before(range.end.to_point(&display_map));
2598 mode = SelectMode::Word(start..end);
2599 auto_scroll = true;
2600 }
2601 3 => {
2602 let position = display_map
2603 .clip_point(position, Bias::Left)
2604 .to_point(&display_map);
2605 let line_start = display_map.prev_line_boundary(position).0;
2606 let next_line_start = buffer.clip_point(
2607 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2608 Bias::Left,
2609 );
2610 start = buffer.anchor_before(line_start);
2611 end = buffer.anchor_before(next_line_start);
2612 mode = SelectMode::Line(start..end);
2613 auto_scroll = true;
2614 }
2615 _ => {
2616 start = buffer.anchor_before(0);
2617 end = buffer.anchor_before(buffer.len());
2618 mode = SelectMode::All;
2619 auto_scroll = false;
2620 }
2621 }
2622 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2623
2624 let point_to_delete: Option<usize> = {
2625 let selected_points: Vec<Selection<Point>> =
2626 self.selections.disjoint_in_range(start..end, cx);
2627
2628 if !add || click_count > 1 {
2629 None
2630 } else if !selected_points.is_empty() {
2631 Some(selected_points[0].id)
2632 } else {
2633 let clicked_point_already_selected =
2634 self.selections.disjoint.iter().find(|selection| {
2635 selection.start.to_point(buffer) == start.to_point(buffer)
2636 || selection.end.to_point(buffer) == end.to_point(buffer)
2637 });
2638
2639 clicked_point_already_selected.map(|selection| selection.id)
2640 }
2641 };
2642
2643 let selections_count = self.selections.count();
2644
2645 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2646 if let Some(point_to_delete) = point_to_delete {
2647 s.delete(point_to_delete);
2648
2649 if selections_count == 1 {
2650 s.set_pending_anchor_range(start..end, mode);
2651 }
2652 } else {
2653 if !add {
2654 s.clear_disjoint();
2655 } else if click_count > 1 {
2656 s.delete(newest_selection.id)
2657 }
2658
2659 s.set_pending_anchor_range(start..end, mode);
2660 }
2661 });
2662 }
2663
2664 fn begin_columnar_selection(
2665 &mut self,
2666 position: DisplayPoint,
2667 goal_column: u32,
2668 reset: bool,
2669 window: &mut Window,
2670 cx: &mut Context<Self>,
2671 ) {
2672 if !self.focus_handle.is_focused(window) {
2673 self.last_focused_descendant = None;
2674 window.focus(&self.focus_handle);
2675 }
2676
2677 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2678
2679 if reset {
2680 let pointer_position = display_map
2681 .buffer_snapshot
2682 .anchor_before(position.to_point(&display_map));
2683
2684 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2685 s.clear_disjoint();
2686 s.set_pending_anchor_range(
2687 pointer_position..pointer_position,
2688 SelectMode::Character,
2689 );
2690 });
2691 }
2692
2693 let tail = self.selections.newest::<Point>(cx).tail();
2694 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2695
2696 if !reset {
2697 self.select_columns(
2698 tail.to_display_point(&display_map),
2699 position,
2700 goal_column,
2701 &display_map,
2702 window,
2703 cx,
2704 );
2705 }
2706 }
2707
2708 fn update_selection(
2709 &mut self,
2710 position: DisplayPoint,
2711 goal_column: u32,
2712 scroll_delta: gpui::Point<f32>,
2713 window: &mut Window,
2714 cx: &mut Context<Self>,
2715 ) {
2716 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2717
2718 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2719 let tail = tail.to_display_point(&display_map);
2720 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2721 } else if let Some(mut pending) = self.selections.pending_anchor() {
2722 let buffer = self.buffer.read(cx).snapshot(cx);
2723 let head;
2724 let tail;
2725 let mode = self.selections.pending_mode().unwrap();
2726 match &mode {
2727 SelectMode::Character => {
2728 head = position.to_point(&display_map);
2729 tail = pending.tail().to_point(&buffer);
2730 }
2731 SelectMode::Word(original_range) => {
2732 let original_display_range = original_range.start.to_display_point(&display_map)
2733 ..original_range.end.to_display_point(&display_map);
2734 let original_buffer_range = original_display_range.start.to_point(&display_map)
2735 ..original_display_range.end.to_point(&display_map);
2736 if movement::is_inside_word(&display_map, position)
2737 || original_display_range.contains(&position)
2738 {
2739 let word_range = movement::surrounding_word(&display_map, position);
2740 if word_range.start < original_display_range.start {
2741 head = word_range.start.to_point(&display_map);
2742 } else {
2743 head = word_range.end.to_point(&display_map);
2744 }
2745 } else {
2746 head = position.to_point(&display_map);
2747 }
2748
2749 if head <= original_buffer_range.start {
2750 tail = original_buffer_range.end;
2751 } else {
2752 tail = original_buffer_range.start;
2753 }
2754 }
2755 SelectMode::Line(original_range) => {
2756 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2757
2758 let position = display_map
2759 .clip_point(position, Bias::Left)
2760 .to_point(&display_map);
2761 let line_start = display_map.prev_line_boundary(position).0;
2762 let next_line_start = buffer.clip_point(
2763 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2764 Bias::Left,
2765 );
2766
2767 if line_start < original_range.start {
2768 head = line_start
2769 } else {
2770 head = next_line_start
2771 }
2772
2773 if head <= original_range.start {
2774 tail = original_range.end;
2775 } else {
2776 tail = original_range.start;
2777 }
2778 }
2779 SelectMode::All => {
2780 return;
2781 }
2782 };
2783
2784 if head < tail {
2785 pending.start = buffer.anchor_before(head);
2786 pending.end = buffer.anchor_before(tail);
2787 pending.reversed = true;
2788 } else {
2789 pending.start = buffer.anchor_before(tail);
2790 pending.end = buffer.anchor_before(head);
2791 pending.reversed = false;
2792 }
2793
2794 self.change_selections(None, window, cx, |s| {
2795 s.set_pending(pending, mode);
2796 });
2797 } else {
2798 log::error!("update_selection dispatched with no pending selection");
2799 return;
2800 }
2801
2802 self.apply_scroll_delta(scroll_delta, window, cx);
2803 cx.notify();
2804 }
2805
2806 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2807 self.columnar_selection_tail.take();
2808 if self.selections.pending_anchor().is_some() {
2809 let selections = self.selections.all::<usize>(cx);
2810 self.change_selections(None, window, cx, |s| {
2811 s.select(selections);
2812 s.clear_pending();
2813 });
2814 }
2815 }
2816
2817 fn select_columns(
2818 &mut self,
2819 tail: DisplayPoint,
2820 head: DisplayPoint,
2821 goal_column: u32,
2822 display_map: &DisplaySnapshot,
2823 window: &mut Window,
2824 cx: &mut Context<Self>,
2825 ) {
2826 let start_row = cmp::min(tail.row(), head.row());
2827 let end_row = cmp::max(tail.row(), head.row());
2828 let start_column = cmp::min(tail.column(), goal_column);
2829 let end_column = cmp::max(tail.column(), goal_column);
2830 let reversed = start_column < tail.column();
2831
2832 let selection_ranges = (start_row.0..=end_row.0)
2833 .map(DisplayRow)
2834 .filter_map(|row| {
2835 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2836 let start = display_map
2837 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2838 .to_point(display_map);
2839 let end = display_map
2840 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2841 .to_point(display_map);
2842 if reversed {
2843 Some(end..start)
2844 } else {
2845 Some(start..end)
2846 }
2847 } else {
2848 None
2849 }
2850 })
2851 .collect::<Vec<_>>();
2852
2853 self.change_selections(None, window, cx, |s| {
2854 s.select_ranges(selection_ranges);
2855 });
2856 cx.notify();
2857 }
2858
2859 pub fn has_pending_nonempty_selection(&self) -> bool {
2860 let pending_nonempty_selection = match self.selections.pending_anchor() {
2861 Some(Selection { start, end, .. }) => start != end,
2862 None => false,
2863 };
2864
2865 pending_nonempty_selection
2866 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2867 }
2868
2869 pub fn has_pending_selection(&self) -> bool {
2870 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2871 }
2872
2873 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2874 self.selection_mark_mode = false;
2875
2876 if self.clear_expanded_diff_hunks(cx) {
2877 cx.notify();
2878 return;
2879 }
2880 if self.dismiss_menus_and_popups(true, window, cx) {
2881 return;
2882 }
2883
2884 if self.mode == EditorMode::Full
2885 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2886 {
2887 return;
2888 }
2889
2890 cx.propagate();
2891 }
2892
2893 pub fn dismiss_menus_and_popups(
2894 &mut self,
2895 is_user_requested: bool,
2896 window: &mut Window,
2897 cx: &mut Context<Self>,
2898 ) -> bool {
2899 if self.take_rename(false, window, cx).is_some() {
2900 return true;
2901 }
2902
2903 if hide_hover(self, cx) {
2904 return true;
2905 }
2906
2907 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2908 return true;
2909 }
2910
2911 if self.hide_context_menu(window, cx).is_some() {
2912 return true;
2913 }
2914
2915 if self.mouse_context_menu.take().is_some() {
2916 return true;
2917 }
2918
2919 if is_user_requested && self.discard_inline_completion(true, cx) {
2920 return true;
2921 }
2922
2923 if self.snippet_stack.pop().is_some() {
2924 return true;
2925 }
2926
2927 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2928 self.dismiss_diagnostics(cx);
2929 return true;
2930 }
2931
2932 false
2933 }
2934
2935 fn linked_editing_ranges_for(
2936 &self,
2937 selection: Range<text::Anchor>,
2938 cx: &App,
2939 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2940 if self.linked_edit_ranges.is_empty() {
2941 return None;
2942 }
2943 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2944 selection.end.buffer_id.and_then(|end_buffer_id| {
2945 if selection.start.buffer_id != Some(end_buffer_id) {
2946 return None;
2947 }
2948 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2949 let snapshot = buffer.read(cx).snapshot();
2950 self.linked_edit_ranges
2951 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2952 .map(|ranges| (ranges, snapshot, buffer))
2953 })?;
2954 use text::ToOffset as TO;
2955 // find offset from the start of current range to current cursor position
2956 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2957
2958 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2959 let start_difference = start_offset - start_byte_offset;
2960 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2961 let end_difference = end_offset - start_byte_offset;
2962 // Current range has associated linked ranges.
2963 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2964 for range in linked_ranges.iter() {
2965 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2966 let end_offset = start_offset + end_difference;
2967 let start_offset = start_offset + start_difference;
2968 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2969 continue;
2970 }
2971 if self.selections.disjoint_anchor_ranges().any(|s| {
2972 if s.start.buffer_id != selection.start.buffer_id
2973 || s.end.buffer_id != selection.end.buffer_id
2974 {
2975 return false;
2976 }
2977 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2978 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2979 }) {
2980 continue;
2981 }
2982 let start = buffer_snapshot.anchor_after(start_offset);
2983 let end = buffer_snapshot.anchor_after(end_offset);
2984 linked_edits
2985 .entry(buffer.clone())
2986 .or_default()
2987 .push(start..end);
2988 }
2989 Some(linked_edits)
2990 }
2991
2992 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2993 let text: Arc<str> = text.into();
2994
2995 if self.read_only(cx) {
2996 return;
2997 }
2998
2999 let selections = self.selections.all_adjusted(cx);
3000 let mut bracket_inserted = false;
3001 let mut edits = Vec::new();
3002 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3003 let mut new_selections = Vec::with_capacity(selections.len());
3004 let mut new_autoclose_regions = Vec::new();
3005 let snapshot = self.buffer.read(cx).read(cx);
3006
3007 for (selection, autoclose_region) in
3008 self.selections_with_autoclose_regions(selections, &snapshot)
3009 {
3010 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3011 // Determine if the inserted text matches the opening or closing
3012 // bracket of any of this language's bracket pairs.
3013 let mut bracket_pair = None;
3014 let mut is_bracket_pair_start = false;
3015 let mut is_bracket_pair_end = false;
3016 if !text.is_empty() {
3017 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3018 // and they are removing the character that triggered IME popup.
3019 for (pair, enabled) in scope.brackets() {
3020 if !pair.close && !pair.surround {
3021 continue;
3022 }
3023
3024 if enabled && pair.start.ends_with(text.as_ref()) {
3025 let prefix_len = pair.start.len() - text.len();
3026 let preceding_text_matches_prefix = prefix_len == 0
3027 || (selection.start.column >= (prefix_len as u32)
3028 && snapshot.contains_str_at(
3029 Point::new(
3030 selection.start.row,
3031 selection.start.column - (prefix_len as u32),
3032 ),
3033 &pair.start[..prefix_len],
3034 ));
3035 if preceding_text_matches_prefix {
3036 bracket_pair = Some(pair.clone());
3037 is_bracket_pair_start = true;
3038 break;
3039 }
3040 }
3041 if pair.end.as_str() == text.as_ref() {
3042 bracket_pair = Some(pair.clone());
3043 is_bracket_pair_end = true;
3044 break;
3045 }
3046 }
3047 }
3048
3049 if let Some(bracket_pair) = bracket_pair {
3050 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3051 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3052 let auto_surround =
3053 self.use_auto_surround && snapshot_settings.use_auto_surround;
3054 if selection.is_empty() {
3055 if is_bracket_pair_start {
3056 // If the inserted text is a suffix of an opening bracket and the
3057 // selection is preceded by the rest of the opening bracket, then
3058 // insert the closing bracket.
3059 let following_text_allows_autoclose = snapshot
3060 .chars_at(selection.start)
3061 .next()
3062 .map_or(true, |c| scope.should_autoclose_before(c));
3063
3064 let preceding_text_allows_autoclose = selection.start.column == 0
3065 || snapshot.reversed_chars_at(selection.start).next().map_or(
3066 true,
3067 |c| {
3068 bracket_pair.start != bracket_pair.end
3069 || !snapshot
3070 .char_classifier_at(selection.start)
3071 .is_word(c)
3072 },
3073 );
3074
3075 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3076 && bracket_pair.start.len() == 1
3077 {
3078 let target = bracket_pair.start.chars().next().unwrap();
3079 let current_line_count = snapshot
3080 .reversed_chars_at(selection.start)
3081 .take_while(|&c| c != '\n')
3082 .filter(|&c| c == target)
3083 .count();
3084 current_line_count % 2 == 1
3085 } else {
3086 false
3087 };
3088
3089 if autoclose
3090 && bracket_pair.close
3091 && following_text_allows_autoclose
3092 && preceding_text_allows_autoclose
3093 && !is_closing_quote
3094 {
3095 let anchor = snapshot.anchor_before(selection.end);
3096 new_selections.push((selection.map(|_| anchor), text.len()));
3097 new_autoclose_regions.push((
3098 anchor,
3099 text.len(),
3100 selection.id,
3101 bracket_pair.clone(),
3102 ));
3103 edits.push((
3104 selection.range(),
3105 format!("{}{}", text, bracket_pair.end).into(),
3106 ));
3107 bracket_inserted = true;
3108 continue;
3109 }
3110 }
3111
3112 if let Some(region) = autoclose_region {
3113 // If the selection is followed by an auto-inserted closing bracket,
3114 // then don't insert that closing bracket again; just move the selection
3115 // past the closing bracket.
3116 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3117 && text.as_ref() == region.pair.end.as_str();
3118 if should_skip {
3119 let anchor = snapshot.anchor_after(selection.end);
3120 new_selections
3121 .push((selection.map(|_| anchor), region.pair.end.len()));
3122 continue;
3123 }
3124 }
3125
3126 let always_treat_brackets_as_autoclosed = snapshot
3127 .language_settings_at(selection.start, cx)
3128 .always_treat_brackets_as_autoclosed;
3129 if always_treat_brackets_as_autoclosed
3130 && is_bracket_pair_end
3131 && snapshot.contains_str_at(selection.end, text.as_ref())
3132 {
3133 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3134 // and the inserted text is a closing bracket and the selection is followed
3135 // by the closing bracket then move the selection past the closing bracket.
3136 let anchor = snapshot.anchor_after(selection.end);
3137 new_selections.push((selection.map(|_| anchor), text.len()));
3138 continue;
3139 }
3140 }
3141 // If an opening bracket is 1 character long and is typed while
3142 // text is selected, then surround that text with the bracket pair.
3143 else if auto_surround
3144 && bracket_pair.surround
3145 && is_bracket_pair_start
3146 && bracket_pair.start.chars().count() == 1
3147 {
3148 edits.push((selection.start..selection.start, text.clone()));
3149 edits.push((
3150 selection.end..selection.end,
3151 bracket_pair.end.as_str().into(),
3152 ));
3153 bracket_inserted = true;
3154 new_selections.push((
3155 Selection {
3156 id: selection.id,
3157 start: snapshot.anchor_after(selection.start),
3158 end: snapshot.anchor_before(selection.end),
3159 reversed: selection.reversed,
3160 goal: selection.goal,
3161 },
3162 0,
3163 ));
3164 continue;
3165 }
3166 }
3167 }
3168
3169 if self.auto_replace_emoji_shortcode
3170 && selection.is_empty()
3171 && text.as_ref().ends_with(':')
3172 {
3173 if let Some(possible_emoji_short_code) =
3174 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3175 {
3176 if !possible_emoji_short_code.is_empty() {
3177 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3178 let emoji_shortcode_start = Point::new(
3179 selection.start.row,
3180 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3181 );
3182
3183 // Remove shortcode from buffer
3184 edits.push((
3185 emoji_shortcode_start..selection.start,
3186 "".to_string().into(),
3187 ));
3188 new_selections.push((
3189 Selection {
3190 id: selection.id,
3191 start: snapshot.anchor_after(emoji_shortcode_start),
3192 end: snapshot.anchor_before(selection.start),
3193 reversed: selection.reversed,
3194 goal: selection.goal,
3195 },
3196 0,
3197 ));
3198
3199 // Insert emoji
3200 let selection_start_anchor = snapshot.anchor_after(selection.start);
3201 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3202 edits.push((selection.start..selection.end, emoji.to_string().into()));
3203
3204 continue;
3205 }
3206 }
3207 }
3208 }
3209
3210 // If not handling any auto-close operation, then just replace the selected
3211 // text with the given input and move the selection to the end of the
3212 // newly inserted text.
3213 let anchor = snapshot.anchor_after(selection.end);
3214 if !self.linked_edit_ranges.is_empty() {
3215 let start_anchor = snapshot.anchor_before(selection.start);
3216
3217 let is_word_char = text.chars().next().map_or(true, |char| {
3218 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3219 classifier.is_word(char)
3220 });
3221
3222 if is_word_char {
3223 if let Some(ranges) = self
3224 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3225 {
3226 for (buffer, edits) in ranges {
3227 linked_edits
3228 .entry(buffer.clone())
3229 .or_default()
3230 .extend(edits.into_iter().map(|range| (range, text.clone())));
3231 }
3232 }
3233 }
3234 }
3235
3236 new_selections.push((selection.map(|_| anchor), 0));
3237 edits.push((selection.start..selection.end, text.clone()));
3238 }
3239
3240 drop(snapshot);
3241
3242 self.transact(window, cx, |this, window, cx| {
3243 let initial_buffer_versions =
3244 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3245
3246 this.buffer.update(cx, |buffer, cx| {
3247 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3248 });
3249 for (buffer, edits) in linked_edits {
3250 buffer.update(cx, |buffer, cx| {
3251 let snapshot = buffer.snapshot();
3252 let edits = edits
3253 .into_iter()
3254 .map(|(range, text)| {
3255 use text::ToPoint as TP;
3256 let end_point = TP::to_point(&range.end, &snapshot);
3257 let start_point = TP::to_point(&range.start, &snapshot);
3258 (start_point..end_point, text)
3259 })
3260 .sorted_by_key(|(range, _)| range.start);
3261 buffer.edit(edits, None, cx);
3262 })
3263 }
3264 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3265 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3266 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3267 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3268 .zip(new_selection_deltas)
3269 .map(|(selection, delta)| Selection {
3270 id: selection.id,
3271 start: selection.start + delta,
3272 end: selection.end + delta,
3273 reversed: selection.reversed,
3274 goal: SelectionGoal::None,
3275 })
3276 .collect::<Vec<_>>();
3277
3278 let mut i = 0;
3279 for (position, delta, selection_id, pair) in new_autoclose_regions {
3280 let position = position.to_offset(&map.buffer_snapshot) + delta;
3281 let start = map.buffer_snapshot.anchor_before(position);
3282 let end = map.buffer_snapshot.anchor_after(position);
3283 while let Some(existing_state) = this.autoclose_regions.get(i) {
3284 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3285 Ordering::Less => i += 1,
3286 Ordering::Greater => break,
3287 Ordering::Equal => {
3288 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3289 Ordering::Less => i += 1,
3290 Ordering::Equal => break,
3291 Ordering::Greater => break,
3292 }
3293 }
3294 }
3295 }
3296 this.autoclose_regions.insert(
3297 i,
3298 AutocloseRegion {
3299 selection_id,
3300 range: start..end,
3301 pair,
3302 },
3303 );
3304 }
3305
3306 let had_active_inline_completion = this.has_active_inline_completion();
3307 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3308 s.select(new_selections)
3309 });
3310
3311 if !bracket_inserted {
3312 if let Some(on_type_format_task) =
3313 this.trigger_on_type_formatting(text.to_string(), window, cx)
3314 {
3315 on_type_format_task.detach_and_log_err(cx);
3316 }
3317 }
3318
3319 let editor_settings = EditorSettings::get_global(cx);
3320 if bracket_inserted
3321 && (editor_settings.auto_signature_help
3322 || editor_settings.show_signature_help_after_edits)
3323 {
3324 this.show_signature_help(&ShowSignatureHelp, window, cx);
3325 }
3326
3327 let trigger_in_words =
3328 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3329 if this.hard_wrap.is_some() {
3330 let latest: Range<Point> = this.selections.newest(cx).range();
3331 if latest.is_empty()
3332 && this
3333 .buffer()
3334 .read(cx)
3335 .snapshot(cx)
3336 .line_len(MultiBufferRow(latest.start.row))
3337 == latest.start.column
3338 {
3339 this.rewrap_impl(
3340 RewrapOptions {
3341 override_language_settings: true,
3342 preserve_existing_whitespace: true,
3343 },
3344 cx,
3345 )
3346 }
3347 }
3348 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3349 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3350 this.refresh_inline_completion(true, false, window, cx);
3351 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3352 });
3353 }
3354
3355 fn find_possible_emoji_shortcode_at_position(
3356 snapshot: &MultiBufferSnapshot,
3357 position: Point,
3358 ) -> Option<String> {
3359 let mut chars = Vec::new();
3360 let mut found_colon = false;
3361 for char in snapshot.reversed_chars_at(position).take(100) {
3362 // Found a possible emoji shortcode in the middle of the buffer
3363 if found_colon {
3364 if char.is_whitespace() {
3365 chars.reverse();
3366 return Some(chars.iter().collect());
3367 }
3368 // If the previous character is not a whitespace, we are in the middle of a word
3369 // and we only want to complete the shortcode if the word is made up of other emojis
3370 let mut containing_word = String::new();
3371 for ch in snapshot
3372 .reversed_chars_at(position)
3373 .skip(chars.len() + 1)
3374 .take(100)
3375 {
3376 if ch.is_whitespace() {
3377 break;
3378 }
3379 containing_word.push(ch);
3380 }
3381 let containing_word = containing_word.chars().rev().collect::<String>();
3382 if util::word_consists_of_emojis(containing_word.as_str()) {
3383 chars.reverse();
3384 return Some(chars.iter().collect());
3385 }
3386 }
3387
3388 if char.is_whitespace() || !char.is_ascii() {
3389 return None;
3390 }
3391 if char == ':' {
3392 found_colon = true;
3393 } else {
3394 chars.push(char);
3395 }
3396 }
3397 // Found a possible emoji shortcode at the beginning of the buffer
3398 chars.reverse();
3399 Some(chars.iter().collect())
3400 }
3401
3402 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3403 self.transact(window, cx, |this, window, cx| {
3404 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3405 let selections = this.selections.all::<usize>(cx);
3406 let multi_buffer = this.buffer.read(cx);
3407 let buffer = multi_buffer.snapshot(cx);
3408 selections
3409 .iter()
3410 .map(|selection| {
3411 let start_point = selection.start.to_point(&buffer);
3412 let mut indent =
3413 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3414 indent.len = cmp::min(indent.len, start_point.column);
3415 let start = selection.start;
3416 let end = selection.end;
3417 let selection_is_empty = start == end;
3418 let language_scope = buffer.language_scope_at(start);
3419 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3420 &language_scope
3421 {
3422 let insert_extra_newline =
3423 insert_extra_newline_brackets(&buffer, start..end, language)
3424 || insert_extra_newline_tree_sitter(&buffer, start..end);
3425
3426 // Comment extension on newline is allowed only for cursor selections
3427 let comment_delimiter = maybe!({
3428 if !selection_is_empty {
3429 return None;
3430 }
3431
3432 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3433 return None;
3434 }
3435
3436 let delimiters = language.line_comment_prefixes();
3437 let max_len_of_delimiter =
3438 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3439 let (snapshot, range) =
3440 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3441
3442 let mut index_of_first_non_whitespace = 0;
3443 let comment_candidate = snapshot
3444 .chars_for_range(range)
3445 .skip_while(|c| {
3446 let should_skip = c.is_whitespace();
3447 if should_skip {
3448 index_of_first_non_whitespace += 1;
3449 }
3450 should_skip
3451 })
3452 .take(max_len_of_delimiter)
3453 .collect::<String>();
3454 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3455 comment_candidate.starts_with(comment_prefix.as_ref())
3456 })?;
3457 let cursor_is_placed_after_comment_marker =
3458 index_of_first_non_whitespace + comment_prefix.len()
3459 <= start_point.column as usize;
3460 if cursor_is_placed_after_comment_marker {
3461 Some(comment_prefix.clone())
3462 } else {
3463 None
3464 }
3465 });
3466 (comment_delimiter, insert_extra_newline)
3467 } else {
3468 (None, false)
3469 };
3470
3471 let capacity_for_delimiter = comment_delimiter
3472 .as_deref()
3473 .map(str::len)
3474 .unwrap_or_default();
3475 let mut new_text =
3476 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3477 new_text.push('\n');
3478 new_text.extend(indent.chars());
3479 if let Some(delimiter) = &comment_delimiter {
3480 new_text.push_str(delimiter);
3481 }
3482 if insert_extra_newline {
3483 new_text = new_text.repeat(2);
3484 }
3485
3486 let anchor = buffer.anchor_after(end);
3487 let new_selection = selection.map(|_| anchor);
3488 (
3489 (start..end, new_text),
3490 (insert_extra_newline, new_selection),
3491 )
3492 })
3493 .unzip()
3494 };
3495
3496 this.edit_with_autoindent(edits, cx);
3497 let buffer = this.buffer.read(cx).snapshot(cx);
3498 let new_selections = selection_fixup_info
3499 .into_iter()
3500 .map(|(extra_newline_inserted, new_selection)| {
3501 let mut cursor = new_selection.end.to_point(&buffer);
3502 if extra_newline_inserted {
3503 cursor.row -= 1;
3504 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3505 }
3506 new_selection.map(|_| cursor)
3507 })
3508 .collect();
3509
3510 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3511 s.select(new_selections)
3512 });
3513 this.refresh_inline_completion(true, false, window, cx);
3514 });
3515 }
3516
3517 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3518 let buffer = self.buffer.read(cx);
3519 let snapshot = buffer.snapshot(cx);
3520
3521 let mut edits = Vec::new();
3522 let mut rows = Vec::new();
3523
3524 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3525 let cursor = selection.head();
3526 let row = cursor.row;
3527
3528 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3529
3530 let newline = "\n".to_string();
3531 edits.push((start_of_line..start_of_line, newline));
3532
3533 rows.push(row + rows_inserted as u32);
3534 }
3535
3536 self.transact(window, cx, |editor, window, cx| {
3537 editor.edit(edits, cx);
3538
3539 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3540 let mut index = 0;
3541 s.move_cursors_with(|map, _, _| {
3542 let row = rows[index];
3543 index += 1;
3544
3545 let point = Point::new(row, 0);
3546 let boundary = map.next_line_boundary(point).1;
3547 let clipped = map.clip_point(boundary, Bias::Left);
3548
3549 (clipped, SelectionGoal::None)
3550 });
3551 });
3552
3553 let mut indent_edits = Vec::new();
3554 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3555 for row in rows {
3556 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3557 for (row, indent) in indents {
3558 if indent.len == 0 {
3559 continue;
3560 }
3561
3562 let text = match indent.kind {
3563 IndentKind::Space => " ".repeat(indent.len as usize),
3564 IndentKind::Tab => "\t".repeat(indent.len as usize),
3565 };
3566 let point = Point::new(row.0, 0);
3567 indent_edits.push((point..point, text));
3568 }
3569 }
3570 editor.edit(indent_edits, cx);
3571 });
3572 }
3573
3574 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3575 let buffer = self.buffer.read(cx);
3576 let snapshot = buffer.snapshot(cx);
3577
3578 let mut edits = Vec::new();
3579 let mut rows = Vec::new();
3580 let mut rows_inserted = 0;
3581
3582 for selection in self.selections.all_adjusted(cx) {
3583 let cursor = selection.head();
3584 let row = cursor.row;
3585
3586 let point = Point::new(row + 1, 0);
3587 let start_of_line = snapshot.clip_point(point, Bias::Left);
3588
3589 let newline = "\n".to_string();
3590 edits.push((start_of_line..start_of_line, newline));
3591
3592 rows_inserted += 1;
3593 rows.push(row + rows_inserted);
3594 }
3595
3596 self.transact(window, cx, |editor, window, cx| {
3597 editor.edit(edits, cx);
3598
3599 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3600 let mut index = 0;
3601 s.move_cursors_with(|map, _, _| {
3602 let row = rows[index];
3603 index += 1;
3604
3605 let point = Point::new(row, 0);
3606 let boundary = map.next_line_boundary(point).1;
3607 let clipped = map.clip_point(boundary, Bias::Left);
3608
3609 (clipped, SelectionGoal::None)
3610 });
3611 });
3612
3613 let mut indent_edits = Vec::new();
3614 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3615 for row in rows {
3616 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3617 for (row, indent) in indents {
3618 if indent.len == 0 {
3619 continue;
3620 }
3621
3622 let text = match indent.kind {
3623 IndentKind::Space => " ".repeat(indent.len as usize),
3624 IndentKind::Tab => "\t".repeat(indent.len as usize),
3625 };
3626 let point = Point::new(row.0, 0);
3627 indent_edits.push((point..point, text));
3628 }
3629 }
3630 editor.edit(indent_edits, cx);
3631 });
3632 }
3633
3634 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3635 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3636 original_indent_columns: Vec::new(),
3637 });
3638 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3639 }
3640
3641 fn insert_with_autoindent_mode(
3642 &mut self,
3643 text: &str,
3644 autoindent_mode: Option<AutoindentMode>,
3645 window: &mut Window,
3646 cx: &mut Context<Self>,
3647 ) {
3648 if self.read_only(cx) {
3649 return;
3650 }
3651
3652 let text: Arc<str> = text.into();
3653 self.transact(window, cx, |this, window, cx| {
3654 let old_selections = this.selections.all_adjusted(cx);
3655 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3656 let anchors = {
3657 let snapshot = buffer.read(cx);
3658 old_selections
3659 .iter()
3660 .map(|s| {
3661 let anchor = snapshot.anchor_after(s.head());
3662 s.map(|_| anchor)
3663 })
3664 .collect::<Vec<_>>()
3665 };
3666 buffer.edit(
3667 old_selections
3668 .iter()
3669 .map(|s| (s.start..s.end, text.clone())),
3670 autoindent_mode,
3671 cx,
3672 );
3673 anchors
3674 });
3675
3676 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3677 s.select_anchors(selection_anchors);
3678 });
3679
3680 cx.notify();
3681 });
3682 }
3683
3684 fn trigger_completion_on_input(
3685 &mut self,
3686 text: &str,
3687 trigger_in_words: bool,
3688 window: &mut Window,
3689 cx: &mut Context<Self>,
3690 ) {
3691 let ignore_completion_provider = self
3692 .context_menu
3693 .borrow()
3694 .as_ref()
3695 .map(|menu| match menu {
3696 CodeContextMenu::Completions(completions_menu) => {
3697 completions_menu.ignore_completion_provider
3698 }
3699 CodeContextMenu::CodeActions(_) => false,
3700 })
3701 .unwrap_or(false);
3702
3703 if ignore_completion_provider {
3704 self.show_word_completions(&ShowWordCompletions, window, cx);
3705 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3706 self.show_completions(
3707 &ShowCompletions {
3708 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3709 },
3710 window,
3711 cx,
3712 );
3713 } else {
3714 self.hide_context_menu(window, cx);
3715 }
3716 }
3717
3718 fn is_completion_trigger(
3719 &self,
3720 text: &str,
3721 trigger_in_words: bool,
3722 cx: &mut Context<Self>,
3723 ) -> bool {
3724 let position = self.selections.newest_anchor().head();
3725 let multibuffer = self.buffer.read(cx);
3726 let Some(buffer) = position
3727 .buffer_id
3728 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3729 else {
3730 return false;
3731 };
3732
3733 if let Some(completion_provider) = &self.completion_provider {
3734 completion_provider.is_completion_trigger(
3735 &buffer,
3736 position.text_anchor,
3737 text,
3738 trigger_in_words,
3739 cx,
3740 )
3741 } else {
3742 false
3743 }
3744 }
3745
3746 /// If any empty selections is touching the start of its innermost containing autoclose
3747 /// region, expand it to select the brackets.
3748 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3749 let selections = self.selections.all::<usize>(cx);
3750 let buffer = self.buffer.read(cx).read(cx);
3751 let new_selections = self
3752 .selections_with_autoclose_regions(selections, &buffer)
3753 .map(|(mut selection, region)| {
3754 if !selection.is_empty() {
3755 return selection;
3756 }
3757
3758 if let Some(region) = region {
3759 let mut range = region.range.to_offset(&buffer);
3760 if selection.start == range.start && range.start >= region.pair.start.len() {
3761 range.start -= region.pair.start.len();
3762 if buffer.contains_str_at(range.start, ®ion.pair.start)
3763 && buffer.contains_str_at(range.end, ®ion.pair.end)
3764 {
3765 range.end += region.pair.end.len();
3766 selection.start = range.start;
3767 selection.end = range.end;
3768
3769 return selection;
3770 }
3771 }
3772 }
3773
3774 let always_treat_brackets_as_autoclosed = buffer
3775 .language_settings_at(selection.start, cx)
3776 .always_treat_brackets_as_autoclosed;
3777
3778 if !always_treat_brackets_as_autoclosed {
3779 return selection;
3780 }
3781
3782 if let Some(scope) = buffer.language_scope_at(selection.start) {
3783 for (pair, enabled) in scope.brackets() {
3784 if !enabled || !pair.close {
3785 continue;
3786 }
3787
3788 if buffer.contains_str_at(selection.start, &pair.end) {
3789 let pair_start_len = pair.start.len();
3790 if buffer.contains_str_at(
3791 selection.start.saturating_sub(pair_start_len),
3792 &pair.start,
3793 ) {
3794 selection.start -= pair_start_len;
3795 selection.end += pair.end.len();
3796
3797 return selection;
3798 }
3799 }
3800 }
3801 }
3802
3803 selection
3804 })
3805 .collect();
3806
3807 drop(buffer);
3808 self.change_selections(None, window, cx, |selections| {
3809 selections.select(new_selections)
3810 });
3811 }
3812
3813 /// Iterate the given selections, and for each one, find the smallest surrounding
3814 /// autoclose region. This uses the ordering of the selections and the autoclose
3815 /// regions to avoid repeated comparisons.
3816 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3817 &'a self,
3818 selections: impl IntoIterator<Item = Selection<D>>,
3819 buffer: &'a MultiBufferSnapshot,
3820 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3821 let mut i = 0;
3822 let mut regions = self.autoclose_regions.as_slice();
3823 selections.into_iter().map(move |selection| {
3824 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3825
3826 let mut enclosing = None;
3827 while let Some(pair_state) = regions.get(i) {
3828 if pair_state.range.end.to_offset(buffer) < range.start {
3829 regions = ®ions[i + 1..];
3830 i = 0;
3831 } else if pair_state.range.start.to_offset(buffer) > range.end {
3832 break;
3833 } else {
3834 if pair_state.selection_id == selection.id {
3835 enclosing = Some(pair_state);
3836 }
3837 i += 1;
3838 }
3839 }
3840
3841 (selection, enclosing)
3842 })
3843 }
3844
3845 /// Remove any autoclose regions that no longer contain their selection.
3846 fn invalidate_autoclose_regions(
3847 &mut self,
3848 mut selections: &[Selection<Anchor>],
3849 buffer: &MultiBufferSnapshot,
3850 ) {
3851 self.autoclose_regions.retain(|state| {
3852 let mut i = 0;
3853 while let Some(selection) = selections.get(i) {
3854 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3855 selections = &selections[1..];
3856 continue;
3857 }
3858 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3859 break;
3860 }
3861 if selection.id == state.selection_id {
3862 return true;
3863 } else {
3864 i += 1;
3865 }
3866 }
3867 false
3868 });
3869 }
3870
3871 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3872 let offset = position.to_offset(buffer);
3873 let (word_range, kind) = buffer.surrounding_word(offset, true);
3874 if offset > word_range.start && kind == Some(CharKind::Word) {
3875 Some(
3876 buffer
3877 .text_for_range(word_range.start..offset)
3878 .collect::<String>(),
3879 )
3880 } else {
3881 None
3882 }
3883 }
3884
3885 pub fn toggle_inlay_hints(
3886 &mut self,
3887 _: &ToggleInlayHints,
3888 _: &mut Window,
3889 cx: &mut Context<Self>,
3890 ) {
3891 self.refresh_inlay_hints(
3892 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3893 cx,
3894 );
3895 }
3896
3897 pub fn inlay_hints_enabled(&self) -> bool {
3898 self.inlay_hint_cache.enabled
3899 }
3900
3901 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3902 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3903 return;
3904 }
3905
3906 let reason_description = reason.description();
3907 let ignore_debounce = matches!(
3908 reason,
3909 InlayHintRefreshReason::SettingsChange(_)
3910 | InlayHintRefreshReason::Toggle(_)
3911 | InlayHintRefreshReason::ExcerptsRemoved(_)
3912 | InlayHintRefreshReason::ModifiersChanged(_)
3913 );
3914 let (invalidate_cache, required_languages) = match reason {
3915 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3916 match self.inlay_hint_cache.modifiers_override(enabled) {
3917 Some(enabled) => {
3918 if enabled {
3919 (InvalidationStrategy::RefreshRequested, None)
3920 } else {
3921 self.splice_inlays(
3922 &self
3923 .visible_inlay_hints(cx)
3924 .iter()
3925 .map(|inlay| inlay.id)
3926 .collect::<Vec<InlayId>>(),
3927 Vec::new(),
3928 cx,
3929 );
3930 return;
3931 }
3932 }
3933 None => return,
3934 }
3935 }
3936 InlayHintRefreshReason::Toggle(enabled) => {
3937 if self.inlay_hint_cache.toggle(enabled) {
3938 if enabled {
3939 (InvalidationStrategy::RefreshRequested, None)
3940 } else {
3941 self.splice_inlays(
3942 &self
3943 .visible_inlay_hints(cx)
3944 .iter()
3945 .map(|inlay| inlay.id)
3946 .collect::<Vec<InlayId>>(),
3947 Vec::new(),
3948 cx,
3949 );
3950 return;
3951 }
3952 } else {
3953 return;
3954 }
3955 }
3956 InlayHintRefreshReason::SettingsChange(new_settings) => {
3957 match self.inlay_hint_cache.update_settings(
3958 &self.buffer,
3959 new_settings,
3960 self.visible_inlay_hints(cx),
3961 cx,
3962 ) {
3963 ControlFlow::Break(Some(InlaySplice {
3964 to_remove,
3965 to_insert,
3966 })) => {
3967 self.splice_inlays(&to_remove, to_insert, cx);
3968 return;
3969 }
3970 ControlFlow::Break(None) => return,
3971 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3972 }
3973 }
3974 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3975 if let Some(InlaySplice {
3976 to_remove,
3977 to_insert,
3978 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3979 {
3980 self.splice_inlays(&to_remove, to_insert, cx);
3981 }
3982 return;
3983 }
3984 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3985 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3986 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3987 }
3988 InlayHintRefreshReason::RefreshRequested => {
3989 (InvalidationStrategy::RefreshRequested, None)
3990 }
3991 };
3992
3993 if let Some(InlaySplice {
3994 to_remove,
3995 to_insert,
3996 }) = self.inlay_hint_cache.spawn_hint_refresh(
3997 reason_description,
3998 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3999 invalidate_cache,
4000 ignore_debounce,
4001 cx,
4002 ) {
4003 self.splice_inlays(&to_remove, to_insert, cx);
4004 }
4005 }
4006
4007 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4008 self.display_map
4009 .read(cx)
4010 .current_inlays()
4011 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4012 .cloned()
4013 .collect()
4014 }
4015
4016 pub fn excerpts_for_inlay_hints_query(
4017 &self,
4018 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4019 cx: &mut Context<Editor>,
4020 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4021 let Some(project) = self.project.as_ref() else {
4022 return HashMap::default();
4023 };
4024 let project = project.read(cx);
4025 let multi_buffer = self.buffer().read(cx);
4026 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4027 let multi_buffer_visible_start = self
4028 .scroll_manager
4029 .anchor()
4030 .anchor
4031 .to_point(&multi_buffer_snapshot);
4032 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4033 multi_buffer_visible_start
4034 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4035 Bias::Left,
4036 );
4037 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4038 multi_buffer_snapshot
4039 .range_to_buffer_ranges(multi_buffer_visible_range)
4040 .into_iter()
4041 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4042 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4043 let buffer_file = project::File::from_dyn(buffer.file())?;
4044 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4045 let worktree_entry = buffer_worktree
4046 .read(cx)
4047 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4048 if worktree_entry.is_ignored {
4049 return None;
4050 }
4051
4052 let language = buffer.language()?;
4053 if let Some(restrict_to_languages) = restrict_to_languages {
4054 if !restrict_to_languages.contains(language) {
4055 return None;
4056 }
4057 }
4058 Some((
4059 excerpt_id,
4060 (
4061 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4062 buffer.version().clone(),
4063 excerpt_visible_range,
4064 ),
4065 ))
4066 })
4067 .collect()
4068 }
4069
4070 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4071 TextLayoutDetails {
4072 text_system: window.text_system().clone(),
4073 editor_style: self.style.clone().unwrap(),
4074 rem_size: window.rem_size(),
4075 scroll_anchor: self.scroll_manager.anchor(),
4076 visible_rows: self.visible_line_count(),
4077 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4078 }
4079 }
4080
4081 pub fn splice_inlays(
4082 &self,
4083 to_remove: &[InlayId],
4084 to_insert: Vec<Inlay>,
4085 cx: &mut Context<Self>,
4086 ) {
4087 self.display_map.update(cx, |display_map, cx| {
4088 display_map.splice_inlays(to_remove, to_insert, cx)
4089 });
4090 cx.notify();
4091 }
4092
4093 fn trigger_on_type_formatting(
4094 &self,
4095 input: String,
4096 window: &mut Window,
4097 cx: &mut Context<Self>,
4098 ) -> Option<Task<Result<()>>> {
4099 if input.len() != 1 {
4100 return None;
4101 }
4102
4103 let project = self.project.as_ref()?;
4104 let position = self.selections.newest_anchor().head();
4105 let (buffer, buffer_position) = self
4106 .buffer
4107 .read(cx)
4108 .text_anchor_for_position(position, cx)?;
4109
4110 let settings = language_settings::language_settings(
4111 buffer
4112 .read(cx)
4113 .language_at(buffer_position)
4114 .map(|l| l.name()),
4115 buffer.read(cx).file(),
4116 cx,
4117 );
4118 if !settings.use_on_type_format {
4119 return None;
4120 }
4121
4122 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4123 // hence we do LSP request & edit on host side only — add formats to host's history.
4124 let push_to_lsp_host_history = true;
4125 // If this is not the host, append its history with new edits.
4126 let push_to_client_history = project.read(cx).is_via_collab();
4127
4128 let on_type_formatting = project.update(cx, |project, cx| {
4129 project.on_type_format(
4130 buffer.clone(),
4131 buffer_position,
4132 input,
4133 push_to_lsp_host_history,
4134 cx,
4135 )
4136 });
4137 Some(cx.spawn_in(window, async move |editor, cx| {
4138 if let Some(transaction) = on_type_formatting.await? {
4139 if push_to_client_history {
4140 buffer
4141 .update(cx, |buffer, _| {
4142 buffer.push_transaction(transaction, Instant::now());
4143 })
4144 .ok();
4145 }
4146 editor.update(cx, |editor, cx| {
4147 editor.refresh_document_highlights(cx);
4148 })?;
4149 }
4150 Ok(())
4151 }))
4152 }
4153
4154 pub fn show_word_completions(
4155 &mut self,
4156 _: &ShowWordCompletions,
4157 window: &mut Window,
4158 cx: &mut Context<Self>,
4159 ) {
4160 self.open_completions_menu(true, None, window, cx);
4161 }
4162
4163 pub fn show_completions(
4164 &mut self,
4165 options: &ShowCompletions,
4166 window: &mut Window,
4167 cx: &mut Context<Self>,
4168 ) {
4169 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4170 }
4171
4172 fn open_completions_menu(
4173 &mut self,
4174 ignore_completion_provider: bool,
4175 trigger: Option<&str>,
4176 window: &mut Window,
4177 cx: &mut Context<Self>,
4178 ) {
4179 if self.pending_rename.is_some() {
4180 return;
4181 }
4182 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4183 return;
4184 }
4185
4186 let position = self.selections.newest_anchor().head();
4187 if position.diff_base_anchor.is_some() {
4188 return;
4189 }
4190 let (buffer, buffer_position) =
4191 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4192 output
4193 } else {
4194 return;
4195 };
4196 let buffer_snapshot = buffer.read(cx).snapshot();
4197 let show_completion_documentation = buffer_snapshot
4198 .settings_at(buffer_position, cx)
4199 .show_completion_documentation;
4200
4201 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4202
4203 let trigger_kind = match trigger {
4204 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4205 CompletionTriggerKind::TRIGGER_CHARACTER
4206 }
4207 _ => CompletionTriggerKind::INVOKED,
4208 };
4209 let completion_context = CompletionContext {
4210 trigger_character: trigger.and_then(|trigger| {
4211 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4212 Some(String::from(trigger))
4213 } else {
4214 None
4215 }
4216 }),
4217 trigger_kind,
4218 };
4219
4220 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4221 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4222 let word_to_exclude = buffer_snapshot
4223 .text_for_range(old_range.clone())
4224 .collect::<String>();
4225 (
4226 buffer_snapshot.anchor_before(old_range.start)
4227 ..buffer_snapshot.anchor_after(old_range.end),
4228 Some(word_to_exclude),
4229 )
4230 } else {
4231 (buffer_position..buffer_position, None)
4232 };
4233
4234 let completion_settings = language_settings(
4235 buffer_snapshot
4236 .language_at(buffer_position)
4237 .map(|language| language.name()),
4238 buffer_snapshot.file(),
4239 cx,
4240 )
4241 .completions;
4242
4243 // The document can be large, so stay in reasonable bounds when searching for words,
4244 // otherwise completion pop-up might be slow to appear.
4245 const WORD_LOOKUP_ROWS: u32 = 5_000;
4246 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4247 let min_word_search = buffer_snapshot.clip_point(
4248 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4249 Bias::Left,
4250 );
4251 let max_word_search = buffer_snapshot.clip_point(
4252 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4253 Bias::Right,
4254 );
4255 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4256 ..buffer_snapshot.point_to_offset(max_word_search);
4257
4258 let provider = self
4259 .completion_provider
4260 .as_ref()
4261 .filter(|_| !ignore_completion_provider);
4262 let skip_digits = query
4263 .as_ref()
4264 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4265
4266 let (mut words, provided_completions) = match provider {
4267 Some(provider) => {
4268 let completions = provider.completions(
4269 position.excerpt_id,
4270 &buffer,
4271 buffer_position,
4272 completion_context,
4273 window,
4274 cx,
4275 );
4276
4277 let words = match completion_settings.words {
4278 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4279 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4280 .background_spawn(async move {
4281 buffer_snapshot.words_in_range(WordsQuery {
4282 fuzzy_contents: None,
4283 range: word_search_range,
4284 skip_digits,
4285 })
4286 }),
4287 };
4288
4289 (words, completions)
4290 }
4291 None => (
4292 cx.background_spawn(async move {
4293 buffer_snapshot.words_in_range(WordsQuery {
4294 fuzzy_contents: None,
4295 range: word_search_range,
4296 skip_digits,
4297 })
4298 }),
4299 Task::ready(Ok(None)),
4300 ),
4301 };
4302
4303 let sort_completions = provider
4304 .as_ref()
4305 .map_or(true, |provider| provider.sort_completions());
4306
4307 let id = post_inc(&mut self.next_completion_id);
4308 let task = cx.spawn_in(window, async move |editor, cx| {
4309 async move {
4310 editor.update(cx, |this, _| {
4311 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4312 })?;
4313
4314 let mut completions = Vec::new();
4315 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4316 completions.extend(provided_completions);
4317 if completion_settings.words == WordsCompletionMode::Fallback {
4318 words = Task::ready(HashMap::default());
4319 }
4320 }
4321
4322 let mut words = words.await;
4323 if let Some(word_to_exclude) = &word_to_exclude {
4324 words.remove(word_to_exclude);
4325 }
4326 for lsp_completion in &completions {
4327 words.remove(&lsp_completion.new_text);
4328 }
4329 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4330 old_range: old_range.clone(),
4331 new_text: word.clone(),
4332 label: CodeLabel::plain(word, None),
4333 icon_path: None,
4334 documentation: None,
4335 source: CompletionSource::BufferWord {
4336 word_range,
4337 resolved: false,
4338 },
4339 confirm: None,
4340 }));
4341
4342 let menu = if completions.is_empty() {
4343 None
4344 } else {
4345 let mut menu = CompletionsMenu::new(
4346 id,
4347 sort_completions,
4348 show_completion_documentation,
4349 ignore_completion_provider,
4350 position,
4351 buffer.clone(),
4352 completions.into(),
4353 );
4354
4355 menu.filter(query.as_deref(), cx.background_executor().clone())
4356 .await;
4357
4358 menu.visible().then_some(menu)
4359 };
4360
4361 editor.update_in(cx, |editor, window, cx| {
4362 match editor.context_menu.borrow().as_ref() {
4363 None => {}
4364 Some(CodeContextMenu::Completions(prev_menu)) => {
4365 if prev_menu.id > id {
4366 return;
4367 }
4368 }
4369 _ => return,
4370 }
4371
4372 if editor.focus_handle.is_focused(window) && menu.is_some() {
4373 let mut menu = menu.unwrap();
4374 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4375
4376 *editor.context_menu.borrow_mut() =
4377 Some(CodeContextMenu::Completions(menu));
4378
4379 if editor.show_edit_predictions_in_menu() {
4380 editor.update_visible_inline_completion(window, cx);
4381 } else {
4382 editor.discard_inline_completion(false, cx);
4383 }
4384
4385 cx.notify();
4386 } else if editor.completion_tasks.len() <= 1 {
4387 // If there are no more completion tasks and the last menu was
4388 // empty, we should hide it.
4389 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4390 // If it was already hidden and we don't show inline
4391 // completions in the menu, we should also show the
4392 // inline-completion when available.
4393 if was_hidden && editor.show_edit_predictions_in_menu() {
4394 editor.update_visible_inline_completion(window, cx);
4395 }
4396 }
4397 })?;
4398
4399 anyhow::Ok(())
4400 }
4401 .log_err()
4402 .await
4403 });
4404
4405 self.completion_tasks.push((id, task));
4406 }
4407
4408 #[cfg(feature = "test-support")]
4409 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4410 let menu = self.context_menu.borrow();
4411 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4412 let completions = menu.completions.borrow();
4413 Some(completions.to_vec())
4414 } else {
4415 None
4416 }
4417 }
4418
4419 pub fn confirm_completion(
4420 &mut self,
4421 action: &ConfirmCompletion,
4422 window: &mut Window,
4423 cx: &mut Context<Self>,
4424 ) -> Option<Task<Result<()>>> {
4425 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4426 }
4427
4428 pub fn compose_completion(
4429 &mut self,
4430 action: &ComposeCompletion,
4431 window: &mut Window,
4432 cx: &mut Context<Self>,
4433 ) -> Option<Task<Result<()>>> {
4434 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4435 }
4436
4437 fn do_completion(
4438 &mut self,
4439 item_ix: Option<usize>,
4440 intent: CompletionIntent,
4441 window: &mut Window,
4442 cx: &mut Context<Editor>,
4443 ) -> Option<Task<Result<()>>> {
4444 use language::ToOffset as _;
4445
4446 let completions_menu =
4447 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4448 menu
4449 } else {
4450 return None;
4451 };
4452
4453 let candidate_id = {
4454 let entries = completions_menu.entries.borrow();
4455 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4456 if self.show_edit_predictions_in_menu() {
4457 self.discard_inline_completion(true, cx);
4458 }
4459 mat.candidate_id
4460 };
4461
4462 let buffer_handle = completions_menu.buffer;
4463 let completion = completions_menu
4464 .completions
4465 .borrow()
4466 .get(candidate_id)?
4467 .clone();
4468 cx.stop_propagation();
4469
4470 let snippet;
4471 let new_text;
4472 if completion.is_snippet() {
4473 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4474 new_text = snippet.as_ref().unwrap().text.clone();
4475 } else {
4476 snippet = None;
4477 new_text = completion.new_text.clone();
4478 };
4479 let selections = self.selections.all::<usize>(cx);
4480 let buffer = buffer_handle.read(cx);
4481 let old_range = completion.old_range.to_offset(buffer);
4482 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4483
4484 let newest_selection = self.selections.newest_anchor();
4485 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4486 return None;
4487 }
4488
4489 let lookbehind = newest_selection
4490 .start
4491 .text_anchor
4492 .to_offset(buffer)
4493 .saturating_sub(old_range.start);
4494 let lookahead = old_range
4495 .end
4496 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4497 let mut common_prefix_len = old_text
4498 .bytes()
4499 .zip(new_text.bytes())
4500 .take_while(|(a, b)| a == b)
4501 .count();
4502
4503 let snapshot = self.buffer.read(cx).snapshot(cx);
4504 let mut range_to_replace: Option<Range<isize>> = None;
4505 let mut ranges = Vec::new();
4506 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4507 for selection in &selections {
4508 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4509 let start = selection.start.saturating_sub(lookbehind);
4510 let end = selection.end + lookahead;
4511 if selection.id == newest_selection.id {
4512 range_to_replace = Some(
4513 ((start + common_prefix_len) as isize - selection.start as isize)
4514 ..(end as isize - selection.start as isize),
4515 );
4516 }
4517 ranges.push(start + common_prefix_len..end);
4518 } else {
4519 common_prefix_len = 0;
4520 ranges.clear();
4521 ranges.extend(selections.iter().map(|s| {
4522 if s.id == newest_selection.id {
4523 range_to_replace = Some(
4524 old_range.start.to_offset_utf16(&snapshot).0 as isize
4525 - selection.start as isize
4526 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4527 - selection.start as isize,
4528 );
4529 old_range.clone()
4530 } else {
4531 s.start..s.end
4532 }
4533 }));
4534 break;
4535 }
4536 if !self.linked_edit_ranges.is_empty() {
4537 let start_anchor = snapshot.anchor_before(selection.head());
4538 let end_anchor = snapshot.anchor_after(selection.tail());
4539 if let Some(ranges) = self
4540 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4541 {
4542 for (buffer, edits) in ranges {
4543 linked_edits.entry(buffer.clone()).or_default().extend(
4544 edits
4545 .into_iter()
4546 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4547 );
4548 }
4549 }
4550 }
4551 }
4552 let text = &new_text[common_prefix_len..];
4553
4554 cx.emit(EditorEvent::InputHandled {
4555 utf16_range_to_replace: range_to_replace,
4556 text: text.into(),
4557 });
4558
4559 self.transact(window, cx, |this, window, cx| {
4560 if let Some(mut snippet) = snippet {
4561 snippet.text = text.to_string();
4562 for tabstop in snippet
4563 .tabstops
4564 .iter_mut()
4565 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4566 {
4567 tabstop.start -= common_prefix_len as isize;
4568 tabstop.end -= common_prefix_len as isize;
4569 }
4570
4571 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4572 } else {
4573 this.buffer.update(cx, |buffer, cx| {
4574 let edits = ranges.iter().map(|range| (range.clone(), text));
4575 buffer.edit(edits, this.autoindent_mode.clone(), cx);
4576 });
4577 }
4578 for (buffer, edits) in linked_edits {
4579 buffer.update(cx, |buffer, cx| {
4580 let snapshot = buffer.snapshot();
4581 let edits = edits
4582 .into_iter()
4583 .map(|(range, text)| {
4584 use text::ToPoint as TP;
4585 let end_point = TP::to_point(&range.end, &snapshot);
4586 let start_point = TP::to_point(&range.start, &snapshot);
4587 (start_point..end_point, text)
4588 })
4589 .sorted_by_key(|(range, _)| range.start);
4590 buffer.edit(edits, None, cx);
4591 })
4592 }
4593
4594 this.refresh_inline_completion(true, false, window, cx);
4595 });
4596
4597 let show_new_completions_on_confirm = completion
4598 .confirm
4599 .as_ref()
4600 .map_or(false, |confirm| confirm(intent, window, cx));
4601 if show_new_completions_on_confirm {
4602 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4603 }
4604
4605 let provider = self.completion_provider.as_ref()?;
4606 drop(completion);
4607 let apply_edits = provider.apply_additional_edits_for_completion(
4608 buffer_handle,
4609 completions_menu.completions.clone(),
4610 candidate_id,
4611 true,
4612 cx,
4613 );
4614
4615 let editor_settings = EditorSettings::get_global(cx);
4616 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4617 // After the code completion is finished, users often want to know what signatures are needed.
4618 // so we should automatically call signature_help
4619 self.show_signature_help(&ShowSignatureHelp, window, cx);
4620 }
4621
4622 Some(cx.foreground_executor().spawn(async move {
4623 apply_edits.await?;
4624 Ok(())
4625 }))
4626 }
4627
4628 pub fn toggle_code_actions(
4629 &mut self,
4630 action: &ToggleCodeActions,
4631 window: &mut Window,
4632 cx: &mut Context<Self>,
4633 ) {
4634 let mut context_menu = self.context_menu.borrow_mut();
4635 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4636 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4637 // Toggle if we're selecting the same one
4638 *context_menu = None;
4639 cx.notify();
4640 return;
4641 } else {
4642 // Otherwise, clear it and start a new one
4643 *context_menu = None;
4644 cx.notify();
4645 }
4646 }
4647 drop(context_menu);
4648 let snapshot = self.snapshot(window, cx);
4649 let deployed_from_indicator = action.deployed_from_indicator;
4650 let mut task = self.code_actions_task.take();
4651 let action = action.clone();
4652 cx.spawn_in(window, async move |editor, cx| {
4653 while let Some(prev_task) = task {
4654 prev_task.await.log_err();
4655 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4656 }
4657
4658 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4659 if editor.focus_handle.is_focused(window) {
4660 let multibuffer_point = action
4661 .deployed_from_indicator
4662 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4663 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4664 let (buffer, buffer_row) = snapshot
4665 .buffer_snapshot
4666 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4667 .and_then(|(buffer_snapshot, range)| {
4668 editor
4669 .buffer
4670 .read(cx)
4671 .buffer(buffer_snapshot.remote_id())
4672 .map(|buffer| (buffer, range.start.row))
4673 })?;
4674 let (_, code_actions) = editor
4675 .available_code_actions
4676 .clone()
4677 .and_then(|(location, code_actions)| {
4678 let snapshot = location.buffer.read(cx).snapshot();
4679 let point_range = location.range.to_point(&snapshot);
4680 let point_range = point_range.start.row..=point_range.end.row;
4681 if point_range.contains(&buffer_row) {
4682 Some((location, code_actions))
4683 } else {
4684 None
4685 }
4686 })
4687 .unzip();
4688 let buffer_id = buffer.read(cx).remote_id();
4689 let tasks = editor
4690 .tasks
4691 .get(&(buffer_id, buffer_row))
4692 .map(|t| Arc::new(t.to_owned()));
4693 if tasks.is_none() && code_actions.is_none() {
4694 return None;
4695 }
4696
4697 editor.completion_tasks.clear();
4698 editor.discard_inline_completion(false, cx);
4699 let task_context =
4700 tasks
4701 .as_ref()
4702 .zip(editor.project.clone())
4703 .map(|(tasks, project)| {
4704 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4705 });
4706
4707 Some(cx.spawn_in(window, async move |editor, cx| {
4708 let task_context = match task_context {
4709 Some(task_context) => task_context.await,
4710 None => None,
4711 };
4712 let resolved_tasks =
4713 tasks.zip(task_context).map(|(tasks, task_context)| {
4714 Rc::new(ResolvedTasks {
4715 templates: tasks.resolve(&task_context).collect(),
4716 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4717 multibuffer_point.row,
4718 tasks.column,
4719 )),
4720 })
4721 });
4722 let spawn_straight_away = resolved_tasks
4723 .as_ref()
4724 .map_or(false, |tasks| tasks.templates.len() == 1)
4725 && code_actions
4726 .as_ref()
4727 .map_or(true, |actions| actions.is_empty());
4728 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4729 *editor.context_menu.borrow_mut() =
4730 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4731 buffer,
4732 actions: CodeActionContents {
4733 tasks: resolved_tasks,
4734 actions: code_actions,
4735 },
4736 selected_item: Default::default(),
4737 scroll_handle: UniformListScrollHandle::default(),
4738 deployed_from_indicator,
4739 }));
4740 if spawn_straight_away {
4741 if let Some(task) = editor.confirm_code_action(
4742 &ConfirmCodeAction { item_ix: Some(0) },
4743 window,
4744 cx,
4745 ) {
4746 cx.notify();
4747 return task;
4748 }
4749 }
4750 cx.notify();
4751 Task::ready(Ok(()))
4752 }) {
4753 task.await
4754 } else {
4755 Ok(())
4756 }
4757 }))
4758 } else {
4759 Some(Task::ready(Ok(())))
4760 }
4761 })?;
4762 if let Some(task) = spawned_test_task {
4763 task.await?;
4764 }
4765
4766 Ok::<_, anyhow::Error>(())
4767 })
4768 .detach_and_log_err(cx);
4769 }
4770
4771 pub fn confirm_code_action(
4772 &mut self,
4773 action: &ConfirmCodeAction,
4774 window: &mut Window,
4775 cx: &mut Context<Self>,
4776 ) -> Option<Task<Result<()>>> {
4777 let actions_menu =
4778 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4779 menu
4780 } else {
4781 return None;
4782 };
4783 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4784 let action = actions_menu.actions.get(action_ix)?;
4785 let title = action.label();
4786 let buffer = actions_menu.buffer;
4787 let workspace = self.workspace()?;
4788
4789 match action {
4790 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4791 workspace.update(cx, |workspace, cx| {
4792 workspace::tasks::schedule_resolved_task(
4793 workspace,
4794 task_source_kind,
4795 resolved_task,
4796 false,
4797 cx,
4798 );
4799
4800 Some(Task::ready(Ok(())))
4801 })
4802 }
4803 CodeActionsItem::CodeAction {
4804 excerpt_id,
4805 action,
4806 provider,
4807 } => {
4808 let apply_code_action =
4809 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4810 let workspace = workspace.downgrade();
4811 Some(cx.spawn_in(window, async move |editor, cx| {
4812 let project_transaction = apply_code_action.await?;
4813 Self::open_project_transaction(
4814 &editor,
4815 workspace,
4816 project_transaction,
4817 title,
4818 cx,
4819 )
4820 .await
4821 }))
4822 }
4823 }
4824 }
4825
4826 pub async fn open_project_transaction(
4827 this: &WeakEntity<Editor>,
4828 workspace: WeakEntity<Workspace>,
4829 transaction: ProjectTransaction,
4830 title: String,
4831 cx: &mut AsyncWindowContext,
4832 ) -> Result<()> {
4833 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4834 cx.update(|_, cx| {
4835 entries.sort_unstable_by_key(|(buffer, _)| {
4836 buffer.read(cx).file().map(|f| f.path().clone())
4837 });
4838 })?;
4839
4840 // If the project transaction's edits are all contained within this editor, then
4841 // avoid opening a new editor to display them.
4842
4843 if let Some((buffer, transaction)) = entries.first() {
4844 if entries.len() == 1 {
4845 let excerpt = this.update(cx, |editor, cx| {
4846 editor
4847 .buffer()
4848 .read(cx)
4849 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4850 })?;
4851 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4852 if excerpted_buffer == *buffer {
4853 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
4854 let excerpt_range = excerpt_range.to_offset(buffer);
4855 buffer
4856 .edited_ranges_for_transaction::<usize>(transaction)
4857 .all(|range| {
4858 excerpt_range.start <= range.start
4859 && excerpt_range.end >= range.end
4860 })
4861 })?;
4862
4863 if all_edits_within_excerpt {
4864 return Ok(());
4865 }
4866 }
4867 }
4868 }
4869 } else {
4870 return Ok(());
4871 }
4872
4873 let mut ranges_to_highlight = Vec::new();
4874 let excerpt_buffer = cx.new(|cx| {
4875 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4876 for (buffer_handle, transaction) in &entries {
4877 let buffer = buffer_handle.read(cx);
4878 ranges_to_highlight.extend(
4879 multibuffer.push_excerpts_with_context_lines(
4880 buffer_handle.clone(),
4881 buffer
4882 .edited_ranges_for_transaction::<usize>(transaction)
4883 .collect(),
4884 DEFAULT_MULTIBUFFER_CONTEXT,
4885 cx,
4886 ),
4887 );
4888 }
4889 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4890 multibuffer
4891 })?;
4892
4893 workspace.update_in(cx, |workspace, window, cx| {
4894 let project = workspace.project().clone();
4895 let editor =
4896 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
4897 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4898 editor.update(cx, |editor, cx| {
4899 editor.highlight_background::<Self>(
4900 &ranges_to_highlight,
4901 |theme| theme.editor_highlighted_line_background,
4902 cx,
4903 );
4904 });
4905 })?;
4906
4907 Ok(())
4908 }
4909
4910 pub fn clear_code_action_providers(&mut self) {
4911 self.code_action_providers.clear();
4912 self.available_code_actions.take();
4913 }
4914
4915 pub fn add_code_action_provider(
4916 &mut self,
4917 provider: Rc<dyn CodeActionProvider>,
4918 window: &mut Window,
4919 cx: &mut Context<Self>,
4920 ) {
4921 if self
4922 .code_action_providers
4923 .iter()
4924 .any(|existing_provider| existing_provider.id() == provider.id())
4925 {
4926 return;
4927 }
4928
4929 self.code_action_providers.push(provider);
4930 self.refresh_code_actions(window, cx);
4931 }
4932
4933 pub fn remove_code_action_provider(
4934 &mut self,
4935 id: Arc<str>,
4936 window: &mut Window,
4937 cx: &mut Context<Self>,
4938 ) {
4939 self.code_action_providers
4940 .retain(|provider| provider.id() != id);
4941 self.refresh_code_actions(window, cx);
4942 }
4943
4944 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4945 let buffer = self.buffer.read(cx);
4946 let newest_selection = self.selections.newest_anchor().clone();
4947 if newest_selection.head().diff_base_anchor.is_some() {
4948 return None;
4949 }
4950 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4951 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4952 if start_buffer != end_buffer {
4953 return None;
4954 }
4955
4956 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
4957 cx.background_executor()
4958 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4959 .await;
4960
4961 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
4962 let providers = this.code_action_providers.clone();
4963 let tasks = this
4964 .code_action_providers
4965 .iter()
4966 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4967 .collect::<Vec<_>>();
4968 (providers, tasks)
4969 })?;
4970
4971 let mut actions = Vec::new();
4972 for (provider, provider_actions) in
4973 providers.into_iter().zip(future::join_all(tasks).await)
4974 {
4975 if let Some(provider_actions) = provider_actions.log_err() {
4976 actions.extend(provider_actions.into_iter().map(|action| {
4977 AvailableCodeAction {
4978 excerpt_id: newest_selection.start.excerpt_id,
4979 action,
4980 provider: provider.clone(),
4981 }
4982 }));
4983 }
4984 }
4985
4986 this.update(cx, |this, cx| {
4987 this.available_code_actions = if actions.is_empty() {
4988 None
4989 } else {
4990 Some((
4991 Location {
4992 buffer: start_buffer,
4993 range: start..end,
4994 },
4995 actions.into(),
4996 ))
4997 };
4998 cx.notify();
4999 })
5000 }));
5001 None
5002 }
5003
5004 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5005 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5006 self.show_git_blame_inline = false;
5007
5008 self.show_git_blame_inline_delay_task =
5009 Some(cx.spawn_in(window, async move |this, cx| {
5010 cx.background_executor().timer(delay).await;
5011
5012 this.update(cx, |this, cx| {
5013 this.show_git_blame_inline = true;
5014 cx.notify();
5015 })
5016 .log_err();
5017 }));
5018 }
5019 }
5020
5021 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5022 if self.pending_rename.is_some() {
5023 return None;
5024 }
5025
5026 let provider = self.semantics_provider.clone()?;
5027 let buffer = self.buffer.read(cx);
5028 let newest_selection = self.selections.newest_anchor().clone();
5029 let cursor_position = newest_selection.head();
5030 let (cursor_buffer, cursor_buffer_position) =
5031 buffer.text_anchor_for_position(cursor_position, cx)?;
5032 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5033 if cursor_buffer != tail_buffer {
5034 return None;
5035 }
5036 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5037 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5038 cx.background_executor()
5039 .timer(Duration::from_millis(debounce))
5040 .await;
5041
5042 let highlights = if let Some(highlights) = cx
5043 .update(|cx| {
5044 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5045 })
5046 .ok()
5047 .flatten()
5048 {
5049 highlights.await.log_err()
5050 } else {
5051 None
5052 };
5053
5054 if let Some(highlights) = highlights {
5055 this.update(cx, |this, cx| {
5056 if this.pending_rename.is_some() {
5057 return;
5058 }
5059
5060 let buffer_id = cursor_position.buffer_id;
5061 let buffer = this.buffer.read(cx);
5062 if !buffer
5063 .text_anchor_for_position(cursor_position, cx)
5064 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5065 {
5066 return;
5067 }
5068
5069 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5070 let mut write_ranges = Vec::new();
5071 let mut read_ranges = Vec::new();
5072 for highlight in highlights {
5073 for (excerpt_id, excerpt_range) in
5074 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5075 {
5076 let start = highlight
5077 .range
5078 .start
5079 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5080 let end = highlight
5081 .range
5082 .end
5083 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5084 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5085 continue;
5086 }
5087
5088 let range = Anchor {
5089 buffer_id,
5090 excerpt_id,
5091 text_anchor: start,
5092 diff_base_anchor: None,
5093 }..Anchor {
5094 buffer_id,
5095 excerpt_id,
5096 text_anchor: end,
5097 diff_base_anchor: None,
5098 };
5099 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5100 write_ranges.push(range);
5101 } else {
5102 read_ranges.push(range);
5103 }
5104 }
5105 }
5106
5107 this.highlight_background::<DocumentHighlightRead>(
5108 &read_ranges,
5109 |theme| theme.editor_document_highlight_read_background,
5110 cx,
5111 );
5112 this.highlight_background::<DocumentHighlightWrite>(
5113 &write_ranges,
5114 |theme| theme.editor_document_highlight_write_background,
5115 cx,
5116 );
5117 cx.notify();
5118 })
5119 .log_err();
5120 }
5121 }));
5122 None
5123 }
5124
5125 pub fn refresh_selected_text_highlights(
5126 &mut self,
5127 window: &mut Window,
5128 cx: &mut Context<Editor>,
5129 ) {
5130 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5131 return;
5132 }
5133 self.selection_highlight_task.take();
5134 if !EditorSettings::get_global(cx).selection_highlight {
5135 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5136 return;
5137 }
5138 if self.selections.count() != 1 || self.selections.line_mode {
5139 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5140 return;
5141 }
5142 let selection = self.selections.newest::<Point>(cx);
5143 if selection.is_empty() || selection.start.row != selection.end.row {
5144 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5145 return;
5146 }
5147 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5148 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5149 cx.background_executor()
5150 .timer(Duration::from_millis(debounce))
5151 .await;
5152 let Some(Some(matches_task)) = editor
5153 .update_in(cx, |editor, _, cx| {
5154 if editor.selections.count() != 1 || editor.selections.line_mode {
5155 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5156 return None;
5157 }
5158 let selection = editor.selections.newest::<Point>(cx);
5159 if selection.is_empty() || selection.start.row != selection.end.row {
5160 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5161 return None;
5162 }
5163 let buffer = editor.buffer().read(cx).snapshot(cx);
5164 let query = buffer.text_for_range(selection.range()).collect::<String>();
5165 if query.trim().is_empty() {
5166 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5167 return None;
5168 }
5169 Some(cx.background_spawn(async move {
5170 let mut ranges = Vec::new();
5171 let selection_anchors = selection.range().to_anchors(&buffer);
5172 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5173 for (search_buffer, search_range, excerpt_id) in
5174 buffer.range_to_buffer_ranges(range)
5175 {
5176 ranges.extend(
5177 project::search::SearchQuery::text(
5178 query.clone(),
5179 false,
5180 false,
5181 false,
5182 Default::default(),
5183 Default::default(),
5184 None,
5185 )
5186 .unwrap()
5187 .search(search_buffer, Some(search_range.clone()))
5188 .await
5189 .into_iter()
5190 .filter_map(
5191 |match_range| {
5192 let start = search_buffer.anchor_after(
5193 search_range.start + match_range.start,
5194 );
5195 let end = search_buffer.anchor_before(
5196 search_range.start + match_range.end,
5197 );
5198 let range = Anchor::range_in_buffer(
5199 excerpt_id,
5200 search_buffer.remote_id(),
5201 start..end,
5202 );
5203 (range != selection_anchors).then_some(range)
5204 },
5205 ),
5206 );
5207 }
5208 }
5209 ranges
5210 }))
5211 })
5212 .log_err()
5213 else {
5214 return;
5215 };
5216 let matches = matches_task.await;
5217 editor
5218 .update_in(cx, |editor, _, cx| {
5219 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5220 if !matches.is_empty() {
5221 editor.highlight_background::<SelectedTextHighlight>(
5222 &matches,
5223 |theme| theme.editor_document_highlight_bracket_background,
5224 cx,
5225 )
5226 }
5227 })
5228 .log_err();
5229 }));
5230 }
5231
5232 pub fn refresh_inline_completion(
5233 &mut self,
5234 debounce: bool,
5235 user_requested: bool,
5236 window: &mut Window,
5237 cx: &mut Context<Self>,
5238 ) -> Option<()> {
5239 let provider = self.edit_prediction_provider()?;
5240 let cursor = self.selections.newest_anchor().head();
5241 let (buffer, cursor_buffer_position) =
5242 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5243
5244 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5245 self.discard_inline_completion(false, cx);
5246 return None;
5247 }
5248
5249 if !user_requested
5250 && (!self.should_show_edit_predictions()
5251 || !self.is_focused(window)
5252 || buffer.read(cx).is_empty())
5253 {
5254 self.discard_inline_completion(false, cx);
5255 return None;
5256 }
5257
5258 self.update_visible_inline_completion(window, cx);
5259 provider.refresh(
5260 self.project.clone(),
5261 buffer,
5262 cursor_buffer_position,
5263 debounce,
5264 cx,
5265 );
5266 Some(())
5267 }
5268
5269 fn show_edit_predictions_in_menu(&self) -> bool {
5270 match self.edit_prediction_settings {
5271 EditPredictionSettings::Disabled => false,
5272 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5273 }
5274 }
5275
5276 pub fn edit_predictions_enabled(&self) -> bool {
5277 match self.edit_prediction_settings {
5278 EditPredictionSettings::Disabled => false,
5279 EditPredictionSettings::Enabled { .. } => true,
5280 }
5281 }
5282
5283 fn edit_prediction_requires_modifier(&self) -> bool {
5284 match self.edit_prediction_settings {
5285 EditPredictionSettings::Disabled => false,
5286 EditPredictionSettings::Enabled {
5287 preview_requires_modifier,
5288 ..
5289 } => preview_requires_modifier,
5290 }
5291 }
5292
5293 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5294 if self.edit_prediction_provider.is_none() {
5295 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5296 } else {
5297 let selection = self.selections.newest_anchor();
5298 let cursor = selection.head();
5299
5300 if let Some((buffer, cursor_buffer_position)) =
5301 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5302 {
5303 self.edit_prediction_settings =
5304 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5305 }
5306 }
5307 }
5308
5309 fn edit_prediction_settings_at_position(
5310 &self,
5311 buffer: &Entity<Buffer>,
5312 buffer_position: language::Anchor,
5313 cx: &App,
5314 ) -> EditPredictionSettings {
5315 if self.mode != EditorMode::Full
5316 || !self.show_inline_completions_override.unwrap_or(true)
5317 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5318 {
5319 return EditPredictionSettings::Disabled;
5320 }
5321
5322 let buffer = buffer.read(cx);
5323
5324 let file = buffer.file();
5325
5326 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5327 return EditPredictionSettings::Disabled;
5328 };
5329
5330 let by_provider = matches!(
5331 self.menu_inline_completions_policy,
5332 MenuInlineCompletionsPolicy::ByProvider
5333 );
5334
5335 let show_in_menu = by_provider
5336 && self
5337 .edit_prediction_provider
5338 .as_ref()
5339 .map_or(false, |provider| {
5340 provider.provider.show_completions_in_menu()
5341 });
5342
5343 let preview_requires_modifier =
5344 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5345
5346 EditPredictionSettings::Enabled {
5347 show_in_menu,
5348 preview_requires_modifier,
5349 }
5350 }
5351
5352 fn should_show_edit_predictions(&self) -> bool {
5353 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5354 }
5355
5356 pub fn edit_prediction_preview_is_active(&self) -> bool {
5357 matches!(
5358 self.edit_prediction_preview,
5359 EditPredictionPreview::Active { .. }
5360 )
5361 }
5362
5363 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5364 let cursor = self.selections.newest_anchor().head();
5365 if let Some((buffer, cursor_position)) =
5366 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5367 {
5368 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5369 } else {
5370 false
5371 }
5372 }
5373
5374 fn edit_predictions_enabled_in_buffer(
5375 &self,
5376 buffer: &Entity<Buffer>,
5377 buffer_position: language::Anchor,
5378 cx: &App,
5379 ) -> bool {
5380 maybe!({
5381 if self.read_only(cx) {
5382 return Some(false);
5383 }
5384 let provider = self.edit_prediction_provider()?;
5385 if !provider.is_enabled(&buffer, buffer_position, cx) {
5386 return Some(false);
5387 }
5388 let buffer = buffer.read(cx);
5389 let Some(file) = buffer.file() else {
5390 return Some(true);
5391 };
5392 let settings = all_language_settings(Some(file), cx);
5393 Some(settings.edit_predictions_enabled_for_file(file, cx))
5394 })
5395 .unwrap_or(false)
5396 }
5397
5398 fn cycle_inline_completion(
5399 &mut self,
5400 direction: Direction,
5401 window: &mut Window,
5402 cx: &mut Context<Self>,
5403 ) -> Option<()> {
5404 let provider = self.edit_prediction_provider()?;
5405 let cursor = self.selections.newest_anchor().head();
5406 let (buffer, cursor_buffer_position) =
5407 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5408 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5409 return None;
5410 }
5411
5412 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5413 self.update_visible_inline_completion(window, cx);
5414
5415 Some(())
5416 }
5417
5418 pub fn show_inline_completion(
5419 &mut self,
5420 _: &ShowEditPrediction,
5421 window: &mut Window,
5422 cx: &mut Context<Self>,
5423 ) {
5424 if !self.has_active_inline_completion() {
5425 self.refresh_inline_completion(false, true, window, cx);
5426 return;
5427 }
5428
5429 self.update_visible_inline_completion(window, cx);
5430 }
5431
5432 pub fn display_cursor_names(
5433 &mut self,
5434 _: &DisplayCursorNames,
5435 window: &mut Window,
5436 cx: &mut Context<Self>,
5437 ) {
5438 self.show_cursor_names(window, cx);
5439 }
5440
5441 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5442 self.show_cursor_names = true;
5443 cx.notify();
5444 cx.spawn_in(window, async move |this, cx| {
5445 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5446 this.update(cx, |this, cx| {
5447 this.show_cursor_names = false;
5448 cx.notify()
5449 })
5450 .ok()
5451 })
5452 .detach();
5453 }
5454
5455 pub fn next_edit_prediction(
5456 &mut self,
5457 _: &NextEditPrediction,
5458 window: &mut Window,
5459 cx: &mut Context<Self>,
5460 ) {
5461 if self.has_active_inline_completion() {
5462 self.cycle_inline_completion(Direction::Next, window, cx);
5463 } else {
5464 let is_copilot_disabled = self
5465 .refresh_inline_completion(false, true, window, cx)
5466 .is_none();
5467 if is_copilot_disabled {
5468 cx.propagate();
5469 }
5470 }
5471 }
5472
5473 pub fn previous_edit_prediction(
5474 &mut self,
5475 _: &PreviousEditPrediction,
5476 window: &mut Window,
5477 cx: &mut Context<Self>,
5478 ) {
5479 if self.has_active_inline_completion() {
5480 self.cycle_inline_completion(Direction::Prev, window, cx);
5481 } else {
5482 let is_copilot_disabled = self
5483 .refresh_inline_completion(false, true, window, cx)
5484 .is_none();
5485 if is_copilot_disabled {
5486 cx.propagate();
5487 }
5488 }
5489 }
5490
5491 pub fn accept_edit_prediction(
5492 &mut self,
5493 _: &AcceptEditPrediction,
5494 window: &mut Window,
5495 cx: &mut Context<Self>,
5496 ) {
5497 if self.show_edit_predictions_in_menu() {
5498 self.hide_context_menu(window, cx);
5499 }
5500
5501 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5502 return;
5503 };
5504
5505 self.report_inline_completion_event(
5506 active_inline_completion.completion_id.clone(),
5507 true,
5508 cx,
5509 );
5510
5511 match &active_inline_completion.completion {
5512 InlineCompletion::Move { target, .. } => {
5513 let target = *target;
5514
5515 if let Some(position_map) = &self.last_position_map {
5516 if position_map
5517 .visible_row_range
5518 .contains(&target.to_display_point(&position_map.snapshot).row())
5519 || !self.edit_prediction_requires_modifier()
5520 {
5521 self.unfold_ranges(&[target..target], true, false, cx);
5522 // Note that this is also done in vim's handler of the Tab action.
5523 self.change_selections(
5524 Some(Autoscroll::newest()),
5525 window,
5526 cx,
5527 |selections| {
5528 selections.select_anchor_ranges([target..target]);
5529 },
5530 );
5531 self.clear_row_highlights::<EditPredictionPreview>();
5532
5533 self.edit_prediction_preview
5534 .set_previous_scroll_position(None);
5535 } else {
5536 self.edit_prediction_preview
5537 .set_previous_scroll_position(Some(
5538 position_map.snapshot.scroll_anchor,
5539 ));
5540
5541 self.highlight_rows::<EditPredictionPreview>(
5542 target..target,
5543 cx.theme().colors().editor_highlighted_line_background,
5544 true,
5545 cx,
5546 );
5547 self.request_autoscroll(Autoscroll::fit(), cx);
5548 }
5549 }
5550 }
5551 InlineCompletion::Edit { edits, .. } => {
5552 if let Some(provider) = self.edit_prediction_provider() {
5553 provider.accept(cx);
5554 }
5555
5556 let snapshot = self.buffer.read(cx).snapshot(cx);
5557 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5558
5559 self.buffer.update(cx, |buffer, cx| {
5560 buffer.edit(edits.iter().cloned(), None, cx)
5561 });
5562
5563 self.change_selections(None, window, cx, |s| {
5564 s.select_anchor_ranges([last_edit_end..last_edit_end])
5565 });
5566
5567 self.update_visible_inline_completion(window, cx);
5568 if self.active_inline_completion.is_none() {
5569 self.refresh_inline_completion(true, true, window, cx);
5570 }
5571
5572 cx.notify();
5573 }
5574 }
5575
5576 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5577 }
5578
5579 pub fn accept_partial_inline_completion(
5580 &mut self,
5581 _: &AcceptPartialEditPrediction,
5582 window: &mut Window,
5583 cx: &mut Context<Self>,
5584 ) {
5585 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5586 return;
5587 };
5588 if self.selections.count() != 1 {
5589 return;
5590 }
5591
5592 self.report_inline_completion_event(
5593 active_inline_completion.completion_id.clone(),
5594 true,
5595 cx,
5596 );
5597
5598 match &active_inline_completion.completion {
5599 InlineCompletion::Move { target, .. } => {
5600 let target = *target;
5601 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5602 selections.select_anchor_ranges([target..target]);
5603 });
5604 }
5605 InlineCompletion::Edit { edits, .. } => {
5606 // Find an insertion that starts at the cursor position.
5607 let snapshot = self.buffer.read(cx).snapshot(cx);
5608 let cursor_offset = self.selections.newest::<usize>(cx).head();
5609 let insertion = edits.iter().find_map(|(range, text)| {
5610 let range = range.to_offset(&snapshot);
5611 if range.is_empty() && range.start == cursor_offset {
5612 Some(text)
5613 } else {
5614 None
5615 }
5616 });
5617
5618 if let Some(text) = insertion {
5619 let mut partial_completion = text
5620 .chars()
5621 .by_ref()
5622 .take_while(|c| c.is_alphabetic())
5623 .collect::<String>();
5624 if partial_completion.is_empty() {
5625 partial_completion = text
5626 .chars()
5627 .by_ref()
5628 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5629 .collect::<String>();
5630 }
5631
5632 cx.emit(EditorEvent::InputHandled {
5633 utf16_range_to_replace: None,
5634 text: partial_completion.clone().into(),
5635 });
5636
5637 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5638
5639 self.refresh_inline_completion(true, true, window, cx);
5640 cx.notify();
5641 } else {
5642 self.accept_edit_prediction(&Default::default(), window, cx);
5643 }
5644 }
5645 }
5646 }
5647
5648 fn discard_inline_completion(
5649 &mut self,
5650 should_report_inline_completion_event: bool,
5651 cx: &mut Context<Self>,
5652 ) -> bool {
5653 if should_report_inline_completion_event {
5654 let completion_id = self
5655 .active_inline_completion
5656 .as_ref()
5657 .and_then(|active_completion| active_completion.completion_id.clone());
5658
5659 self.report_inline_completion_event(completion_id, false, cx);
5660 }
5661
5662 if let Some(provider) = self.edit_prediction_provider() {
5663 provider.discard(cx);
5664 }
5665
5666 self.take_active_inline_completion(cx)
5667 }
5668
5669 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5670 let Some(provider) = self.edit_prediction_provider() else {
5671 return;
5672 };
5673
5674 let Some((_, buffer, _)) = self
5675 .buffer
5676 .read(cx)
5677 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5678 else {
5679 return;
5680 };
5681
5682 let extension = buffer
5683 .read(cx)
5684 .file()
5685 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5686
5687 let event_type = match accepted {
5688 true => "Edit Prediction Accepted",
5689 false => "Edit Prediction Discarded",
5690 };
5691 telemetry::event!(
5692 event_type,
5693 provider = provider.name(),
5694 prediction_id = id,
5695 suggestion_accepted = accepted,
5696 file_extension = extension,
5697 );
5698 }
5699
5700 pub fn has_active_inline_completion(&self) -> bool {
5701 self.active_inline_completion.is_some()
5702 }
5703
5704 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5705 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5706 return false;
5707 };
5708
5709 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5710 self.clear_highlights::<InlineCompletionHighlight>(cx);
5711 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5712 true
5713 }
5714
5715 /// Returns true when we're displaying the edit prediction popover below the cursor
5716 /// like we are not previewing and the LSP autocomplete menu is visible
5717 /// or we are in `when_holding_modifier` mode.
5718 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5719 if self.edit_prediction_preview_is_active()
5720 || !self.show_edit_predictions_in_menu()
5721 || !self.edit_predictions_enabled()
5722 {
5723 return false;
5724 }
5725
5726 if self.has_visible_completions_menu() {
5727 return true;
5728 }
5729
5730 has_completion && self.edit_prediction_requires_modifier()
5731 }
5732
5733 fn handle_modifiers_changed(
5734 &mut self,
5735 modifiers: Modifiers,
5736 position_map: &PositionMap,
5737 window: &mut Window,
5738 cx: &mut Context<Self>,
5739 ) {
5740 if self.show_edit_predictions_in_menu() {
5741 self.update_edit_prediction_preview(&modifiers, window, cx);
5742 }
5743
5744 self.update_selection_mode(&modifiers, position_map, window, cx);
5745
5746 let mouse_position = window.mouse_position();
5747 if !position_map.text_hitbox.is_hovered(window) {
5748 return;
5749 }
5750
5751 self.update_hovered_link(
5752 position_map.point_for_position(mouse_position),
5753 &position_map.snapshot,
5754 modifiers,
5755 window,
5756 cx,
5757 )
5758 }
5759
5760 fn update_selection_mode(
5761 &mut self,
5762 modifiers: &Modifiers,
5763 position_map: &PositionMap,
5764 window: &mut Window,
5765 cx: &mut Context<Self>,
5766 ) {
5767 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5768 return;
5769 }
5770
5771 let mouse_position = window.mouse_position();
5772 let point_for_position = position_map.point_for_position(mouse_position);
5773 let position = point_for_position.previous_valid;
5774
5775 self.select(
5776 SelectPhase::BeginColumnar {
5777 position,
5778 reset: false,
5779 goal_column: point_for_position.exact_unclipped.column(),
5780 },
5781 window,
5782 cx,
5783 );
5784 }
5785
5786 fn update_edit_prediction_preview(
5787 &mut self,
5788 modifiers: &Modifiers,
5789 window: &mut Window,
5790 cx: &mut Context<Self>,
5791 ) {
5792 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5793 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5794 return;
5795 };
5796
5797 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5798 if matches!(
5799 self.edit_prediction_preview,
5800 EditPredictionPreview::Inactive { .. }
5801 ) {
5802 self.edit_prediction_preview = EditPredictionPreview::Active {
5803 previous_scroll_position: None,
5804 since: Instant::now(),
5805 };
5806
5807 self.update_visible_inline_completion(window, cx);
5808 cx.notify();
5809 }
5810 } else if let EditPredictionPreview::Active {
5811 previous_scroll_position,
5812 since,
5813 } = self.edit_prediction_preview
5814 {
5815 if let (Some(previous_scroll_position), Some(position_map)) =
5816 (previous_scroll_position, self.last_position_map.as_ref())
5817 {
5818 self.set_scroll_position(
5819 previous_scroll_position
5820 .scroll_position(&position_map.snapshot.display_snapshot),
5821 window,
5822 cx,
5823 );
5824 }
5825
5826 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5827 released_too_fast: since.elapsed() < Duration::from_millis(200),
5828 };
5829 self.clear_row_highlights::<EditPredictionPreview>();
5830 self.update_visible_inline_completion(window, cx);
5831 cx.notify();
5832 }
5833 }
5834
5835 fn update_visible_inline_completion(
5836 &mut self,
5837 _window: &mut Window,
5838 cx: &mut Context<Self>,
5839 ) -> Option<()> {
5840 let selection = self.selections.newest_anchor();
5841 let cursor = selection.head();
5842 let multibuffer = self.buffer.read(cx).snapshot(cx);
5843 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5844 let excerpt_id = cursor.excerpt_id;
5845
5846 let show_in_menu = self.show_edit_predictions_in_menu();
5847 let completions_menu_has_precedence = !show_in_menu
5848 && (self.context_menu.borrow().is_some()
5849 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5850
5851 if completions_menu_has_precedence
5852 || !offset_selection.is_empty()
5853 || self
5854 .active_inline_completion
5855 .as_ref()
5856 .map_or(false, |completion| {
5857 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5858 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5859 !invalidation_range.contains(&offset_selection.head())
5860 })
5861 {
5862 self.discard_inline_completion(false, cx);
5863 return None;
5864 }
5865
5866 self.take_active_inline_completion(cx);
5867 let Some(provider) = self.edit_prediction_provider() else {
5868 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5869 return None;
5870 };
5871
5872 let (buffer, cursor_buffer_position) =
5873 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5874
5875 self.edit_prediction_settings =
5876 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5877
5878 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5879
5880 if self.edit_prediction_indent_conflict {
5881 let cursor_point = cursor.to_point(&multibuffer);
5882
5883 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5884
5885 if let Some((_, indent)) = indents.iter().next() {
5886 if indent.len == cursor_point.column {
5887 self.edit_prediction_indent_conflict = false;
5888 }
5889 }
5890 }
5891
5892 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5893 let edits = inline_completion
5894 .edits
5895 .into_iter()
5896 .flat_map(|(range, new_text)| {
5897 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5898 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5899 Some((start..end, new_text))
5900 })
5901 .collect::<Vec<_>>();
5902 if edits.is_empty() {
5903 return None;
5904 }
5905
5906 let first_edit_start = edits.first().unwrap().0.start;
5907 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5908 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5909
5910 let last_edit_end = edits.last().unwrap().0.end;
5911 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5912 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5913
5914 let cursor_row = cursor.to_point(&multibuffer).row;
5915
5916 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5917
5918 let mut inlay_ids = Vec::new();
5919 let invalidation_row_range;
5920 let move_invalidation_row_range = if cursor_row < edit_start_row {
5921 Some(cursor_row..edit_end_row)
5922 } else if cursor_row > edit_end_row {
5923 Some(edit_start_row..cursor_row)
5924 } else {
5925 None
5926 };
5927 let is_move =
5928 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5929 let completion = if is_move {
5930 invalidation_row_range =
5931 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5932 let target = first_edit_start;
5933 InlineCompletion::Move { target, snapshot }
5934 } else {
5935 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5936 && !self.inline_completions_hidden_for_vim_mode;
5937
5938 if show_completions_in_buffer {
5939 if edits
5940 .iter()
5941 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5942 {
5943 let mut inlays = Vec::new();
5944 for (range, new_text) in &edits {
5945 let inlay = Inlay::inline_completion(
5946 post_inc(&mut self.next_inlay_id),
5947 range.start,
5948 new_text.as_str(),
5949 );
5950 inlay_ids.push(inlay.id);
5951 inlays.push(inlay);
5952 }
5953
5954 self.splice_inlays(&[], inlays, cx);
5955 } else {
5956 let background_color = cx.theme().status().deleted_background;
5957 self.highlight_text::<InlineCompletionHighlight>(
5958 edits.iter().map(|(range, _)| range.clone()).collect(),
5959 HighlightStyle {
5960 background_color: Some(background_color),
5961 ..Default::default()
5962 },
5963 cx,
5964 );
5965 }
5966 }
5967
5968 invalidation_row_range = edit_start_row..edit_end_row;
5969
5970 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5971 if provider.show_tab_accept_marker() {
5972 EditDisplayMode::TabAccept
5973 } else {
5974 EditDisplayMode::Inline
5975 }
5976 } else {
5977 EditDisplayMode::DiffPopover
5978 };
5979
5980 InlineCompletion::Edit {
5981 edits,
5982 edit_preview: inline_completion.edit_preview,
5983 display_mode,
5984 snapshot,
5985 }
5986 };
5987
5988 let invalidation_range = multibuffer
5989 .anchor_before(Point::new(invalidation_row_range.start, 0))
5990 ..multibuffer.anchor_after(Point::new(
5991 invalidation_row_range.end,
5992 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5993 ));
5994
5995 self.stale_inline_completion_in_menu = None;
5996 self.active_inline_completion = Some(InlineCompletionState {
5997 inlay_ids,
5998 completion,
5999 completion_id: inline_completion.id,
6000 invalidation_range,
6001 });
6002
6003 cx.notify();
6004
6005 Some(())
6006 }
6007
6008 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6009 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6010 }
6011
6012 fn render_code_actions_indicator(
6013 &self,
6014 _style: &EditorStyle,
6015 row: DisplayRow,
6016 is_active: bool,
6017 breakpoint: Option<&(Anchor, Breakpoint)>,
6018 cx: &mut Context<Self>,
6019 ) -> Option<IconButton> {
6020 let color = Color::Muted;
6021
6022 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6023 let bp_kind = Arc::new(
6024 breakpoint
6025 .map(|(_, bp)| bp.kind.clone())
6026 .unwrap_or(BreakpointKind::Standard),
6027 );
6028
6029 if self.available_code_actions.is_some() {
6030 Some(
6031 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6032 .shape(ui::IconButtonShape::Square)
6033 .icon_size(IconSize::XSmall)
6034 .icon_color(color)
6035 .toggle_state(is_active)
6036 .tooltip({
6037 let focus_handle = self.focus_handle.clone();
6038 move |window, cx| {
6039 Tooltip::for_action_in(
6040 "Toggle Code Actions",
6041 &ToggleCodeActions {
6042 deployed_from_indicator: None,
6043 },
6044 &focus_handle,
6045 window,
6046 cx,
6047 )
6048 }
6049 })
6050 .on_click(cx.listener(move |editor, _e, window, cx| {
6051 window.focus(&editor.focus_handle(cx));
6052 editor.toggle_code_actions(
6053 &ToggleCodeActions {
6054 deployed_from_indicator: Some(row),
6055 },
6056 window,
6057 cx,
6058 );
6059 }))
6060 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6061 editor.set_breakpoint_context_menu(
6062 row,
6063 position,
6064 bp_kind.clone(),
6065 event.down.position,
6066 window,
6067 cx,
6068 );
6069 })),
6070 )
6071 } else {
6072 None
6073 }
6074 }
6075
6076 fn clear_tasks(&mut self) {
6077 self.tasks.clear()
6078 }
6079
6080 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6081 if self.tasks.insert(key, value).is_some() {
6082 // This case should hopefully be rare, but just in case...
6083 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
6084 }
6085 }
6086
6087 /// Get all display points of breakpoints that will be rendered within editor
6088 ///
6089 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6090 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6091 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6092 fn active_breakpoints(
6093 &mut self,
6094 range: Range<DisplayRow>,
6095 window: &mut Window,
6096 cx: &mut Context<Self>,
6097 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6098 let mut breakpoint_display_points = HashMap::default();
6099
6100 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6101 return breakpoint_display_points;
6102 };
6103
6104 let snapshot = self.snapshot(window, cx);
6105
6106 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6107 let Some(project) = self.project.as_ref() else {
6108 return breakpoint_display_points;
6109 };
6110
6111 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
6112 let buffer_snapshot = buffer.read(cx).snapshot();
6113
6114 for breakpoint in
6115 breakpoint_store
6116 .read(cx)
6117 .breakpoints(&buffer, None, buffer_snapshot.clone(), cx)
6118 {
6119 let point = buffer_snapshot.summary_for_anchor::<Point>(&breakpoint.0);
6120 let mut anchor = multi_buffer_snapshot.anchor_before(point);
6121 anchor.text_anchor = breakpoint.0;
6122
6123 breakpoint_display_points.insert(
6124 snapshot
6125 .point_to_display_point(
6126 MultiBufferPoint {
6127 row: point.row,
6128 column: point.column,
6129 },
6130 Bias::Left,
6131 )
6132 .row(),
6133 (anchor, breakpoint.1.clone()),
6134 );
6135 }
6136
6137 return breakpoint_display_points;
6138 }
6139
6140 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6141 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6142 for excerpt_boundary in multi_buffer_snapshot.excerpt_boundaries_in_range(range) {
6143 let info = excerpt_boundary.next;
6144
6145 let Some(excerpt_ranges) = multi_buffer_snapshot.range_for_excerpt(info.id) else {
6146 continue;
6147 };
6148
6149 let Some(buffer) =
6150 project.read_with(cx, |this, cx| this.buffer_for_id(info.buffer_id, cx))
6151 else {
6152 continue;
6153 };
6154
6155 if buffer.read(cx).file().is_none() {
6156 continue;
6157 }
6158 let breakpoints = breakpoint_store.read(cx).breakpoints(
6159 &buffer,
6160 Some(info.range.context.start..info.range.context.end),
6161 info.buffer.clone(),
6162 cx,
6163 );
6164
6165 // To translate a breakpoint's position within a singular buffer to a multi buffer
6166 // position we need to know it's excerpt starting location, it's position within
6167 // the singular buffer, and if that position is within the excerpt's range.
6168 let excerpt_head = excerpt_ranges
6169 .start
6170 .to_display_point(&snapshot.display_snapshot);
6171
6172 let buffer_start = info
6173 .buffer
6174 .summary_for_anchor::<Point>(&info.range.context.start);
6175
6176 for (anchor, breakpoint) in breakpoints {
6177 let as_row = info.buffer.summary_for_anchor::<Point>(&anchor).row;
6178 let delta = as_row - buffer_start.row;
6179
6180 let position = excerpt_head + DisplayPoint::new(DisplayRow(delta), 0);
6181
6182 let anchor = snapshot.display_point_to_anchor(position, Bias::Left);
6183
6184 breakpoint_display_points.insert(position.row(), (anchor, breakpoint.clone()));
6185 }
6186 }
6187
6188 breakpoint_display_points
6189 }
6190
6191 fn breakpoint_context_menu(
6192 &self,
6193 anchor: Anchor,
6194 kind: Arc<BreakpointKind>,
6195 window: &mut Window,
6196 cx: &mut Context<Self>,
6197 ) -> Entity<ui::ContextMenu> {
6198 let weak_editor = cx.weak_entity();
6199 let focus_handle = self.focus_handle(cx);
6200
6201 let second_entry_msg = if kind.log_message().is_some() {
6202 "Edit Log Breakpoint"
6203 } else {
6204 "Add Log Breakpoint"
6205 };
6206
6207 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6208 menu.on_blur_subscription(Subscription::new(|| {}))
6209 .context(focus_handle)
6210 .entry("Toggle Breakpoint", None, {
6211 let weak_editor = weak_editor.clone();
6212 move |_window, cx| {
6213 weak_editor
6214 .update(cx, |this, cx| {
6215 this.edit_breakpoint_at_anchor(
6216 anchor,
6217 BreakpointKind::Standard,
6218 BreakpointEditAction::Toggle,
6219 cx,
6220 );
6221 })
6222 .log_err();
6223 }
6224 })
6225 .entry(second_entry_msg, None, move |window, cx| {
6226 weak_editor
6227 .update(cx, |this, cx| {
6228 this.add_edit_breakpoint_block(anchor, kind.as_ref(), window, cx);
6229 })
6230 .log_err();
6231 })
6232 })
6233 }
6234
6235 fn render_breakpoint(
6236 &self,
6237 position: Anchor,
6238 row: DisplayRow,
6239 kind: &BreakpointKind,
6240 cx: &mut Context<Self>,
6241 ) -> IconButton {
6242 let color = if self
6243 .gutter_breakpoint_indicator
6244 .is_some_and(|gutter_bp| gutter_bp.row() == row)
6245 {
6246 Color::Hint
6247 } else {
6248 Color::Debugger
6249 };
6250
6251 let icon = match &kind {
6252 BreakpointKind::Standard => ui::IconName::DebugBreakpoint,
6253 BreakpointKind::Log(_) => ui::IconName::DebugLogBreakpoint,
6254 };
6255 let arc_kind = Arc::new(kind.clone());
6256 let arc_kind2 = arc_kind.clone();
6257
6258 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6259 .icon_size(IconSize::XSmall)
6260 .size(ui::ButtonSize::None)
6261 .icon_color(color)
6262 .style(ButtonStyle::Transparent)
6263 .on_click(cx.listener(move |editor, _e, window, cx| {
6264 window.focus(&editor.focus_handle(cx));
6265 editor.edit_breakpoint_at_anchor(
6266 position,
6267 arc_kind.as_ref().clone(),
6268 BreakpointEditAction::Toggle,
6269 cx,
6270 );
6271 }))
6272 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6273 editor.set_breakpoint_context_menu(
6274 row,
6275 Some(position),
6276 arc_kind2.clone(),
6277 event.down.position,
6278 window,
6279 cx,
6280 );
6281 }))
6282 }
6283
6284 fn build_tasks_context(
6285 project: &Entity<Project>,
6286 buffer: &Entity<Buffer>,
6287 buffer_row: u32,
6288 tasks: &Arc<RunnableTasks>,
6289 cx: &mut Context<Self>,
6290 ) -> Task<Option<task::TaskContext>> {
6291 let position = Point::new(buffer_row, tasks.column);
6292 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6293 let location = Location {
6294 buffer: buffer.clone(),
6295 range: range_start..range_start,
6296 };
6297 // Fill in the environmental variables from the tree-sitter captures
6298 let mut captured_task_variables = TaskVariables::default();
6299 for (capture_name, value) in tasks.extra_variables.clone() {
6300 captured_task_variables.insert(
6301 task::VariableName::Custom(capture_name.into()),
6302 value.clone(),
6303 );
6304 }
6305 project.update(cx, |project, cx| {
6306 project.task_store().update(cx, |task_store, cx| {
6307 task_store.task_context_for_location(captured_task_variables, location, cx)
6308 })
6309 })
6310 }
6311
6312 pub fn spawn_nearest_task(
6313 &mut self,
6314 action: &SpawnNearestTask,
6315 window: &mut Window,
6316 cx: &mut Context<Self>,
6317 ) {
6318 let Some((workspace, _)) = self.workspace.clone() else {
6319 return;
6320 };
6321 let Some(project) = self.project.clone() else {
6322 return;
6323 };
6324
6325 // Try to find a closest, enclosing node using tree-sitter that has a
6326 // task
6327 let Some((buffer, buffer_row, tasks)) = self
6328 .find_enclosing_node_task(cx)
6329 // Or find the task that's closest in row-distance.
6330 .or_else(|| self.find_closest_task(cx))
6331 else {
6332 return;
6333 };
6334
6335 let reveal_strategy = action.reveal;
6336 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6337 cx.spawn_in(window, async move |_, cx| {
6338 let context = task_context.await?;
6339 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6340
6341 let resolved = resolved_task.resolved.as_mut()?;
6342 resolved.reveal = reveal_strategy;
6343
6344 workspace
6345 .update(cx, |workspace, cx| {
6346 workspace::tasks::schedule_resolved_task(
6347 workspace,
6348 task_source_kind,
6349 resolved_task,
6350 false,
6351 cx,
6352 );
6353 })
6354 .ok()
6355 })
6356 .detach();
6357 }
6358
6359 fn find_closest_task(
6360 &mut self,
6361 cx: &mut Context<Self>,
6362 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6363 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6364
6365 let ((buffer_id, row), tasks) = self
6366 .tasks
6367 .iter()
6368 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6369
6370 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6371 let tasks = Arc::new(tasks.to_owned());
6372 Some((buffer, *row, tasks))
6373 }
6374
6375 fn find_enclosing_node_task(
6376 &mut self,
6377 cx: &mut Context<Self>,
6378 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6379 let snapshot = self.buffer.read(cx).snapshot(cx);
6380 let offset = self.selections.newest::<usize>(cx).head();
6381 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6382 let buffer_id = excerpt.buffer().remote_id();
6383
6384 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6385 let mut cursor = layer.node().walk();
6386
6387 while cursor.goto_first_child_for_byte(offset).is_some() {
6388 if cursor.node().end_byte() == offset {
6389 cursor.goto_next_sibling();
6390 }
6391 }
6392
6393 // Ascend to the smallest ancestor that contains the range and has a task.
6394 loop {
6395 let node = cursor.node();
6396 let node_range = node.byte_range();
6397 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6398
6399 // Check if this node contains our offset
6400 if node_range.start <= offset && node_range.end >= offset {
6401 // If it contains offset, check for task
6402 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6403 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6404 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6405 }
6406 }
6407
6408 if !cursor.goto_parent() {
6409 break;
6410 }
6411 }
6412 None
6413 }
6414
6415 fn render_run_indicator(
6416 &self,
6417 _style: &EditorStyle,
6418 is_active: bool,
6419 row: DisplayRow,
6420 breakpoint: Option<(Anchor, Breakpoint)>,
6421 cx: &mut Context<Self>,
6422 ) -> IconButton {
6423 let color = Color::Muted;
6424
6425 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6426 let bp_kind = Arc::new(
6427 breakpoint
6428 .map(|(_, bp)| bp.kind)
6429 .unwrap_or(BreakpointKind::Standard),
6430 );
6431
6432 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6433 .shape(ui::IconButtonShape::Square)
6434 .icon_size(IconSize::XSmall)
6435 .icon_color(color)
6436 .toggle_state(is_active)
6437 .on_click(cx.listener(move |editor, _e, window, cx| {
6438 window.focus(&editor.focus_handle(cx));
6439 editor.toggle_code_actions(
6440 &ToggleCodeActions {
6441 deployed_from_indicator: Some(row),
6442 },
6443 window,
6444 cx,
6445 );
6446 }))
6447 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6448 editor.set_breakpoint_context_menu(
6449 row,
6450 position,
6451 bp_kind.clone(),
6452 event.down.position,
6453 window,
6454 cx,
6455 );
6456 }))
6457 }
6458
6459 pub fn context_menu_visible(&self) -> bool {
6460 !self.edit_prediction_preview_is_active()
6461 && self
6462 .context_menu
6463 .borrow()
6464 .as_ref()
6465 .map_or(false, |menu| menu.visible())
6466 }
6467
6468 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6469 self.context_menu
6470 .borrow()
6471 .as_ref()
6472 .map(|menu| menu.origin())
6473 }
6474
6475 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6476 self.context_menu_options = Some(options);
6477 }
6478
6479 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6480 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6481
6482 fn render_edit_prediction_popover(
6483 &mut self,
6484 text_bounds: &Bounds<Pixels>,
6485 content_origin: gpui::Point<Pixels>,
6486 editor_snapshot: &EditorSnapshot,
6487 visible_row_range: Range<DisplayRow>,
6488 scroll_top: f32,
6489 scroll_bottom: f32,
6490 line_layouts: &[LineWithInvisibles],
6491 line_height: Pixels,
6492 scroll_pixel_position: gpui::Point<Pixels>,
6493 newest_selection_head: Option<DisplayPoint>,
6494 editor_width: Pixels,
6495 style: &EditorStyle,
6496 window: &mut Window,
6497 cx: &mut App,
6498 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6499 let active_inline_completion = self.active_inline_completion.as_ref()?;
6500
6501 if self.edit_prediction_visible_in_cursor_popover(true) {
6502 return None;
6503 }
6504
6505 match &active_inline_completion.completion {
6506 InlineCompletion::Move { target, .. } => {
6507 let target_display_point = target.to_display_point(editor_snapshot);
6508
6509 if self.edit_prediction_requires_modifier() {
6510 if !self.edit_prediction_preview_is_active() {
6511 return None;
6512 }
6513
6514 self.render_edit_prediction_modifier_jump_popover(
6515 text_bounds,
6516 content_origin,
6517 visible_row_range,
6518 line_layouts,
6519 line_height,
6520 scroll_pixel_position,
6521 newest_selection_head,
6522 target_display_point,
6523 window,
6524 cx,
6525 )
6526 } else {
6527 self.render_edit_prediction_eager_jump_popover(
6528 text_bounds,
6529 content_origin,
6530 editor_snapshot,
6531 visible_row_range,
6532 scroll_top,
6533 scroll_bottom,
6534 line_height,
6535 scroll_pixel_position,
6536 target_display_point,
6537 editor_width,
6538 window,
6539 cx,
6540 )
6541 }
6542 }
6543 InlineCompletion::Edit {
6544 display_mode: EditDisplayMode::Inline,
6545 ..
6546 } => None,
6547 InlineCompletion::Edit {
6548 display_mode: EditDisplayMode::TabAccept,
6549 edits,
6550 ..
6551 } => {
6552 let range = &edits.first()?.0;
6553 let target_display_point = range.end.to_display_point(editor_snapshot);
6554
6555 self.render_edit_prediction_end_of_line_popover(
6556 "Accept",
6557 editor_snapshot,
6558 visible_row_range,
6559 target_display_point,
6560 line_height,
6561 scroll_pixel_position,
6562 content_origin,
6563 editor_width,
6564 window,
6565 cx,
6566 )
6567 }
6568 InlineCompletion::Edit {
6569 edits,
6570 edit_preview,
6571 display_mode: EditDisplayMode::DiffPopover,
6572 snapshot,
6573 } => self.render_edit_prediction_diff_popover(
6574 text_bounds,
6575 content_origin,
6576 editor_snapshot,
6577 visible_row_range,
6578 line_layouts,
6579 line_height,
6580 scroll_pixel_position,
6581 newest_selection_head,
6582 editor_width,
6583 style,
6584 edits,
6585 edit_preview,
6586 snapshot,
6587 window,
6588 cx,
6589 ),
6590 }
6591 }
6592
6593 fn render_edit_prediction_modifier_jump_popover(
6594 &mut self,
6595 text_bounds: &Bounds<Pixels>,
6596 content_origin: gpui::Point<Pixels>,
6597 visible_row_range: Range<DisplayRow>,
6598 line_layouts: &[LineWithInvisibles],
6599 line_height: Pixels,
6600 scroll_pixel_position: gpui::Point<Pixels>,
6601 newest_selection_head: Option<DisplayPoint>,
6602 target_display_point: DisplayPoint,
6603 window: &mut Window,
6604 cx: &mut App,
6605 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6606 let scrolled_content_origin =
6607 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6608
6609 const SCROLL_PADDING_Y: Pixels = px(12.);
6610
6611 if target_display_point.row() < visible_row_range.start {
6612 return self.render_edit_prediction_scroll_popover(
6613 |_| SCROLL_PADDING_Y,
6614 IconName::ArrowUp,
6615 visible_row_range,
6616 line_layouts,
6617 newest_selection_head,
6618 scrolled_content_origin,
6619 window,
6620 cx,
6621 );
6622 } else if target_display_point.row() >= visible_row_range.end {
6623 return self.render_edit_prediction_scroll_popover(
6624 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6625 IconName::ArrowDown,
6626 visible_row_range,
6627 line_layouts,
6628 newest_selection_head,
6629 scrolled_content_origin,
6630 window,
6631 cx,
6632 );
6633 }
6634
6635 const POLE_WIDTH: Pixels = px(2.);
6636
6637 let line_layout =
6638 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6639 let target_column = target_display_point.column() as usize;
6640
6641 let target_x = line_layout.x_for_index(target_column);
6642 let target_y =
6643 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6644
6645 let flag_on_right = target_x < text_bounds.size.width / 2.;
6646
6647 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6648 border_color.l += 0.001;
6649
6650 let mut element = v_flex()
6651 .items_end()
6652 .when(flag_on_right, |el| el.items_start())
6653 .child(if flag_on_right {
6654 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6655 .rounded_bl(px(0.))
6656 .rounded_tl(px(0.))
6657 .border_l_2()
6658 .border_color(border_color)
6659 } else {
6660 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6661 .rounded_br(px(0.))
6662 .rounded_tr(px(0.))
6663 .border_r_2()
6664 .border_color(border_color)
6665 })
6666 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6667 .into_any();
6668
6669 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6670
6671 let mut origin = scrolled_content_origin + point(target_x, target_y)
6672 - point(
6673 if flag_on_right {
6674 POLE_WIDTH
6675 } else {
6676 size.width - POLE_WIDTH
6677 },
6678 size.height - line_height,
6679 );
6680
6681 origin.x = origin.x.max(content_origin.x);
6682
6683 element.prepaint_at(origin, window, cx);
6684
6685 Some((element, origin))
6686 }
6687
6688 fn render_edit_prediction_scroll_popover(
6689 &mut self,
6690 to_y: impl Fn(Size<Pixels>) -> Pixels,
6691 scroll_icon: IconName,
6692 visible_row_range: Range<DisplayRow>,
6693 line_layouts: &[LineWithInvisibles],
6694 newest_selection_head: Option<DisplayPoint>,
6695 scrolled_content_origin: gpui::Point<Pixels>,
6696 window: &mut Window,
6697 cx: &mut App,
6698 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6699 let mut element = self
6700 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6701 .into_any();
6702
6703 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6704
6705 let cursor = newest_selection_head?;
6706 let cursor_row_layout =
6707 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6708 let cursor_column = cursor.column() as usize;
6709
6710 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6711
6712 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6713
6714 element.prepaint_at(origin, window, cx);
6715 Some((element, origin))
6716 }
6717
6718 fn render_edit_prediction_eager_jump_popover(
6719 &mut self,
6720 text_bounds: &Bounds<Pixels>,
6721 content_origin: gpui::Point<Pixels>,
6722 editor_snapshot: &EditorSnapshot,
6723 visible_row_range: Range<DisplayRow>,
6724 scroll_top: f32,
6725 scroll_bottom: f32,
6726 line_height: Pixels,
6727 scroll_pixel_position: gpui::Point<Pixels>,
6728 target_display_point: DisplayPoint,
6729 editor_width: Pixels,
6730 window: &mut Window,
6731 cx: &mut App,
6732 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6733 if target_display_point.row().as_f32() < scroll_top {
6734 let mut element = self
6735 .render_edit_prediction_line_popover(
6736 "Jump to Edit",
6737 Some(IconName::ArrowUp),
6738 window,
6739 cx,
6740 )?
6741 .into_any();
6742
6743 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6744 let offset = point(
6745 (text_bounds.size.width - size.width) / 2.,
6746 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6747 );
6748
6749 let origin = text_bounds.origin + offset;
6750 element.prepaint_at(origin, window, cx);
6751 Some((element, origin))
6752 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6753 let mut element = self
6754 .render_edit_prediction_line_popover(
6755 "Jump to Edit",
6756 Some(IconName::ArrowDown),
6757 window,
6758 cx,
6759 )?
6760 .into_any();
6761
6762 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6763 let offset = point(
6764 (text_bounds.size.width - size.width) / 2.,
6765 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6766 );
6767
6768 let origin = text_bounds.origin + offset;
6769 element.prepaint_at(origin, window, cx);
6770 Some((element, origin))
6771 } else {
6772 self.render_edit_prediction_end_of_line_popover(
6773 "Jump to Edit",
6774 editor_snapshot,
6775 visible_row_range,
6776 target_display_point,
6777 line_height,
6778 scroll_pixel_position,
6779 content_origin,
6780 editor_width,
6781 window,
6782 cx,
6783 )
6784 }
6785 }
6786
6787 fn render_edit_prediction_end_of_line_popover(
6788 self: &mut Editor,
6789 label: &'static str,
6790 editor_snapshot: &EditorSnapshot,
6791 visible_row_range: Range<DisplayRow>,
6792 target_display_point: DisplayPoint,
6793 line_height: Pixels,
6794 scroll_pixel_position: gpui::Point<Pixels>,
6795 content_origin: gpui::Point<Pixels>,
6796 editor_width: Pixels,
6797 window: &mut Window,
6798 cx: &mut App,
6799 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6800 let target_line_end = DisplayPoint::new(
6801 target_display_point.row(),
6802 editor_snapshot.line_len(target_display_point.row()),
6803 );
6804
6805 let mut element = self
6806 .render_edit_prediction_line_popover(label, None, window, cx)?
6807 .into_any();
6808
6809 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6810
6811 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6812
6813 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6814 let mut origin = start_point
6815 + line_origin
6816 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6817 origin.x = origin.x.max(content_origin.x);
6818
6819 let max_x = content_origin.x + editor_width - size.width;
6820
6821 if origin.x > max_x {
6822 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6823
6824 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6825 origin.y += offset;
6826 IconName::ArrowUp
6827 } else {
6828 origin.y -= offset;
6829 IconName::ArrowDown
6830 };
6831
6832 element = self
6833 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6834 .into_any();
6835
6836 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6837
6838 origin.x = content_origin.x + editor_width - size.width - px(2.);
6839 }
6840
6841 element.prepaint_at(origin, window, cx);
6842 Some((element, origin))
6843 }
6844
6845 fn render_edit_prediction_diff_popover(
6846 self: &Editor,
6847 text_bounds: &Bounds<Pixels>,
6848 content_origin: gpui::Point<Pixels>,
6849 editor_snapshot: &EditorSnapshot,
6850 visible_row_range: Range<DisplayRow>,
6851 line_layouts: &[LineWithInvisibles],
6852 line_height: Pixels,
6853 scroll_pixel_position: gpui::Point<Pixels>,
6854 newest_selection_head: Option<DisplayPoint>,
6855 editor_width: Pixels,
6856 style: &EditorStyle,
6857 edits: &Vec<(Range<Anchor>, String)>,
6858 edit_preview: &Option<language::EditPreview>,
6859 snapshot: &language::BufferSnapshot,
6860 window: &mut Window,
6861 cx: &mut App,
6862 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6863 let edit_start = edits
6864 .first()
6865 .unwrap()
6866 .0
6867 .start
6868 .to_display_point(editor_snapshot);
6869 let edit_end = edits
6870 .last()
6871 .unwrap()
6872 .0
6873 .end
6874 .to_display_point(editor_snapshot);
6875
6876 let is_visible = visible_row_range.contains(&edit_start.row())
6877 || visible_row_range.contains(&edit_end.row());
6878 if !is_visible {
6879 return None;
6880 }
6881
6882 let highlighted_edits =
6883 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6884
6885 let styled_text = highlighted_edits.to_styled_text(&style.text);
6886 let line_count = highlighted_edits.text.lines().count();
6887
6888 const BORDER_WIDTH: Pixels = px(1.);
6889
6890 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6891 let has_keybind = keybind.is_some();
6892
6893 let mut element = h_flex()
6894 .items_start()
6895 .child(
6896 h_flex()
6897 .bg(cx.theme().colors().editor_background)
6898 .border(BORDER_WIDTH)
6899 .shadow_sm()
6900 .border_color(cx.theme().colors().border)
6901 .rounded_l_lg()
6902 .when(line_count > 1, |el| el.rounded_br_lg())
6903 .pr_1()
6904 .child(styled_text),
6905 )
6906 .child(
6907 h_flex()
6908 .h(line_height + BORDER_WIDTH * px(2.))
6909 .px_1p5()
6910 .gap_1()
6911 // Workaround: For some reason, there's a gap if we don't do this
6912 .ml(-BORDER_WIDTH)
6913 .shadow(smallvec![gpui::BoxShadow {
6914 color: gpui::black().opacity(0.05),
6915 offset: point(px(1.), px(1.)),
6916 blur_radius: px(2.),
6917 spread_radius: px(0.),
6918 }])
6919 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6920 .border(BORDER_WIDTH)
6921 .border_color(cx.theme().colors().border)
6922 .rounded_r_lg()
6923 .id("edit_prediction_diff_popover_keybind")
6924 .when(!has_keybind, |el| {
6925 let status_colors = cx.theme().status();
6926
6927 el.bg(status_colors.error_background)
6928 .border_color(status_colors.error.opacity(0.6))
6929 .child(Icon::new(IconName::Info).color(Color::Error))
6930 .cursor_default()
6931 .hoverable_tooltip(move |_window, cx| {
6932 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6933 })
6934 })
6935 .children(keybind),
6936 )
6937 .into_any();
6938
6939 let longest_row =
6940 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6941 let longest_line_width = if visible_row_range.contains(&longest_row) {
6942 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6943 } else {
6944 layout_line(
6945 longest_row,
6946 editor_snapshot,
6947 style,
6948 editor_width,
6949 |_| false,
6950 window,
6951 cx,
6952 )
6953 .width
6954 };
6955
6956 let viewport_bounds =
6957 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6958 right: -EditorElement::SCROLLBAR_WIDTH,
6959 ..Default::default()
6960 });
6961
6962 let x_after_longest =
6963 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6964 - scroll_pixel_position.x;
6965
6966 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6967
6968 // Fully visible if it can be displayed within the window (allow overlapping other
6969 // panes). However, this is only allowed if the popover starts within text_bounds.
6970 let can_position_to_the_right = x_after_longest < text_bounds.right()
6971 && x_after_longest + element_bounds.width < viewport_bounds.right();
6972
6973 let mut origin = if can_position_to_the_right {
6974 point(
6975 x_after_longest,
6976 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6977 - scroll_pixel_position.y,
6978 )
6979 } else {
6980 let cursor_row = newest_selection_head.map(|head| head.row());
6981 let above_edit = edit_start
6982 .row()
6983 .0
6984 .checked_sub(line_count as u32)
6985 .map(DisplayRow);
6986 let below_edit = Some(edit_end.row() + 1);
6987 let above_cursor =
6988 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6989 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6990
6991 // Place the edit popover adjacent to the edit if there is a location
6992 // available that is onscreen and does not obscure the cursor. Otherwise,
6993 // place it adjacent to the cursor.
6994 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6995 .into_iter()
6996 .flatten()
6997 .find(|&start_row| {
6998 let end_row = start_row + line_count as u32;
6999 visible_row_range.contains(&start_row)
7000 && visible_row_range.contains(&end_row)
7001 && cursor_row.map_or(true, |cursor_row| {
7002 !((start_row..end_row).contains(&cursor_row))
7003 })
7004 })?;
7005
7006 content_origin
7007 + point(
7008 -scroll_pixel_position.x,
7009 row_target.as_f32() * line_height - scroll_pixel_position.y,
7010 )
7011 };
7012
7013 origin.x -= BORDER_WIDTH;
7014
7015 window.defer_draw(element, origin, 1);
7016
7017 // Do not return an element, since it will already be drawn due to defer_draw.
7018 None
7019 }
7020
7021 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7022 px(30.)
7023 }
7024
7025 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7026 if self.read_only(cx) {
7027 cx.theme().players().read_only()
7028 } else {
7029 self.style.as_ref().unwrap().local_player
7030 }
7031 }
7032
7033 fn render_edit_prediction_accept_keybind(
7034 &self,
7035 window: &mut Window,
7036 cx: &App,
7037 ) -> Option<AnyElement> {
7038 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7039 let accept_keystroke = accept_binding.keystroke()?;
7040
7041 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7042
7043 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7044 Color::Accent
7045 } else {
7046 Color::Muted
7047 };
7048
7049 h_flex()
7050 .px_0p5()
7051 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7052 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7053 .text_size(TextSize::XSmall.rems(cx))
7054 .child(h_flex().children(ui::render_modifiers(
7055 &accept_keystroke.modifiers,
7056 PlatformStyle::platform(),
7057 Some(modifiers_color),
7058 Some(IconSize::XSmall.rems().into()),
7059 true,
7060 )))
7061 .when(is_platform_style_mac, |parent| {
7062 parent.child(accept_keystroke.key.clone())
7063 })
7064 .when(!is_platform_style_mac, |parent| {
7065 parent.child(
7066 Key::new(
7067 util::capitalize(&accept_keystroke.key),
7068 Some(Color::Default),
7069 )
7070 .size(Some(IconSize::XSmall.rems().into())),
7071 )
7072 })
7073 .into_any()
7074 .into()
7075 }
7076
7077 fn render_edit_prediction_line_popover(
7078 &self,
7079 label: impl Into<SharedString>,
7080 icon: Option<IconName>,
7081 window: &mut Window,
7082 cx: &App,
7083 ) -> Option<Stateful<Div>> {
7084 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7085
7086 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7087 let has_keybind = keybind.is_some();
7088
7089 let result = h_flex()
7090 .id("ep-line-popover")
7091 .py_0p5()
7092 .pl_1()
7093 .pr(padding_right)
7094 .gap_1()
7095 .rounded_md()
7096 .border_1()
7097 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7098 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7099 .shadow_sm()
7100 .when(!has_keybind, |el| {
7101 let status_colors = cx.theme().status();
7102
7103 el.bg(status_colors.error_background)
7104 .border_color(status_colors.error.opacity(0.6))
7105 .pl_2()
7106 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7107 .cursor_default()
7108 .hoverable_tooltip(move |_window, cx| {
7109 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7110 })
7111 })
7112 .children(keybind)
7113 .child(
7114 Label::new(label)
7115 .size(LabelSize::Small)
7116 .when(!has_keybind, |el| {
7117 el.color(cx.theme().status().error.into()).strikethrough()
7118 }),
7119 )
7120 .when(!has_keybind, |el| {
7121 el.child(
7122 h_flex().ml_1().child(
7123 Icon::new(IconName::Info)
7124 .size(IconSize::Small)
7125 .color(cx.theme().status().error.into()),
7126 ),
7127 )
7128 })
7129 .when_some(icon, |element, icon| {
7130 element.child(
7131 div()
7132 .mt(px(1.5))
7133 .child(Icon::new(icon).size(IconSize::Small)),
7134 )
7135 });
7136
7137 Some(result)
7138 }
7139
7140 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7141 let accent_color = cx.theme().colors().text_accent;
7142 let editor_bg_color = cx.theme().colors().editor_background;
7143 editor_bg_color.blend(accent_color.opacity(0.1))
7144 }
7145
7146 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7147 let accent_color = cx.theme().colors().text_accent;
7148 let editor_bg_color = cx.theme().colors().editor_background;
7149 editor_bg_color.blend(accent_color.opacity(0.6))
7150 }
7151
7152 fn render_edit_prediction_cursor_popover(
7153 &self,
7154 min_width: Pixels,
7155 max_width: Pixels,
7156 cursor_point: Point,
7157 style: &EditorStyle,
7158 accept_keystroke: Option<&gpui::Keystroke>,
7159 _window: &Window,
7160 cx: &mut Context<Editor>,
7161 ) -> Option<AnyElement> {
7162 let provider = self.edit_prediction_provider.as_ref()?;
7163
7164 if provider.provider.needs_terms_acceptance(cx) {
7165 return Some(
7166 h_flex()
7167 .min_w(min_width)
7168 .flex_1()
7169 .px_2()
7170 .py_1()
7171 .gap_3()
7172 .elevation_2(cx)
7173 .hover(|style| style.bg(cx.theme().colors().element_hover))
7174 .id("accept-terms")
7175 .cursor_pointer()
7176 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7177 .on_click(cx.listener(|this, _event, window, cx| {
7178 cx.stop_propagation();
7179 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7180 window.dispatch_action(
7181 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7182 cx,
7183 );
7184 }))
7185 .child(
7186 h_flex()
7187 .flex_1()
7188 .gap_2()
7189 .child(Icon::new(IconName::ZedPredict))
7190 .child(Label::new("Accept Terms of Service"))
7191 .child(div().w_full())
7192 .child(
7193 Icon::new(IconName::ArrowUpRight)
7194 .color(Color::Muted)
7195 .size(IconSize::Small),
7196 )
7197 .into_any_element(),
7198 )
7199 .into_any(),
7200 );
7201 }
7202
7203 let is_refreshing = provider.provider.is_refreshing(cx);
7204
7205 fn pending_completion_container() -> Div {
7206 h_flex()
7207 .h_full()
7208 .flex_1()
7209 .gap_2()
7210 .child(Icon::new(IconName::ZedPredict))
7211 }
7212
7213 let completion = match &self.active_inline_completion {
7214 Some(prediction) => {
7215 if !self.has_visible_completions_menu() {
7216 const RADIUS: Pixels = px(6.);
7217 const BORDER_WIDTH: Pixels = px(1.);
7218
7219 return Some(
7220 h_flex()
7221 .elevation_2(cx)
7222 .border(BORDER_WIDTH)
7223 .border_color(cx.theme().colors().border)
7224 .when(accept_keystroke.is_none(), |el| {
7225 el.border_color(cx.theme().status().error)
7226 })
7227 .rounded(RADIUS)
7228 .rounded_tl(px(0.))
7229 .overflow_hidden()
7230 .child(div().px_1p5().child(match &prediction.completion {
7231 InlineCompletion::Move { target, snapshot } => {
7232 use text::ToPoint as _;
7233 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7234 {
7235 Icon::new(IconName::ZedPredictDown)
7236 } else {
7237 Icon::new(IconName::ZedPredictUp)
7238 }
7239 }
7240 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7241 }))
7242 .child(
7243 h_flex()
7244 .gap_1()
7245 .py_1()
7246 .px_2()
7247 .rounded_r(RADIUS - BORDER_WIDTH)
7248 .border_l_1()
7249 .border_color(cx.theme().colors().border)
7250 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7251 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7252 el.child(
7253 Label::new("Hold")
7254 .size(LabelSize::Small)
7255 .when(accept_keystroke.is_none(), |el| {
7256 el.strikethrough()
7257 })
7258 .line_height_style(LineHeightStyle::UiLabel),
7259 )
7260 })
7261 .id("edit_prediction_cursor_popover_keybind")
7262 .when(accept_keystroke.is_none(), |el| {
7263 let status_colors = cx.theme().status();
7264
7265 el.bg(status_colors.error_background)
7266 .border_color(status_colors.error.opacity(0.6))
7267 .child(Icon::new(IconName::Info).color(Color::Error))
7268 .cursor_default()
7269 .hoverable_tooltip(move |_window, cx| {
7270 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7271 .into()
7272 })
7273 })
7274 .when_some(
7275 accept_keystroke.as_ref(),
7276 |el, accept_keystroke| {
7277 el.child(h_flex().children(ui::render_modifiers(
7278 &accept_keystroke.modifiers,
7279 PlatformStyle::platform(),
7280 Some(Color::Default),
7281 Some(IconSize::XSmall.rems().into()),
7282 false,
7283 )))
7284 },
7285 ),
7286 )
7287 .into_any(),
7288 );
7289 }
7290
7291 self.render_edit_prediction_cursor_popover_preview(
7292 prediction,
7293 cursor_point,
7294 style,
7295 cx,
7296 )?
7297 }
7298
7299 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7300 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7301 stale_completion,
7302 cursor_point,
7303 style,
7304 cx,
7305 )?,
7306
7307 None => {
7308 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7309 }
7310 },
7311
7312 None => pending_completion_container().child(Label::new("No Prediction")),
7313 };
7314
7315 let completion = if is_refreshing {
7316 completion
7317 .with_animation(
7318 "loading-completion",
7319 Animation::new(Duration::from_secs(2))
7320 .repeat()
7321 .with_easing(pulsating_between(0.4, 0.8)),
7322 |label, delta| label.opacity(delta),
7323 )
7324 .into_any_element()
7325 } else {
7326 completion.into_any_element()
7327 };
7328
7329 let has_completion = self.active_inline_completion.is_some();
7330
7331 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7332 Some(
7333 h_flex()
7334 .min_w(min_width)
7335 .max_w(max_width)
7336 .flex_1()
7337 .elevation_2(cx)
7338 .border_color(cx.theme().colors().border)
7339 .child(
7340 div()
7341 .flex_1()
7342 .py_1()
7343 .px_2()
7344 .overflow_hidden()
7345 .child(completion),
7346 )
7347 .when_some(accept_keystroke, |el, accept_keystroke| {
7348 if !accept_keystroke.modifiers.modified() {
7349 return el;
7350 }
7351
7352 el.child(
7353 h_flex()
7354 .h_full()
7355 .border_l_1()
7356 .rounded_r_lg()
7357 .border_color(cx.theme().colors().border)
7358 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7359 .gap_1()
7360 .py_1()
7361 .px_2()
7362 .child(
7363 h_flex()
7364 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7365 .when(is_platform_style_mac, |parent| parent.gap_1())
7366 .child(h_flex().children(ui::render_modifiers(
7367 &accept_keystroke.modifiers,
7368 PlatformStyle::platform(),
7369 Some(if !has_completion {
7370 Color::Muted
7371 } else {
7372 Color::Default
7373 }),
7374 None,
7375 false,
7376 ))),
7377 )
7378 .child(Label::new("Preview").into_any_element())
7379 .opacity(if has_completion { 1.0 } else { 0.4 }),
7380 )
7381 })
7382 .into_any(),
7383 )
7384 }
7385
7386 fn render_edit_prediction_cursor_popover_preview(
7387 &self,
7388 completion: &InlineCompletionState,
7389 cursor_point: Point,
7390 style: &EditorStyle,
7391 cx: &mut Context<Editor>,
7392 ) -> Option<Div> {
7393 use text::ToPoint as _;
7394
7395 fn render_relative_row_jump(
7396 prefix: impl Into<String>,
7397 current_row: u32,
7398 target_row: u32,
7399 ) -> Div {
7400 let (row_diff, arrow) = if target_row < current_row {
7401 (current_row - target_row, IconName::ArrowUp)
7402 } else {
7403 (target_row - current_row, IconName::ArrowDown)
7404 };
7405
7406 h_flex()
7407 .child(
7408 Label::new(format!("{}{}", prefix.into(), row_diff))
7409 .color(Color::Muted)
7410 .size(LabelSize::Small),
7411 )
7412 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7413 }
7414
7415 match &completion.completion {
7416 InlineCompletion::Move {
7417 target, snapshot, ..
7418 } => Some(
7419 h_flex()
7420 .px_2()
7421 .gap_2()
7422 .flex_1()
7423 .child(
7424 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7425 Icon::new(IconName::ZedPredictDown)
7426 } else {
7427 Icon::new(IconName::ZedPredictUp)
7428 },
7429 )
7430 .child(Label::new("Jump to Edit")),
7431 ),
7432
7433 InlineCompletion::Edit {
7434 edits,
7435 edit_preview,
7436 snapshot,
7437 display_mode: _,
7438 } => {
7439 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7440
7441 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7442 &snapshot,
7443 &edits,
7444 edit_preview.as_ref()?,
7445 true,
7446 cx,
7447 )
7448 .first_line_preview();
7449
7450 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7451 .with_default_highlights(&style.text, highlighted_edits.highlights);
7452
7453 let preview = h_flex()
7454 .gap_1()
7455 .min_w_16()
7456 .child(styled_text)
7457 .when(has_more_lines, |parent| parent.child("…"));
7458
7459 let left = if first_edit_row != cursor_point.row {
7460 render_relative_row_jump("", cursor_point.row, first_edit_row)
7461 .into_any_element()
7462 } else {
7463 Icon::new(IconName::ZedPredict).into_any_element()
7464 };
7465
7466 Some(
7467 h_flex()
7468 .h_full()
7469 .flex_1()
7470 .gap_2()
7471 .pr_1()
7472 .overflow_x_hidden()
7473 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7474 .child(left)
7475 .child(preview),
7476 )
7477 }
7478 }
7479 }
7480
7481 fn render_context_menu(
7482 &self,
7483 style: &EditorStyle,
7484 max_height_in_lines: u32,
7485 y_flipped: bool,
7486 window: &mut Window,
7487 cx: &mut Context<Editor>,
7488 ) -> Option<AnyElement> {
7489 let menu = self.context_menu.borrow();
7490 let menu = menu.as_ref()?;
7491 if !menu.visible() {
7492 return None;
7493 };
7494 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7495 }
7496
7497 fn render_context_menu_aside(
7498 &mut self,
7499 max_size: Size<Pixels>,
7500 window: &mut Window,
7501 cx: &mut Context<Editor>,
7502 ) -> Option<AnyElement> {
7503 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7504 if menu.visible() {
7505 menu.render_aside(self, max_size, window, cx)
7506 } else {
7507 None
7508 }
7509 })
7510 }
7511
7512 fn hide_context_menu(
7513 &mut self,
7514 window: &mut Window,
7515 cx: &mut Context<Self>,
7516 ) -> Option<CodeContextMenu> {
7517 cx.notify();
7518 self.completion_tasks.clear();
7519 let context_menu = self.context_menu.borrow_mut().take();
7520 self.stale_inline_completion_in_menu.take();
7521 self.update_visible_inline_completion(window, cx);
7522 context_menu
7523 }
7524
7525 fn show_snippet_choices(
7526 &mut self,
7527 choices: &Vec<String>,
7528 selection: Range<Anchor>,
7529 cx: &mut Context<Self>,
7530 ) {
7531 if selection.start.buffer_id.is_none() {
7532 return;
7533 }
7534 let buffer_id = selection.start.buffer_id.unwrap();
7535 let buffer = self.buffer().read(cx).buffer(buffer_id);
7536 let id = post_inc(&mut self.next_completion_id);
7537
7538 if let Some(buffer) = buffer {
7539 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7540 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7541 ));
7542 }
7543 }
7544
7545 pub fn insert_snippet(
7546 &mut self,
7547 insertion_ranges: &[Range<usize>],
7548 snippet: Snippet,
7549 window: &mut Window,
7550 cx: &mut Context<Self>,
7551 ) -> Result<()> {
7552 struct Tabstop<T> {
7553 is_end_tabstop: bool,
7554 ranges: Vec<Range<T>>,
7555 choices: Option<Vec<String>>,
7556 }
7557
7558 let tabstops = self.buffer.update(cx, |buffer, cx| {
7559 let snippet_text: Arc<str> = snippet.text.clone().into();
7560 let edits = insertion_ranges
7561 .iter()
7562 .cloned()
7563 .map(|range| (range, snippet_text.clone()));
7564 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7565
7566 let snapshot = &*buffer.read(cx);
7567 let snippet = &snippet;
7568 snippet
7569 .tabstops
7570 .iter()
7571 .map(|tabstop| {
7572 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7573 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7574 });
7575 let mut tabstop_ranges = tabstop
7576 .ranges
7577 .iter()
7578 .flat_map(|tabstop_range| {
7579 let mut delta = 0_isize;
7580 insertion_ranges.iter().map(move |insertion_range| {
7581 let insertion_start = insertion_range.start as isize + delta;
7582 delta +=
7583 snippet.text.len() as isize - insertion_range.len() as isize;
7584
7585 let start = ((insertion_start + tabstop_range.start) as usize)
7586 .min(snapshot.len());
7587 let end = ((insertion_start + tabstop_range.end) as usize)
7588 .min(snapshot.len());
7589 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7590 })
7591 })
7592 .collect::<Vec<_>>();
7593 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7594
7595 Tabstop {
7596 is_end_tabstop,
7597 ranges: tabstop_ranges,
7598 choices: tabstop.choices.clone(),
7599 }
7600 })
7601 .collect::<Vec<_>>()
7602 });
7603 if let Some(tabstop) = tabstops.first() {
7604 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7605 s.select_ranges(tabstop.ranges.iter().cloned());
7606 });
7607
7608 if let Some(choices) = &tabstop.choices {
7609 if let Some(selection) = tabstop.ranges.first() {
7610 self.show_snippet_choices(choices, selection.clone(), cx)
7611 }
7612 }
7613
7614 // If we're already at the last tabstop and it's at the end of the snippet,
7615 // we're done, we don't need to keep the state around.
7616 if !tabstop.is_end_tabstop {
7617 let choices = tabstops
7618 .iter()
7619 .map(|tabstop| tabstop.choices.clone())
7620 .collect();
7621
7622 let ranges = tabstops
7623 .into_iter()
7624 .map(|tabstop| tabstop.ranges)
7625 .collect::<Vec<_>>();
7626
7627 self.snippet_stack.push(SnippetState {
7628 active_index: 0,
7629 ranges,
7630 choices,
7631 });
7632 }
7633
7634 // Check whether the just-entered snippet ends with an auto-closable bracket.
7635 if self.autoclose_regions.is_empty() {
7636 let snapshot = self.buffer.read(cx).snapshot(cx);
7637 for selection in &mut self.selections.all::<Point>(cx) {
7638 let selection_head = selection.head();
7639 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7640 continue;
7641 };
7642
7643 let mut bracket_pair = None;
7644 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7645 let prev_chars = snapshot
7646 .reversed_chars_at(selection_head)
7647 .collect::<String>();
7648 for (pair, enabled) in scope.brackets() {
7649 if enabled
7650 && pair.close
7651 && prev_chars.starts_with(pair.start.as_str())
7652 && next_chars.starts_with(pair.end.as_str())
7653 {
7654 bracket_pair = Some(pair.clone());
7655 break;
7656 }
7657 }
7658 if let Some(pair) = bracket_pair {
7659 let start = snapshot.anchor_after(selection_head);
7660 let end = snapshot.anchor_after(selection_head);
7661 self.autoclose_regions.push(AutocloseRegion {
7662 selection_id: selection.id,
7663 range: start..end,
7664 pair,
7665 });
7666 }
7667 }
7668 }
7669 }
7670 Ok(())
7671 }
7672
7673 pub fn move_to_next_snippet_tabstop(
7674 &mut self,
7675 window: &mut Window,
7676 cx: &mut Context<Self>,
7677 ) -> bool {
7678 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7679 }
7680
7681 pub fn move_to_prev_snippet_tabstop(
7682 &mut self,
7683 window: &mut Window,
7684 cx: &mut Context<Self>,
7685 ) -> bool {
7686 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7687 }
7688
7689 pub fn move_to_snippet_tabstop(
7690 &mut self,
7691 bias: Bias,
7692 window: &mut Window,
7693 cx: &mut Context<Self>,
7694 ) -> bool {
7695 if let Some(mut snippet) = self.snippet_stack.pop() {
7696 match bias {
7697 Bias::Left => {
7698 if snippet.active_index > 0 {
7699 snippet.active_index -= 1;
7700 } else {
7701 self.snippet_stack.push(snippet);
7702 return false;
7703 }
7704 }
7705 Bias::Right => {
7706 if snippet.active_index + 1 < snippet.ranges.len() {
7707 snippet.active_index += 1;
7708 } else {
7709 self.snippet_stack.push(snippet);
7710 return false;
7711 }
7712 }
7713 }
7714 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7715 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7716 s.select_anchor_ranges(current_ranges.iter().cloned())
7717 });
7718
7719 if let Some(choices) = &snippet.choices[snippet.active_index] {
7720 if let Some(selection) = current_ranges.first() {
7721 self.show_snippet_choices(&choices, selection.clone(), cx);
7722 }
7723 }
7724
7725 // If snippet state is not at the last tabstop, push it back on the stack
7726 if snippet.active_index + 1 < snippet.ranges.len() {
7727 self.snippet_stack.push(snippet);
7728 }
7729 return true;
7730 }
7731 }
7732
7733 false
7734 }
7735
7736 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7737 self.transact(window, cx, |this, window, cx| {
7738 this.select_all(&SelectAll, window, cx);
7739 this.insert("", window, cx);
7740 });
7741 }
7742
7743 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7744 self.transact(window, cx, |this, window, cx| {
7745 this.select_autoclose_pair(window, cx);
7746 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7747 if !this.linked_edit_ranges.is_empty() {
7748 let selections = this.selections.all::<MultiBufferPoint>(cx);
7749 let snapshot = this.buffer.read(cx).snapshot(cx);
7750
7751 for selection in selections.iter() {
7752 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7753 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7754 if selection_start.buffer_id != selection_end.buffer_id {
7755 continue;
7756 }
7757 if let Some(ranges) =
7758 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7759 {
7760 for (buffer, entries) in ranges {
7761 linked_ranges.entry(buffer).or_default().extend(entries);
7762 }
7763 }
7764 }
7765 }
7766
7767 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7768 if !this.selections.line_mode {
7769 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7770 for selection in &mut selections {
7771 if selection.is_empty() {
7772 let old_head = selection.head();
7773 let mut new_head =
7774 movement::left(&display_map, old_head.to_display_point(&display_map))
7775 .to_point(&display_map);
7776 if let Some((buffer, line_buffer_range)) = display_map
7777 .buffer_snapshot
7778 .buffer_line_for_row(MultiBufferRow(old_head.row))
7779 {
7780 let indent_size =
7781 buffer.indent_size_for_line(line_buffer_range.start.row);
7782 let indent_len = match indent_size.kind {
7783 IndentKind::Space => {
7784 buffer.settings_at(line_buffer_range.start, cx).tab_size
7785 }
7786 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7787 };
7788 if old_head.column <= indent_size.len && old_head.column > 0 {
7789 let indent_len = indent_len.get();
7790 new_head = cmp::min(
7791 new_head,
7792 MultiBufferPoint::new(
7793 old_head.row,
7794 ((old_head.column - 1) / indent_len) * indent_len,
7795 ),
7796 );
7797 }
7798 }
7799
7800 selection.set_head(new_head, SelectionGoal::None);
7801 }
7802 }
7803 }
7804
7805 this.signature_help_state.set_backspace_pressed(true);
7806 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7807 s.select(selections)
7808 });
7809 this.insert("", window, cx);
7810 let empty_str: Arc<str> = Arc::from("");
7811 for (buffer, edits) in linked_ranges {
7812 let snapshot = buffer.read(cx).snapshot();
7813 use text::ToPoint as TP;
7814
7815 let edits = edits
7816 .into_iter()
7817 .map(|range| {
7818 let end_point = TP::to_point(&range.end, &snapshot);
7819 let mut start_point = TP::to_point(&range.start, &snapshot);
7820
7821 if end_point == start_point {
7822 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7823 .saturating_sub(1);
7824 start_point =
7825 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7826 };
7827
7828 (start_point..end_point, empty_str.clone())
7829 })
7830 .sorted_by_key(|(range, _)| range.start)
7831 .collect::<Vec<_>>();
7832 buffer.update(cx, |this, cx| {
7833 this.edit(edits, None, cx);
7834 })
7835 }
7836 this.refresh_inline_completion(true, false, window, cx);
7837 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7838 });
7839 }
7840
7841 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7842 self.transact(window, cx, |this, window, cx| {
7843 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7844 let line_mode = s.line_mode;
7845 s.move_with(|map, selection| {
7846 if selection.is_empty() && !line_mode {
7847 let cursor = movement::right(map, selection.head());
7848 selection.end = cursor;
7849 selection.reversed = true;
7850 selection.goal = SelectionGoal::None;
7851 }
7852 })
7853 });
7854 this.insert("", window, cx);
7855 this.refresh_inline_completion(true, false, window, cx);
7856 });
7857 }
7858
7859 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7860 if self.move_to_prev_snippet_tabstop(window, cx) {
7861 return;
7862 }
7863
7864 self.outdent(&Outdent, window, cx);
7865 }
7866
7867 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7868 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7869 return;
7870 }
7871
7872 let mut selections = self.selections.all_adjusted(cx);
7873 let buffer = self.buffer.read(cx);
7874 let snapshot = buffer.snapshot(cx);
7875 let rows_iter = selections.iter().map(|s| s.head().row);
7876 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7877
7878 let mut edits = Vec::new();
7879 let mut prev_edited_row = 0;
7880 let mut row_delta = 0;
7881 for selection in &mut selections {
7882 if selection.start.row != prev_edited_row {
7883 row_delta = 0;
7884 }
7885 prev_edited_row = selection.end.row;
7886
7887 // If the selection is non-empty, then increase the indentation of the selected lines.
7888 if !selection.is_empty() {
7889 row_delta =
7890 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7891 continue;
7892 }
7893
7894 // If the selection is empty and the cursor is in the leading whitespace before the
7895 // suggested indentation, then auto-indent the line.
7896 let cursor = selection.head();
7897 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7898 if let Some(suggested_indent) =
7899 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7900 {
7901 if cursor.column < suggested_indent.len
7902 && cursor.column <= current_indent.len
7903 && current_indent.len <= suggested_indent.len
7904 {
7905 selection.start = Point::new(cursor.row, suggested_indent.len);
7906 selection.end = selection.start;
7907 if row_delta == 0 {
7908 edits.extend(Buffer::edit_for_indent_size_adjustment(
7909 cursor.row,
7910 current_indent,
7911 suggested_indent,
7912 ));
7913 row_delta = suggested_indent.len - current_indent.len;
7914 }
7915 continue;
7916 }
7917 }
7918
7919 // Otherwise, insert a hard or soft tab.
7920 let settings = buffer.language_settings_at(cursor, cx);
7921 let tab_size = if settings.hard_tabs {
7922 IndentSize::tab()
7923 } else {
7924 let tab_size = settings.tab_size.get();
7925 let char_column = snapshot
7926 .text_for_range(Point::new(cursor.row, 0)..cursor)
7927 .flat_map(str::chars)
7928 .count()
7929 + row_delta as usize;
7930 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7931 IndentSize::spaces(chars_to_next_tab_stop)
7932 };
7933 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7934 selection.end = selection.start;
7935 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7936 row_delta += tab_size.len;
7937 }
7938
7939 self.transact(window, cx, |this, window, cx| {
7940 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7941 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7942 s.select(selections)
7943 });
7944 this.refresh_inline_completion(true, false, window, cx);
7945 });
7946 }
7947
7948 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7949 if self.read_only(cx) {
7950 return;
7951 }
7952 let mut selections = self.selections.all::<Point>(cx);
7953 let mut prev_edited_row = 0;
7954 let mut row_delta = 0;
7955 let mut edits = Vec::new();
7956 let buffer = self.buffer.read(cx);
7957 let snapshot = buffer.snapshot(cx);
7958 for selection in &mut selections {
7959 if selection.start.row != prev_edited_row {
7960 row_delta = 0;
7961 }
7962 prev_edited_row = selection.end.row;
7963
7964 row_delta =
7965 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7966 }
7967
7968 self.transact(window, cx, |this, window, cx| {
7969 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7970 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7971 s.select(selections)
7972 });
7973 });
7974 }
7975
7976 fn indent_selection(
7977 buffer: &MultiBuffer,
7978 snapshot: &MultiBufferSnapshot,
7979 selection: &mut Selection<Point>,
7980 edits: &mut Vec<(Range<Point>, String)>,
7981 delta_for_start_row: u32,
7982 cx: &App,
7983 ) -> u32 {
7984 let settings = buffer.language_settings_at(selection.start, cx);
7985 let tab_size = settings.tab_size.get();
7986 let indent_kind = if settings.hard_tabs {
7987 IndentKind::Tab
7988 } else {
7989 IndentKind::Space
7990 };
7991 let mut start_row = selection.start.row;
7992 let mut end_row = selection.end.row + 1;
7993
7994 // If a selection ends at the beginning of a line, don't indent
7995 // that last line.
7996 if selection.end.column == 0 && selection.end.row > selection.start.row {
7997 end_row -= 1;
7998 }
7999
8000 // Avoid re-indenting a row that has already been indented by a
8001 // previous selection, but still update this selection's column
8002 // to reflect that indentation.
8003 if delta_for_start_row > 0 {
8004 start_row += 1;
8005 selection.start.column += delta_for_start_row;
8006 if selection.end.row == selection.start.row {
8007 selection.end.column += delta_for_start_row;
8008 }
8009 }
8010
8011 let mut delta_for_end_row = 0;
8012 let has_multiple_rows = start_row + 1 != end_row;
8013 for row in start_row..end_row {
8014 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8015 let indent_delta = match (current_indent.kind, indent_kind) {
8016 (IndentKind::Space, IndentKind::Space) => {
8017 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8018 IndentSize::spaces(columns_to_next_tab_stop)
8019 }
8020 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8021 (_, IndentKind::Tab) => IndentSize::tab(),
8022 };
8023
8024 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8025 0
8026 } else {
8027 selection.start.column
8028 };
8029 let row_start = Point::new(row, start);
8030 edits.push((
8031 row_start..row_start,
8032 indent_delta.chars().collect::<String>(),
8033 ));
8034
8035 // Update this selection's endpoints to reflect the indentation.
8036 if row == selection.start.row {
8037 selection.start.column += indent_delta.len;
8038 }
8039 if row == selection.end.row {
8040 selection.end.column += indent_delta.len;
8041 delta_for_end_row = indent_delta.len;
8042 }
8043 }
8044
8045 if selection.start.row == selection.end.row {
8046 delta_for_start_row + delta_for_end_row
8047 } else {
8048 delta_for_end_row
8049 }
8050 }
8051
8052 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8053 if self.read_only(cx) {
8054 return;
8055 }
8056 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8057 let selections = self.selections.all::<Point>(cx);
8058 let mut deletion_ranges = Vec::new();
8059 let mut last_outdent = None;
8060 {
8061 let buffer = self.buffer.read(cx);
8062 let snapshot = buffer.snapshot(cx);
8063 for selection in &selections {
8064 let settings = buffer.language_settings_at(selection.start, cx);
8065 let tab_size = settings.tab_size.get();
8066 let mut rows = selection.spanned_rows(false, &display_map);
8067
8068 // Avoid re-outdenting a row that has already been outdented by a
8069 // previous selection.
8070 if let Some(last_row) = last_outdent {
8071 if last_row == rows.start {
8072 rows.start = rows.start.next_row();
8073 }
8074 }
8075 let has_multiple_rows = rows.len() > 1;
8076 for row in rows.iter_rows() {
8077 let indent_size = snapshot.indent_size_for_line(row);
8078 if indent_size.len > 0 {
8079 let deletion_len = match indent_size.kind {
8080 IndentKind::Space => {
8081 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8082 if columns_to_prev_tab_stop == 0 {
8083 tab_size
8084 } else {
8085 columns_to_prev_tab_stop
8086 }
8087 }
8088 IndentKind::Tab => 1,
8089 };
8090 let start = if has_multiple_rows
8091 || deletion_len > selection.start.column
8092 || indent_size.len < selection.start.column
8093 {
8094 0
8095 } else {
8096 selection.start.column - deletion_len
8097 };
8098 deletion_ranges.push(
8099 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8100 );
8101 last_outdent = Some(row);
8102 }
8103 }
8104 }
8105 }
8106
8107 self.transact(window, cx, |this, window, cx| {
8108 this.buffer.update(cx, |buffer, cx| {
8109 let empty_str: Arc<str> = Arc::default();
8110 buffer.edit(
8111 deletion_ranges
8112 .into_iter()
8113 .map(|range| (range, empty_str.clone())),
8114 None,
8115 cx,
8116 );
8117 });
8118 let selections = this.selections.all::<usize>(cx);
8119 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8120 s.select(selections)
8121 });
8122 });
8123 }
8124
8125 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8126 if self.read_only(cx) {
8127 return;
8128 }
8129 let selections = self
8130 .selections
8131 .all::<usize>(cx)
8132 .into_iter()
8133 .map(|s| s.range());
8134
8135 self.transact(window, cx, |this, window, cx| {
8136 this.buffer.update(cx, |buffer, cx| {
8137 buffer.autoindent_ranges(selections, cx);
8138 });
8139 let selections = this.selections.all::<usize>(cx);
8140 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8141 s.select(selections)
8142 });
8143 });
8144 }
8145
8146 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8147 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8148 let selections = self.selections.all::<Point>(cx);
8149
8150 let mut new_cursors = Vec::new();
8151 let mut edit_ranges = Vec::new();
8152 let mut selections = selections.iter().peekable();
8153 while let Some(selection) = selections.next() {
8154 let mut rows = selection.spanned_rows(false, &display_map);
8155 let goal_display_column = selection.head().to_display_point(&display_map).column();
8156
8157 // Accumulate contiguous regions of rows that we want to delete.
8158 while let Some(next_selection) = selections.peek() {
8159 let next_rows = next_selection.spanned_rows(false, &display_map);
8160 if next_rows.start <= rows.end {
8161 rows.end = next_rows.end;
8162 selections.next().unwrap();
8163 } else {
8164 break;
8165 }
8166 }
8167
8168 let buffer = &display_map.buffer_snapshot;
8169 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8170 let edit_end;
8171 let cursor_buffer_row;
8172 if buffer.max_point().row >= rows.end.0 {
8173 // If there's a line after the range, delete the \n from the end of the row range
8174 // and position the cursor on the next line.
8175 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8176 cursor_buffer_row = rows.end;
8177 } else {
8178 // If there isn't a line after the range, delete the \n from the line before the
8179 // start of the row range and position the cursor there.
8180 edit_start = edit_start.saturating_sub(1);
8181 edit_end = buffer.len();
8182 cursor_buffer_row = rows.start.previous_row();
8183 }
8184
8185 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8186 *cursor.column_mut() =
8187 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8188
8189 new_cursors.push((
8190 selection.id,
8191 buffer.anchor_after(cursor.to_point(&display_map)),
8192 ));
8193 edit_ranges.push(edit_start..edit_end);
8194 }
8195
8196 self.transact(window, cx, |this, window, cx| {
8197 let buffer = this.buffer.update(cx, |buffer, cx| {
8198 let empty_str: Arc<str> = Arc::default();
8199 buffer.edit(
8200 edit_ranges
8201 .into_iter()
8202 .map(|range| (range, empty_str.clone())),
8203 None,
8204 cx,
8205 );
8206 buffer.snapshot(cx)
8207 });
8208 let new_selections = new_cursors
8209 .into_iter()
8210 .map(|(id, cursor)| {
8211 let cursor = cursor.to_point(&buffer);
8212 Selection {
8213 id,
8214 start: cursor,
8215 end: cursor,
8216 reversed: false,
8217 goal: SelectionGoal::None,
8218 }
8219 })
8220 .collect();
8221
8222 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8223 s.select(new_selections);
8224 });
8225 });
8226 }
8227
8228 pub fn join_lines_impl(
8229 &mut self,
8230 insert_whitespace: bool,
8231 window: &mut Window,
8232 cx: &mut Context<Self>,
8233 ) {
8234 if self.read_only(cx) {
8235 return;
8236 }
8237 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8238 for selection in self.selections.all::<Point>(cx) {
8239 let start = MultiBufferRow(selection.start.row);
8240 // Treat single line selections as if they include the next line. Otherwise this action
8241 // would do nothing for single line selections individual cursors.
8242 let end = if selection.start.row == selection.end.row {
8243 MultiBufferRow(selection.start.row + 1)
8244 } else {
8245 MultiBufferRow(selection.end.row)
8246 };
8247
8248 if let Some(last_row_range) = row_ranges.last_mut() {
8249 if start <= last_row_range.end {
8250 last_row_range.end = end;
8251 continue;
8252 }
8253 }
8254 row_ranges.push(start..end);
8255 }
8256
8257 let snapshot = self.buffer.read(cx).snapshot(cx);
8258 let mut cursor_positions = Vec::new();
8259 for row_range in &row_ranges {
8260 let anchor = snapshot.anchor_before(Point::new(
8261 row_range.end.previous_row().0,
8262 snapshot.line_len(row_range.end.previous_row()),
8263 ));
8264 cursor_positions.push(anchor..anchor);
8265 }
8266
8267 self.transact(window, cx, |this, window, cx| {
8268 for row_range in row_ranges.into_iter().rev() {
8269 for row in row_range.iter_rows().rev() {
8270 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8271 let next_line_row = row.next_row();
8272 let indent = snapshot.indent_size_for_line(next_line_row);
8273 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8274
8275 let replace =
8276 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8277 " "
8278 } else {
8279 ""
8280 };
8281
8282 this.buffer.update(cx, |buffer, cx| {
8283 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8284 });
8285 }
8286 }
8287
8288 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8289 s.select_anchor_ranges(cursor_positions)
8290 });
8291 });
8292 }
8293
8294 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8295 self.join_lines_impl(true, window, cx);
8296 }
8297
8298 pub fn sort_lines_case_sensitive(
8299 &mut self,
8300 _: &SortLinesCaseSensitive,
8301 window: &mut Window,
8302 cx: &mut Context<Self>,
8303 ) {
8304 self.manipulate_lines(window, cx, |lines| lines.sort())
8305 }
8306
8307 pub fn sort_lines_case_insensitive(
8308 &mut self,
8309 _: &SortLinesCaseInsensitive,
8310 window: &mut Window,
8311 cx: &mut Context<Self>,
8312 ) {
8313 self.manipulate_lines(window, cx, |lines| {
8314 lines.sort_by_key(|line| line.to_lowercase())
8315 })
8316 }
8317
8318 pub fn unique_lines_case_insensitive(
8319 &mut self,
8320 _: &UniqueLinesCaseInsensitive,
8321 window: &mut Window,
8322 cx: &mut Context<Self>,
8323 ) {
8324 self.manipulate_lines(window, cx, |lines| {
8325 let mut seen = HashSet::default();
8326 lines.retain(|line| seen.insert(line.to_lowercase()));
8327 })
8328 }
8329
8330 pub fn unique_lines_case_sensitive(
8331 &mut self,
8332 _: &UniqueLinesCaseSensitive,
8333 window: &mut Window,
8334 cx: &mut Context<Self>,
8335 ) {
8336 self.manipulate_lines(window, cx, |lines| {
8337 let mut seen = HashSet::default();
8338 lines.retain(|line| seen.insert(*line));
8339 })
8340 }
8341
8342 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8343 let Some(project) = self.project.clone() else {
8344 return;
8345 };
8346 self.reload(project, window, cx)
8347 .detach_and_notify_err(window, cx);
8348 }
8349
8350 pub fn restore_file(
8351 &mut self,
8352 _: &::git::RestoreFile,
8353 window: &mut Window,
8354 cx: &mut Context<Self>,
8355 ) {
8356 let mut buffer_ids = HashSet::default();
8357 let snapshot = self.buffer().read(cx).snapshot(cx);
8358 for selection in self.selections.all::<usize>(cx) {
8359 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8360 }
8361
8362 let buffer = self.buffer().read(cx);
8363 let ranges = buffer_ids
8364 .into_iter()
8365 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8366 .collect::<Vec<_>>();
8367
8368 self.restore_hunks_in_ranges(ranges, window, cx);
8369 }
8370
8371 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8372 let selections = self
8373 .selections
8374 .all(cx)
8375 .into_iter()
8376 .map(|s| s.range())
8377 .collect();
8378 self.restore_hunks_in_ranges(selections, window, cx);
8379 }
8380
8381 fn restore_hunks_in_ranges(
8382 &mut self,
8383 ranges: Vec<Range<Point>>,
8384 window: &mut Window,
8385 cx: &mut Context<Editor>,
8386 ) {
8387 let mut revert_changes = HashMap::default();
8388 let chunk_by = self
8389 .snapshot(window, cx)
8390 .hunks_for_ranges(ranges)
8391 .into_iter()
8392 .chunk_by(|hunk| hunk.buffer_id);
8393 for (buffer_id, hunks) in &chunk_by {
8394 let hunks = hunks.collect::<Vec<_>>();
8395 for hunk in &hunks {
8396 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8397 }
8398 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8399 }
8400 drop(chunk_by);
8401 if !revert_changes.is_empty() {
8402 self.transact(window, cx, |editor, window, cx| {
8403 editor.restore(revert_changes, window, cx);
8404 });
8405 }
8406 }
8407
8408 pub fn open_active_item_in_terminal(
8409 &mut self,
8410 _: &OpenInTerminal,
8411 window: &mut Window,
8412 cx: &mut Context<Self>,
8413 ) {
8414 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8415 let project_path = buffer.read(cx).project_path(cx)?;
8416 let project = self.project.as_ref()?.read(cx);
8417 let entry = project.entry_for_path(&project_path, cx)?;
8418 let parent = match &entry.canonical_path {
8419 Some(canonical_path) => canonical_path.to_path_buf(),
8420 None => project.absolute_path(&project_path, cx)?,
8421 }
8422 .parent()?
8423 .to_path_buf();
8424 Some(parent)
8425 }) {
8426 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8427 }
8428 }
8429
8430 fn set_breakpoint_context_menu(
8431 &mut self,
8432 row: DisplayRow,
8433 position: Option<Anchor>,
8434 kind: Arc<BreakpointKind>,
8435 clicked_point: gpui::Point<Pixels>,
8436 window: &mut Window,
8437 cx: &mut Context<Self>,
8438 ) {
8439 if !cx.has_flag::<Debugger>() {
8440 return;
8441 }
8442 let source = self
8443 .buffer
8444 .read(cx)
8445 .snapshot(cx)
8446 .anchor_before(Point::new(row.0, 0u32));
8447
8448 let context_menu =
8449 self.breakpoint_context_menu(position.unwrap_or(source), kind, window, cx);
8450
8451 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8452 self,
8453 source,
8454 clicked_point,
8455 context_menu,
8456 window,
8457 cx,
8458 );
8459 }
8460
8461 fn add_edit_breakpoint_block(
8462 &mut self,
8463 anchor: Anchor,
8464 kind: &BreakpointKind,
8465 window: &mut Window,
8466 cx: &mut Context<Self>,
8467 ) {
8468 let weak_editor = cx.weak_entity();
8469 let bp_prompt =
8470 cx.new(|cx| BreakpointPromptEditor::new(weak_editor, anchor, kind.clone(), window, cx));
8471
8472 let height = bp_prompt.update(cx, |this, cx| {
8473 this.prompt
8474 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8475 });
8476 let cloned_prompt = bp_prompt.clone();
8477 let blocks = vec![BlockProperties {
8478 style: BlockStyle::Sticky,
8479 placement: BlockPlacement::Above(anchor),
8480 height,
8481 render: Arc::new(move |cx| {
8482 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8483 cloned_prompt.clone().into_any_element()
8484 }),
8485 priority: 0,
8486 }];
8487
8488 let focus_handle = bp_prompt.focus_handle(cx);
8489 window.focus(&focus_handle);
8490
8491 let block_ids = self.insert_blocks(blocks, None, cx);
8492 bp_prompt.update(cx, |prompt, _| {
8493 prompt.add_block_ids(block_ids);
8494 });
8495 }
8496
8497 pub(crate) fn breakpoint_at_cursor_head(
8498 &self,
8499 window: &mut Window,
8500 cx: &mut Context<Self>,
8501 ) -> Option<(Anchor, Breakpoint)> {
8502 let cursor_position: Point = self.selections.newest(cx).head();
8503 let snapshot = self.snapshot(window, cx);
8504 // We Set the column position to zero so this function interacts correctly
8505 // between calls by clicking on the gutter & using an action to toggle a
8506 // breakpoint. Otherwise, toggling a breakpoint through an action wouldn't
8507 // untoggle a breakpoint that was added through clicking on the gutter
8508 let cursor_position = snapshot
8509 .display_snapshot
8510 .buffer_snapshot
8511 .anchor_before(Point::new(cursor_position.row, 0));
8512
8513 let project = self.project.clone();
8514
8515 let buffer_id = cursor_position.text_anchor.buffer_id?;
8516 let enclosing_excerpt = snapshot
8517 .buffer_snapshot
8518 .excerpt_ids_for_range(cursor_position..cursor_position)
8519 .next()?;
8520 let buffer = project?.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8521 let buffer_snapshot = buffer.read(cx).snapshot();
8522
8523 let row = buffer_snapshot
8524 .summary_for_anchor::<text::PointUtf16>(&cursor_position.text_anchor)
8525 .row;
8526
8527 let bp = self
8528 .breakpoint_store
8529 .as_ref()?
8530 .read_with(cx, |breakpoint_store, cx| {
8531 breakpoint_store
8532 .breakpoints(
8533 &buffer,
8534 Some(cursor_position.text_anchor..(text::Anchor::MAX)),
8535 buffer_snapshot.clone(),
8536 cx,
8537 )
8538 .next()
8539 .and_then(move |(anchor, bp)| {
8540 let breakpoint_row = buffer_snapshot
8541 .summary_for_anchor::<text::PointUtf16>(anchor)
8542 .row;
8543
8544 if breakpoint_row == row {
8545 snapshot
8546 .buffer_snapshot
8547 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8548 .map(|anchor| (anchor, bp.clone()))
8549 } else {
8550 None
8551 }
8552 })
8553 });
8554 bp
8555 }
8556
8557 pub fn edit_log_breakpoint(
8558 &mut self,
8559 _: &EditLogBreakpoint,
8560 window: &mut Window,
8561 cx: &mut Context<Self>,
8562 ) {
8563 let (anchor, bp) = self
8564 .breakpoint_at_cursor_head(window, cx)
8565 .unwrap_or_else(|| {
8566 let cursor_position: Point = self.selections.newest(cx).head();
8567
8568 let breakpoint_position = self
8569 .snapshot(window, cx)
8570 .display_snapshot
8571 .buffer_snapshot
8572 .anchor_before(Point::new(cursor_position.row, 0));
8573
8574 (
8575 breakpoint_position,
8576 Breakpoint {
8577 kind: BreakpointKind::Standard,
8578 },
8579 )
8580 });
8581
8582 self.add_edit_breakpoint_block(anchor, &bp.kind, window, cx);
8583 }
8584
8585 pub fn toggle_breakpoint(
8586 &mut self,
8587 _: &crate::actions::ToggleBreakpoint,
8588 window: &mut Window,
8589 cx: &mut Context<Self>,
8590 ) {
8591 let edit_action = BreakpointEditAction::Toggle;
8592
8593 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8594 self.edit_breakpoint_at_anchor(anchor, breakpoint.kind, edit_action, cx);
8595 } else {
8596 let cursor_position: Point = self.selections.newest(cx).head();
8597
8598 let breakpoint_position = self
8599 .snapshot(window, cx)
8600 .display_snapshot
8601 .buffer_snapshot
8602 .anchor_before(Point::new(cursor_position.row, 0));
8603
8604 self.edit_breakpoint_at_anchor(
8605 breakpoint_position,
8606 BreakpointKind::Standard,
8607 edit_action,
8608 cx,
8609 );
8610 }
8611 }
8612
8613 pub fn edit_breakpoint_at_anchor(
8614 &mut self,
8615 breakpoint_position: Anchor,
8616 kind: BreakpointKind,
8617 edit_action: BreakpointEditAction,
8618 cx: &mut Context<Self>,
8619 ) {
8620 let Some(breakpoint_store) = &self.breakpoint_store else {
8621 return;
8622 };
8623
8624 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8625 if breakpoint_position == Anchor::min() {
8626 self.buffer()
8627 .read(cx)
8628 .excerpt_buffer_ids()
8629 .into_iter()
8630 .next()
8631 } else {
8632 None
8633 }
8634 }) else {
8635 return;
8636 };
8637
8638 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8639 return;
8640 };
8641
8642 breakpoint_store.update(cx, |breakpoint_store, cx| {
8643 breakpoint_store.toggle_breakpoint(
8644 buffer,
8645 (breakpoint_position.text_anchor, Breakpoint { kind }),
8646 edit_action,
8647 cx,
8648 );
8649 });
8650
8651 cx.notify();
8652 }
8653
8654 #[cfg(any(test, feature = "test-support"))]
8655 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8656 self.breakpoint_store.clone()
8657 }
8658
8659 pub fn prepare_restore_change(
8660 &self,
8661 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8662 hunk: &MultiBufferDiffHunk,
8663 cx: &mut App,
8664 ) -> Option<()> {
8665 if hunk.is_created_file() {
8666 return None;
8667 }
8668 let buffer = self.buffer.read(cx);
8669 let diff = buffer.diff_for(hunk.buffer_id)?;
8670 let buffer = buffer.buffer(hunk.buffer_id)?;
8671 let buffer = buffer.read(cx);
8672 let original_text = diff
8673 .read(cx)
8674 .base_text()
8675 .as_rope()
8676 .slice(hunk.diff_base_byte_range.clone());
8677 let buffer_snapshot = buffer.snapshot();
8678 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8679 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8680 probe
8681 .0
8682 .start
8683 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8684 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8685 }) {
8686 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8687 Some(())
8688 } else {
8689 None
8690 }
8691 }
8692
8693 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8694 self.manipulate_lines(window, cx, |lines| lines.reverse())
8695 }
8696
8697 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8698 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8699 }
8700
8701 fn manipulate_lines<Fn>(
8702 &mut self,
8703 window: &mut Window,
8704 cx: &mut Context<Self>,
8705 mut callback: Fn,
8706 ) where
8707 Fn: FnMut(&mut Vec<&str>),
8708 {
8709 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8710 let buffer = self.buffer.read(cx).snapshot(cx);
8711
8712 let mut edits = Vec::new();
8713
8714 let selections = self.selections.all::<Point>(cx);
8715 let mut selections = selections.iter().peekable();
8716 let mut contiguous_row_selections = Vec::new();
8717 let mut new_selections = Vec::new();
8718 let mut added_lines = 0;
8719 let mut removed_lines = 0;
8720
8721 while let Some(selection) = selections.next() {
8722 let (start_row, end_row) = consume_contiguous_rows(
8723 &mut contiguous_row_selections,
8724 selection,
8725 &display_map,
8726 &mut selections,
8727 );
8728
8729 let start_point = Point::new(start_row.0, 0);
8730 let end_point = Point::new(
8731 end_row.previous_row().0,
8732 buffer.line_len(end_row.previous_row()),
8733 );
8734 let text = buffer
8735 .text_for_range(start_point..end_point)
8736 .collect::<String>();
8737
8738 let mut lines = text.split('\n').collect_vec();
8739
8740 let lines_before = lines.len();
8741 callback(&mut lines);
8742 let lines_after = lines.len();
8743
8744 edits.push((start_point..end_point, lines.join("\n")));
8745
8746 // Selections must change based on added and removed line count
8747 let start_row =
8748 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8749 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8750 new_selections.push(Selection {
8751 id: selection.id,
8752 start: start_row,
8753 end: end_row,
8754 goal: SelectionGoal::None,
8755 reversed: selection.reversed,
8756 });
8757
8758 if lines_after > lines_before {
8759 added_lines += lines_after - lines_before;
8760 } else if lines_before > lines_after {
8761 removed_lines += lines_before - lines_after;
8762 }
8763 }
8764
8765 self.transact(window, cx, |this, window, cx| {
8766 let buffer = this.buffer.update(cx, |buffer, cx| {
8767 buffer.edit(edits, None, cx);
8768 buffer.snapshot(cx)
8769 });
8770
8771 // Recalculate offsets on newly edited buffer
8772 let new_selections = new_selections
8773 .iter()
8774 .map(|s| {
8775 let start_point = Point::new(s.start.0, 0);
8776 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8777 Selection {
8778 id: s.id,
8779 start: buffer.point_to_offset(start_point),
8780 end: buffer.point_to_offset(end_point),
8781 goal: s.goal,
8782 reversed: s.reversed,
8783 }
8784 })
8785 .collect();
8786
8787 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8788 s.select(new_selections);
8789 });
8790
8791 this.request_autoscroll(Autoscroll::fit(), cx);
8792 });
8793 }
8794
8795 pub fn convert_to_upper_case(
8796 &mut self,
8797 _: &ConvertToUpperCase,
8798 window: &mut Window,
8799 cx: &mut Context<Self>,
8800 ) {
8801 self.manipulate_text(window, cx, |text| text.to_uppercase())
8802 }
8803
8804 pub fn convert_to_lower_case(
8805 &mut self,
8806 _: &ConvertToLowerCase,
8807 window: &mut Window,
8808 cx: &mut Context<Self>,
8809 ) {
8810 self.manipulate_text(window, cx, |text| text.to_lowercase())
8811 }
8812
8813 pub fn convert_to_title_case(
8814 &mut self,
8815 _: &ConvertToTitleCase,
8816 window: &mut Window,
8817 cx: &mut Context<Self>,
8818 ) {
8819 self.manipulate_text(window, cx, |text| {
8820 text.split('\n')
8821 .map(|line| line.to_case(Case::Title))
8822 .join("\n")
8823 })
8824 }
8825
8826 pub fn convert_to_snake_case(
8827 &mut self,
8828 _: &ConvertToSnakeCase,
8829 window: &mut Window,
8830 cx: &mut Context<Self>,
8831 ) {
8832 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8833 }
8834
8835 pub fn convert_to_kebab_case(
8836 &mut self,
8837 _: &ConvertToKebabCase,
8838 window: &mut Window,
8839 cx: &mut Context<Self>,
8840 ) {
8841 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8842 }
8843
8844 pub fn convert_to_upper_camel_case(
8845 &mut self,
8846 _: &ConvertToUpperCamelCase,
8847 window: &mut Window,
8848 cx: &mut Context<Self>,
8849 ) {
8850 self.manipulate_text(window, cx, |text| {
8851 text.split('\n')
8852 .map(|line| line.to_case(Case::UpperCamel))
8853 .join("\n")
8854 })
8855 }
8856
8857 pub fn convert_to_lower_camel_case(
8858 &mut self,
8859 _: &ConvertToLowerCamelCase,
8860 window: &mut Window,
8861 cx: &mut Context<Self>,
8862 ) {
8863 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8864 }
8865
8866 pub fn convert_to_opposite_case(
8867 &mut self,
8868 _: &ConvertToOppositeCase,
8869 window: &mut Window,
8870 cx: &mut Context<Self>,
8871 ) {
8872 self.manipulate_text(window, cx, |text| {
8873 text.chars()
8874 .fold(String::with_capacity(text.len()), |mut t, c| {
8875 if c.is_uppercase() {
8876 t.extend(c.to_lowercase());
8877 } else {
8878 t.extend(c.to_uppercase());
8879 }
8880 t
8881 })
8882 })
8883 }
8884
8885 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8886 where
8887 Fn: FnMut(&str) -> String,
8888 {
8889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8890 let buffer = self.buffer.read(cx).snapshot(cx);
8891
8892 let mut new_selections = Vec::new();
8893 let mut edits = Vec::new();
8894 let mut selection_adjustment = 0i32;
8895
8896 for selection in self.selections.all::<usize>(cx) {
8897 let selection_is_empty = selection.is_empty();
8898
8899 let (start, end) = if selection_is_empty {
8900 let word_range = movement::surrounding_word(
8901 &display_map,
8902 selection.start.to_display_point(&display_map),
8903 );
8904 let start = word_range.start.to_offset(&display_map, Bias::Left);
8905 let end = word_range.end.to_offset(&display_map, Bias::Left);
8906 (start, end)
8907 } else {
8908 (selection.start, selection.end)
8909 };
8910
8911 let text = buffer.text_for_range(start..end).collect::<String>();
8912 let old_length = text.len() as i32;
8913 let text = callback(&text);
8914
8915 new_selections.push(Selection {
8916 start: (start as i32 - selection_adjustment) as usize,
8917 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8918 goal: SelectionGoal::None,
8919 ..selection
8920 });
8921
8922 selection_adjustment += old_length - text.len() as i32;
8923
8924 edits.push((start..end, text));
8925 }
8926
8927 self.transact(window, cx, |this, window, cx| {
8928 this.buffer.update(cx, |buffer, cx| {
8929 buffer.edit(edits, None, cx);
8930 });
8931
8932 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8933 s.select(new_selections);
8934 });
8935
8936 this.request_autoscroll(Autoscroll::fit(), cx);
8937 });
8938 }
8939
8940 pub fn duplicate(
8941 &mut self,
8942 upwards: bool,
8943 whole_lines: bool,
8944 window: &mut Window,
8945 cx: &mut Context<Self>,
8946 ) {
8947 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8948 let buffer = &display_map.buffer_snapshot;
8949 let selections = self.selections.all::<Point>(cx);
8950
8951 let mut edits = Vec::new();
8952 let mut selections_iter = selections.iter().peekable();
8953 while let Some(selection) = selections_iter.next() {
8954 let mut rows = selection.spanned_rows(false, &display_map);
8955 // duplicate line-wise
8956 if whole_lines || selection.start == selection.end {
8957 // Avoid duplicating the same lines twice.
8958 while let Some(next_selection) = selections_iter.peek() {
8959 let next_rows = next_selection.spanned_rows(false, &display_map);
8960 if next_rows.start < rows.end {
8961 rows.end = next_rows.end;
8962 selections_iter.next().unwrap();
8963 } else {
8964 break;
8965 }
8966 }
8967
8968 // Copy the text from the selected row region and splice it either at the start
8969 // or end of the region.
8970 let start = Point::new(rows.start.0, 0);
8971 let end = Point::new(
8972 rows.end.previous_row().0,
8973 buffer.line_len(rows.end.previous_row()),
8974 );
8975 let text = buffer
8976 .text_for_range(start..end)
8977 .chain(Some("\n"))
8978 .collect::<String>();
8979 let insert_location = if upwards {
8980 Point::new(rows.end.0, 0)
8981 } else {
8982 start
8983 };
8984 edits.push((insert_location..insert_location, text));
8985 } else {
8986 // duplicate character-wise
8987 let start = selection.start;
8988 let end = selection.end;
8989 let text = buffer.text_for_range(start..end).collect::<String>();
8990 edits.push((selection.end..selection.end, text));
8991 }
8992 }
8993
8994 self.transact(window, cx, |this, _, cx| {
8995 this.buffer.update(cx, |buffer, cx| {
8996 buffer.edit(edits, None, cx);
8997 });
8998
8999 this.request_autoscroll(Autoscroll::fit(), cx);
9000 });
9001 }
9002
9003 pub fn duplicate_line_up(
9004 &mut self,
9005 _: &DuplicateLineUp,
9006 window: &mut Window,
9007 cx: &mut Context<Self>,
9008 ) {
9009 self.duplicate(true, true, window, cx);
9010 }
9011
9012 pub fn duplicate_line_down(
9013 &mut self,
9014 _: &DuplicateLineDown,
9015 window: &mut Window,
9016 cx: &mut Context<Self>,
9017 ) {
9018 self.duplicate(false, true, window, cx);
9019 }
9020
9021 pub fn duplicate_selection(
9022 &mut self,
9023 _: &DuplicateSelection,
9024 window: &mut Window,
9025 cx: &mut Context<Self>,
9026 ) {
9027 self.duplicate(false, false, window, cx);
9028 }
9029
9030 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9031 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9032 let buffer = self.buffer.read(cx).snapshot(cx);
9033
9034 let mut edits = Vec::new();
9035 let mut unfold_ranges = Vec::new();
9036 let mut refold_creases = Vec::new();
9037
9038 let selections = self.selections.all::<Point>(cx);
9039 let mut selections = selections.iter().peekable();
9040 let mut contiguous_row_selections = Vec::new();
9041 let mut new_selections = Vec::new();
9042
9043 while let Some(selection) = selections.next() {
9044 // Find all the selections that span a contiguous row range
9045 let (start_row, end_row) = consume_contiguous_rows(
9046 &mut contiguous_row_selections,
9047 selection,
9048 &display_map,
9049 &mut selections,
9050 );
9051
9052 // Move the text spanned by the row range to be before the line preceding the row range
9053 if start_row.0 > 0 {
9054 let range_to_move = Point::new(
9055 start_row.previous_row().0,
9056 buffer.line_len(start_row.previous_row()),
9057 )
9058 ..Point::new(
9059 end_row.previous_row().0,
9060 buffer.line_len(end_row.previous_row()),
9061 );
9062 let insertion_point = display_map
9063 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9064 .0;
9065
9066 // Don't move lines across excerpts
9067 if buffer
9068 .excerpt_containing(insertion_point..range_to_move.end)
9069 .is_some()
9070 {
9071 let text = buffer
9072 .text_for_range(range_to_move.clone())
9073 .flat_map(|s| s.chars())
9074 .skip(1)
9075 .chain(['\n'])
9076 .collect::<String>();
9077
9078 edits.push((
9079 buffer.anchor_after(range_to_move.start)
9080 ..buffer.anchor_before(range_to_move.end),
9081 String::new(),
9082 ));
9083 let insertion_anchor = buffer.anchor_after(insertion_point);
9084 edits.push((insertion_anchor..insertion_anchor, text));
9085
9086 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9087
9088 // Move selections up
9089 new_selections.extend(contiguous_row_selections.drain(..).map(
9090 |mut selection| {
9091 selection.start.row -= row_delta;
9092 selection.end.row -= row_delta;
9093 selection
9094 },
9095 ));
9096
9097 // Move folds up
9098 unfold_ranges.push(range_to_move.clone());
9099 for fold in display_map.folds_in_range(
9100 buffer.anchor_before(range_to_move.start)
9101 ..buffer.anchor_after(range_to_move.end),
9102 ) {
9103 let mut start = fold.range.start.to_point(&buffer);
9104 let mut end = fold.range.end.to_point(&buffer);
9105 start.row -= row_delta;
9106 end.row -= row_delta;
9107 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9108 }
9109 }
9110 }
9111
9112 // If we didn't move line(s), preserve the existing selections
9113 new_selections.append(&mut contiguous_row_selections);
9114 }
9115
9116 self.transact(window, cx, |this, window, cx| {
9117 this.unfold_ranges(&unfold_ranges, true, true, cx);
9118 this.buffer.update(cx, |buffer, cx| {
9119 for (range, text) in edits {
9120 buffer.edit([(range, text)], None, cx);
9121 }
9122 });
9123 this.fold_creases(refold_creases, true, window, cx);
9124 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9125 s.select(new_selections);
9126 })
9127 });
9128 }
9129
9130 pub fn move_line_down(
9131 &mut self,
9132 _: &MoveLineDown,
9133 window: &mut Window,
9134 cx: &mut Context<Self>,
9135 ) {
9136 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9137 let buffer = self.buffer.read(cx).snapshot(cx);
9138
9139 let mut edits = Vec::new();
9140 let mut unfold_ranges = Vec::new();
9141 let mut refold_creases = Vec::new();
9142
9143 let selections = self.selections.all::<Point>(cx);
9144 let mut selections = selections.iter().peekable();
9145 let mut contiguous_row_selections = Vec::new();
9146 let mut new_selections = Vec::new();
9147
9148 while let Some(selection) = selections.next() {
9149 // Find all the selections that span a contiguous row range
9150 let (start_row, end_row) = consume_contiguous_rows(
9151 &mut contiguous_row_selections,
9152 selection,
9153 &display_map,
9154 &mut selections,
9155 );
9156
9157 // Move the text spanned by the row range to be after the last line of the row range
9158 if end_row.0 <= buffer.max_point().row {
9159 let range_to_move =
9160 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9161 let insertion_point = display_map
9162 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9163 .0;
9164
9165 // Don't move lines across excerpt boundaries
9166 if buffer
9167 .excerpt_containing(range_to_move.start..insertion_point)
9168 .is_some()
9169 {
9170 let mut text = String::from("\n");
9171 text.extend(buffer.text_for_range(range_to_move.clone()));
9172 text.pop(); // Drop trailing newline
9173 edits.push((
9174 buffer.anchor_after(range_to_move.start)
9175 ..buffer.anchor_before(range_to_move.end),
9176 String::new(),
9177 ));
9178 let insertion_anchor = buffer.anchor_after(insertion_point);
9179 edits.push((insertion_anchor..insertion_anchor, text));
9180
9181 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9182
9183 // Move selections down
9184 new_selections.extend(contiguous_row_selections.drain(..).map(
9185 |mut selection| {
9186 selection.start.row += row_delta;
9187 selection.end.row += row_delta;
9188 selection
9189 },
9190 ));
9191
9192 // Move folds down
9193 unfold_ranges.push(range_to_move.clone());
9194 for fold in display_map.folds_in_range(
9195 buffer.anchor_before(range_to_move.start)
9196 ..buffer.anchor_after(range_to_move.end),
9197 ) {
9198 let mut start = fold.range.start.to_point(&buffer);
9199 let mut end = fold.range.end.to_point(&buffer);
9200 start.row += row_delta;
9201 end.row += row_delta;
9202 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9203 }
9204 }
9205 }
9206
9207 // If we didn't move line(s), preserve the existing selections
9208 new_selections.append(&mut contiguous_row_selections);
9209 }
9210
9211 self.transact(window, cx, |this, window, cx| {
9212 this.unfold_ranges(&unfold_ranges, true, true, cx);
9213 this.buffer.update(cx, |buffer, cx| {
9214 for (range, text) in edits {
9215 buffer.edit([(range, text)], None, cx);
9216 }
9217 });
9218 this.fold_creases(refold_creases, true, window, cx);
9219 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9220 s.select(new_selections)
9221 });
9222 });
9223 }
9224
9225 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9226 let text_layout_details = &self.text_layout_details(window);
9227 self.transact(window, cx, |this, window, cx| {
9228 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9229 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9230 let line_mode = s.line_mode;
9231 s.move_with(|display_map, selection| {
9232 if !selection.is_empty() || line_mode {
9233 return;
9234 }
9235
9236 let mut head = selection.head();
9237 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9238 if head.column() == display_map.line_len(head.row()) {
9239 transpose_offset = display_map
9240 .buffer_snapshot
9241 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9242 }
9243
9244 if transpose_offset == 0 {
9245 return;
9246 }
9247
9248 *head.column_mut() += 1;
9249 head = display_map.clip_point(head, Bias::Right);
9250 let goal = SelectionGoal::HorizontalPosition(
9251 display_map
9252 .x_for_display_point(head, text_layout_details)
9253 .into(),
9254 );
9255 selection.collapse_to(head, goal);
9256
9257 let transpose_start = display_map
9258 .buffer_snapshot
9259 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9260 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9261 let transpose_end = display_map
9262 .buffer_snapshot
9263 .clip_offset(transpose_offset + 1, Bias::Right);
9264 if let Some(ch) =
9265 display_map.buffer_snapshot.chars_at(transpose_start).next()
9266 {
9267 edits.push((transpose_start..transpose_offset, String::new()));
9268 edits.push((transpose_end..transpose_end, ch.to_string()));
9269 }
9270 }
9271 });
9272 edits
9273 });
9274 this.buffer
9275 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9276 let selections = this.selections.all::<usize>(cx);
9277 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9278 s.select(selections);
9279 });
9280 });
9281 }
9282
9283 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9284 self.rewrap_impl(RewrapOptions::default(), cx)
9285 }
9286
9287 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9288 let buffer = self.buffer.read(cx).snapshot(cx);
9289 let selections = self.selections.all::<Point>(cx);
9290 let mut selections = selections.iter().peekable();
9291
9292 let mut edits = Vec::new();
9293 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9294
9295 while let Some(selection) = selections.next() {
9296 let mut start_row = selection.start.row;
9297 let mut end_row = selection.end.row;
9298
9299 // Skip selections that overlap with a range that has already been rewrapped.
9300 let selection_range = start_row..end_row;
9301 if rewrapped_row_ranges
9302 .iter()
9303 .any(|range| range.overlaps(&selection_range))
9304 {
9305 continue;
9306 }
9307
9308 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9309
9310 // Since not all lines in the selection may be at the same indent
9311 // level, choose the indent size that is the most common between all
9312 // of the lines.
9313 //
9314 // If there is a tie, we use the deepest indent.
9315 let (indent_size, indent_end) = {
9316 let mut indent_size_occurrences = HashMap::default();
9317 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9318
9319 for row in start_row..=end_row {
9320 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9321 rows_by_indent_size.entry(indent).or_default().push(row);
9322 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9323 }
9324
9325 let indent_size = indent_size_occurrences
9326 .into_iter()
9327 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9328 .map(|(indent, _)| indent)
9329 .unwrap_or_default();
9330 let row = rows_by_indent_size[&indent_size][0];
9331 let indent_end = Point::new(row, indent_size.len);
9332
9333 (indent_size, indent_end)
9334 };
9335
9336 let mut line_prefix = indent_size.chars().collect::<String>();
9337
9338 let mut inside_comment = false;
9339 if let Some(comment_prefix) =
9340 buffer
9341 .language_scope_at(selection.head())
9342 .and_then(|language| {
9343 language
9344 .line_comment_prefixes()
9345 .iter()
9346 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9347 .cloned()
9348 })
9349 {
9350 line_prefix.push_str(&comment_prefix);
9351 inside_comment = true;
9352 }
9353
9354 let language_settings = buffer.language_settings_at(selection.head(), cx);
9355 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9356 RewrapBehavior::InComments => inside_comment,
9357 RewrapBehavior::InSelections => !selection.is_empty(),
9358 RewrapBehavior::Anywhere => true,
9359 };
9360
9361 let should_rewrap = options.override_language_settings
9362 || allow_rewrap_based_on_language
9363 || self.hard_wrap.is_some();
9364 if !should_rewrap {
9365 continue;
9366 }
9367
9368 if selection.is_empty() {
9369 'expand_upwards: while start_row > 0 {
9370 let prev_row = start_row - 1;
9371 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9372 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9373 {
9374 start_row = prev_row;
9375 } else {
9376 break 'expand_upwards;
9377 }
9378 }
9379
9380 'expand_downwards: while end_row < buffer.max_point().row {
9381 let next_row = end_row + 1;
9382 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9383 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9384 {
9385 end_row = next_row;
9386 } else {
9387 break 'expand_downwards;
9388 }
9389 }
9390 }
9391
9392 let start = Point::new(start_row, 0);
9393 let start_offset = start.to_offset(&buffer);
9394 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9395 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9396 let Some(lines_without_prefixes) = selection_text
9397 .lines()
9398 .map(|line| {
9399 line.strip_prefix(&line_prefix)
9400 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9401 .ok_or_else(|| {
9402 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9403 })
9404 })
9405 .collect::<Result<Vec<_>, _>>()
9406 .log_err()
9407 else {
9408 continue;
9409 };
9410
9411 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9412 buffer
9413 .language_settings_at(Point::new(start_row, 0), cx)
9414 .preferred_line_length as usize
9415 });
9416 let wrapped_text = wrap_with_prefix(
9417 line_prefix,
9418 lines_without_prefixes.join("\n"),
9419 wrap_column,
9420 tab_size,
9421 options.preserve_existing_whitespace,
9422 );
9423
9424 // TODO: should always use char-based diff while still supporting cursor behavior that
9425 // matches vim.
9426 let mut diff_options = DiffOptions::default();
9427 if options.override_language_settings {
9428 diff_options.max_word_diff_len = 0;
9429 diff_options.max_word_diff_line_count = 0;
9430 } else {
9431 diff_options.max_word_diff_len = usize::MAX;
9432 diff_options.max_word_diff_line_count = usize::MAX;
9433 }
9434
9435 for (old_range, new_text) in
9436 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9437 {
9438 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9439 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9440 edits.push((edit_start..edit_end, new_text));
9441 }
9442
9443 rewrapped_row_ranges.push(start_row..=end_row);
9444 }
9445
9446 self.buffer
9447 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9448 }
9449
9450 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9451 let mut text = String::new();
9452 let buffer = self.buffer.read(cx).snapshot(cx);
9453 let mut selections = self.selections.all::<Point>(cx);
9454 let mut clipboard_selections = Vec::with_capacity(selections.len());
9455 {
9456 let max_point = buffer.max_point();
9457 let mut is_first = true;
9458 for selection in &mut selections {
9459 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9460 if is_entire_line {
9461 selection.start = Point::new(selection.start.row, 0);
9462 if !selection.is_empty() && selection.end.column == 0 {
9463 selection.end = cmp::min(max_point, selection.end);
9464 } else {
9465 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9466 }
9467 selection.goal = SelectionGoal::None;
9468 }
9469 if is_first {
9470 is_first = false;
9471 } else {
9472 text += "\n";
9473 }
9474 let mut len = 0;
9475 for chunk in buffer.text_for_range(selection.start..selection.end) {
9476 text.push_str(chunk);
9477 len += chunk.len();
9478 }
9479 clipboard_selections.push(ClipboardSelection {
9480 len,
9481 is_entire_line,
9482 first_line_indent: buffer
9483 .indent_size_for_line(MultiBufferRow(selection.start.row))
9484 .len,
9485 });
9486 }
9487 }
9488
9489 self.transact(window, cx, |this, window, cx| {
9490 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9491 s.select(selections);
9492 });
9493 this.insert("", window, cx);
9494 });
9495 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9496 }
9497
9498 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9499 let item = self.cut_common(window, cx);
9500 cx.write_to_clipboard(item);
9501 }
9502
9503 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9504 self.change_selections(None, window, cx, |s| {
9505 s.move_with(|snapshot, sel| {
9506 if sel.is_empty() {
9507 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9508 }
9509 });
9510 });
9511 let item = self.cut_common(window, cx);
9512 cx.set_global(KillRing(item))
9513 }
9514
9515 pub fn kill_ring_yank(
9516 &mut self,
9517 _: &KillRingYank,
9518 window: &mut Window,
9519 cx: &mut Context<Self>,
9520 ) {
9521 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9522 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9523 (kill_ring.text().to_string(), kill_ring.metadata_json())
9524 } else {
9525 return;
9526 }
9527 } else {
9528 return;
9529 };
9530 self.do_paste(&text, metadata, false, window, cx);
9531 }
9532
9533 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9534 self.do_copy(true, cx);
9535 }
9536
9537 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9538 self.do_copy(false, cx);
9539 }
9540
9541 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9542 let selections = self.selections.all::<Point>(cx);
9543 let buffer = self.buffer.read(cx).read(cx);
9544 let mut text = String::new();
9545
9546 let mut clipboard_selections = Vec::with_capacity(selections.len());
9547 {
9548 let max_point = buffer.max_point();
9549 let mut is_first = true;
9550 for selection in &selections {
9551 let mut start = selection.start;
9552 let mut end = selection.end;
9553 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9554 if is_entire_line {
9555 start = Point::new(start.row, 0);
9556 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9557 }
9558
9559 let mut trimmed_selections = Vec::new();
9560 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9561 let row = MultiBufferRow(start.row);
9562 let first_indent = buffer.indent_size_for_line(row);
9563 if first_indent.len == 0 || start.column > first_indent.len {
9564 trimmed_selections.push(start..end);
9565 } else {
9566 trimmed_selections.push(
9567 Point::new(row.0, first_indent.len)
9568 ..Point::new(row.0, buffer.line_len(row)),
9569 );
9570 for row in start.row + 1..=end.row {
9571 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9572 if row_indent_size.len >= first_indent.len {
9573 trimmed_selections.push(
9574 Point::new(row, first_indent.len)
9575 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9576 );
9577 } else {
9578 trimmed_selections.clear();
9579 trimmed_selections.push(start..end);
9580 break;
9581 }
9582 }
9583 }
9584 } else {
9585 trimmed_selections.push(start..end);
9586 }
9587
9588 for trimmed_range in trimmed_selections {
9589 if is_first {
9590 is_first = false;
9591 } else {
9592 text += "\n";
9593 }
9594 let mut len = 0;
9595 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9596 text.push_str(chunk);
9597 len += chunk.len();
9598 }
9599 clipboard_selections.push(ClipboardSelection {
9600 len,
9601 is_entire_line,
9602 first_line_indent: buffer
9603 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9604 .len,
9605 });
9606 }
9607 }
9608 }
9609
9610 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9611 text,
9612 clipboard_selections,
9613 ));
9614 }
9615
9616 pub fn do_paste(
9617 &mut self,
9618 text: &String,
9619 clipboard_selections: Option<Vec<ClipboardSelection>>,
9620 handle_entire_lines: bool,
9621 window: &mut Window,
9622 cx: &mut Context<Self>,
9623 ) {
9624 if self.read_only(cx) {
9625 return;
9626 }
9627
9628 let clipboard_text = Cow::Borrowed(text);
9629
9630 self.transact(window, cx, |this, window, cx| {
9631 if let Some(mut clipboard_selections) = clipboard_selections {
9632 let old_selections = this.selections.all::<usize>(cx);
9633 let all_selections_were_entire_line =
9634 clipboard_selections.iter().all(|s| s.is_entire_line);
9635 let first_selection_indent_column =
9636 clipboard_selections.first().map(|s| s.first_line_indent);
9637 if clipboard_selections.len() != old_selections.len() {
9638 clipboard_selections.drain(..);
9639 }
9640 let cursor_offset = this.selections.last::<usize>(cx).head();
9641 let mut auto_indent_on_paste = true;
9642
9643 this.buffer.update(cx, |buffer, cx| {
9644 let snapshot = buffer.read(cx);
9645 auto_indent_on_paste = snapshot
9646 .language_settings_at(cursor_offset, cx)
9647 .auto_indent_on_paste;
9648
9649 let mut start_offset = 0;
9650 let mut edits = Vec::new();
9651 let mut original_indent_columns = Vec::new();
9652 for (ix, selection) in old_selections.iter().enumerate() {
9653 let to_insert;
9654 let entire_line;
9655 let original_indent_column;
9656 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
9657 let end_offset = start_offset + clipboard_selection.len;
9658 to_insert = &clipboard_text[start_offset..end_offset];
9659 entire_line = clipboard_selection.is_entire_line;
9660 start_offset = end_offset + 1;
9661 original_indent_column = Some(clipboard_selection.first_line_indent);
9662 } else {
9663 to_insert = clipboard_text.as_str();
9664 entire_line = all_selections_were_entire_line;
9665 original_indent_column = first_selection_indent_column
9666 }
9667
9668 // If the corresponding selection was empty when this slice of the
9669 // clipboard text was written, then the entire line containing the
9670 // selection was copied. If this selection is also currently empty,
9671 // then paste the line before the current line of the buffer.
9672 let range = if selection.is_empty() && handle_entire_lines && entire_line {
9673 let column = selection.start.to_point(&snapshot).column as usize;
9674 let line_start = selection.start - column;
9675 line_start..line_start
9676 } else {
9677 selection.range()
9678 };
9679
9680 edits.push((range, to_insert));
9681 original_indent_columns.push(original_indent_column);
9682 }
9683 drop(snapshot);
9684
9685 buffer.edit(
9686 edits,
9687 if auto_indent_on_paste {
9688 Some(AutoindentMode::Block {
9689 original_indent_columns,
9690 })
9691 } else {
9692 None
9693 },
9694 cx,
9695 );
9696 });
9697
9698 let selections = this.selections.all::<usize>(cx);
9699 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9700 s.select(selections)
9701 });
9702 } else {
9703 this.insert(&clipboard_text, window, cx);
9704 }
9705 });
9706 }
9707
9708 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
9709 if let Some(item) = cx.read_from_clipboard() {
9710 let entries = item.entries();
9711
9712 match entries.first() {
9713 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
9714 // of all the pasted entries.
9715 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9716 .do_paste(
9717 clipboard_string.text(),
9718 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9719 true,
9720 window,
9721 cx,
9722 ),
9723 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9724 }
9725 }
9726 }
9727
9728 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9729 if self.read_only(cx) {
9730 return;
9731 }
9732
9733 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9734 if let Some((selections, _)) =
9735 self.selection_history.transaction(transaction_id).cloned()
9736 {
9737 self.change_selections(None, window, cx, |s| {
9738 s.select_anchors(selections.to_vec());
9739 });
9740 } else {
9741 log::error!(
9742 "No entry in selection_history found for undo. \
9743 This may correspond to a bug where undo does not update the selection. \
9744 If this is occurring, please add details to \
9745 https://github.com/zed-industries/zed/issues/22692"
9746 );
9747 }
9748 self.request_autoscroll(Autoscroll::fit(), cx);
9749 self.unmark_text(window, cx);
9750 self.refresh_inline_completion(true, false, window, cx);
9751 cx.emit(EditorEvent::Edited { transaction_id });
9752 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9753 }
9754 }
9755
9756 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9757 if self.read_only(cx) {
9758 return;
9759 }
9760
9761 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9762 if let Some((_, Some(selections))) =
9763 self.selection_history.transaction(transaction_id).cloned()
9764 {
9765 self.change_selections(None, window, cx, |s| {
9766 s.select_anchors(selections.to_vec());
9767 });
9768 } else {
9769 log::error!(
9770 "No entry in selection_history found for redo. \
9771 This may correspond to a bug where undo does not update the selection. \
9772 If this is occurring, please add details to \
9773 https://github.com/zed-industries/zed/issues/22692"
9774 );
9775 }
9776 self.request_autoscroll(Autoscroll::fit(), cx);
9777 self.unmark_text(window, cx);
9778 self.refresh_inline_completion(true, false, window, cx);
9779 cx.emit(EditorEvent::Edited { transaction_id });
9780 }
9781 }
9782
9783 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9784 self.buffer
9785 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9786 }
9787
9788 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9789 self.buffer
9790 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9791 }
9792
9793 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9794 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9795 let line_mode = s.line_mode;
9796 s.move_with(|map, selection| {
9797 let cursor = if selection.is_empty() && !line_mode {
9798 movement::left(map, selection.start)
9799 } else {
9800 selection.start
9801 };
9802 selection.collapse_to(cursor, SelectionGoal::None);
9803 });
9804 })
9805 }
9806
9807 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9808 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9809 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9810 })
9811 }
9812
9813 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9814 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9815 let line_mode = s.line_mode;
9816 s.move_with(|map, selection| {
9817 let cursor = if selection.is_empty() && !line_mode {
9818 movement::right(map, selection.end)
9819 } else {
9820 selection.end
9821 };
9822 selection.collapse_to(cursor, SelectionGoal::None)
9823 });
9824 })
9825 }
9826
9827 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9828 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9829 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9830 })
9831 }
9832
9833 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9834 if self.take_rename(true, window, cx).is_some() {
9835 return;
9836 }
9837
9838 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9839 cx.propagate();
9840 return;
9841 }
9842
9843 let text_layout_details = &self.text_layout_details(window);
9844 let selection_count = self.selections.count();
9845 let first_selection = self.selections.first_anchor();
9846
9847 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9848 let line_mode = s.line_mode;
9849 s.move_with(|map, selection| {
9850 if !selection.is_empty() && !line_mode {
9851 selection.goal = SelectionGoal::None;
9852 }
9853 let (cursor, goal) = movement::up(
9854 map,
9855 selection.start,
9856 selection.goal,
9857 false,
9858 text_layout_details,
9859 );
9860 selection.collapse_to(cursor, goal);
9861 });
9862 });
9863
9864 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9865 {
9866 cx.propagate();
9867 }
9868 }
9869
9870 pub fn move_up_by_lines(
9871 &mut self,
9872 action: &MoveUpByLines,
9873 window: &mut Window,
9874 cx: &mut Context<Self>,
9875 ) {
9876 if self.take_rename(true, window, cx).is_some() {
9877 return;
9878 }
9879
9880 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9881 cx.propagate();
9882 return;
9883 }
9884
9885 let text_layout_details = &self.text_layout_details(window);
9886
9887 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9888 let line_mode = s.line_mode;
9889 s.move_with(|map, selection| {
9890 if !selection.is_empty() && !line_mode {
9891 selection.goal = SelectionGoal::None;
9892 }
9893 let (cursor, goal) = movement::up_by_rows(
9894 map,
9895 selection.start,
9896 action.lines,
9897 selection.goal,
9898 false,
9899 text_layout_details,
9900 );
9901 selection.collapse_to(cursor, goal);
9902 });
9903 })
9904 }
9905
9906 pub fn move_down_by_lines(
9907 &mut self,
9908 action: &MoveDownByLines,
9909 window: &mut Window,
9910 cx: &mut Context<Self>,
9911 ) {
9912 if self.take_rename(true, window, cx).is_some() {
9913 return;
9914 }
9915
9916 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9917 cx.propagate();
9918 return;
9919 }
9920
9921 let text_layout_details = &self.text_layout_details(window);
9922
9923 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9924 let line_mode = s.line_mode;
9925 s.move_with(|map, selection| {
9926 if !selection.is_empty() && !line_mode {
9927 selection.goal = SelectionGoal::None;
9928 }
9929 let (cursor, goal) = movement::down_by_rows(
9930 map,
9931 selection.start,
9932 action.lines,
9933 selection.goal,
9934 false,
9935 text_layout_details,
9936 );
9937 selection.collapse_to(cursor, goal);
9938 });
9939 })
9940 }
9941
9942 pub fn select_down_by_lines(
9943 &mut self,
9944 action: &SelectDownByLines,
9945 window: &mut Window,
9946 cx: &mut Context<Self>,
9947 ) {
9948 let text_layout_details = &self.text_layout_details(window);
9949 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9950 s.move_heads_with(|map, head, goal| {
9951 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9952 })
9953 })
9954 }
9955
9956 pub fn select_up_by_lines(
9957 &mut self,
9958 action: &SelectUpByLines,
9959 window: &mut Window,
9960 cx: &mut Context<Self>,
9961 ) {
9962 let text_layout_details = &self.text_layout_details(window);
9963 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9964 s.move_heads_with(|map, head, goal| {
9965 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9966 })
9967 })
9968 }
9969
9970 pub fn select_page_up(
9971 &mut self,
9972 _: &SelectPageUp,
9973 window: &mut Window,
9974 cx: &mut Context<Self>,
9975 ) {
9976 let Some(row_count) = self.visible_row_count() else {
9977 return;
9978 };
9979
9980 let text_layout_details = &self.text_layout_details(window);
9981
9982 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9983 s.move_heads_with(|map, head, goal| {
9984 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9985 })
9986 })
9987 }
9988
9989 pub fn move_page_up(
9990 &mut self,
9991 action: &MovePageUp,
9992 window: &mut Window,
9993 cx: &mut Context<Self>,
9994 ) {
9995 if self.take_rename(true, window, cx).is_some() {
9996 return;
9997 }
9998
9999 if self
10000 .context_menu
10001 .borrow_mut()
10002 .as_mut()
10003 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10004 .unwrap_or(false)
10005 {
10006 return;
10007 }
10008
10009 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10010 cx.propagate();
10011 return;
10012 }
10013
10014 let Some(row_count) = self.visible_row_count() else {
10015 return;
10016 };
10017
10018 let autoscroll = if action.center_cursor {
10019 Autoscroll::center()
10020 } else {
10021 Autoscroll::fit()
10022 };
10023
10024 let text_layout_details = &self.text_layout_details(window);
10025
10026 self.change_selections(Some(autoscroll), window, cx, |s| {
10027 let line_mode = s.line_mode;
10028 s.move_with(|map, selection| {
10029 if !selection.is_empty() && !line_mode {
10030 selection.goal = SelectionGoal::None;
10031 }
10032 let (cursor, goal) = movement::up_by_rows(
10033 map,
10034 selection.end,
10035 row_count,
10036 selection.goal,
10037 false,
10038 text_layout_details,
10039 );
10040 selection.collapse_to(cursor, goal);
10041 });
10042 });
10043 }
10044
10045 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10046 let text_layout_details = &self.text_layout_details(window);
10047 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10048 s.move_heads_with(|map, head, goal| {
10049 movement::up(map, head, goal, false, text_layout_details)
10050 })
10051 })
10052 }
10053
10054 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10055 self.take_rename(true, window, cx);
10056
10057 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10058 cx.propagate();
10059 return;
10060 }
10061
10062 let text_layout_details = &self.text_layout_details(window);
10063 let selection_count = self.selections.count();
10064 let first_selection = self.selections.first_anchor();
10065
10066 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10067 let line_mode = s.line_mode;
10068 s.move_with(|map, selection| {
10069 if !selection.is_empty() && !line_mode {
10070 selection.goal = SelectionGoal::None;
10071 }
10072 let (cursor, goal) = movement::down(
10073 map,
10074 selection.end,
10075 selection.goal,
10076 false,
10077 text_layout_details,
10078 );
10079 selection.collapse_to(cursor, goal);
10080 });
10081 });
10082
10083 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10084 {
10085 cx.propagate();
10086 }
10087 }
10088
10089 pub fn select_page_down(
10090 &mut self,
10091 _: &SelectPageDown,
10092 window: &mut Window,
10093 cx: &mut Context<Self>,
10094 ) {
10095 let Some(row_count) = self.visible_row_count() else {
10096 return;
10097 };
10098
10099 let text_layout_details = &self.text_layout_details(window);
10100
10101 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10102 s.move_heads_with(|map, head, goal| {
10103 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10104 })
10105 })
10106 }
10107
10108 pub fn move_page_down(
10109 &mut self,
10110 action: &MovePageDown,
10111 window: &mut Window,
10112 cx: &mut Context<Self>,
10113 ) {
10114 if self.take_rename(true, window, cx).is_some() {
10115 return;
10116 }
10117
10118 if self
10119 .context_menu
10120 .borrow_mut()
10121 .as_mut()
10122 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10123 .unwrap_or(false)
10124 {
10125 return;
10126 }
10127
10128 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10129 cx.propagate();
10130 return;
10131 }
10132
10133 let Some(row_count) = self.visible_row_count() else {
10134 return;
10135 };
10136
10137 let autoscroll = if action.center_cursor {
10138 Autoscroll::center()
10139 } else {
10140 Autoscroll::fit()
10141 };
10142
10143 let text_layout_details = &self.text_layout_details(window);
10144 self.change_selections(Some(autoscroll), window, cx, |s| {
10145 let line_mode = s.line_mode;
10146 s.move_with(|map, selection| {
10147 if !selection.is_empty() && !line_mode {
10148 selection.goal = SelectionGoal::None;
10149 }
10150 let (cursor, goal) = movement::down_by_rows(
10151 map,
10152 selection.end,
10153 row_count,
10154 selection.goal,
10155 false,
10156 text_layout_details,
10157 );
10158 selection.collapse_to(cursor, goal);
10159 });
10160 });
10161 }
10162
10163 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10164 let text_layout_details = &self.text_layout_details(window);
10165 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10166 s.move_heads_with(|map, head, goal| {
10167 movement::down(map, head, goal, false, text_layout_details)
10168 })
10169 });
10170 }
10171
10172 pub fn context_menu_first(
10173 &mut self,
10174 _: &ContextMenuFirst,
10175 _window: &mut Window,
10176 cx: &mut Context<Self>,
10177 ) {
10178 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10179 context_menu.select_first(self.completion_provider.as_deref(), cx);
10180 }
10181 }
10182
10183 pub fn context_menu_prev(
10184 &mut self,
10185 _: &ContextMenuPrevious,
10186 _window: &mut Window,
10187 cx: &mut Context<Self>,
10188 ) {
10189 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10190 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10191 }
10192 }
10193
10194 pub fn context_menu_next(
10195 &mut self,
10196 _: &ContextMenuNext,
10197 _window: &mut Window,
10198 cx: &mut Context<Self>,
10199 ) {
10200 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10201 context_menu.select_next(self.completion_provider.as_deref(), cx);
10202 }
10203 }
10204
10205 pub fn context_menu_last(
10206 &mut self,
10207 _: &ContextMenuLast,
10208 _window: &mut Window,
10209 cx: &mut Context<Self>,
10210 ) {
10211 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10212 context_menu.select_last(self.completion_provider.as_deref(), cx);
10213 }
10214 }
10215
10216 pub fn move_to_previous_word_start(
10217 &mut self,
10218 _: &MoveToPreviousWordStart,
10219 window: &mut Window,
10220 cx: &mut Context<Self>,
10221 ) {
10222 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10223 s.move_cursors_with(|map, head, _| {
10224 (
10225 movement::previous_word_start(map, head),
10226 SelectionGoal::None,
10227 )
10228 });
10229 })
10230 }
10231
10232 pub fn move_to_previous_subword_start(
10233 &mut self,
10234 _: &MoveToPreviousSubwordStart,
10235 window: &mut Window,
10236 cx: &mut Context<Self>,
10237 ) {
10238 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10239 s.move_cursors_with(|map, head, _| {
10240 (
10241 movement::previous_subword_start(map, head),
10242 SelectionGoal::None,
10243 )
10244 });
10245 })
10246 }
10247
10248 pub fn select_to_previous_word_start(
10249 &mut self,
10250 _: &SelectToPreviousWordStart,
10251 window: &mut Window,
10252 cx: &mut Context<Self>,
10253 ) {
10254 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10255 s.move_heads_with(|map, head, _| {
10256 (
10257 movement::previous_word_start(map, head),
10258 SelectionGoal::None,
10259 )
10260 });
10261 })
10262 }
10263
10264 pub fn select_to_previous_subword_start(
10265 &mut self,
10266 _: &SelectToPreviousSubwordStart,
10267 window: &mut Window,
10268 cx: &mut Context<Self>,
10269 ) {
10270 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10271 s.move_heads_with(|map, head, _| {
10272 (
10273 movement::previous_subword_start(map, head),
10274 SelectionGoal::None,
10275 )
10276 });
10277 })
10278 }
10279
10280 pub fn delete_to_previous_word_start(
10281 &mut self,
10282 action: &DeleteToPreviousWordStart,
10283 window: &mut Window,
10284 cx: &mut Context<Self>,
10285 ) {
10286 self.transact(window, cx, |this, window, cx| {
10287 this.select_autoclose_pair(window, cx);
10288 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10289 let line_mode = s.line_mode;
10290 s.move_with(|map, selection| {
10291 if selection.is_empty() && !line_mode {
10292 let cursor = if action.ignore_newlines {
10293 movement::previous_word_start(map, selection.head())
10294 } else {
10295 movement::previous_word_start_or_newline(map, selection.head())
10296 };
10297 selection.set_head(cursor, SelectionGoal::None);
10298 }
10299 });
10300 });
10301 this.insert("", window, cx);
10302 });
10303 }
10304
10305 pub fn delete_to_previous_subword_start(
10306 &mut self,
10307 _: &DeleteToPreviousSubwordStart,
10308 window: &mut Window,
10309 cx: &mut Context<Self>,
10310 ) {
10311 self.transact(window, cx, |this, window, cx| {
10312 this.select_autoclose_pair(window, cx);
10313 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10314 let line_mode = s.line_mode;
10315 s.move_with(|map, selection| {
10316 if selection.is_empty() && !line_mode {
10317 let cursor = movement::previous_subword_start(map, selection.head());
10318 selection.set_head(cursor, SelectionGoal::None);
10319 }
10320 });
10321 });
10322 this.insert("", window, cx);
10323 });
10324 }
10325
10326 pub fn move_to_next_word_end(
10327 &mut self,
10328 _: &MoveToNextWordEnd,
10329 window: &mut Window,
10330 cx: &mut Context<Self>,
10331 ) {
10332 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10333 s.move_cursors_with(|map, head, _| {
10334 (movement::next_word_end(map, head), SelectionGoal::None)
10335 });
10336 })
10337 }
10338
10339 pub fn move_to_next_subword_end(
10340 &mut self,
10341 _: &MoveToNextSubwordEnd,
10342 window: &mut Window,
10343 cx: &mut Context<Self>,
10344 ) {
10345 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10346 s.move_cursors_with(|map, head, _| {
10347 (movement::next_subword_end(map, head), SelectionGoal::None)
10348 });
10349 })
10350 }
10351
10352 pub fn select_to_next_word_end(
10353 &mut self,
10354 _: &SelectToNextWordEnd,
10355 window: &mut Window,
10356 cx: &mut Context<Self>,
10357 ) {
10358 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10359 s.move_heads_with(|map, head, _| {
10360 (movement::next_word_end(map, head), SelectionGoal::None)
10361 });
10362 })
10363 }
10364
10365 pub fn select_to_next_subword_end(
10366 &mut self,
10367 _: &SelectToNextSubwordEnd,
10368 window: &mut Window,
10369 cx: &mut Context<Self>,
10370 ) {
10371 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10372 s.move_heads_with(|map, head, _| {
10373 (movement::next_subword_end(map, head), SelectionGoal::None)
10374 });
10375 })
10376 }
10377
10378 pub fn delete_to_next_word_end(
10379 &mut self,
10380 action: &DeleteToNextWordEnd,
10381 window: &mut Window,
10382 cx: &mut Context<Self>,
10383 ) {
10384 self.transact(window, cx, |this, window, cx| {
10385 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10386 let line_mode = s.line_mode;
10387 s.move_with(|map, selection| {
10388 if selection.is_empty() && !line_mode {
10389 let cursor = if action.ignore_newlines {
10390 movement::next_word_end(map, selection.head())
10391 } else {
10392 movement::next_word_end_or_newline(map, selection.head())
10393 };
10394 selection.set_head(cursor, SelectionGoal::None);
10395 }
10396 });
10397 });
10398 this.insert("", window, cx);
10399 });
10400 }
10401
10402 pub fn delete_to_next_subword_end(
10403 &mut self,
10404 _: &DeleteToNextSubwordEnd,
10405 window: &mut Window,
10406 cx: &mut Context<Self>,
10407 ) {
10408 self.transact(window, cx, |this, window, cx| {
10409 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10410 s.move_with(|map, selection| {
10411 if selection.is_empty() {
10412 let cursor = movement::next_subword_end(map, selection.head());
10413 selection.set_head(cursor, SelectionGoal::None);
10414 }
10415 });
10416 });
10417 this.insert("", window, cx);
10418 });
10419 }
10420
10421 pub fn move_to_beginning_of_line(
10422 &mut self,
10423 action: &MoveToBeginningOfLine,
10424 window: &mut Window,
10425 cx: &mut Context<Self>,
10426 ) {
10427 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10428 s.move_cursors_with(|map, head, _| {
10429 (
10430 movement::indented_line_beginning(
10431 map,
10432 head,
10433 action.stop_at_soft_wraps,
10434 action.stop_at_indent,
10435 ),
10436 SelectionGoal::None,
10437 )
10438 });
10439 })
10440 }
10441
10442 pub fn select_to_beginning_of_line(
10443 &mut self,
10444 action: &SelectToBeginningOfLine,
10445 window: &mut Window,
10446 cx: &mut Context<Self>,
10447 ) {
10448 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10449 s.move_heads_with(|map, head, _| {
10450 (
10451 movement::indented_line_beginning(
10452 map,
10453 head,
10454 action.stop_at_soft_wraps,
10455 action.stop_at_indent,
10456 ),
10457 SelectionGoal::None,
10458 )
10459 });
10460 });
10461 }
10462
10463 pub fn delete_to_beginning_of_line(
10464 &mut self,
10465 action: &DeleteToBeginningOfLine,
10466 window: &mut Window,
10467 cx: &mut Context<Self>,
10468 ) {
10469 self.transact(window, cx, |this, window, cx| {
10470 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10471 s.move_with(|_, selection| {
10472 selection.reversed = true;
10473 });
10474 });
10475
10476 this.select_to_beginning_of_line(
10477 &SelectToBeginningOfLine {
10478 stop_at_soft_wraps: false,
10479 stop_at_indent: action.stop_at_indent,
10480 },
10481 window,
10482 cx,
10483 );
10484 this.backspace(&Backspace, window, cx);
10485 });
10486 }
10487
10488 pub fn move_to_end_of_line(
10489 &mut self,
10490 action: &MoveToEndOfLine,
10491 window: &mut Window,
10492 cx: &mut Context<Self>,
10493 ) {
10494 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10495 s.move_cursors_with(|map, head, _| {
10496 (
10497 movement::line_end(map, head, action.stop_at_soft_wraps),
10498 SelectionGoal::None,
10499 )
10500 });
10501 })
10502 }
10503
10504 pub fn select_to_end_of_line(
10505 &mut self,
10506 action: &SelectToEndOfLine,
10507 window: &mut Window,
10508 cx: &mut Context<Self>,
10509 ) {
10510 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10511 s.move_heads_with(|map, head, _| {
10512 (
10513 movement::line_end(map, head, action.stop_at_soft_wraps),
10514 SelectionGoal::None,
10515 )
10516 });
10517 })
10518 }
10519
10520 pub fn delete_to_end_of_line(
10521 &mut self,
10522 _: &DeleteToEndOfLine,
10523 window: &mut Window,
10524 cx: &mut Context<Self>,
10525 ) {
10526 self.transact(window, cx, |this, window, cx| {
10527 this.select_to_end_of_line(
10528 &SelectToEndOfLine {
10529 stop_at_soft_wraps: false,
10530 },
10531 window,
10532 cx,
10533 );
10534 this.delete(&Delete, window, cx);
10535 });
10536 }
10537
10538 pub fn cut_to_end_of_line(
10539 &mut self,
10540 _: &CutToEndOfLine,
10541 window: &mut Window,
10542 cx: &mut Context<Self>,
10543 ) {
10544 self.transact(window, cx, |this, window, cx| {
10545 this.select_to_end_of_line(
10546 &SelectToEndOfLine {
10547 stop_at_soft_wraps: false,
10548 },
10549 window,
10550 cx,
10551 );
10552 this.cut(&Cut, window, cx);
10553 });
10554 }
10555
10556 pub fn move_to_start_of_paragraph(
10557 &mut self,
10558 _: &MoveToStartOfParagraph,
10559 window: &mut Window,
10560 cx: &mut Context<Self>,
10561 ) {
10562 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10563 cx.propagate();
10564 return;
10565 }
10566
10567 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10568 s.move_with(|map, selection| {
10569 selection.collapse_to(
10570 movement::start_of_paragraph(map, selection.head(), 1),
10571 SelectionGoal::None,
10572 )
10573 });
10574 })
10575 }
10576
10577 pub fn move_to_end_of_paragraph(
10578 &mut self,
10579 _: &MoveToEndOfParagraph,
10580 window: &mut Window,
10581 cx: &mut Context<Self>,
10582 ) {
10583 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10584 cx.propagate();
10585 return;
10586 }
10587
10588 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10589 s.move_with(|map, selection| {
10590 selection.collapse_to(
10591 movement::end_of_paragraph(map, selection.head(), 1),
10592 SelectionGoal::None,
10593 )
10594 });
10595 })
10596 }
10597
10598 pub fn select_to_start_of_paragraph(
10599 &mut self,
10600 _: &SelectToStartOfParagraph,
10601 window: &mut Window,
10602 cx: &mut Context<Self>,
10603 ) {
10604 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10605 cx.propagate();
10606 return;
10607 }
10608
10609 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10610 s.move_heads_with(|map, head, _| {
10611 (
10612 movement::start_of_paragraph(map, head, 1),
10613 SelectionGoal::None,
10614 )
10615 });
10616 })
10617 }
10618
10619 pub fn select_to_end_of_paragraph(
10620 &mut self,
10621 _: &SelectToEndOfParagraph,
10622 window: &mut Window,
10623 cx: &mut Context<Self>,
10624 ) {
10625 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10626 cx.propagate();
10627 return;
10628 }
10629
10630 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10631 s.move_heads_with(|map, head, _| {
10632 (
10633 movement::end_of_paragraph(map, head, 1),
10634 SelectionGoal::None,
10635 )
10636 });
10637 })
10638 }
10639
10640 pub fn move_to_start_of_excerpt(
10641 &mut self,
10642 _: &MoveToStartOfExcerpt,
10643 window: &mut Window,
10644 cx: &mut Context<Self>,
10645 ) {
10646 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10647 cx.propagate();
10648 return;
10649 }
10650
10651 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10652 s.move_with(|map, selection| {
10653 selection.collapse_to(
10654 movement::start_of_excerpt(
10655 map,
10656 selection.head(),
10657 workspace::searchable::Direction::Prev,
10658 ),
10659 SelectionGoal::None,
10660 )
10661 });
10662 })
10663 }
10664
10665 pub fn move_to_start_of_next_excerpt(
10666 &mut self,
10667 _: &MoveToStartOfNextExcerpt,
10668 window: &mut Window,
10669 cx: &mut Context<Self>,
10670 ) {
10671 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10672 cx.propagate();
10673 return;
10674 }
10675
10676 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10677 s.move_with(|map, selection| {
10678 selection.collapse_to(
10679 movement::start_of_excerpt(
10680 map,
10681 selection.head(),
10682 workspace::searchable::Direction::Next,
10683 ),
10684 SelectionGoal::None,
10685 )
10686 });
10687 })
10688 }
10689
10690 pub fn move_to_end_of_excerpt(
10691 &mut self,
10692 _: &MoveToEndOfExcerpt,
10693 window: &mut Window,
10694 cx: &mut Context<Self>,
10695 ) {
10696 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10697 cx.propagate();
10698 return;
10699 }
10700
10701 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10702 s.move_with(|map, selection| {
10703 selection.collapse_to(
10704 movement::end_of_excerpt(
10705 map,
10706 selection.head(),
10707 workspace::searchable::Direction::Next,
10708 ),
10709 SelectionGoal::None,
10710 )
10711 });
10712 })
10713 }
10714
10715 pub fn move_to_end_of_previous_excerpt(
10716 &mut self,
10717 _: &MoveToEndOfPreviousExcerpt,
10718 window: &mut Window,
10719 cx: &mut Context<Self>,
10720 ) {
10721 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10722 cx.propagate();
10723 return;
10724 }
10725
10726 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10727 s.move_with(|map, selection| {
10728 selection.collapse_to(
10729 movement::end_of_excerpt(
10730 map,
10731 selection.head(),
10732 workspace::searchable::Direction::Prev,
10733 ),
10734 SelectionGoal::None,
10735 )
10736 });
10737 })
10738 }
10739
10740 pub fn select_to_start_of_excerpt(
10741 &mut self,
10742 _: &SelectToStartOfExcerpt,
10743 window: &mut Window,
10744 cx: &mut Context<Self>,
10745 ) {
10746 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10747 cx.propagate();
10748 return;
10749 }
10750
10751 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10752 s.move_heads_with(|map, head, _| {
10753 (
10754 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10755 SelectionGoal::None,
10756 )
10757 });
10758 })
10759 }
10760
10761 pub fn select_to_start_of_next_excerpt(
10762 &mut self,
10763 _: &SelectToStartOfNextExcerpt,
10764 window: &mut Window,
10765 cx: &mut Context<Self>,
10766 ) {
10767 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10768 cx.propagate();
10769 return;
10770 }
10771
10772 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10773 s.move_heads_with(|map, head, _| {
10774 (
10775 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10776 SelectionGoal::None,
10777 )
10778 });
10779 })
10780 }
10781
10782 pub fn select_to_end_of_excerpt(
10783 &mut self,
10784 _: &SelectToEndOfExcerpt,
10785 window: &mut Window,
10786 cx: &mut Context<Self>,
10787 ) {
10788 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10789 cx.propagate();
10790 return;
10791 }
10792
10793 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10794 s.move_heads_with(|map, head, _| {
10795 (
10796 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10797 SelectionGoal::None,
10798 )
10799 });
10800 })
10801 }
10802
10803 pub fn select_to_end_of_previous_excerpt(
10804 &mut self,
10805 _: &SelectToEndOfPreviousExcerpt,
10806 window: &mut Window,
10807 cx: &mut Context<Self>,
10808 ) {
10809 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10810 cx.propagate();
10811 return;
10812 }
10813
10814 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10815 s.move_heads_with(|map, head, _| {
10816 (
10817 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10818 SelectionGoal::None,
10819 )
10820 });
10821 })
10822 }
10823
10824 pub fn move_to_beginning(
10825 &mut self,
10826 _: &MoveToBeginning,
10827 window: &mut Window,
10828 cx: &mut Context<Self>,
10829 ) {
10830 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10831 cx.propagate();
10832 return;
10833 }
10834
10835 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10836 s.select_ranges(vec![0..0]);
10837 });
10838 }
10839
10840 pub fn select_to_beginning(
10841 &mut self,
10842 _: &SelectToBeginning,
10843 window: &mut Window,
10844 cx: &mut Context<Self>,
10845 ) {
10846 let mut selection = self.selections.last::<Point>(cx);
10847 selection.set_head(Point::zero(), SelectionGoal::None);
10848
10849 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10850 s.select(vec![selection]);
10851 });
10852 }
10853
10854 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10855 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10856 cx.propagate();
10857 return;
10858 }
10859
10860 let cursor = self.buffer.read(cx).read(cx).len();
10861 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10862 s.select_ranges(vec![cursor..cursor])
10863 });
10864 }
10865
10866 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10867 self.nav_history = nav_history;
10868 }
10869
10870 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10871 self.nav_history.as_ref()
10872 }
10873
10874 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
10875 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
10876 }
10877
10878 fn push_to_nav_history(
10879 &mut self,
10880 cursor_anchor: Anchor,
10881 new_position: Option<Point>,
10882 is_deactivate: bool,
10883 cx: &mut Context<Self>,
10884 ) {
10885 if let Some(nav_history) = self.nav_history.as_mut() {
10886 let buffer = self.buffer.read(cx).read(cx);
10887 let cursor_position = cursor_anchor.to_point(&buffer);
10888 let scroll_state = self.scroll_manager.anchor();
10889 let scroll_top_row = scroll_state.top_row(&buffer);
10890 drop(buffer);
10891
10892 if let Some(new_position) = new_position {
10893 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10894 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10895 return;
10896 }
10897 }
10898
10899 nav_history.push(
10900 Some(NavigationData {
10901 cursor_anchor,
10902 cursor_position,
10903 scroll_anchor: scroll_state,
10904 scroll_top_row,
10905 }),
10906 cx,
10907 );
10908 cx.emit(EditorEvent::PushedToNavHistory {
10909 anchor: cursor_anchor,
10910 is_deactivate,
10911 })
10912 }
10913 }
10914
10915 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10916 let buffer = self.buffer.read(cx).snapshot(cx);
10917 let mut selection = self.selections.first::<usize>(cx);
10918 selection.set_head(buffer.len(), SelectionGoal::None);
10919 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10920 s.select(vec![selection]);
10921 });
10922 }
10923
10924 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10925 let end = self.buffer.read(cx).read(cx).len();
10926 self.change_selections(None, window, cx, |s| {
10927 s.select_ranges(vec![0..end]);
10928 });
10929 }
10930
10931 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10932 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10933 let mut selections = self.selections.all::<Point>(cx);
10934 let max_point = display_map.buffer_snapshot.max_point();
10935 for selection in &mut selections {
10936 let rows = selection.spanned_rows(true, &display_map);
10937 selection.start = Point::new(rows.start.0, 0);
10938 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10939 selection.reversed = false;
10940 }
10941 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10942 s.select(selections);
10943 });
10944 }
10945
10946 pub fn split_selection_into_lines(
10947 &mut self,
10948 _: &SplitSelectionIntoLines,
10949 window: &mut Window,
10950 cx: &mut Context<Self>,
10951 ) {
10952 let selections = self
10953 .selections
10954 .all::<Point>(cx)
10955 .into_iter()
10956 .map(|selection| selection.start..selection.end)
10957 .collect::<Vec<_>>();
10958 self.unfold_ranges(&selections, true, true, cx);
10959
10960 let mut new_selection_ranges = Vec::new();
10961 {
10962 let buffer = self.buffer.read(cx).read(cx);
10963 for selection in selections {
10964 for row in selection.start.row..selection.end.row {
10965 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10966 new_selection_ranges.push(cursor..cursor);
10967 }
10968
10969 let is_multiline_selection = selection.start.row != selection.end.row;
10970 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10971 // so this action feels more ergonomic when paired with other selection operations
10972 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10973 if !should_skip_last {
10974 new_selection_ranges.push(selection.end..selection.end);
10975 }
10976 }
10977 }
10978 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10979 s.select_ranges(new_selection_ranges);
10980 });
10981 }
10982
10983 pub fn add_selection_above(
10984 &mut self,
10985 _: &AddSelectionAbove,
10986 window: &mut Window,
10987 cx: &mut Context<Self>,
10988 ) {
10989 self.add_selection(true, window, cx);
10990 }
10991
10992 pub fn add_selection_below(
10993 &mut self,
10994 _: &AddSelectionBelow,
10995 window: &mut Window,
10996 cx: &mut Context<Self>,
10997 ) {
10998 self.add_selection(false, window, cx);
10999 }
11000
11001 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11002 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11003 let mut selections = self.selections.all::<Point>(cx);
11004 let text_layout_details = self.text_layout_details(window);
11005 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11006 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11007 let range = oldest_selection.display_range(&display_map).sorted();
11008
11009 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11010 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11011 let positions = start_x.min(end_x)..start_x.max(end_x);
11012
11013 selections.clear();
11014 let mut stack = Vec::new();
11015 for row in range.start.row().0..=range.end.row().0 {
11016 if let Some(selection) = self.selections.build_columnar_selection(
11017 &display_map,
11018 DisplayRow(row),
11019 &positions,
11020 oldest_selection.reversed,
11021 &text_layout_details,
11022 ) {
11023 stack.push(selection.id);
11024 selections.push(selection);
11025 }
11026 }
11027
11028 if above {
11029 stack.reverse();
11030 }
11031
11032 AddSelectionsState { above, stack }
11033 });
11034
11035 let last_added_selection = *state.stack.last().unwrap();
11036 let mut new_selections = Vec::new();
11037 if above == state.above {
11038 let end_row = if above {
11039 DisplayRow(0)
11040 } else {
11041 display_map.max_point().row()
11042 };
11043
11044 'outer: for selection in selections {
11045 if selection.id == last_added_selection {
11046 let range = selection.display_range(&display_map).sorted();
11047 debug_assert_eq!(range.start.row(), range.end.row());
11048 let mut row = range.start.row();
11049 let positions =
11050 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11051 px(start)..px(end)
11052 } else {
11053 let start_x =
11054 display_map.x_for_display_point(range.start, &text_layout_details);
11055 let end_x =
11056 display_map.x_for_display_point(range.end, &text_layout_details);
11057 start_x.min(end_x)..start_x.max(end_x)
11058 };
11059
11060 while row != end_row {
11061 if above {
11062 row.0 -= 1;
11063 } else {
11064 row.0 += 1;
11065 }
11066
11067 if let Some(new_selection) = self.selections.build_columnar_selection(
11068 &display_map,
11069 row,
11070 &positions,
11071 selection.reversed,
11072 &text_layout_details,
11073 ) {
11074 state.stack.push(new_selection.id);
11075 if above {
11076 new_selections.push(new_selection);
11077 new_selections.push(selection);
11078 } else {
11079 new_selections.push(selection);
11080 new_selections.push(new_selection);
11081 }
11082
11083 continue 'outer;
11084 }
11085 }
11086 }
11087
11088 new_selections.push(selection);
11089 }
11090 } else {
11091 new_selections = selections;
11092 new_selections.retain(|s| s.id != last_added_selection);
11093 state.stack.pop();
11094 }
11095
11096 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11097 s.select(new_selections);
11098 });
11099 if state.stack.len() > 1 {
11100 self.add_selections_state = Some(state);
11101 }
11102 }
11103
11104 pub fn select_next_match_internal(
11105 &mut self,
11106 display_map: &DisplaySnapshot,
11107 replace_newest: bool,
11108 autoscroll: Option<Autoscroll>,
11109 window: &mut Window,
11110 cx: &mut Context<Self>,
11111 ) -> Result<()> {
11112 fn select_next_match_ranges(
11113 this: &mut Editor,
11114 range: Range<usize>,
11115 replace_newest: bool,
11116 auto_scroll: Option<Autoscroll>,
11117 window: &mut Window,
11118 cx: &mut Context<Editor>,
11119 ) {
11120 this.unfold_ranges(&[range.clone()], false, true, cx);
11121 this.change_selections(auto_scroll, window, cx, |s| {
11122 if replace_newest {
11123 s.delete(s.newest_anchor().id);
11124 }
11125 s.insert_range(range.clone());
11126 });
11127 }
11128
11129 let buffer = &display_map.buffer_snapshot;
11130 let mut selections = self.selections.all::<usize>(cx);
11131 if let Some(mut select_next_state) = self.select_next_state.take() {
11132 let query = &select_next_state.query;
11133 if !select_next_state.done {
11134 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11135 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11136 let mut next_selected_range = None;
11137
11138 let bytes_after_last_selection =
11139 buffer.bytes_in_range(last_selection.end..buffer.len());
11140 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11141 let query_matches = query
11142 .stream_find_iter(bytes_after_last_selection)
11143 .map(|result| (last_selection.end, result))
11144 .chain(
11145 query
11146 .stream_find_iter(bytes_before_first_selection)
11147 .map(|result| (0, result)),
11148 );
11149
11150 for (start_offset, query_match) in query_matches {
11151 let query_match = query_match.unwrap(); // can only fail due to I/O
11152 let offset_range =
11153 start_offset + query_match.start()..start_offset + query_match.end();
11154 let display_range = offset_range.start.to_display_point(display_map)
11155 ..offset_range.end.to_display_point(display_map);
11156
11157 if !select_next_state.wordwise
11158 || (!movement::is_inside_word(display_map, display_range.start)
11159 && !movement::is_inside_word(display_map, display_range.end))
11160 {
11161 // TODO: This is n^2, because we might check all the selections
11162 if !selections
11163 .iter()
11164 .any(|selection| selection.range().overlaps(&offset_range))
11165 {
11166 next_selected_range = Some(offset_range);
11167 break;
11168 }
11169 }
11170 }
11171
11172 if let Some(next_selected_range) = next_selected_range {
11173 select_next_match_ranges(
11174 self,
11175 next_selected_range,
11176 replace_newest,
11177 autoscroll,
11178 window,
11179 cx,
11180 );
11181 } else {
11182 select_next_state.done = true;
11183 }
11184 }
11185
11186 self.select_next_state = Some(select_next_state);
11187 } else {
11188 let mut only_carets = true;
11189 let mut same_text_selected = true;
11190 let mut selected_text = None;
11191
11192 let mut selections_iter = selections.iter().peekable();
11193 while let Some(selection) = selections_iter.next() {
11194 if selection.start != selection.end {
11195 only_carets = false;
11196 }
11197
11198 if same_text_selected {
11199 if selected_text.is_none() {
11200 selected_text =
11201 Some(buffer.text_for_range(selection.range()).collect::<String>());
11202 }
11203
11204 if let Some(next_selection) = selections_iter.peek() {
11205 if next_selection.range().len() == selection.range().len() {
11206 let next_selected_text = buffer
11207 .text_for_range(next_selection.range())
11208 .collect::<String>();
11209 if Some(next_selected_text) != selected_text {
11210 same_text_selected = false;
11211 selected_text = None;
11212 }
11213 } else {
11214 same_text_selected = false;
11215 selected_text = None;
11216 }
11217 }
11218 }
11219 }
11220
11221 if only_carets {
11222 for selection in &mut selections {
11223 let word_range = movement::surrounding_word(
11224 display_map,
11225 selection.start.to_display_point(display_map),
11226 );
11227 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11228 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11229 selection.goal = SelectionGoal::None;
11230 selection.reversed = false;
11231 select_next_match_ranges(
11232 self,
11233 selection.start..selection.end,
11234 replace_newest,
11235 autoscroll,
11236 window,
11237 cx,
11238 );
11239 }
11240
11241 if selections.len() == 1 {
11242 let selection = selections
11243 .last()
11244 .expect("ensured that there's only one selection");
11245 let query = buffer
11246 .text_for_range(selection.start..selection.end)
11247 .collect::<String>();
11248 let is_empty = query.is_empty();
11249 let select_state = SelectNextState {
11250 query: AhoCorasick::new(&[query])?,
11251 wordwise: true,
11252 done: is_empty,
11253 };
11254 self.select_next_state = Some(select_state);
11255 } else {
11256 self.select_next_state = None;
11257 }
11258 } else if let Some(selected_text) = selected_text {
11259 self.select_next_state = Some(SelectNextState {
11260 query: AhoCorasick::new(&[selected_text])?,
11261 wordwise: false,
11262 done: false,
11263 });
11264 self.select_next_match_internal(
11265 display_map,
11266 replace_newest,
11267 autoscroll,
11268 window,
11269 cx,
11270 )?;
11271 }
11272 }
11273 Ok(())
11274 }
11275
11276 pub fn select_all_matches(
11277 &mut self,
11278 _action: &SelectAllMatches,
11279 window: &mut Window,
11280 cx: &mut Context<Self>,
11281 ) -> Result<()> {
11282 self.push_to_selection_history();
11283 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11284
11285 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11286 let Some(select_next_state) = self.select_next_state.as_mut() else {
11287 return Ok(());
11288 };
11289 if select_next_state.done {
11290 return Ok(());
11291 }
11292
11293 let mut new_selections = self.selections.all::<usize>(cx);
11294
11295 let buffer = &display_map.buffer_snapshot;
11296 let query_matches = select_next_state
11297 .query
11298 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11299
11300 for query_match in query_matches {
11301 let query_match = query_match.unwrap(); // can only fail due to I/O
11302 let offset_range = query_match.start()..query_match.end();
11303 let display_range = offset_range.start.to_display_point(&display_map)
11304 ..offset_range.end.to_display_point(&display_map);
11305
11306 if !select_next_state.wordwise
11307 || (!movement::is_inside_word(&display_map, display_range.start)
11308 && !movement::is_inside_word(&display_map, display_range.end))
11309 {
11310 self.selections.change_with(cx, |selections| {
11311 new_selections.push(Selection {
11312 id: selections.new_selection_id(),
11313 start: offset_range.start,
11314 end: offset_range.end,
11315 reversed: false,
11316 goal: SelectionGoal::None,
11317 });
11318 });
11319 }
11320 }
11321
11322 new_selections.sort_by_key(|selection| selection.start);
11323 let mut ix = 0;
11324 while ix + 1 < new_selections.len() {
11325 let current_selection = &new_selections[ix];
11326 let next_selection = &new_selections[ix + 1];
11327 if current_selection.range().overlaps(&next_selection.range()) {
11328 if current_selection.id < next_selection.id {
11329 new_selections.remove(ix + 1);
11330 } else {
11331 new_selections.remove(ix);
11332 }
11333 } else {
11334 ix += 1;
11335 }
11336 }
11337
11338 let reversed = self.selections.oldest::<usize>(cx).reversed;
11339
11340 for selection in new_selections.iter_mut() {
11341 selection.reversed = reversed;
11342 }
11343
11344 select_next_state.done = true;
11345 self.unfold_ranges(
11346 &new_selections
11347 .iter()
11348 .map(|selection| selection.range())
11349 .collect::<Vec<_>>(),
11350 false,
11351 false,
11352 cx,
11353 );
11354 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11355 selections.select(new_selections)
11356 });
11357
11358 Ok(())
11359 }
11360
11361 pub fn select_next(
11362 &mut self,
11363 action: &SelectNext,
11364 window: &mut Window,
11365 cx: &mut Context<Self>,
11366 ) -> Result<()> {
11367 self.push_to_selection_history();
11368 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11369 self.select_next_match_internal(
11370 &display_map,
11371 action.replace_newest,
11372 Some(Autoscroll::newest()),
11373 window,
11374 cx,
11375 )?;
11376 Ok(())
11377 }
11378
11379 pub fn select_previous(
11380 &mut self,
11381 action: &SelectPrevious,
11382 window: &mut Window,
11383 cx: &mut Context<Self>,
11384 ) -> Result<()> {
11385 self.push_to_selection_history();
11386 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11387 let buffer = &display_map.buffer_snapshot;
11388 let mut selections = self.selections.all::<usize>(cx);
11389 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11390 let query = &select_prev_state.query;
11391 if !select_prev_state.done {
11392 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11393 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11394 let mut next_selected_range = None;
11395 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11396 let bytes_before_last_selection =
11397 buffer.reversed_bytes_in_range(0..last_selection.start);
11398 let bytes_after_first_selection =
11399 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11400 let query_matches = query
11401 .stream_find_iter(bytes_before_last_selection)
11402 .map(|result| (last_selection.start, result))
11403 .chain(
11404 query
11405 .stream_find_iter(bytes_after_first_selection)
11406 .map(|result| (buffer.len(), result)),
11407 );
11408 for (end_offset, query_match) in query_matches {
11409 let query_match = query_match.unwrap(); // can only fail due to I/O
11410 let offset_range =
11411 end_offset - query_match.end()..end_offset - query_match.start();
11412 let display_range = offset_range.start.to_display_point(&display_map)
11413 ..offset_range.end.to_display_point(&display_map);
11414
11415 if !select_prev_state.wordwise
11416 || (!movement::is_inside_word(&display_map, display_range.start)
11417 && !movement::is_inside_word(&display_map, display_range.end))
11418 {
11419 next_selected_range = Some(offset_range);
11420 break;
11421 }
11422 }
11423
11424 if let Some(next_selected_range) = next_selected_range {
11425 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11426 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11427 if action.replace_newest {
11428 s.delete(s.newest_anchor().id);
11429 }
11430 s.insert_range(next_selected_range);
11431 });
11432 } else {
11433 select_prev_state.done = true;
11434 }
11435 }
11436
11437 self.select_prev_state = Some(select_prev_state);
11438 } else {
11439 let mut only_carets = true;
11440 let mut same_text_selected = true;
11441 let mut selected_text = None;
11442
11443 let mut selections_iter = selections.iter().peekable();
11444 while let Some(selection) = selections_iter.next() {
11445 if selection.start != selection.end {
11446 only_carets = false;
11447 }
11448
11449 if same_text_selected {
11450 if selected_text.is_none() {
11451 selected_text =
11452 Some(buffer.text_for_range(selection.range()).collect::<String>());
11453 }
11454
11455 if let Some(next_selection) = selections_iter.peek() {
11456 if next_selection.range().len() == selection.range().len() {
11457 let next_selected_text = buffer
11458 .text_for_range(next_selection.range())
11459 .collect::<String>();
11460 if Some(next_selected_text) != selected_text {
11461 same_text_selected = false;
11462 selected_text = None;
11463 }
11464 } else {
11465 same_text_selected = false;
11466 selected_text = None;
11467 }
11468 }
11469 }
11470 }
11471
11472 if only_carets {
11473 for selection in &mut selections {
11474 let word_range = movement::surrounding_word(
11475 &display_map,
11476 selection.start.to_display_point(&display_map),
11477 );
11478 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11479 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11480 selection.goal = SelectionGoal::None;
11481 selection.reversed = false;
11482 }
11483 if selections.len() == 1 {
11484 let selection = selections
11485 .last()
11486 .expect("ensured that there's only one selection");
11487 let query = buffer
11488 .text_for_range(selection.start..selection.end)
11489 .collect::<String>();
11490 let is_empty = query.is_empty();
11491 let select_state = SelectNextState {
11492 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11493 wordwise: true,
11494 done: is_empty,
11495 };
11496 self.select_prev_state = Some(select_state);
11497 } else {
11498 self.select_prev_state = None;
11499 }
11500
11501 self.unfold_ranges(
11502 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11503 false,
11504 true,
11505 cx,
11506 );
11507 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11508 s.select(selections);
11509 });
11510 } else if let Some(selected_text) = selected_text {
11511 self.select_prev_state = Some(SelectNextState {
11512 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11513 wordwise: false,
11514 done: false,
11515 });
11516 self.select_previous(action, window, cx)?;
11517 }
11518 }
11519 Ok(())
11520 }
11521
11522 pub fn toggle_comments(
11523 &mut self,
11524 action: &ToggleComments,
11525 window: &mut Window,
11526 cx: &mut Context<Self>,
11527 ) {
11528 if self.read_only(cx) {
11529 return;
11530 }
11531 let text_layout_details = &self.text_layout_details(window);
11532 self.transact(window, cx, |this, window, cx| {
11533 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11534 let mut edits = Vec::new();
11535 let mut selection_edit_ranges = Vec::new();
11536 let mut last_toggled_row = None;
11537 let snapshot = this.buffer.read(cx).read(cx);
11538 let empty_str: Arc<str> = Arc::default();
11539 let mut suffixes_inserted = Vec::new();
11540 let ignore_indent = action.ignore_indent;
11541
11542 fn comment_prefix_range(
11543 snapshot: &MultiBufferSnapshot,
11544 row: MultiBufferRow,
11545 comment_prefix: &str,
11546 comment_prefix_whitespace: &str,
11547 ignore_indent: bool,
11548 ) -> Range<Point> {
11549 let indent_size = if ignore_indent {
11550 0
11551 } else {
11552 snapshot.indent_size_for_line(row).len
11553 };
11554
11555 let start = Point::new(row.0, indent_size);
11556
11557 let mut line_bytes = snapshot
11558 .bytes_in_range(start..snapshot.max_point())
11559 .flatten()
11560 .copied();
11561
11562 // If this line currently begins with the line comment prefix, then record
11563 // the range containing the prefix.
11564 if line_bytes
11565 .by_ref()
11566 .take(comment_prefix.len())
11567 .eq(comment_prefix.bytes())
11568 {
11569 // Include any whitespace that matches the comment prefix.
11570 let matching_whitespace_len = line_bytes
11571 .zip(comment_prefix_whitespace.bytes())
11572 .take_while(|(a, b)| a == b)
11573 .count() as u32;
11574 let end = Point::new(
11575 start.row,
11576 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11577 );
11578 start..end
11579 } else {
11580 start..start
11581 }
11582 }
11583
11584 fn comment_suffix_range(
11585 snapshot: &MultiBufferSnapshot,
11586 row: MultiBufferRow,
11587 comment_suffix: &str,
11588 comment_suffix_has_leading_space: bool,
11589 ) -> Range<Point> {
11590 let end = Point::new(row.0, snapshot.line_len(row));
11591 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11592
11593 let mut line_end_bytes = snapshot
11594 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11595 .flatten()
11596 .copied();
11597
11598 let leading_space_len = if suffix_start_column > 0
11599 && line_end_bytes.next() == Some(b' ')
11600 && comment_suffix_has_leading_space
11601 {
11602 1
11603 } else {
11604 0
11605 };
11606
11607 // If this line currently begins with the line comment prefix, then record
11608 // the range containing the prefix.
11609 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11610 let start = Point::new(end.row, suffix_start_column - leading_space_len);
11611 start..end
11612 } else {
11613 end..end
11614 }
11615 }
11616
11617 // TODO: Handle selections that cross excerpts
11618 for selection in &mut selections {
11619 let start_column = snapshot
11620 .indent_size_for_line(MultiBufferRow(selection.start.row))
11621 .len;
11622 let language = if let Some(language) =
11623 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11624 {
11625 language
11626 } else {
11627 continue;
11628 };
11629
11630 selection_edit_ranges.clear();
11631
11632 // If multiple selections contain a given row, avoid processing that
11633 // row more than once.
11634 let mut start_row = MultiBufferRow(selection.start.row);
11635 if last_toggled_row == Some(start_row) {
11636 start_row = start_row.next_row();
11637 }
11638 let end_row =
11639 if selection.end.row > selection.start.row && selection.end.column == 0 {
11640 MultiBufferRow(selection.end.row - 1)
11641 } else {
11642 MultiBufferRow(selection.end.row)
11643 };
11644 last_toggled_row = Some(end_row);
11645
11646 if start_row > end_row {
11647 continue;
11648 }
11649
11650 // If the language has line comments, toggle those.
11651 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11652
11653 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11654 if ignore_indent {
11655 full_comment_prefixes = full_comment_prefixes
11656 .into_iter()
11657 .map(|s| Arc::from(s.trim_end()))
11658 .collect();
11659 }
11660
11661 if !full_comment_prefixes.is_empty() {
11662 let first_prefix = full_comment_prefixes
11663 .first()
11664 .expect("prefixes is non-empty");
11665 let prefix_trimmed_lengths = full_comment_prefixes
11666 .iter()
11667 .map(|p| p.trim_end_matches(' ').len())
11668 .collect::<SmallVec<[usize; 4]>>();
11669
11670 let mut all_selection_lines_are_comments = true;
11671
11672 for row in start_row.0..=end_row.0 {
11673 let row = MultiBufferRow(row);
11674 if start_row < end_row && snapshot.is_line_blank(row) {
11675 continue;
11676 }
11677
11678 let prefix_range = full_comment_prefixes
11679 .iter()
11680 .zip(prefix_trimmed_lengths.iter().copied())
11681 .map(|(prefix, trimmed_prefix_len)| {
11682 comment_prefix_range(
11683 snapshot.deref(),
11684 row,
11685 &prefix[..trimmed_prefix_len],
11686 &prefix[trimmed_prefix_len..],
11687 ignore_indent,
11688 )
11689 })
11690 .max_by_key(|range| range.end.column - range.start.column)
11691 .expect("prefixes is non-empty");
11692
11693 if prefix_range.is_empty() {
11694 all_selection_lines_are_comments = false;
11695 }
11696
11697 selection_edit_ranges.push(prefix_range);
11698 }
11699
11700 if all_selection_lines_are_comments {
11701 edits.extend(
11702 selection_edit_ranges
11703 .iter()
11704 .cloned()
11705 .map(|range| (range, empty_str.clone())),
11706 );
11707 } else {
11708 let min_column = selection_edit_ranges
11709 .iter()
11710 .map(|range| range.start.column)
11711 .min()
11712 .unwrap_or(0);
11713 edits.extend(selection_edit_ranges.iter().map(|range| {
11714 let position = Point::new(range.start.row, min_column);
11715 (position..position, first_prefix.clone())
11716 }));
11717 }
11718 } else if let Some((full_comment_prefix, comment_suffix)) =
11719 language.block_comment_delimiters()
11720 {
11721 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11722 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11723 let prefix_range = comment_prefix_range(
11724 snapshot.deref(),
11725 start_row,
11726 comment_prefix,
11727 comment_prefix_whitespace,
11728 ignore_indent,
11729 );
11730 let suffix_range = comment_suffix_range(
11731 snapshot.deref(),
11732 end_row,
11733 comment_suffix.trim_start_matches(' '),
11734 comment_suffix.starts_with(' '),
11735 );
11736
11737 if prefix_range.is_empty() || suffix_range.is_empty() {
11738 edits.push((
11739 prefix_range.start..prefix_range.start,
11740 full_comment_prefix.clone(),
11741 ));
11742 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11743 suffixes_inserted.push((end_row, comment_suffix.len()));
11744 } else {
11745 edits.push((prefix_range, empty_str.clone()));
11746 edits.push((suffix_range, empty_str.clone()));
11747 }
11748 } else {
11749 continue;
11750 }
11751 }
11752
11753 drop(snapshot);
11754 this.buffer.update(cx, |buffer, cx| {
11755 buffer.edit(edits, None, cx);
11756 });
11757
11758 // Adjust selections so that they end before any comment suffixes that
11759 // were inserted.
11760 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11761 let mut selections = this.selections.all::<Point>(cx);
11762 let snapshot = this.buffer.read(cx).read(cx);
11763 for selection in &mut selections {
11764 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11765 match row.cmp(&MultiBufferRow(selection.end.row)) {
11766 Ordering::Less => {
11767 suffixes_inserted.next();
11768 continue;
11769 }
11770 Ordering::Greater => break,
11771 Ordering::Equal => {
11772 if selection.end.column == snapshot.line_len(row) {
11773 if selection.is_empty() {
11774 selection.start.column -= suffix_len as u32;
11775 }
11776 selection.end.column -= suffix_len as u32;
11777 }
11778 break;
11779 }
11780 }
11781 }
11782 }
11783
11784 drop(snapshot);
11785 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11786 s.select(selections)
11787 });
11788
11789 let selections = this.selections.all::<Point>(cx);
11790 let selections_on_single_row = selections.windows(2).all(|selections| {
11791 selections[0].start.row == selections[1].start.row
11792 && selections[0].end.row == selections[1].end.row
11793 && selections[0].start.row == selections[0].end.row
11794 });
11795 let selections_selecting = selections
11796 .iter()
11797 .any(|selection| selection.start != selection.end);
11798 let advance_downwards = action.advance_downwards
11799 && selections_on_single_row
11800 && !selections_selecting
11801 && !matches!(this.mode, EditorMode::SingleLine { .. });
11802
11803 if advance_downwards {
11804 let snapshot = this.buffer.read(cx).snapshot(cx);
11805
11806 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11807 s.move_cursors_with(|display_snapshot, display_point, _| {
11808 let mut point = display_point.to_point(display_snapshot);
11809 point.row += 1;
11810 point = snapshot.clip_point(point, Bias::Left);
11811 let display_point = point.to_display_point(display_snapshot);
11812 let goal = SelectionGoal::HorizontalPosition(
11813 display_snapshot
11814 .x_for_display_point(display_point, text_layout_details)
11815 .into(),
11816 );
11817 (display_point, goal)
11818 })
11819 });
11820 }
11821 });
11822 }
11823
11824 pub fn select_enclosing_symbol(
11825 &mut self,
11826 _: &SelectEnclosingSymbol,
11827 window: &mut Window,
11828 cx: &mut Context<Self>,
11829 ) {
11830 let buffer = self.buffer.read(cx).snapshot(cx);
11831 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11832
11833 fn update_selection(
11834 selection: &Selection<usize>,
11835 buffer_snap: &MultiBufferSnapshot,
11836 ) -> Option<Selection<usize>> {
11837 let cursor = selection.head();
11838 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11839 for symbol in symbols.iter().rev() {
11840 let start = symbol.range.start.to_offset(buffer_snap);
11841 let end = symbol.range.end.to_offset(buffer_snap);
11842 let new_range = start..end;
11843 if start < selection.start || end > selection.end {
11844 return Some(Selection {
11845 id: selection.id,
11846 start: new_range.start,
11847 end: new_range.end,
11848 goal: SelectionGoal::None,
11849 reversed: selection.reversed,
11850 });
11851 }
11852 }
11853 None
11854 }
11855
11856 let mut selected_larger_symbol = false;
11857 let new_selections = old_selections
11858 .iter()
11859 .map(|selection| match update_selection(selection, &buffer) {
11860 Some(new_selection) => {
11861 if new_selection.range() != selection.range() {
11862 selected_larger_symbol = true;
11863 }
11864 new_selection
11865 }
11866 None => selection.clone(),
11867 })
11868 .collect::<Vec<_>>();
11869
11870 if selected_larger_symbol {
11871 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11872 s.select(new_selections);
11873 });
11874 }
11875 }
11876
11877 pub fn select_larger_syntax_node(
11878 &mut self,
11879 _: &SelectLargerSyntaxNode,
11880 window: &mut Window,
11881 cx: &mut Context<Self>,
11882 ) {
11883 let Some(visible_row_count) = self.visible_row_count() else {
11884 return;
11885 };
11886 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
11887 if old_selections.is_empty() {
11888 return;
11889 }
11890
11891 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11892 let buffer = self.buffer.read(cx).snapshot(cx);
11893
11894 let mut selected_larger_node = false;
11895 let mut new_selections = old_selections
11896 .iter()
11897 .map(|selection| {
11898 let old_range = selection.start..selection.end;
11899 let mut new_range = old_range.clone();
11900 let mut new_node = None;
11901 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11902 {
11903 new_node = Some(node);
11904 new_range = match containing_range {
11905 MultiOrSingleBufferOffsetRange::Single(_) => break,
11906 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11907 };
11908 if !display_map.intersects_fold(new_range.start)
11909 && !display_map.intersects_fold(new_range.end)
11910 {
11911 break;
11912 }
11913 }
11914
11915 if let Some(node) = new_node {
11916 // Log the ancestor, to support using this action as a way to explore TreeSitter
11917 // nodes. Parent and grandparent are also logged because this operation will not
11918 // visit nodes that have the same range as their parent.
11919 log::info!("Node: {node:?}");
11920 let parent = node.parent();
11921 log::info!("Parent: {parent:?}");
11922 let grandparent = parent.and_then(|x| x.parent());
11923 log::info!("Grandparent: {grandparent:?}");
11924 }
11925
11926 selected_larger_node |= new_range != old_range;
11927 Selection {
11928 id: selection.id,
11929 start: new_range.start,
11930 end: new_range.end,
11931 goal: SelectionGoal::None,
11932 reversed: selection.reversed,
11933 }
11934 })
11935 .collect::<Vec<_>>();
11936
11937 if !selected_larger_node {
11938 return; // don't put this call in the history
11939 }
11940
11941 // scroll based on transformation done to the last selection created by the user
11942 let (last_old, last_new) = old_selections
11943 .last()
11944 .zip(new_selections.last().cloned())
11945 .expect("old_selections isn't empty");
11946
11947 // revert selection
11948 let is_selection_reversed = {
11949 let should_newest_selection_be_reversed = last_old.start != last_new.start;
11950 new_selections.last_mut().expect("checked above").reversed =
11951 should_newest_selection_be_reversed;
11952 should_newest_selection_be_reversed
11953 };
11954
11955 if selected_larger_node {
11956 self.select_syntax_node_history.disable_clearing = true;
11957 self.change_selections(None, window, cx, |s| {
11958 s.select(new_selections.clone());
11959 });
11960 self.select_syntax_node_history.disable_clearing = false;
11961 }
11962
11963 let start_row = last_new.start.to_display_point(&display_map).row().0;
11964 let end_row = last_new.end.to_display_point(&display_map).row().0;
11965 let selection_height = end_row - start_row + 1;
11966 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
11967
11968 // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
11969 let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
11970 let middle_row = (end_row + start_row) / 2;
11971 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
11972 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
11973 SelectSyntaxNodeScrollBehavior::CenterSelection
11974 } else if is_selection_reversed {
11975 self.scroll_cursor_top(&Default::default(), window, cx);
11976 SelectSyntaxNodeScrollBehavior::CursorTop
11977 } else {
11978 self.scroll_cursor_bottom(&Default::default(), window, cx);
11979 SelectSyntaxNodeScrollBehavior::CursorBottom
11980 };
11981
11982 self.select_syntax_node_history.push((
11983 old_selections,
11984 scroll_behavior,
11985 is_selection_reversed,
11986 ));
11987 }
11988
11989 pub fn select_smaller_syntax_node(
11990 &mut self,
11991 _: &SelectSmallerSyntaxNode,
11992 window: &mut Window,
11993 cx: &mut Context<Self>,
11994 ) {
11995 let Some(visible_row_count) = self.visible_row_count() else {
11996 return;
11997 };
11998
11999 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12000 self.select_syntax_node_history.pop()
12001 {
12002 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12003
12004 if let Some(selection) = selections.last_mut() {
12005 selection.reversed = is_selection_reversed;
12006 }
12007
12008 self.select_syntax_node_history.disable_clearing = true;
12009 self.change_selections(None, window, cx, |s| {
12010 s.select(selections.to_vec());
12011 });
12012 self.select_syntax_node_history.disable_clearing = false;
12013
12014 let newest = self.selections.newest::<usize>(cx);
12015 let start_row = newest.start.to_display_point(&display_map).row().0;
12016 let end_row = newest.end.to_display_point(&display_map).row().0;
12017
12018 match scroll_behavior {
12019 SelectSyntaxNodeScrollBehavior::CursorTop => {
12020 self.scroll_cursor_top(&Default::default(), window, cx);
12021 }
12022 SelectSyntaxNodeScrollBehavior::CenterSelection => {
12023 let middle_row = (end_row + start_row) / 2;
12024 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12025 // centralize the selection, not the cursor
12026 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12027 }
12028 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12029 self.scroll_cursor_bottom(&Default::default(), window, cx);
12030 }
12031 }
12032 }
12033 }
12034
12035 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12036 if !EditorSettings::get_global(cx).gutter.runnables {
12037 self.clear_tasks();
12038 return Task::ready(());
12039 }
12040 let project = self.project.as_ref().map(Entity::downgrade);
12041 cx.spawn_in(window, async move |this, cx| {
12042 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12043 let Some(project) = project.and_then(|p| p.upgrade()) else {
12044 return;
12045 };
12046 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12047 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12048 }) else {
12049 return;
12050 };
12051
12052 let hide_runnables = project
12053 .update(cx, |project, cx| {
12054 // Do not display any test indicators in non-dev server remote projects.
12055 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12056 })
12057 .unwrap_or(true);
12058 if hide_runnables {
12059 return;
12060 }
12061 let new_rows =
12062 cx.background_spawn({
12063 let snapshot = display_snapshot.clone();
12064 async move {
12065 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12066 }
12067 })
12068 .await;
12069
12070 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12071 this.update(cx, |this, _| {
12072 this.clear_tasks();
12073 for (key, value) in rows {
12074 this.insert_tasks(key, value);
12075 }
12076 })
12077 .ok();
12078 })
12079 }
12080 fn fetch_runnable_ranges(
12081 snapshot: &DisplaySnapshot,
12082 range: Range<Anchor>,
12083 ) -> Vec<language::RunnableRange> {
12084 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12085 }
12086
12087 fn runnable_rows(
12088 project: Entity<Project>,
12089 snapshot: DisplaySnapshot,
12090 runnable_ranges: Vec<RunnableRange>,
12091 mut cx: AsyncWindowContext,
12092 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12093 runnable_ranges
12094 .into_iter()
12095 .filter_map(|mut runnable| {
12096 let tasks = cx
12097 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12098 .ok()?;
12099 if tasks.is_empty() {
12100 return None;
12101 }
12102
12103 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12104
12105 let row = snapshot
12106 .buffer_snapshot
12107 .buffer_line_for_row(MultiBufferRow(point.row))?
12108 .1
12109 .start
12110 .row;
12111
12112 let context_range =
12113 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12114 Some((
12115 (runnable.buffer_id, row),
12116 RunnableTasks {
12117 templates: tasks,
12118 offset: snapshot
12119 .buffer_snapshot
12120 .anchor_before(runnable.run_range.start),
12121 context_range,
12122 column: point.column,
12123 extra_variables: runnable.extra_captures,
12124 },
12125 ))
12126 })
12127 .collect()
12128 }
12129
12130 fn templates_with_tags(
12131 project: &Entity<Project>,
12132 runnable: &mut Runnable,
12133 cx: &mut App,
12134 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12135 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12136 let (worktree_id, file) = project
12137 .buffer_for_id(runnable.buffer, cx)
12138 .and_then(|buffer| buffer.read(cx).file())
12139 .map(|file| (file.worktree_id(cx), file.clone()))
12140 .unzip();
12141
12142 (
12143 project.task_store().read(cx).task_inventory().cloned(),
12144 worktree_id,
12145 file,
12146 )
12147 });
12148
12149 let tags = mem::take(&mut runnable.tags);
12150 let mut tags: Vec<_> = tags
12151 .into_iter()
12152 .flat_map(|tag| {
12153 let tag = tag.0.clone();
12154 inventory
12155 .as_ref()
12156 .into_iter()
12157 .flat_map(|inventory| {
12158 inventory.read(cx).list_tasks(
12159 file.clone(),
12160 Some(runnable.language.clone()),
12161 worktree_id,
12162 cx,
12163 )
12164 })
12165 .filter(move |(_, template)| {
12166 template.tags.iter().any(|source_tag| source_tag == &tag)
12167 })
12168 })
12169 .sorted_by_key(|(kind, _)| kind.to_owned())
12170 .collect();
12171 if let Some((leading_tag_source, _)) = tags.first() {
12172 // Strongest source wins; if we have worktree tag binding, prefer that to
12173 // global and language bindings;
12174 // if we have a global binding, prefer that to language binding.
12175 let first_mismatch = tags
12176 .iter()
12177 .position(|(tag_source, _)| tag_source != leading_tag_source);
12178 if let Some(index) = first_mismatch {
12179 tags.truncate(index);
12180 }
12181 }
12182
12183 tags
12184 }
12185
12186 pub fn move_to_enclosing_bracket(
12187 &mut self,
12188 _: &MoveToEnclosingBracket,
12189 window: &mut Window,
12190 cx: &mut Context<Self>,
12191 ) {
12192 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12193 s.move_offsets_with(|snapshot, selection| {
12194 let Some(enclosing_bracket_ranges) =
12195 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12196 else {
12197 return;
12198 };
12199
12200 let mut best_length = usize::MAX;
12201 let mut best_inside = false;
12202 let mut best_in_bracket_range = false;
12203 let mut best_destination = None;
12204 for (open, close) in enclosing_bracket_ranges {
12205 let close = close.to_inclusive();
12206 let length = close.end() - open.start;
12207 let inside = selection.start >= open.end && selection.end <= *close.start();
12208 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12209 || close.contains(&selection.head());
12210
12211 // If best is next to a bracket and current isn't, skip
12212 if !in_bracket_range && best_in_bracket_range {
12213 continue;
12214 }
12215
12216 // Prefer smaller lengths unless best is inside and current isn't
12217 if length > best_length && (best_inside || !inside) {
12218 continue;
12219 }
12220
12221 best_length = length;
12222 best_inside = inside;
12223 best_in_bracket_range = in_bracket_range;
12224 best_destination = Some(
12225 if close.contains(&selection.start) && close.contains(&selection.end) {
12226 if inside {
12227 open.end
12228 } else {
12229 open.start
12230 }
12231 } else if inside {
12232 *close.start()
12233 } else {
12234 *close.end()
12235 },
12236 );
12237 }
12238
12239 if let Some(destination) = best_destination {
12240 selection.collapse_to(destination, SelectionGoal::None);
12241 }
12242 })
12243 });
12244 }
12245
12246 pub fn undo_selection(
12247 &mut self,
12248 _: &UndoSelection,
12249 window: &mut Window,
12250 cx: &mut Context<Self>,
12251 ) {
12252 self.end_selection(window, cx);
12253 self.selection_history.mode = SelectionHistoryMode::Undoing;
12254 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12255 self.change_selections(None, window, cx, |s| {
12256 s.select_anchors(entry.selections.to_vec())
12257 });
12258 self.select_next_state = entry.select_next_state;
12259 self.select_prev_state = entry.select_prev_state;
12260 self.add_selections_state = entry.add_selections_state;
12261 self.request_autoscroll(Autoscroll::newest(), cx);
12262 }
12263 self.selection_history.mode = SelectionHistoryMode::Normal;
12264 }
12265
12266 pub fn redo_selection(
12267 &mut self,
12268 _: &RedoSelection,
12269 window: &mut Window,
12270 cx: &mut Context<Self>,
12271 ) {
12272 self.end_selection(window, cx);
12273 self.selection_history.mode = SelectionHistoryMode::Redoing;
12274 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12275 self.change_selections(None, window, cx, |s| {
12276 s.select_anchors(entry.selections.to_vec())
12277 });
12278 self.select_next_state = entry.select_next_state;
12279 self.select_prev_state = entry.select_prev_state;
12280 self.add_selections_state = entry.add_selections_state;
12281 self.request_autoscroll(Autoscroll::newest(), cx);
12282 }
12283 self.selection_history.mode = SelectionHistoryMode::Normal;
12284 }
12285
12286 pub fn expand_excerpts(
12287 &mut self,
12288 action: &ExpandExcerpts,
12289 _: &mut Window,
12290 cx: &mut Context<Self>,
12291 ) {
12292 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12293 }
12294
12295 pub fn expand_excerpts_down(
12296 &mut self,
12297 action: &ExpandExcerptsDown,
12298 _: &mut Window,
12299 cx: &mut Context<Self>,
12300 ) {
12301 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12302 }
12303
12304 pub fn expand_excerpts_up(
12305 &mut self,
12306 action: &ExpandExcerptsUp,
12307 _: &mut Window,
12308 cx: &mut Context<Self>,
12309 ) {
12310 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12311 }
12312
12313 pub fn expand_excerpts_for_direction(
12314 &mut self,
12315 lines: u32,
12316 direction: ExpandExcerptDirection,
12317
12318 cx: &mut Context<Self>,
12319 ) {
12320 let selections = self.selections.disjoint_anchors();
12321
12322 let lines = if lines == 0 {
12323 EditorSettings::get_global(cx).expand_excerpt_lines
12324 } else {
12325 lines
12326 };
12327
12328 self.buffer.update(cx, |buffer, cx| {
12329 let snapshot = buffer.snapshot(cx);
12330 let mut excerpt_ids = selections
12331 .iter()
12332 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12333 .collect::<Vec<_>>();
12334 excerpt_ids.sort();
12335 excerpt_ids.dedup();
12336 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12337 })
12338 }
12339
12340 pub fn expand_excerpt(
12341 &mut self,
12342 excerpt: ExcerptId,
12343 direction: ExpandExcerptDirection,
12344 window: &mut Window,
12345 cx: &mut Context<Self>,
12346 ) {
12347 let current_scroll_position = self.scroll_position(cx);
12348 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12349 self.buffer.update(cx, |buffer, cx| {
12350 buffer.expand_excerpts([excerpt], lines, direction, cx)
12351 });
12352 if direction == ExpandExcerptDirection::Down {
12353 let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12354 self.set_scroll_position(new_scroll_position, window, cx);
12355 }
12356 }
12357
12358 pub fn go_to_singleton_buffer_point(
12359 &mut self,
12360 point: Point,
12361 window: &mut Window,
12362 cx: &mut Context<Self>,
12363 ) {
12364 self.go_to_singleton_buffer_range(point..point, window, cx);
12365 }
12366
12367 pub fn go_to_singleton_buffer_range(
12368 &mut self,
12369 range: Range<Point>,
12370 window: &mut Window,
12371 cx: &mut Context<Self>,
12372 ) {
12373 let multibuffer = self.buffer().read(cx);
12374 let Some(buffer) = multibuffer.as_singleton() else {
12375 return;
12376 };
12377 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12378 return;
12379 };
12380 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12381 return;
12382 };
12383 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12384 s.select_anchor_ranges([start..end])
12385 });
12386 }
12387
12388 fn go_to_diagnostic(
12389 &mut self,
12390 _: &GoToDiagnostic,
12391 window: &mut Window,
12392 cx: &mut Context<Self>,
12393 ) {
12394 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12395 }
12396
12397 fn go_to_prev_diagnostic(
12398 &mut self,
12399 _: &GoToPreviousDiagnostic,
12400 window: &mut Window,
12401 cx: &mut Context<Self>,
12402 ) {
12403 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12404 }
12405
12406 pub fn go_to_diagnostic_impl(
12407 &mut self,
12408 direction: Direction,
12409 window: &mut Window,
12410 cx: &mut Context<Self>,
12411 ) {
12412 let buffer = self.buffer.read(cx).snapshot(cx);
12413 let selection = self.selections.newest::<usize>(cx);
12414
12415 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12416 if direction == Direction::Next {
12417 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12418 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12419 return;
12420 };
12421 self.activate_diagnostics(
12422 buffer_id,
12423 popover.local_diagnostic.diagnostic.group_id,
12424 window,
12425 cx,
12426 );
12427 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12428 let primary_range_start = active_diagnostics.primary_range.start;
12429 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12430 let mut new_selection = s.newest_anchor().clone();
12431 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12432 s.select_anchors(vec![new_selection.clone()]);
12433 });
12434 self.refresh_inline_completion(false, true, window, cx);
12435 }
12436 return;
12437 }
12438 }
12439
12440 let active_group_id = self
12441 .active_diagnostics
12442 .as_ref()
12443 .map(|active_group| active_group.group_id);
12444 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12445 active_diagnostics
12446 .primary_range
12447 .to_offset(&buffer)
12448 .to_inclusive()
12449 });
12450 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12451 if active_primary_range.contains(&selection.head()) {
12452 *active_primary_range.start()
12453 } else {
12454 selection.head()
12455 }
12456 } else {
12457 selection.head()
12458 };
12459
12460 let snapshot = self.snapshot(window, cx);
12461 let primary_diagnostics_before = buffer
12462 .diagnostics_in_range::<usize>(0..search_start)
12463 .filter(|entry| entry.diagnostic.is_primary)
12464 .filter(|entry| entry.range.start != entry.range.end)
12465 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12466 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12467 .collect::<Vec<_>>();
12468 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12469 primary_diagnostics_before
12470 .iter()
12471 .position(|entry| entry.diagnostic.group_id == active_group_id)
12472 });
12473
12474 let primary_diagnostics_after = buffer
12475 .diagnostics_in_range::<usize>(search_start..buffer.len())
12476 .filter(|entry| entry.diagnostic.is_primary)
12477 .filter(|entry| entry.range.start != entry.range.end)
12478 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12479 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12480 .collect::<Vec<_>>();
12481 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12482 primary_diagnostics_after
12483 .iter()
12484 .enumerate()
12485 .rev()
12486 .find_map(|(i, entry)| {
12487 if entry.diagnostic.group_id == active_group_id {
12488 Some(i)
12489 } else {
12490 None
12491 }
12492 })
12493 });
12494
12495 let next_primary_diagnostic = match direction {
12496 Direction::Prev => primary_diagnostics_before
12497 .iter()
12498 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12499 .rev()
12500 .next(),
12501 Direction::Next => primary_diagnostics_after
12502 .iter()
12503 .skip(
12504 last_same_group_diagnostic_after
12505 .map(|index| index + 1)
12506 .unwrap_or(0),
12507 )
12508 .next(),
12509 };
12510
12511 // Cycle around to the start of the buffer, potentially moving back to the start of
12512 // the currently active diagnostic.
12513 let cycle_around = || match direction {
12514 Direction::Prev => primary_diagnostics_after
12515 .iter()
12516 .rev()
12517 .chain(primary_diagnostics_before.iter().rev())
12518 .next(),
12519 Direction::Next => primary_diagnostics_before
12520 .iter()
12521 .chain(primary_diagnostics_after.iter())
12522 .next(),
12523 };
12524
12525 if let Some((primary_range, group_id)) = next_primary_diagnostic
12526 .or_else(cycle_around)
12527 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12528 {
12529 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12530 return;
12531 };
12532 self.activate_diagnostics(buffer_id, group_id, window, cx);
12533 if self.active_diagnostics.is_some() {
12534 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12535 s.select(vec![Selection {
12536 id: selection.id,
12537 start: primary_range.start,
12538 end: primary_range.start,
12539 reversed: false,
12540 goal: SelectionGoal::None,
12541 }]);
12542 });
12543 self.refresh_inline_completion(false, true, window, cx);
12544 }
12545 }
12546 }
12547
12548 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12549 let snapshot = self.snapshot(window, cx);
12550 let selection = self.selections.newest::<Point>(cx);
12551 self.go_to_hunk_before_or_after_position(
12552 &snapshot,
12553 selection.head(),
12554 Direction::Next,
12555 window,
12556 cx,
12557 );
12558 }
12559
12560 fn go_to_hunk_before_or_after_position(
12561 &mut self,
12562 snapshot: &EditorSnapshot,
12563 position: Point,
12564 direction: Direction,
12565 window: &mut Window,
12566 cx: &mut Context<Editor>,
12567 ) {
12568 let row = if direction == Direction::Next {
12569 self.hunk_after_position(snapshot, position)
12570 .map(|hunk| hunk.row_range.start)
12571 } else {
12572 self.hunk_before_position(snapshot, position)
12573 };
12574
12575 if let Some(row) = row {
12576 let destination = Point::new(row.0, 0);
12577 let autoscroll = Autoscroll::center();
12578
12579 self.unfold_ranges(&[destination..destination], false, false, cx);
12580 self.change_selections(Some(autoscroll), window, cx, |s| {
12581 s.select_ranges([destination..destination]);
12582 });
12583 }
12584 }
12585
12586 fn hunk_after_position(
12587 &mut self,
12588 snapshot: &EditorSnapshot,
12589 position: Point,
12590 ) -> Option<MultiBufferDiffHunk> {
12591 snapshot
12592 .buffer_snapshot
12593 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12594 .find(|hunk| hunk.row_range.start.0 > position.row)
12595 .or_else(|| {
12596 snapshot
12597 .buffer_snapshot
12598 .diff_hunks_in_range(Point::zero()..position)
12599 .find(|hunk| hunk.row_range.end.0 < position.row)
12600 })
12601 }
12602
12603 fn go_to_prev_hunk(
12604 &mut self,
12605 _: &GoToPreviousHunk,
12606 window: &mut Window,
12607 cx: &mut Context<Self>,
12608 ) {
12609 let snapshot = self.snapshot(window, cx);
12610 let selection = self.selections.newest::<Point>(cx);
12611 self.go_to_hunk_before_or_after_position(
12612 &snapshot,
12613 selection.head(),
12614 Direction::Prev,
12615 window,
12616 cx,
12617 );
12618 }
12619
12620 fn hunk_before_position(
12621 &mut self,
12622 snapshot: &EditorSnapshot,
12623 position: Point,
12624 ) -> Option<MultiBufferRow> {
12625 snapshot
12626 .buffer_snapshot
12627 .diff_hunk_before(position)
12628 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12629 }
12630
12631 fn go_to_line<T: 'static>(
12632 &mut self,
12633 position: Anchor,
12634 highlight_color: Option<Hsla>,
12635 window: &mut Window,
12636 cx: &mut Context<Self>,
12637 ) {
12638 let snapshot = self.snapshot(window, cx).display_snapshot;
12639 let position = position.to_point(&snapshot.buffer_snapshot);
12640 let start = snapshot
12641 .buffer_snapshot
12642 .clip_point(Point::new(position.row, 0), Bias::Left);
12643 let end = start + Point::new(1, 0);
12644 let start = snapshot.buffer_snapshot.anchor_before(start);
12645 let end = snapshot.buffer_snapshot.anchor_before(end);
12646
12647 self.clear_row_highlights::<T>();
12648 self.highlight_rows::<T>(
12649 start..end,
12650 highlight_color
12651 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12652 true,
12653 cx,
12654 );
12655 self.request_autoscroll(Autoscroll::center(), cx);
12656 }
12657
12658 pub fn go_to_definition(
12659 &mut self,
12660 _: &GoToDefinition,
12661 window: &mut Window,
12662 cx: &mut Context<Self>,
12663 ) -> Task<Result<Navigated>> {
12664 let definition =
12665 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12666 cx.spawn_in(window, async move |editor, cx| {
12667 if definition.await? == Navigated::Yes {
12668 return Ok(Navigated::Yes);
12669 }
12670 match editor.update_in(cx, |editor, window, cx| {
12671 editor.find_all_references(&FindAllReferences, window, cx)
12672 })? {
12673 Some(references) => references.await,
12674 None => Ok(Navigated::No),
12675 }
12676 })
12677 }
12678
12679 pub fn go_to_declaration(
12680 &mut self,
12681 _: &GoToDeclaration,
12682 window: &mut Window,
12683 cx: &mut Context<Self>,
12684 ) -> Task<Result<Navigated>> {
12685 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12686 }
12687
12688 pub fn go_to_declaration_split(
12689 &mut self,
12690 _: &GoToDeclaration,
12691 window: &mut Window,
12692 cx: &mut Context<Self>,
12693 ) -> Task<Result<Navigated>> {
12694 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12695 }
12696
12697 pub fn go_to_implementation(
12698 &mut self,
12699 _: &GoToImplementation,
12700 window: &mut Window,
12701 cx: &mut Context<Self>,
12702 ) -> Task<Result<Navigated>> {
12703 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12704 }
12705
12706 pub fn go_to_implementation_split(
12707 &mut self,
12708 _: &GoToImplementationSplit,
12709 window: &mut Window,
12710 cx: &mut Context<Self>,
12711 ) -> Task<Result<Navigated>> {
12712 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12713 }
12714
12715 pub fn go_to_type_definition(
12716 &mut self,
12717 _: &GoToTypeDefinition,
12718 window: &mut Window,
12719 cx: &mut Context<Self>,
12720 ) -> Task<Result<Navigated>> {
12721 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12722 }
12723
12724 pub fn go_to_definition_split(
12725 &mut self,
12726 _: &GoToDefinitionSplit,
12727 window: &mut Window,
12728 cx: &mut Context<Self>,
12729 ) -> Task<Result<Navigated>> {
12730 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12731 }
12732
12733 pub fn go_to_type_definition_split(
12734 &mut self,
12735 _: &GoToTypeDefinitionSplit,
12736 window: &mut Window,
12737 cx: &mut Context<Self>,
12738 ) -> Task<Result<Navigated>> {
12739 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12740 }
12741
12742 fn go_to_definition_of_kind(
12743 &mut self,
12744 kind: GotoDefinitionKind,
12745 split: bool,
12746 window: &mut Window,
12747 cx: &mut Context<Self>,
12748 ) -> Task<Result<Navigated>> {
12749 let Some(provider) = self.semantics_provider.clone() else {
12750 return Task::ready(Ok(Navigated::No));
12751 };
12752 let head = self.selections.newest::<usize>(cx).head();
12753 let buffer = self.buffer.read(cx);
12754 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12755 text_anchor
12756 } else {
12757 return Task::ready(Ok(Navigated::No));
12758 };
12759
12760 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12761 return Task::ready(Ok(Navigated::No));
12762 };
12763
12764 cx.spawn_in(window, async move |editor, cx| {
12765 let definitions = definitions.await?;
12766 let navigated = editor
12767 .update_in(cx, |editor, window, cx| {
12768 editor.navigate_to_hover_links(
12769 Some(kind),
12770 definitions
12771 .into_iter()
12772 .filter(|location| {
12773 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12774 })
12775 .map(HoverLink::Text)
12776 .collect::<Vec<_>>(),
12777 split,
12778 window,
12779 cx,
12780 )
12781 })?
12782 .await?;
12783 anyhow::Ok(navigated)
12784 })
12785 }
12786
12787 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12788 let selection = self.selections.newest_anchor();
12789 let head = selection.head();
12790 let tail = selection.tail();
12791
12792 let Some((buffer, start_position)) =
12793 self.buffer.read(cx).text_anchor_for_position(head, cx)
12794 else {
12795 return;
12796 };
12797
12798 let end_position = if head != tail {
12799 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12800 return;
12801 };
12802 Some(pos)
12803 } else {
12804 None
12805 };
12806
12807 let url_finder = cx.spawn_in(window, async move |editor, cx| {
12808 let url = if let Some(end_pos) = end_position {
12809 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12810 } else {
12811 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12812 };
12813
12814 if let Some(url) = url {
12815 editor.update(cx, |_, cx| {
12816 cx.open_url(&url);
12817 })
12818 } else {
12819 Ok(())
12820 }
12821 });
12822
12823 url_finder.detach();
12824 }
12825
12826 pub fn open_selected_filename(
12827 &mut self,
12828 _: &OpenSelectedFilename,
12829 window: &mut Window,
12830 cx: &mut Context<Self>,
12831 ) {
12832 let Some(workspace) = self.workspace() else {
12833 return;
12834 };
12835
12836 let position = self.selections.newest_anchor().head();
12837
12838 let Some((buffer, buffer_position)) =
12839 self.buffer.read(cx).text_anchor_for_position(position, cx)
12840 else {
12841 return;
12842 };
12843
12844 let project = self.project.clone();
12845
12846 cx.spawn_in(window, async move |_, cx| {
12847 let result = find_file(&buffer, project, buffer_position, cx).await;
12848
12849 if let Some((_, path)) = result {
12850 workspace
12851 .update_in(cx, |workspace, window, cx| {
12852 workspace.open_resolved_path(path, window, cx)
12853 })?
12854 .await?;
12855 }
12856 anyhow::Ok(())
12857 })
12858 .detach();
12859 }
12860
12861 pub(crate) fn navigate_to_hover_links(
12862 &mut self,
12863 kind: Option<GotoDefinitionKind>,
12864 mut definitions: Vec<HoverLink>,
12865 split: bool,
12866 window: &mut Window,
12867 cx: &mut Context<Editor>,
12868 ) -> Task<Result<Navigated>> {
12869 // If there is one definition, just open it directly
12870 if definitions.len() == 1 {
12871 let definition = definitions.pop().unwrap();
12872
12873 enum TargetTaskResult {
12874 Location(Option<Location>),
12875 AlreadyNavigated,
12876 }
12877
12878 let target_task = match definition {
12879 HoverLink::Text(link) => {
12880 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12881 }
12882 HoverLink::InlayHint(lsp_location, server_id) => {
12883 let computation =
12884 self.compute_target_location(lsp_location, server_id, window, cx);
12885 cx.background_spawn(async move {
12886 let location = computation.await?;
12887 Ok(TargetTaskResult::Location(location))
12888 })
12889 }
12890 HoverLink::Url(url) => {
12891 cx.open_url(&url);
12892 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12893 }
12894 HoverLink::File(path) => {
12895 if let Some(workspace) = self.workspace() {
12896 cx.spawn_in(window, async move |_, cx| {
12897 workspace
12898 .update_in(cx, |workspace, window, cx| {
12899 workspace.open_resolved_path(path, window, cx)
12900 })?
12901 .await
12902 .map(|_| TargetTaskResult::AlreadyNavigated)
12903 })
12904 } else {
12905 Task::ready(Ok(TargetTaskResult::Location(None)))
12906 }
12907 }
12908 };
12909 cx.spawn_in(window, async move |editor, cx| {
12910 let target = match target_task.await.context("target resolution task")? {
12911 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12912 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12913 TargetTaskResult::Location(Some(target)) => target,
12914 };
12915
12916 editor.update_in(cx, |editor, window, cx| {
12917 let Some(workspace) = editor.workspace() else {
12918 return Navigated::No;
12919 };
12920 let pane = workspace.read(cx).active_pane().clone();
12921
12922 let range = target.range.to_point(target.buffer.read(cx));
12923 let range = editor.range_for_match(&range);
12924 let range = collapse_multiline_range(range);
12925
12926 if !split
12927 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12928 {
12929 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12930 } else {
12931 window.defer(cx, move |window, cx| {
12932 let target_editor: Entity<Self> =
12933 workspace.update(cx, |workspace, cx| {
12934 let pane = if split {
12935 workspace.adjacent_pane(window, cx)
12936 } else {
12937 workspace.active_pane().clone()
12938 };
12939
12940 workspace.open_project_item(
12941 pane,
12942 target.buffer.clone(),
12943 true,
12944 true,
12945 window,
12946 cx,
12947 )
12948 });
12949 target_editor.update(cx, |target_editor, cx| {
12950 // When selecting a definition in a different buffer, disable the nav history
12951 // to avoid creating a history entry at the previous cursor location.
12952 pane.update(cx, |pane, _| pane.disable_history());
12953 target_editor.go_to_singleton_buffer_range(range, window, cx);
12954 pane.update(cx, |pane, _| pane.enable_history());
12955 });
12956 });
12957 }
12958 Navigated::Yes
12959 })
12960 })
12961 } else if !definitions.is_empty() {
12962 cx.spawn_in(window, async move |editor, cx| {
12963 let (title, location_tasks, workspace) = editor
12964 .update_in(cx, |editor, window, cx| {
12965 let tab_kind = match kind {
12966 Some(GotoDefinitionKind::Implementation) => "Implementations",
12967 _ => "Definitions",
12968 };
12969 let title = definitions
12970 .iter()
12971 .find_map(|definition| match definition {
12972 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12973 let buffer = origin.buffer.read(cx);
12974 format!(
12975 "{} for {}",
12976 tab_kind,
12977 buffer
12978 .text_for_range(origin.range.clone())
12979 .collect::<String>()
12980 )
12981 }),
12982 HoverLink::InlayHint(_, _) => None,
12983 HoverLink::Url(_) => None,
12984 HoverLink::File(_) => None,
12985 })
12986 .unwrap_or(tab_kind.to_string());
12987 let location_tasks = definitions
12988 .into_iter()
12989 .map(|definition| match definition {
12990 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12991 HoverLink::InlayHint(lsp_location, server_id) => editor
12992 .compute_target_location(lsp_location, server_id, window, cx),
12993 HoverLink::Url(_) => Task::ready(Ok(None)),
12994 HoverLink::File(_) => Task::ready(Ok(None)),
12995 })
12996 .collect::<Vec<_>>();
12997 (title, location_tasks, editor.workspace().clone())
12998 })
12999 .context("location tasks preparation")?;
13000
13001 let locations = future::join_all(location_tasks)
13002 .await
13003 .into_iter()
13004 .filter_map(|location| location.transpose())
13005 .collect::<Result<_>>()
13006 .context("location tasks")?;
13007
13008 let Some(workspace) = workspace else {
13009 return Ok(Navigated::No);
13010 };
13011 let opened = workspace
13012 .update_in(cx, |workspace, window, cx| {
13013 Self::open_locations_in_multibuffer(
13014 workspace,
13015 locations,
13016 title,
13017 split,
13018 MultibufferSelectionMode::First,
13019 window,
13020 cx,
13021 )
13022 })
13023 .ok();
13024
13025 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13026 })
13027 } else {
13028 Task::ready(Ok(Navigated::No))
13029 }
13030 }
13031
13032 fn compute_target_location(
13033 &self,
13034 lsp_location: lsp::Location,
13035 server_id: LanguageServerId,
13036 window: &mut Window,
13037 cx: &mut Context<Self>,
13038 ) -> Task<anyhow::Result<Option<Location>>> {
13039 let Some(project) = self.project.clone() else {
13040 return Task::ready(Ok(None));
13041 };
13042
13043 cx.spawn_in(window, async move |editor, cx| {
13044 let location_task = editor.update(cx, |_, cx| {
13045 project.update(cx, |project, cx| {
13046 let language_server_name = project
13047 .language_server_statuses(cx)
13048 .find(|(id, _)| server_id == *id)
13049 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13050 language_server_name.map(|language_server_name| {
13051 project.open_local_buffer_via_lsp(
13052 lsp_location.uri.clone(),
13053 server_id,
13054 language_server_name,
13055 cx,
13056 )
13057 })
13058 })
13059 })?;
13060 let location = match location_task {
13061 Some(task) => Some({
13062 let target_buffer_handle = task.await.context("open local buffer")?;
13063 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13064 let target_start = target_buffer
13065 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13066 let target_end = target_buffer
13067 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13068 target_buffer.anchor_after(target_start)
13069 ..target_buffer.anchor_before(target_end)
13070 })?;
13071 Location {
13072 buffer: target_buffer_handle,
13073 range,
13074 }
13075 }),
13076 None => None,
13077 };
13078 Ok(location)
13079 })
13080 }
13081
13082 pub fn find_all_references(
13083 &mut self,
13084 _: &FindAllReferences,
13085 window: &mut Window,
13086 cx: &mut Context<Self>,
13087 ) -> Option<Task<Result<Navigated>>> {
13088 let selection = self.selections.newest::<usize>(cx);
13089 let multi_buffer = self.buffer.read(cx);
13090 let head = selection.head();
13091
13092 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13093 let head_anchor = multi_buffer_snapshot.anchor_at(
13094 head,
13095 if head < selection.tail() {
13096 Bias::Right
13097 } else {
13098 Bias::Left
13099 },
13100 );
13101
13102 match self
13103 .find_all_references_task_sources
13104 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13105 {
13106 Ok(_) => {
13107 log::info!(
13108 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13109 );
13110 return None;
13111 }
13112 Err(i) => {
13113 self.find_all_references_task_sources.insert(i, head_anchor);
13114 }
13115 }
13116
13117 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13118 let workspace = self.workspace()?;
13119 let project = workspace.read(cx).project().clone();
13120 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13121 Some(cx.spawn_in(window, async move |editor, cx| {
13122 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13123 if let Ok(i) = editor
13124 .find_all_references_task_sources
13125 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13126 {
13127 editor.find_all_references_task_sources.remove(i);
13128 }
13129 });
13130
13131 let locations = references.await?;
13132 if locations.is_empty() {
13133 return anyhow::Ok(Navigated::No);
13134 }
13135
13136 workspace.update_in(cx, |workspace, window, cx| {
13137 let title = locations
13138 .first()
13139 .as_ref()
13140 .map(|location| {
13141 let buffer = location.buffer.read(cx);
13142 format!(
13143 "References to `{}`",
13144 buffer
13145 .text_for_range(location.range.clone())
13146 .collect::<String>()
13147 )
13148 })
13149 .unwrap();
13150 Self::open_locations_in_multibuffer(
13151 workspace,
13152 locations,
13153 title,
13154 false,
13155 MultibufferSelectionMode::First,
13156 window,
13157 cx,
13158 );
13159 Navigated::Yes
13160 })
13161 }))
13162 }
13163
13164 /// Opens a multibuffer with the given project locations in it
13165 pub fn open_locations_in_multibuffer(
13166 workspace: &mut Workspace,
13167 mut locations: Vec<Location>,
13168 title: String,
13169 split: bool,
13170 multibuffer_selection_mode: MultibufferSelectionMode,
13171 window: &mut Window,
13172 cx: &mut Context<Workspace>,
13173 ) {
13174 // If there are multiple definitions, open them in a multibuffer
13175 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13176 let mut locations = locations.into_iter().peekable();
13177 let mut ranges = Vec::new();
13178 let capability = workspace.project().read(cx).capability();
13179
13180 let excerpt_buffer = cx.new(|cx| {
13181 let mut multibuffer = MultiBuffer::new(capability);
13182 while let Some(location) = locations.next() {
13183 let buffer = location.buffer.read(cx);
13184 let mut ranges_for_buffer = Vec::new();
13185 let range = location.range.to_offset(buffer);
13186 ranges_for_buffer.push(range.clone());
13187
13188 while let Some(next_location) = locations.peek() {
13189 if next_location.buffer == location.buffer {
13190 ranges_for_buffer.push(next_location.range.to_offset(buffer));
13191 locations.next();
13192 } else {
13193 break;
13194 }
13195 }
13196
13197 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13198 ranges.extend(multibuffer.push_excerpts_with_context_lines(
13199 location.buffer.clone(),
13200 ranges_for_buffer,
13201 DEFAULT_MULTIBUFFER_CONTEXT,
13202 cx,
13203 ))
13204 }
13205
13206 multibuffer.with_title(title)
13207 });
13208
13209 let editor = cx.new(|cx| {
13210 Editor::for_multibuffer(
13211 excerpt_buffer,
13212 Some(workspace.project().clone()),
13213 window,
13214 cx,
13215 )
13216 });
13217 editor.update(cx, |editor, cx| {
13218 match multibuffer_selection_mode {
13219 MultibufferSelectionMode::First => {
13220 if let Some(first_range) = ranges.first() {
13221 editor.change_selections(None, window, cx, |selections| {
13222 selections.clear_disjoint();
13223 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13224 });
13225 }
13226 editor.highlight_background::<Self>(
13227 &ranges,
13228 |theme| theme.editor_highlighted_line_background,
13229 cx,
13230 );
13231 }
13232 MultibufferSelectionMode::All => {
13233 editor.change_selections(None, window, cx, |selections| {
13234 selections.clear_disjoint();
13235 selections.select_anchor_ranges(ranges);
13236 });
13237 }
13238 }
13239 editor.register_buffers_with_language_servers(cx);
13240 });
13241
13242 let item = Box::new(editor);
13243 let item_id = item.item_id();
13244
13245 if split {
13246 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13247 } else {
13248 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13249 let (preview_item_id, preview_item_idx) =
13250 workspace.active_pane().update(cx, |pane, _| {
13251 (pane.preview_item_id(), pane.preview_item_idx())
13252 });
13253
13254 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13255
13256 if let Some(preview_item_id) = preview_item_id {
13257 workspace.active_pane().update(cx, |pane, cx| {
13258 pane.remove_item(preview_item_id, false, false, window, cx);
13259 });
13260 }
13261 } else {
13262 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13263 }
13264 }
13265 workspace.active_pane().update(cx, |pane, cx| {
13266 pane.set_preview_item_id(Some(item_id), cx);
13267 });
13268 }
13269
13270 pub fn rename(
13271 &mut self,
13272 _: &Rename,
13273 window: &mut Window,
13274 cx: &mut Context<Self>,
13275 ) -> Option<Task<Result<()>>> {
13276 use language::ToOffset as _;
13277
13278 let provider = self.semantics_provider.clone()?;
13279 let selection = self.selections.newest_anchor().clone();
13280 let (cursor_buffer, cursor_buffer_position) = self
13281 .buffer
13282 .read(cx)
13283 .text_anchor_for_position(selection.head(), cx)?;
13284 let (tail_buffer, cursor_buffer_position_end) = self
13285 .buffer
13286 .read(cx)
13287 .text_anchor_for_position(selection.tail(), cx)?;
13288 if tail_buffer != cursor_buffer {
13289 return None;
13290 }
13291
13292 let snapshot = cursor_buffer.read(cx).snapshot();
13293 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13294 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13295 let prepare_rename = provider
13296 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13297 .unwrap_or_else(|| Task::ready(Ok(None)));
13298 drop(snapshot);
13299
13300 Some(cx.spawn_in(window, async move |this, cx| {
13301 let rename_range = if let Some(range) = prepare_rename.await? {
13302 Some(range)
13303 } else {
13304 this.update(cx, |this, cx| {
13305 let buffer = this.buffer.read(cx).snapshot(cx);
13306 let mut buffer_highlights = this
13307 .document_highlights_for_position(selection.head(), &buffer)
13308 .filter(|highlight| {
13309 highlight.start.excerpt_id == selection.head().excerpt_id
13310 && highlight.end.excerpt_id == selection.head().excerpt_id
13311 });
13312 buffer_highlights
13313 .next()
13314 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13315 })?
13316 };
13317 if let Some(rename_range) = rename_range {
13318 this.update_in(cx, |this, window, cx| {
13319 let snapshot = cursor_buffer.read(cx).snapshot();
13320 let rename_buffer_range = rename_range.to_offset(&snapshot);
13321 let cursor_offset_in_rename_range =
13322 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13323 let cursor_offset_in_rename_range_end =
13324 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13325
13326 this.take_rename(false, window, cx);
13327 let buffer = this.buffer.read(cx).read(cx);
13328 let cursor_offset = selection.head().to_offset(&buffer);
13329 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13330 let rename_end = rename_start + rename_buffer_range.len();
13331 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13332 let mut old_highlight_id = None;
13333 let old_name: Arc<str> = buffer
13334 .chunks(rename_start..rename_end, true)
13335 .map(|chunk| {
13336 if old_highlight_id.is_none() {
13337 old_highlight_id = chunk.syntax_highlight_id;
13338 }
13339 chunk.text
13340 })
13341 .collect::<String>()
13342 .into();
13343
13344 drop(buffer);
13345
13346 // Position the selection in the rename editor so that it matches the current selection.
13347 this.show_local_selections = false;
13348 let rename_editor = cx.new(|cx| {
13349 let mut editor = Editor::single_line(window, cx);
13350 editor.buffer.update(cx, |buffer, cx| {
13351 buffer.edit([(0..0, old_name.clone())], None, cx)
13352 });
13353 let rename_selection_range = match cursor_offset_in_rename_range
13354 .cmp(&cursor_offset_in_rename_range_end)
13355 {
13356 Ordering::Equal => {
13357 editor.select_all(&SelectAll, window, cx);
13358 return editor;
13359 }
13360 Ordering::Less => {
13361 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13362 }
13363 Ordering::Greater => {
13364 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13365 }
13366 };
13367 if rename_selection_range.end > old_name.len() {
13368 editor.select_all(&SelectAll, window, cx);
13369 } else {
13370 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13371 s.select_ranges([rename_selection_range]);
13372 });
13373 }
13374 editor
13375 });
13376 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13377 if e == &EditorEvent::Focused {
13378 cx.emit(EditorEvent::FocusedIn)
13379 }
13380 })
13381 .detach();
13382
13383 let write_highlights =
13384 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13385 let read_highlights =
13386 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13387 let ranges = write_highlights
13388 .iter()
13389 .flat_map(|(_, ranges)| ranges.iter())
13390 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13391 .cloned()
13392 .collect();
13393
13394 this.highlight_text::<Rename>(
13395 ranges,
13396 HighlightStyle {
13397 fade_out: Some(0.6),
13398 ..Default::default()
13399 },
13400 cx,
13401 );
13402 let rename_focus_handle = rename_editor.focus_handle(cx);
13403 window.focus(&rename_focus_handle);
13404 let block_id = this.insert_blocks(
13405 [BlockProperties {
13406 style: BlockStyle::Flex,
13407 placement: BlockPlacement::Below(range.start),
13408 height: 1,
13409 render: Arc::new({
13410 let rename_editor = rename_editor.clone();
13411 move |cx: &mut BlockContext| {
13412 let mut text_style = cx.editor_style.text.clone();
13413 if let Some(highlight_style) = old_highlight_id
13414 .and_then(|h| h.style(&cx.editor_style.syntax))
13415 {
13416 text_style = text_style.highlight(highlight_style);
13417 }
13418 div()
13419 .block_mouse_down()
13420 .pl(cx.anchor_x)
13421 .child(EditorElement::new(
13422 &rename_editor,
13423 EditorStyle {
13424 background: cx.theme().system().transparent,
13425 local_player: cx.editor_style.local_player,
13426 text: text_style,
13427 scrollbar_width: cx.editor_style.scrollbar_width,
13428 syntax: cx.editor_style.syntax.clone(),
13429 status: cx.editor_style.status.clone(),
13430 inlay_hints_style: HighlightStyle {
13431 font_weight: Some(FontWeight::BOLD),
13432 ..make_inlay_hints_style(cx.app)
13433 },
13434 inline_completion_styles: make_suggestion_styles(
13435 cx.app,
13436 ),
13437 ..EditorStyle::default()
13438 },
13439 ))
13440 .into_any_element()
13441 }
13442 }),
13443 priority: 0,
13444 }],
13445 Some(Autoscroll::fit()),
13446 cx,
13447 )[0];
13448 this.pending_rename = Some(RenameState {
13449 range,
13450 old_name,
13451 editor: rename_editor,
13452 block_id,
13453 });
13454 })?;
13455 }
13456
13457 Ok(())
13458 }))
13459 }
13460
13461 pub fn confirm_rename(
13462 &mut self,
13463 _: &ConfirmRename,
13464 window: &mut Window,
13465 cx: &mut Context<Self>,
13466 ) -> Option<Task<Result<()>>> {
13467 let rename = self.take_rename(false, window, cx)?;
13468 let workspace = self.workspace()?.downgrade();
13469 let (buffer, start) = self
13470 .buffer
13471 .read(cx)
13472 .text_anchor_for_position(rename.range.start, cx)?;
13473 let (end_buffer, _) = self
13474 .buffer
13475 .read(cx)
13476 .text_anchor_for_position(rename.range.end, cx)?;
13477 if buffer != end_buffer {
13478 return None;
13479 }
13480
13481 let old_name = rename.old_name;
13482 let new_name = rename.editor.read(cx).text(cx);
13483
13484 let rename = self.semantics_provider.as_ref()?.perform_rename(
13485 &buffer,
13486 start,
13487 new_name.clone(),
13488 cx,
13489 )?;
13490
13491 Some(cx.spawn_in(window, async move |editor, cx| {
13492 let project_transaction = rename.await?;
13493 Self::open_project_transaction(
13494 &editor,
13495 workspace,
13496 project_transaction,
13497 format!("Rename: {} → {}", old_name, new_name),
13498 cx,
13499 )
13500 .await?;
13501
13502 editor.update(cx, |editor, cx| {
13503 editor.refresh_document_highlights(cx);
13504 })?;
13505 Ok(())
13506 }))
13507 }
13508
13509 fn take_rename(
13510 &mut self,
13511 moving_cursor: bool,
13512 window: &mut Window,
13513 cx: &mut Context<Self>,
13514 ) -> Option<RenameState> {
13515 let rename = self.pending_rename.take()?;
13516 if rename.editor.focus_handle(cx).is_focused(window) {
13517 window.focus(&self.focus_handle);
13518 }
13519
13520 self.remove_blocks(
13521 [rename.block_id].into_iter().collect(),
13522 Some(Autoscroll::fit()),
13523 cx,
13524 );
13525 self.clear_highlights::<Rename>(cx);
13526 self.show_local_selections = true;
13527
13528 if moving_cursor {
13529 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13530 editor.selections.newest::<usize>(cx).head()
13531 });
13532
13533 // Update the selection to match the position of the selection inside
13534 // the rename editor.
13535 let snapshot = self.buffer.read(cx).read(cx);
13536 let rename_range = rename.range.to_offset(&snapshot);
13537 let cursor_in_editor = snapshot
13538 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13539 .min(rename_range.end);
13540 drop(snapshot);
13541
13542 self.change_selections(None, window, cx, |s| {
13543 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13544 });
13545 } else {
13546 self.refresh_document_highlights(cx);
13547 }
13548
13549 Some(rename)
13550 }
13551
13552 pub fn pending_rename(&self) -> Option<&RenameState> {
13553 self.pending_rename.as_ref()
13554 }
13555
13556 fn format(
13557 &mut self,
13558 _: &Format,
13559 window: &mut Window,
13560 cx: &mut Context<Self>,
13561 ) -> Option<Task<Result<()>>> {
13562 let project = match &self.project {
13563 Some(project) => project.clone(),
13564 None => return None,
13565 };
13566
13567 Some(self.perform_format(
13568 project,
13569 FormatTrigger::Manual,
13570 FormatTarget::Buffers,
13571 window,
13572 cx,
13573 ))
13574 }
13575
13576 fn format_selections(
13577 &mut self,
13578 _: &FormatSelections,
13579 window: &mut Window,
13580 cx: &mut Context<Self>,
13581 ) -> Option<Task<Result<()>>> {
13582 let project = match &self.project {
13583 Some(project) => project.clone(),
13584 None => return None,
13585 };
13586
13587 let ranges = self
13588 .selections
13589 .all_adjusted(cx)
13590 .into_iter()
13591 .map(|selection| selection.range())
13592 .collect_vec();
13593
13594 Some(self.perform_format(
13595 project,
13596 FormatTrigger::Manual,
13597 FormatTarget::Ranges(ranges),
13598 window,
13599 cx,
13600 ))
13601 }
13602
13603 fn perform_format(
13604 &mut self,
13605 project: Entity<Project>,
13606 trigger: FormatTrigger,
13607 target: FormatTarget,
13608 window: &mut Window,
13609 cx: &mut Context<Self>,
13610 ) -> Task<Result<()>> {
13611 let buffer = self.buffer.clone();
13612 let (buffers, target) = match target {
13613 FormatTarget::Buffers => {
13614 let mut buffers = buffer.read(cx).all_buffers();
13615 if trigger == FormatTrigger::Save {
13616 buffers.retain(|buffer| buffer.read(cx).is_dirty());
13617 }
13618 (buffers, LspFormatTarget::Buffers)
13619 }
13620 FormatTarget::Ranges(selection_ranges) => {
13621 let multi_buffer = buffer.read(cx);
13622 let snapshot = multi_buffer.read(cx);
13623 let mut buffers = HashSet::default();
13624 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13625 BTreeMap::new();
13626 for selection_range in selection_ranges {
13627 for (buffer, buffer_range, _) in
13628 snapshot.range_to_buffer_ranges(selection_range)
13629 {
13630 let buffer_id = buffer.remote_id();
13631 let start = buffer.anchor_before(buffer_range.start);
13632 let end = buffer.anchor_after(buffer_range.end);
13633 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13634 buffer_id_to_ranges
13635 .entry(buffer_id)
13636 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13637 .or_insert_with(|| vec![start..end]);
13638 }
13639 }
13640 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13641 }
13642 };
13643
13644 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13645 let format = project.update(cx, |project, cx| {
13646 project.format(buffers, target, true, trigger, cx)
13647 });
13648
13649 cx.spawn_in(window, async move |_, cx| {
13650 let transaction = futures::select_biased! {
13651 transaction = format.log_err().fuse() => transaction,
13652 () = timeout => {
13653 log::warn!("timed out waiting for formatting");
13654 None
13655 }
13656 };
13657
13658 buffer
13659 .update(cx, |buffer, cx| {
13660 if let Some(transaction) = transaction {
13661 if !buffer.is_singleton() {
13662 buffer.push_transaction(&transaction.0, cx);
13663 }
13664 }
13665 cx.notify();
13666 })
13667 .ok();
13668
13669 Ok(())
13670 })
13671 }
13672
13673 fn organize_imports(
13674 &mut self,
13675 _: &OrganizeImports,
13676 window: &mut Window,
13677 cx: &mut Context<Self>,
13678 ) -> Option<Task<Result<()>>> {
13679 let project = match &self.project {
13680 Some(project) => project.clone(),
13681 None => return None,
13682 };
13683 Some(self.perform_code_action_kind(
13684 project,
13685 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13686 window,
13687 cx,
13688 ))
13689 }
13690
13691 fn perform_code_action_kind(
13692 &mut self,
13693 project: Entity<Project>,
13694 kind: CodeActionKind,
13695 window: &mut Window,
13696 cx: &mut Context<Self>,
13697 ) -> Task<Result<()>> {
13698 let buffer = self.buffer.clone();
13699 let buffers = buffer.read(cx).all_buffers();
13700 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13701 let apply_action = project.update(cx, |project, cx| {
13702 project.apply_code_action_kind(buffers, kind, true, cx)
13703 });
13704 cx.spawn_in(window, async move |_, cx| {
13705 let transaction = futures::select_biased! {
13706 () = timeout => {
13707 log::warn!("timed out waiting for executing code action");
13708 None
13709 }
13710 transaction = apply_action.log_err().fuse() => transaction,
13711 };
13712 buffer
13713 .update(cx, |buffer, cx| {
13714 // check if we need this
13715 if let Some(transaction) = transaction {
13716 if !buffer.is_singleton() {
13717 buffer.push_transaction(&transaction.0, cx);
13718 }
13719 }
13720 cx.notify();
13721 })
13722 .ok();
13723 Ok(())
13724 })
13725 }
13726
13727 fn restart_language_server(
13728 &mut self,
13729 _: &RestartLanguageServer,
13730 _: &mut Window,
13731 cx: &mut Context<Self>,
13732 ) {
13733 if let Some(project) = self.project.clone() {
13734 self.buffer.update(cx, |multi_buffer, cx| {
13735 project.update(cx, |project, cx| {
13736 project.restart_language_servers_for_buffers(
13737 multi_buffer.all_buffers().into_iter().collect(),
13738 cx,
13739 );
13740 });
13741 })
13742 }
13743 }
13744
13745 fn cancel_language_server_work(
13746 workspace: &mut Workspace,
13747 _: &actions::CancelLanguageServerWork,
13748 _: &mut Window,
13749 cx: &mut Context<Workspace>,
13750 ) {
13751 let project = workspace.project();
13752 let buffers = workspace
13753 .active_item(cx)
13754 .and_then(|item| item.act_as::<Editor>(cx))
13755 .map_or(HashSet::default(), |editor| {
13756 editor.read(cx).buffer.read(cx).all_buffers()
13757 });
13758 project.update(cx, |project, cx| {
13759 project.cancel_language_server_work_for_buffers(buffers, cx);
13760 });
13761 }
13762
13763 fn show_character_palette(
13764 &mut self,
13765 _: &ShowCharacterPalette,
13766 window: &mut Window,
13767 _: &mut Context<Self>,
13768 ) {
13769 window.show_character_palette();
13770 }
13771
13772 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13773 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13774 let buffer = self.buffer.read(cx).snapshot(cx);
13775 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13776 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13777 let is_valid = buffer
13778 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13779 .any(|entry| {
13780 entry.diagnostic.is_primary
13781 && !entry.range.is_empty()
13782 && entry.range.start == primary_range_start
13783 && entry.diagnostic.message == active_diagnostics.primary_message
13784 });
13785
13786 if is_valid != active_diagnostics.is_valid {
13787 active_diagnostics.is_valid = is_valid;
13788 if is_valid {
13789 let mut new_styles = HashMap::default();
13790 for (block_id, diagnostic) in &active_diagnostics.blocks {
13791 new_styles.insert(
13792 *block_id,
13793 diagnostic_block_renderer(diagnostic.clone(), None, true),
13794 );
13795 }
13796 self.display_map.update(cx, |display_map, _cx| {
13797 display_map.replace_blocks(new_styles);
13798 });
13799 } else {
13800 self.dismiss_diagnostics(cx);
13801 }
13802 }
13803 }
13804 }
13805
13806 fn activate_diagnostics(
13807 &mut self,
13808 buffer_id: BufferId,
13809 group_id: usize,
13810 window: &mut Window,
13811 cx: &mut Context<Self>,
13812 ) {
13813 self.dismiss_diagnostics(cx);
13814 let snapshot = self.snapshot(window, cx);
13815 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13816 let buffer = self.buffer.read(cx).snapshot(cx);
13817
13818 let mut primary_range = None;
13819 let mut primary_message = None;
13820 let diagnostic_group = buffer
13821 .diagnostic_group(buffer_id, group_id)
13822 .filter_map(|entry| {
13823 let start = entry.range.start;
13824 let end = entry.range.end;
13825 if snapshot.is_line_folded(MultiBufferRow(start.row))
13826 && (start.row == end.row
13827 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13828 {
13829 return None;
13830 }
13831 if entry.diagnostic.is_primary {
13832 primary_range = Some(entry.range.clone());
13833 primary_message = Some(entry.diagnostic.message.clone());
13834 }
13835 Some(entry)
13836 })
13837 .collect::<Vec<_>>();
13838 let primary_range = primary_range?;
13839 let primary_message = primary_message?;
13840
13841 let blocks = display_map
13842 .insert_blocks(
13843 diagnostic_group.iter().map(|entry| {
13844 let diagnostic = entry.diagnostic.clone();
13845 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13846 BlockProperties {
13847 style: BlockStyle::Fixed,
13848 placement: BlockPlacement::Below(
13849 buffer.anchor_after(entry.range.start),
13850 ),
13851 height: message_height,
13852 render: diagnostic_block_renderer(diagnostic, None, true),
13853 priority: 0,
13854 }
13855 }),
13856 cx,
13857 )
13858 .into_iter()
13859 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13860 .collect();
13861
13862 Some(ActiveDiagnosticGroup {
13863 primary_range: buffer.anchor_before(primary_range.start)
13864 ..buffer.anchor_after(primary_range.end),
13865 primary_message,
13866 group_id,
13867 blocks,
13868 is_valid: true,
13869 })
13870 });
13871 }
13872
13873 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13874 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13875 self.display_map.update(cx, |display_map, cx| {
13876 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13877 });
13878 cx.notify();
13879 }
13880 }
13881
13882 /// Disable inline diagnostics rendering for this editor.
13883 pub fn disable_inline_diagnostics(&mut self) {
13884 self.inline_diagnostics_enabled = false;
13885 self.inline_diagnostics_update = Task::ready(());
13886 self.inline_diagnostics.clear();
13887 }
13888
13889 pub fn inline_diagnostics_enabled(&self) -> bool {
13890 self.inline_diagnostics_enabled
13891 }
13892
13893 pub fn show_inline_diagnostics(&self) -> bool {
13894 self.show_inline_diagnostics
13895 }
13896
13897 pub fn toggle_inline_diagnostics(
13898 &mut self,
13899 _: &ToggleInlineDiagnostics,
13900 window: &mut Window,
13901 cx: &mut Context<'_, Editor>,
13902 ) {
13903 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13904 self.refresh_inline_diagnostics(false, window, cx);
13905 }
13906
13907 fn refresh_inline_diagnostics(
13908 &mut self,
13909 debounce: bool,
13910 window: &mut Window,
13911 cx: &mut Context<Self>,
13912 ) {
13913 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13914 self.inline_diagnostics_update = Task::ready(());
13915 self.inline_diagnostics.clear();
13916 return;
13917 }
13918
13919 let debounce_ms = ProjectSettings::get_global(cx)
13920 .diagnostics
13921 .inline
13922 .update_debounce_ms;
13923 let debounce = if debounce && debounce_ms > 0 {
13924 Some(Duration::from_millis(debounce_ms))
13925 } else {
13926 None
13927 };
13928 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
13929 if let Some(debounce) = debounce {
13930 cx.background_executor().timer(debounce).await;
13931 }
13932 let Some(snapshot) = editor
13933 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13934 .ok()
13935 else {
13936 return;
13937 };
13938
13939 let new_inline_diagnostics = cx
13940 .background_spawn(async move {
13941 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13942 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13943 let message = diagnostic_entry
13944 .diagnostic
13945 .message
13946 .split_once('\n')
13947 .map(|(line, _)| line)
13948 .map(SharedString::new)
13949 .unwrap_or_else(|| {
13950 SharedString::from(diagnostic_entry.diagnostic.message)
13951 });
13952 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13953 let (Ok(i) | Err(i)) = inline_diagnostics
13954 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13955 inline_diagnostics.insert(
13956 i,
13957 (
13958 start_anchor,
13959 InlineDiagnostic {
13960 message,
13961 group_id: diagnostic_entry.diagnostic.group_id,
13962 start: diagnostic_entry.range.start.to_point(&snapshot),
13963 is_primary: diagnostic_entry.diagnostic.is_primary,
13964 severity: diagnostic_entry.diagnostic.severity,
13965 },
13966 ),
13967 );
13968 }
13969 inline_diagnostics
13970 })
13971 .await;
13972
13973 editor
13974 .update(cx, |editor, cx| {
13975 editor.inline_diagnostics = new_inline_diagnostics;
13976 cx.notify();
13977 })
13978 .ok();
13979 });
13980 }
13981
13982 pub fn set_selections_from_remote(
13983 &mut self,
13984 selections: Vec<Selection<Anchor>>,
13985 pending_selection: Option<Selection<Anchor>>,
13986 window: &mut Window,
13987 cx: &mut Context<Self>,
13988 ) {
13989 let old_cursor_position = self.selections.newest_anchor().head();
13990 self.selections.change_with(cx, |s| {
13991 s.select_anchors(selections);
13992 if let Some(pending_selection) = pending_selection {
13993 s.set_pending(pending_selection, SelectMode::Character);
13994 } else {
13995 s.clear_pending();
13996 }
13997 });
13998 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13999 }
14000
14001 fn push_to_selection_history(&mut self) {
14002 self.selection_history.push(SelectionHistoryEntry {
14003 selections: self.selections.disjoint_anchors(),
14004 select_next_state: self.select_next_state.clone(),
14005 select_prev_state: self.select_prev_state.clone(),
14006 add_selections_state: self.add_selections_state.clone(),
14007 });
14008 }
14009
14010 pub fn transact(
14011 &mut self,
14012 window: &mut Window,
14013 cx: &mut Context<Self>,
14014 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14015 ) -> Option<TransactionId> {
14016 self.start_transaction_at(Instant::now(), window, cx);
14017 update(self, window, cx);
14018 self.end_transaction_at(Instant::now(), cx)
14019 }
14020
14021 pub fn start_transaction_at(
14022 &mut self,
14023 now: Instant,
14024 window: &mut Window,
14025 cx: &mut Context<Self>,
14026 ) {
14027 self.end_selection(window, cx);
14028 if let Some(tx_id) = self
14029 .buffer
14030 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14031 {
14032 self.selection_history
14033 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14034 cx.emit(EditorEvent::TransactionBegun {
14035 transaction_id: tx_id,
14036 })
14037 }
14038 }
14039
14040 pub fn end_transaction_at(
14041 &mut self,
14042 now: Instant,
14043 cx: &mut Context<Self>,
14044 ) -> Option<TransactionId> {
14045 if let Some(transaction_id) = self
14046 .buffer
14047 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14048 {
14049 if let Some((_, end_selections)) =
14050 self.selection_history.transaction_mut(transaction_id)
14051 {
14052 *end_selections = Some(self.selections.disjoint_anchors());
14053 } else {
14054 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14055 }
14056
14057 cx.emit(EditorEvent::Edited { transaction_id });
14058 Some(transaction_id)
14059 } else {
14060 None
14061 }
14062 }
14063
14064 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14065 if self.selection_mark_mode {
14066 self.change_selections(None, window, cx, |s| {
14067 s.move_with(|_, sel| {
14068 sel.collapse_to(sel.head(), SelectionGoal::None);
14069 });
14070 })
14071 }
14072 self.selection_mark_mode = true;
14073 cx.notify();
14074 }
14075
14076 pub fn swap_selection_ends(
14077 &mut self,
14078 _: &actions::SwapSelectionEnds,
14079 window: &mut Window,
14080 cx: &mut Context<Self>,
14081 ) {
14082 self.change_selections(None, window, cx, |s| {
14083 s.move_with(|_, sel| {
14084 if sel.start != sel.end {
14085 sel.reversed = !sel.reversed
14086 }
14087 });
14088 });
14089 self.request_autoscroll(Autoscroll::newest(), cx);
14090 cx.notify();
14091 }
14092
14093 pub fn toggle_fold(
14094 &mut self,
14095 _: &actions::ToggleFold,
14096 window: &mut Window,
14097 cx: &mut Context<Self>,
14098 ) {
14099 if self.is_singleton(cx) {
14100 let selection = self.selections.newest::<Point>(cx);
14101
14102 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14103 let range = if selection.is_empty() {
14104 let point = selection.head().to_display_point(&display_map);
14105 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14106 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14107 .to_point(&display_map);
14108 start..end
14109 } else {
14110 selection.range()
14111 };
14112 if display_map.folds_in_range(range).next().is_some() {
14113 self.unfold_lines(&Default::default(), window, cx)
14114 } else {
14115 self.fold(&Default::default(), window, cx)
14116 }
14117 } else {
14118 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14119 let buffer_ids: HashSet<_> = self
14120 .selections
14121 .disjoint_anchor_ranges()
14122 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14123 .collect();
14124
14125 let should_unfold = buffer_ids
14126 .iter()
14127 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14128
14129 for buffer_id in buffer_ids {
14130 if should_unfold {
14131 self.unfold_buffer(buffer_id, cx);
14132 } else {
14133 self.fold_buffer(buffer_id, cx);
14134 }
14135 }
14136 }
14137 }
14138
14139 pub fn toggle_fold_recursive(
14140 &mut self,
14141 _: &actions::ToggleFoldRecursive,
14142 window: &mut Window,
14143 cx: &mut Context<Self>,
14144 ) {
14145 let selection = self.selections.newest::<Point>(cx);
14146
14147 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14148 let range = if selection.is_empty() {
14149 let point = selection.head().to_display_point(&display_map);
14150 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14151 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14152 .to_point(&display_map);
14153 start..end
14154 } else {
14155 selection.range()
14156 };
14157 if display_map.folds_in_range(range).next().is_some() {
14158 self.unfold_recursive(&Default::default(), window, cx)
14159 } else {
14160 self.fold_recursive(&Default::default(), window, cx)
14161 }
14162 }
14163
14164 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14165 if self.is_singleton(cx) {
14166 let mut to_fold = Vec::new();
14167 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14168 let selections = self.selections.all_adjusted(cx);
14169
14170 for selection in selections {
14171 let range = selection.range().sorted();
14172 let buffer_start_row = range.start.row;
14173
14174 if range.start.row != range.end.row {
14175 let mut found = false;
14176 let mut row = range.start.row;
14177 while row <= range.end.row {
14178 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14179 {
14180 found = true;
14181 row = crease.range().end.row + 1;
14182 to_fold.push(crease);
14183 } else {
14184 row += 1
14185 }
14186 }
14187 if found {
14188 continue;
14189 }
14190 }
14191
14192 for row in (0..=range.start.row).rev() {
14193 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14194 if crease.range().end.row >= buffer_start_row {
14195 to_fold.push(crease);
14196 if row <= range.start.row {
14197 break;
14198 }
14199 }
14200 }
14201 }
14202 }
14203
14204 self.fold_creases(to_fold, true, window, cx);
14205 } else {
14206 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14207 let buffer_ids = self
14208 .selections
14209 .disjoint_anchor_ranges()
14210 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14211 .collect::<HashSet<_>>();
14212 for buffer_id in buffer_ids {
14213 self.fold_buffer(buffer_id, cx);
14214 }
14215 }
14216 }
14217
14218 fn fold_at_level(
14219 &mut self,
14220 fold_at: &FoldAtLevel,
14221 window: &mut Window,
14222 cx: &mut Context<Self>,
14223 ) {
14224 if !self.buffer.read(cx).is_singleton() {
14225 return;
14226 }
14227
14228 let fold_at_level = fold_at.0;
14229 let snapshot = self.buffer.read(cx).snapshot(cx);
14230 let mut to_fold = Vec::new();
14231 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14232
14233 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14234 while start_row < end_row {
14235 match self
14236 .snapshot(window, cx)
14237 .crease_for_buffer_row(MultiBufferRow(start_row))
14238 {
14239 Some(crease) => {
14240 let nested_start_row = crease.range().start.row + 1;
14241 let nested_end_row = crease.range().end.row;
14242
14243 if current_level < fold_at_level {
14244 stack.push((nested_start_row, nested_end_row, current_level + 1));
14245 } else if current_level == fold_at_level {
14246 to_fold.push(crease);
14247 }
14248
14249 start_row = nested_end_row + 1;
14250 }
14251 None => start_row += 1,
14252 }
14253 }
14254 }
14255
14256 self.fold_creases(to_fold, true, window, cx);
14257 }
14258
14259 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14260 if self.buffer.read(cx).is_singleton() {
14261 let mut fold_ranges = Vec::new();
14262 let snapshot = self.buffer.read(cx).snapshot(cx);
14263
14264 for row in 0..snapshot.max_row().0 {
14265 if let Some(foldable_range) = self
14266 .snapshot(window, cx)
14267 .crease_for_buffer_row(MultiBufferRow(row))
14268 {
14269 fold_ranges.push(foldable_range);
14270 }
14271 }
14272
14273 self.fold_creases(fold_ranges, true, window, cx);
14274 } else {
14275 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14276 editor
14277 .update_in(cx, |editor, _, cx| {
14278 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14279 editor.fold_buffer(buffer_id, cx);
14280 }
14281 })
14282 .ok();
14283 });
14284 }
14285 }
14286
14287 pub fn fold_function_bodies(
14288 &mut self,
14289 _: &actions::FoldFunctionBodies,
14290 window: &mut Window,
14291 cx: &mut Context<Self>,
14292 ) {
14293 let snapshot = self.buffer.read(cx).snapshot(cx);
14294
14295 let ranges = snapshot
14296 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14297 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14298 .collect::<Vec<_>>();
14299
14300 let creases = ranges
14301 .into_iter()
14302 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14303 .collect();
14304
14305 self.fold_creases(creases, true, window, cx);
14306 }
14307
14308 pub fn fold_recursive(
14309 &mut self,
14310 _: &actions::FoldRecursive,
14311 window: &mut Window,
14312 cx: &mut Context<Self>,
14313 ) {
14314 let mut to_fold = Vec::new();
14315 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14316 let selections = self.selections.all_adjusted(cx);
14317
14318 for selection in selections {
14319 let range = selection.range().sorted();
14320 let buffer_start_row = range.start.row;
14321
14322 if range.start.row != range.end.row {
14323 let mut found = false;
14324 for row in range.start.row..=range.end.row {
14325 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14326 found = true;
14327 to_fold.push(crease);
14328 }
14329 }
14330 if found {
14331 continue;
14332 }
14333 }
14334
14335 for row in (0..=range.start.row).rev() {
14336 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14337 if crease.range().end.row >= buffer_start_row {
14338 to_fold.push(crease);
14339 } else {
14340 break;
14341 }
14342 }
14343 }
14344 }
14345
14346 self.fold_creases(to_fold, true, window, cx);
14347 }
14348
14349 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14350 let buffer_row = fold_at.buffer_row;
14351 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14352
14353 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14354 let autoscroll = self
14355 .selections
14356 .all::<Point>(cx)
14357 .iter()
14358 .any(|selection| crease.range().overlaps(&selection.range()));
14359
14360 self.fold_creases(vec![crease], autoscroll, window, cx);
14361 }
14362 }
14363
14364 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14365 if self.is_singleton(cx) {
14366 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14367 let buffer = &display_map.buffer_snapshot;
14368 let selections = self.selections.all::<Point>(cx);
14369 let ranges = selections
14370 .iter()
14371 .map(|s| {
14372 let range = s.display_range(&display_map).sorted();
14373 let mut start = range.start.to_point(&display_map);
14374 let mut end = range.end.to_point(&display_map);
14375 start.column = 0;
14376 end.column = buffer.line_len(MultiBufferRow(end.row));
14377 start..end
14378 })
14379 .collect::<Vec<_>>();
14380
14381 self.unfold_ranges(&ranges, true, true, cx);
14382 } else {
14383 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14384 let buffer_ids = self
14385 .selections
14386 .disjoint_anchor_ranges()
14387 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14388 .collect::<HashSet<_>>();
14389 for buffer_id in buffer_ids {
14390 self.unfold_buffer(buffer_id, cx);
14391 }
14392 }
14393 }
14394
14395 pub fn unfold_recursive(
14396 &mut self,
14397 _: &UnfoldRecursive,
14398 _window: &mut Window,
14399 cx: &mut Context<Self>,
14400 ) {
14401 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14402 let selections = self.selections.all::<Point>(cx);
14403 let ranges = selections
14404 .iter()
14405 .map(|s| {
14406 let mut range = s.display_range(&display_map).sorted();
14407 *range.start.column_mut() = 0;
14408 *range.end.column_mut() = display_map.line_len(range.end.row());
14409 let start = range.start.to_point(&display_map);
14410 let end = range.end.to_point(&display_map);
14411 start..end
14412 })
14413 .collect::<Vec<_>>();
14414
14415 self.unfold_ranges(&ranges, true, true, cx);
14416 }
14417
14418 pub fn unfold_at(
14419 &mut self,
14420 unfold_at: &UnfoldAt,
14421 _window: &mut Window,
14422 cx: &mut Context<Self>,
14423 ) {
14424 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14425
14426 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14427 ..Point::new(
14428 unfold_at.buffer_row.0,
14429 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14430 );
14431
14432 let autoscroll = self
14433 .selections
14434 .all::<Point>(cx)
14435 .iter()
14436 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14437
14438 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14439 }
14440
14441 pub fn unfold_all(
14442 &mut self,
14443 _: &actions::UnfoldAll,
14444 _window: &mut Window,
14445 cx: &mut Context<Self>,
14446 ) {
14447 if self.buffer.read(cx).is_singleton() {
14448 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14449 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14450 } else {
14451 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14452 editor
14453 .update(cx, |editor, cx| {
14454 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14455 editor.unfold_buffer(buffer_id, cx);
14456 }
14457 })
14458 .ok();
14459 });
14460 }
14461 }
14462
14463 pub fn fold_selected_ranges(
14464 &mut self,
14465 _: &FoldSelectedRanges,
14466 window: &mut Window,
14467 cx: &mut Context<Self>,
14468 ) {
14469 let selections = self.selections.all::<Point>(cx);
14470 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14471 let line_mode = self.selections.line_mode;
14472 let ranges = selections
14473 .into_iter()
14474 .map(|s| {
14475 if line_mode {
14476 let start = Point::new(s.start.row, 0);
14477 let end = Point::new(
14478 s.end.row,
14479 display_map
14480 .buffer_snapshot
14481 .line_len(MultiBufferRow(s.end.row)),
14482 );
14483 Crease::simple(start..end, display_map.fold_placeholder.clone())
14484 } else {
14485 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14486 }
14487 })
14488 .collect::<Vec<_>>();
14489 self.fold_creases(ranges, true, window, cx);
14490 }
14491
14492 pub fn fold_ranges<T: ToOffset + Clone>(
14493 &mut self,
14494 ranges: Vec<Range<T>>,
14495 auto_scroll: bool,
14496 window: &mut Window,
14497 cx: &mut Context<Self>,
14498 ) {
14499 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14500 let ranges = ranges
14501 .into_iter()
14502 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14503 .collect::<Vec<_>>();
14504 self.fold_creases(ranges, auto_scroll, window, cx);
14505 }
14506
14507 pub fn fold_creases<T: ToOffset + Clone>(
14508 &mut self,
14509 creases: Vec<Crease<T>>,
14510 auto_scroll: bool,
14511 window: &mut Window,
14512 cx: &mut Context<Self>,
14513 ) {
14514 if creases.is_empty() {
14515 return;
14516 }
14517
14518 let mut buffers_affected = HashSet::default();
14519 let multi_buffer = self.buffer().read(cx);
14520 for crease in &creases {
14521 if let Some((_, buffer, _)) =
14522 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14523 {
14524 buffers_affected.insert(buffer.read(cx).remote_id());
14525 };
14526 }
14527
14528 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14529
14530 if auto_scroll {
14531 self.request_autoscroll(Autoscroll::fit(), cx);
14532 }
14533
14534 cx.notify();
14535
14536 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14537 // Clear diagnostics block when folding a range that contains it.
14538 let snapshot = self.snapshot(window, cx);
14539 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14540 drop(snapshot);
14541 self.active_diagnostics = Some(active_diagnostics);
14542 self.dismiss_diagnostics(cx);
14543 } else {
14544 self.active_diagnostics = Some(active_diagnostics);
14545 }
14546 }
14547
14548 self.scrollbar_marker_state.dirty = true;
14549 self.folds_did_change(cx);
14550 }
14551
14552 /// Removes any folds whose ranges intersect any of the given ranges.
14553 pub fn unfold_ranges<T: ToOffset + Clone>(
14554 &mut self,
14555 ranges: &[Range<T>],
14556 inclusive: bool,
14557 auto_scroll: bool,
14558 cx: &mut Context<Self>,
14559 ) {
14560 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14561 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14562 });
14563 self.folds_did_change(cx);
14564 }
14565
14566 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14567 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14568 return;
14569 }
14570 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14571 self.display_map.update(cx, |display_map, cx| {
14572 display_map.fold_buffers([buffer_id], cx)
14573 });
14574 cx.emit(EditorEvent::BufferFoldToggled {
14575 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14576 folded: true,
14577 });
14578 cx.notify();
14579 }
14580
14581 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14582 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14583 return;
14584 }
14585 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14586 self.display_map.update(cx, |display_map, cx| {
14587 display_map.unfold_buffers([buffer_id], cx);
14588 });
14589 cx.emit(EditorEvent::BufferFoldToggled {
14590 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14591 folded: false,
14592 });
14593 cx.notify();
14594 }
14595
14596 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14597 self.display_map.read(cx).is_buffer_folded(buffer)
14598 }
14599
14600 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14601 self.display_map.read(cx).folded_buffers()
14602 }
14603
14604 /// Removes any folds with the given ranges.
14605 pub fn remove_folds_with_type<T: ToOffset + Clone>(
14606 &mut self,
14607 ranges: &[Range<T>],
14608 type_id: TypeId,
14609 auto_scroll: bool,
14610 cx: &mut Context<Self>,
14611 ) {
14612 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14613 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14614 });
14615 self.folds_did_change(cx);
14616 }
14617
14618 fn remove_folds_with<T: ToOffset + Clone>(
14619 &mut self,
14620 ranges: &[Range<T>],
14621 auto_scroll: bool,
14622 cx: &mut Context<Self>,
14623 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14624 ) {
14625 if ranges.is_empty() {
14626 return;
14627 }
14628
14629 let mut buffers_affected = HashSet::default();
14630 let multi_buffer = self.buffer().read(cx);
14631 for range in ranges {
14632 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14633 buffers_affected.insert(buffer.read(cx).remote_id());
14634 };
14635 }
14636
14637 self.display_map.update(cx, update);
14638
14639 if auto_scroll {
14640 self.request_autoscroll(Autoscroll::fit(), cx);
14641 }
14642
14643 cx.notify();
14644 self.scrollbar_marker_state.dirty = true;
14645 self.active_indent_guides_state.dirty = true;
14646 }
14647
14648 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14649 self.display_map.read(cx).fold_placeholder.clone()
14650 }
14651
14652 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14653 self.buffer.update(cx, |buffer, cx| {
14654 buffer.set_all_diff_hunks_expanded(cx);
14655 });
14656 }
14657
14658 pub fn expand_all_diff_hunks(
14659 &mut self,
14660 _: &ExpandAllDiffHunks,
14661 _window: &mut Window,
14662 cx: &mut Context<Self>,
14663 ) {
14664 self.buffer.update(cx, |buffer, cx| {
14665 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14666 });
14667 }
14668
14669 pub fn toggle_selected_diff_hunks(
14670 &mut self,
14671 _: &ToggleSelectedDiffHunks,
14672 _window: &mut Window,
14673 cx: &mut Context<Self>,
14674 ) {
14675 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14676 self.toggle_diff_hunks_in_ranges(ranges, cx);
14677 }
14678
14679 pub fn diff_hunks_in_ranges<'a>(
14680 &'a self,
14681 ranges: &'a [Range<Anchor>],
14682 buffer: &'a MultiBufferSnapshot,
14683 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14684 ranges.iter().flat_map(move |range| {
14685 let end_excerpt_id = range.end.excerpt_id;
14686 let range = range.to_point(buffer);
14687 let mut peek_end = range.end;
14688 if range.end.row < buffer.max_row().0 {
14689 peek_end = Point::new(range.end.row + 1, 0);
14690 }
14691 buffer
14692 .diff_hunks_in_range(range.start..peek_end)
14693 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14694 })
14695 }
14696
14697 pub fn has_stageable_diff_hunks_in_ranges(
14698 &self,
14699 ranges: &[Range<Anchor>],
14700 snapshot: &MultiBufferSnapshot,
14701 ) -> bool {
14702 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14703 hunks.any(|hunk| hunk.status().has_secondary_hunk())
14704 }
14705
14706 pub fn toggle_staged_selected_diff_hunks(
14707 &mut self,
14708 _: &::git::ToggleStaged,
14709 _: &mut Window,
14710 cx: &mut Context<Self>,
14711 ) {
14712 let snapshot = self.buffer.read(cx).snapshot(cx);
14713 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14714 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14715 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14716 }
14717
14718 pub fn stage_and_next(
14719 &mut self,
14720 _: &::git::StageAndNext,
14721 window: &mut Window,
14722 cx: &mut Context<Self>,
14723 ) {
14724 self.do_stage_or_unstage_and_next(true, window, cx);
14725 }
14726
14727 pub fn unstage_and_next(
14728 &mut self,
14729 _: &::git::UnstageAndNext,
14730 window: &mut Window,
14731 cx: &mut Context<Self>,
14732 ) {
14733 self.do_stage_or_unstage_and_next(false, window, cx);
14734 }
14735
14736 pub fn stage_or_unstage_diff_hunks(
14737 &mut self,
14738 stage: bool,
14739 ranges: Vec<Range<Anchor>>,
14740 cx: &mut Context<Self>,
14741 ) {
14742 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14743 cx.spawn(async move |this, cx| {
14744 task.await?;
14745 this.update(cx, |this, cx| {
14746 let snapshot = this.buffer.read(cx).snapshot(cx);
14747 let chunk_by = this
14748 .diff_hunks_in_ranges(&ranges, &snapshot)
14749 .chunk_by(|hunk| hunk.buffer_id);
14750 for (buffer_id, hunks) in &chunk_by {
14751 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14752 }
14753 })
14754 })
14755 .detach_and_log_err(cx);
14756 }
14757
14758 fn save_buffers_for_ranges_if_needed(
14759 &mut self,
14760 ranges: &[Range<Anchor>],
14761 cx: &mut Context<'_, Editor>,
14762 ) -> Task<Result<()>> {
14763 let multibuffer = self.buffer.read(cx);
14764 let snapshot = multibuffer.read(cx);
14765 let buffer_ids: HashSet<_> = ranges
14766 .iter()
14767 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14768 .collect();
14769 drop(snapshot);
14770
14771 let mut buffers = HashSet::default();
14772 for buffer_id in buffer_ids {
14773 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14774 let buffer = buffer_entity.read(cx);
14775 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14776 {
14777 buffers.insert(buffer_entity);
14778 }
14779 }
14780 }
14781
14782 if let Some(project) = &self.project {
14783 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14784 } else {
14785 Task::ready(Ok(()))
14786 }
14787 }
14788
14789 fn do_stage_or_unstage_and_next(
14790 &mut self,
14791 stage: bool,
14792 window: &mut Window,
14793 cx: &mut Context<Self>,
14794 ) {
14795 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14796
14797 if ranges.iter().any(|range| range.start != range.end) {
14798 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14799 return;
14800 }
14801
14802 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14803 let snapshot = self.snapshot(window, cx);
14804 let position = self.selections.newest::<Point>(cx).head();
14805 let mut row = snapshot
14806 .buffer_snapshot
14807 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14808 .find(|hunk| hunk.row_range.start.0 > position.row)
14809 .map(|hunk| hunk.row_range.start);
14810
14811 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14812 // Outside of the project diff editor, wrap around to the beginning.
14813 if !all_diff_hunks_expanded {
14814 row = row.or_else(|| {
14815 snapshot
14816 .buffer_snapshot
14817 .diff_hunks_in_range(Point::zero()..position)
14818 .find(|hunk| hunk.row_range.end.0 < position.row)
14819 .map(|hunk| hunk.row_range.start)
14820 });
14821 }
14822
14823 if let Some(row) = row {
14824 let destination = Point::new(row.0, 0);
14825 let autoscroll = Autoscroll::center();
14826
14827 self.unfold_ranges(&[destination..destination], false, false, cx);
14828 self.change_selections(Some(autoscroll), window, cx, |s| {
14829 s.select_ranges([destination..destination]);
14830 });
14831 }
14832 }
14833
14834 fn do_stage_or_unstage(
14835 &self,
14836 stage: bool,
14837 buffer_id: BufferId,
14838 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14839 cx: &mut App,
14840 ) -> Option<()> {
14841 let project = self.project.as_ref()?;
14842 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14843 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14844 let buffer_snapshot = buffer.read(cx).snapshot();
14845 let file_exists = buffer_snapshot
14846 .file()
14847 .is_some_and(|file| file.disk_state().exists());
14848 diff.update(cx, |diff, cx| {
14849 diff.stage_or_unstage_hunks(
14850 stage,
14851 &hunks
14852 .map(|hunk| buffer_diff::DiffHunk {
14853 buffer_range: hunk.buffer_range,
14854 diff_base_byte_range: hunk.diff_base_byte_range,
14855 secondary_status: hunk.secondary_status,
14856 range: Point::zero()..Point::zero(), // unused
14857 })
14858 .collect::<Vec<_>>(),
14859 &buffer_snapshot,
14860 file_exists,
14861 cx,
14862 )
14863 });
14864 None
14865 }
14866
14867 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14868 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14869 self.buffer
14870 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14871 }
14872
14873 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14874 self.buffer.update(cx, |buffer, cx| {
14875 let ranges = vec![Anchor::min()..Anchor::max()];
14876 if !buffer.all_diff_hunks_expanded()
14877 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14878 {
14879 buffer.collapse_diff_hunks(ranges, cx);
14880 true
14881 } else {
14882 false
14883 }
14884 })
14885 }
14886
14887 fn toggle_diff_hunks_in_ranges(
14888 &mut self,
14889 ranges: Vec<Range<Anchor>>,
14890 cx: &mut Context<'_, Editor>,
14891 ) {
14892 self.buffer.update(cx, |buffer, cx| {
14893 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14894 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14895 })
14896 }
14897
14898 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14899 self.buffer.update(cx, |buffer, cx| {
14900 let snapshot = buffer.snapshot(cx);
14901 let excerpt_id = range.end.excerpt_id;
14902 let point_range = range.to_point(&snapshot);
14903 let expand = !buffer.single_hunk_is_expanded(range, cx);
14904 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14905 })
14906 }
14907
14908 pub(crate) fn apply_all_diff_hunks(
14909 &mut self,
14910 _: &ApplyAllDiffHunks,
14911 window: &mut Window,
14912 cx: &mut Context<Self>,
14913 ) {
14914 let buffers = self.buffer.read(cx).all_buffers();
14915 for branch_buffer in buffers {
14916 branch_buffer.update(cx, |branch_buffer, cx| {
14917 branch_buffer.merge_into_base(Vec::new(), cx);
14918 });
14919 }
14920
14921 if let Some(project) = self.project.clone() {
14922 self.save(true, project, window, cx).detach_and_log_err(cx);
14923 }
14924 }
14925
14926 pub(crate) fn apply_selected_diff_hunks(
14927 &mut self,
14928 _: &ApplyDiffHunk,
14929 window: &mut Window,
14930 cx: &mut Context<Self>,
14931 ) {
14932 let snapshot = self.snapshot(window, cx);
14933 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14934 let mut ranges_by_buffer = HashMap::default();
14935 self.transact(window, cx, |editor, _window, cx| {
14936 for hunk in hunks {
14937 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14938 ranges_by_buffer
14939 .entry(buffer.clone())
14940 .or_insert_with(Vec::new)
14941 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14942 }
14943 }
14944
14945 for (buffer, ranges) in ranges_by_buffer {
14946 buffer.update(cx, |buffer, cx| {
14947 buffer.merge_into_base(ranges, cx);
14948 });
14949 }
14950 });
14951
14952 if let Some(project) = self.project.clone() {
14953 self.save(true, project, window, cx).detach_and_log_err(cx);
14954 }
14955 }
14956
14957 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14958 if hovered != self.gutter_hovered {
14959 self.gutter_hovered = hovered;
14960 cx.notify();
14961 }
14962 }
14963
14964 pub fn insert_blocks(
14965 &mut self,
14966 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14967 autoscroll: Option<Autoscroll>,
14968 cx: &mut Context<Self>,
14969 ) -> Vec<CustomBlockId> {
14970 let blocks = self
14971 .display_map
14972 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14973 if let Some(autoscroll) = autoscroll {
14974 self.request_autoscroll(autoscroll, cx);
14975 }
14976 cx.notify();
14977 blocks
14978 }
14979
14980 pub fn resize_blocks(
14981 &mut self,
14982 heights: HashMap<CustomBlockId, u32>,
14983 autoscroll: Option<Autoscroll>,
14984 cx: &mut Context<Self>,
14985 ) {
14986 self.display_map
14987 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14988 if let Some(autoscroll) = autoscroll {
14989 self.request_autoscroll(autoscroll, cx);
14990 }
14991 cx.notify();
14992 }
14993
14994 pub fn replace_blocks(
14995 &mut self,
14996 renderers: HashMap<CustomBlockId, RenderBlock>,
14997 autoscroll: Option<Autoscroll>,
14998 cx: &mut Context<Self>,
14999 ) {
15000 self.display_map
15001 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15002 if let Some(autoscroll) = autoscroll {
15003 self.request_autoscroll(autoscroll, cx);
15004 }
15005 cx.notify();
15006 }
15007
15008 pub fn remove_blocks(
15009 &mut self,
15010 block_ids: HashSet<CustomBlockId>,
15011 autoscroll: Option<Autoscroll>,
15012 cx: &mut Context<Self>,
15013 ) {
15014 self.display_map.update(cx, |display_map, cx| {
15015 display_map.remove_blocks(block_ids, cx)
15016 });
15017 if let Some(autoscroll) = autoscroll {
15018 self.request_autoscroll(autoscroll, cx);
15019 }
15020 cx.notify();
15021 }
15022
15023 pub fn row_for_block(
15024 &self,
15025 block_id: CustomBlockId,
15026 cx: &mut Context<Self>,
15027 ) -> Option<DisplayRow> {
15028 self.display_map
15029 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15030 }
15031
15032 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15033 self.focused_block = Some(focused_block);
15034 }
15035
15036 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15037 self.focused_block.take()
15038 }
15039
15040 pub fn insert_creases(
15041 &mut self,
15042 creases: impl IntoIterator<Item = Crease<Anchor>>,
15043 cx: &mut Context<Self>,
15044 ) -> Vec<CreaseId> {
15045 self.display_map
15046 .update(cx, |map, cx| map.insert_creases(creases, cx))
15047 }
15048
15049 pub fn remove_creases(
15050 &mut self,
15051 ids: impl IntoIterator<Item = CreaseId>,
15052 cx: &mut Context<Self>,
15053 ) {
15054 self.display_map
15055 .update(cx, |map, cx| map.remove_creases(ids, cx));
15056 }
15057
15058 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15059 self.display_map
15060 .update(cx, |map, cx| map.snapshot(cx))
15061 .longest_row()
15062 }
15063
15064 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15065 self.display_map
15066 .update(cx, |map, cx| map.snapshot(cx))
15067 .max_point()
15068 }
15069
15070 pub fn text(&self, cx: &App) -> String {
15071 self.buffer.read(cx).read(cx).text()
15072 }
15073
15074 pub fn is_empty(&self, cx: &App) -> bool {
15075 self.buffer.read(cx).read(cx).is_empty()
15076 }
15077
15078 pub fn text_option(&self, cx: &App) -> Option<String> {
15079 let text = self.text(cx);
15080 let text = text.trim();
15081
15082 if text.is_empty() {
15083 return None;
15084 }
15085
15086 Some(text.to_string())
15087 }
15088
15089 pub fn set_text(
15090 &mut self,
15091 text: impl Into<Arc<str>>,
15092 window: &mut Window,
15093 cx: &mut Context<Self>,
15094 ) {
15095 self.transact(window, cx, |this, _, cx| {
15096 this.buffer
15097 .read(cx)
15098 .as_singleton()
15099 .expect("you can only call set_text on editors for singleton buffers")
15100 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15101 });
15102 }
15103
15104 pub fn display_text(&self, cx: &mut App) -> String {
15105 self.display_map
15106 .update(cx, |map, cx| map.snapshot(cx))
15107 .text()
15108 }
15109
15110 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15111 let mut wrap_guides = smallvec::smallvec![];
15112
15113 if self.show_wrap_guides == Some(false) {
15114 return wrap_guides;
15115 }
15116
15117 let settings = self.buffer.read(cx).language_settings(cx);
15118 if settings.show_wrap_guides {
15119 match self.soft_wrap_mode(cx) {
15120 SoftWrap::Column(soft_wrap) => {
15121 wrap_guides.push((soft_wrap as usize, true));
15122 }
15123 SoftWrap::Bounded(soft_wrap) => {
15124 wrap_guides.push((soft_wrap as usize, true));
15125 }
15126 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15127 }
15128 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15129 }
15130
15131 wrap_guides
15132 }
15133
15134 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15135 let settings = self.buffer.read(cx).language_settings(cx);
15136 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15137 match mode {
15138 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15139 SoftWrap::None
15140 }
15141 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15142 language_settings::SoftWrap::PreferredLineLength => {
15143 SoftWrap::Column(settings.preferred_line_length)
15144 }
15145 language_settings::SoftWrap::Bounded => {
15146 SoftWrap::Bounded(settings.preferred_line_length)
15147 }
15148 }
15149 }
15150
15151 pub fn set_soft_wrap_mode(
15152 &mut self,
15153 mode: language_settings::SoftWrap,
15154
15155 cx: &mut Context<Self>,
15156 ) {
15157 self.soft_wrap_mode_override = Some(mode);
15158 cx.notify();
15159 }
15160
15161 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15162 self.hard_wrap = hard_wrap;
15163 cx.notify();
15164 }
15165
15166 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15167 self.text_style_refinement = Some(style);
15168 }
15169
15170 /// called by the Element so we know what style we were most recently rendered with.
15171 pub(crate) fn set_style(
15172 &mut self,
15173 style: EditorStyle,
15174 window: &mut Window,
15175 cx: &mut Context<Self>,
15176 ) {
15177 let rem_size = window.rem_size();
15178 self.display_map.update(cx, |map, cx| {
15179 map.set_font(
15180 style.text.font(),
15181 style.text.font_size.to_pixels(rem_size),
15182 cx,
15183 )
15184 });
15185 self.style = Some(style);
15186 }
15187
15188 pub fn style(&self) -> Option<&EditorStyle> {
15189 self.style.as_ref()
15190 }
15191
15192 // Called by the element. This method is not designed to be called outside of the editor
15193 // element's layout code because it does not notify when rewrapping is computed synchronously.
15194 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15195 self.display_map
15196 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15197 }
15198
15199 pub fn set_soft_wrap(&mut self) {
15200 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15201 }
15202
15203 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15204 if self.soft_wrap_mode_override.is_some() {
15205 self.soft_wrap_mode_override.take();
15206 } else {
15207 let soft_wrap = match self.soft_wrap_mode(cx) {
15208 SoftWrap::GitDiff => return,
15209 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15210 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15211 language_settings::SoftWrap::None
15212 }
15213 };
15214 self.soft_wrap_mode_override = Some(soft_wrap);
15215 }
15216 cx.notify();
15217 }
15218
15219 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15220 let Some(workspace) = self.workspace() else {
15221 return;
15222 };
15223 let fs = workspace.read(cx).app_state().fs.clone();
15224 let current_show = TabBarSettings::get_global(cx).show;
15225 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15226 setting.show = Some(!current_show);
15227 });
15228 }
15229
15230 pub fn toggle_indent_guides(
15231 &mut self,
15232 _: &ToggleIndentGuides,
15233 _: &mut Window,
15234 cx: &mut Context<Self>,
15235 ) {
15236 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15237 self.buffer
15238 .read(cx)
15239 .language_settings(cx)
15240 .indent_guides
15241 .enabled
15242 });
15243 self.show_indent_guides = Some(!currently_enabled);
15244 cx.notify();
15245 }
15246
15247 fn should_show_indent_guides(&self) -> Option<bool> {
15248 self.show_indent_guides
15249 }
15250
15251 pub fn toggle_line_numbers(
15252 &mut self,
15253 _: &ToggleLineNumbers,
15254 _: &mut Window,
15255 cx: &mut Context<Self>,
15256 ) {
15257 let mut editor_settings = EditorSettings::get_global(cx).clone();
15258 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15259 EditorSettings::override_global(editor_settings, cx);
15260 }
15261
15262 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15263 if let Some(show_line_numbers) = self.show_line_numbers {
15264 return show_line_numbers;
15265 }
15266 EditorSettings::get_global(cx).gutter.line_numbers
15267 }
15268
15269 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15270 self.use_relative_line_numbers
15271 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15272 }
15273
15274 pub fn toggle_relative_line_numbers(
15275 &mut self,
15276 _: &ToggleRelativeLineNumbers,
15277 _: &mut Window,
15278 cx: &mut Context<Self>,
15279 ) {
15280 let is_relative = self.should_use_relative_line_numbers(cx);
15281 self.set_relative_line_number(Some(!is_relative), cx)
15282 }
15283
15284 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15285 self.use_relative_line_numbers = is_relative;
15286 cx.notify();
15287 }
15288
15289 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15290 self.show_gutter = show_gutter;
15291 cx.notify();
15292 }
15293
15294 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15295 self.show_scrollbars = show_scrollbars;
15296 cx.notify();
15297 }
15298
15299 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15300 self.show_line_numbers = Some(show_line_numbers);
15301 cx.notify();
15302 }
15303
15304 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15305 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15306 cx.notify();
15307 }
15308
15309 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15310 self.show_code_actions = Some(show_code_actions);
15311 cx.notify();
15312 }
15313
15314 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15315 self.show_runnables = Some(show_runnables);
15316 cx.notify();
15317 }
15318
15319 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15320 self.show_breakpoints = Some(show_breakpoints);
15321 cx.notify();
15322 }
15323
15324 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15325 if self.display_map.read(cx).masked != masked {
15326 self.display_map.update(cx, |map, _| map.masked = masked);
15327 }
15328 cx.notify()
15329 }
15330
15331 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15332 self.show_wrap_guides = Some(show_wrap_guides);
15333 cx.notify();
15334 }
15335
15336 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15337 self.show_indent_guides = Some(show_indent_guides);
15338 cx.notify();
15339 }
15340
15341 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15342 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15343 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15344 if let Some(dir) = file.abs_path(cx).parent() {
15345 return Some(dir.to_owned());
15346 }
15347 }
15348
15349 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15350 return Some(project_path.path.to_path_buf());
15351 }
15352 }
15353
15354 None
15355 }
15356
15357 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15358 self.active_excerpt(cx)?
15359 .1
15360 .read(cx)
15361 .file()
15362 .and_then(|f| f.as_local())
15363 }
15364
15365 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15366 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15367 let buffer = buffer.read(cx);
15368 if let Some(project_path) = buffer.project_path(cx) {
15369 let project = self.project.as_ref()?.read(cx);
15370 project.absolute_path(&project_path, cx)
15371 } else {
15372 buffer
15373 .file()
15374 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15375 }
15376 })
15377 }
15378
15379 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15380 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15381 let project_path = buffer.read(cx).project_path(cx)?;
15382 let project = self.project.as_ref()?.read(cx);
15383 let entry = project.entry_for_path(&project_path, cx)?;
15384 let path = entry.path.to_path_buf();
15385 Some(path)
15386 })
15387 }
15388
15389 pub fn reveal_in_finder(
15390 &mut self,
15391 _: &RevealInFileManager,
15392 _window: &mut Window,
15393 cx: &mut Context<Self>,
15394 ) {
15395 if let Some(target) = self.target_file(cx) {
15396 cx.reveal_path(&target.abs_path(cx));
15397 }
15398 }
15399
15400 pub fn copy_path(
15401 &mut self,
15402 _: &zed_actions::workspace::CopyPath,
15403 _window: &mut Window,
15404 cx: &mut Context<Self>,
15405 ) {
15406 if let Some(path) = self.target_file_abs_path(cx) {
15407 if let Some(path) = path.to_str() {
15408 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15409 }
15410 }
15411 }
15412
15413 pub fn copy_relative_path(
15414 &mut self,
15415 _: &zed_actions::workspace::CopyRelativePath,
15416 _window: &mut Window,
15417 cx: &mut Context<Self>,
15418 ) {
15419 if let Some(path) = self.target_file_path(cx) {
15420 if let Some(path) = path.to_str() {
15421 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15422 }
15423 }
15424 }
15425
15426 pub fn project_path(&self, cx: &mut Context<Self>) -> Option<ProjectPath> {
15427 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15428 buffer.read_with(cx, |buffer, cx| buffer.project_path(cx))
15429 } else {
15430 None
15431 }
15432 }
15433
15434 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15435 let _ = maybe!({
15436 let breakpoint_store = self.breakpoint_store.as_ref()?;
15437
15438 let Some((_, _, active_position)) =
15439 breakpoint_store.read(cx).active_position().cloned()
15440 else {
15441 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15442 return None;
15443 };
15444
15445 let snapshot = self
15446 .project
15447 .as_ref()?
15448 .read(cx)
15449 .buffer_for_id(active_position.buffer_id?, cx)?
15450 .read(cx)
15451 .snapshot();
15452
15453 for (id, ExcerptRange { context, .. }) in self
15454 .buffer
15455 .read(cx)
15456 .excerpts_for_buffer(active_position.buffer_id?, cx)
15457 {
15458 if context.start.cmp(&active_position, &snapshot).is_ge()
15459 || context.end.cmp(&active_position, &snapshot).is_lt()
15460 {
15461 continue;
15462 }
15463 let snapshot = self.buffer.read(cx).snapshot(cx);
15464 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15465
15466 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15467 self.go_to_line::<DebugCurrentRowHighlight>(
15468 multibuffer_anchor,
15469 Some(cx.theme().colors().editor_debugger_active_line_background),
15470 window,
15471 cx,
15472 );
15473
15474 cx.notify();
15475 }
15476
15477 Some(())
15478 });
15479 }
15480
15481 pub fn copy_file_name_without_extension(
15482 &mut self,
15483 _: &CopyFileNameWithoutExtension,
15484 _: &mut Window,
15485 cx: &mut Context<Self>,
15486 ) {
15487 if let Some(file) = self.target_file(cx) {
15488 if let Some(file_stem) = file.path().file_stem() {
15489 if let Some(name) = file_stem.to_str() {
15490 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15491 }
15492 }
15493 }
15494 }
15495
15496 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15497 if let Some(file) = self.target_file(cx) {
15498 if let Some(file_name) = file.path().file_name() {
15499 if let Some(name) = file_name.to_str() {
15500 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15501 }
15502 }
15503 }
15504 }
15505
15506 pub fn toggle_git_blame(
15507 &mut self,
15508 _: &::git::Blame,
15509 window: &mut Window,
15510 cx: &mut Context<Self>,
15511 ) {
15512 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15513
15514 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15515 self.start_git_blame(true, window, cx);
15516 }
15517
15518 cx.notify();
15519 }
15520
15521 pub fn toggle_git_blame_inline(
15522 &mut self,
15523 _: &ToggleGitBlameInline,
15524 window: &mut Window,
15525 cx: &mut Context<Self>,
15526 ) {
15527 self.toggle_git_blame_inline_internal(true, window, cx);
15528 cx.notify();
15529 }
15530
15531 pub fn git_blame_inline_enabled(&self) -> bool {
15532 self.git_blame_inline_enabled
15533 }
15534
15535 pub fn toggle_selection_menu(
15536 &mut self,
15537 _: &ToggleSelectionMenu,
15538 _: &mut Window,
15539 cx: &mut Context<Self>,
15540 ) {
15541 self.show_selection_menu = self
15542 .show_selection_menu
15543 .map(|show_selections_menu| !show_selections_menu)
15544 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15545
15546 cx.notify();
15547 }
15548
15549 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15550 self.show_selection_menu
15551 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15552 }
15553
15554 fn start_git_blame(
15555 &mut self,
15556 user_triggered: bool,
15557 window: &mut Window,
15558 cx: &mut Context<Self>,
15559 ) {
15560 if let Some(project) = self.project.as_ref() {
15561 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15562 return;
15563 };
15564
15565 if buffer.read(cx).file().is_none() {
15566 return;
15567 }
15568
15569 let focused = self.focus_handle(cx).contains_focused(window, cx);
15570
15571 let project = project.clone();
15572 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15573 self.blame_subscription =
15574 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15575 self.blame = Some(blame);
15576 }
15577 }
15578
15579 fn toggle_git_blame_inline_internal(
15580 &mut self,
15581 user_triggered: bool,
15582 window: &mut Window,
15583 cx: &mut Context<Self>,
15584 ) {
15585 if self.git_blame_inline_enabled {
15586 self.git_blame_inline_enabled = false;
15587 self.show_git_blame_inline = false;
15588 self.show_git_blame_inline_delay_task.take();
15589 } else {
15590 self.git_blame_inline_enabled = true;
15591 self.start_git_blame_inline(user_triggered, window, cx);
15592 }
15593
15594 cx.notify();
15595 }
15596
15597 fn start_git_blame_inline(
15598 &mut self,
15599 user_triggered: bool,
15600 window: &mut Window,
15601 cx: &mut Context<Self>,
15602 ) {
15603 self.start_git_blame(user_triggered, window, cx);
15604
15605 if ProjectSettings::get_global(cx)
15606 .git
15607 .inline_blame_delay()
15608 .is_some()
15609 {
15610 self.start_inline_blame_timer(window, cx);
15611 } else {
15612 self.show_git_blame_inline = true
15613 }
15614 }
15615
15616 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15617 self.blame.as_ref()
15618 }
15619
15620 pub fn show_git_blame_gutter(&self) -> bool {
15621 self.show_git_blame_gutter
15622 }
15623
15624 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15625 self.show_git_blame_gutter && self.has_blame_entries(cx)
15626 }
15627
15628 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15629 self.show_git_blame_inline
15630 && (self.focus_handle.is_focused(window)
15631 || self
15632 .git_blame_inline_tooltip
15633 .as_ref()
15634 .and_then(|t| t.upgrade())
15635 .is_some())
15636 && !self.newest_selection_head_on_empty_line(cx)
15637 && self.has_blame_entries(cx)
15638 }
15639
15640 fn has_blame_entries(&self, cx: &App) -> bool {
15641 self.blame()
15642 .map_or(false, |blame| blame.read(cx).has_generated_entries())
15643 }
15644
15645 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15646 let cursor_anchor = self.selections.newest_anchor().head();
15647
15648 let snapshot = self.buffer.read(cx).snapshot(cx);
15649 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15650
15651 snapshot.line_len(buffer_row) == 0
15652 }
15653
15654 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15655 let buffer_and_selection = maybe!({
15656 let selection = self.selections.newest::<Point>(cx);
15657 let selection_range = selection.range();
15658
15659 let multi_buffer = self.buffer().read(cx);
15660 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15661 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15662
15663 let (buffer, range, _) = if selection.reversed {
15664 buffer_ranges.first()
15665 } else {
15666 buffer_ranges.last()
15667 }?;
15668
15669 let selection = text::ToPoint::to_point(&range.start, &buffer).row
15670 ..text::ToPoint::to_point(&range.end, &buffer).row;
15671 Some((
15672 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15673 selection,
15674 ))
15675 });
15676
15677 let Some((buffer, selection)) = buffer_and_selection else {
15678 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15679 };
15680
15681 let Some(project) = self.project.as_ref() else {
15682 return Task::ready(Err(anyhow!("editor does not have project")));
15683 };
15684
15685 project.update(cx, |project, cx| {
15686 project.get_permalink_to_line(&buffer, selection, cx)
15687 })
15688 }
15689
15690 pub fn copy_permalink_to_line(
15691 &mut self,
15692 _: &CopyPermalinkToLine,
15693 window: &mut Window,
15694 cx: &mut Context<Self>,
15695 ) {
15696 let permalink_task = self.get_permalink_to_line(cx);
15697 let workspace = self.workspace();
15698
15699 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15700 Ok(permalink) => {
15701 cx.update(|_, cx| {
15702 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15703 })
15704 .ok();
15705 }
15706 Err(err) => {
15707 let message = format!("Failed to copy permalink: {err}");
15708
15709 Err::<(), anyhow::Error>(err).log_err();
15710
15711 if let Some(workspace) = workspace {
15712 workspace
15713 .update_in(cx, |workspace, _, cx| {
15714 struct CopyPermalinkToLine;
15715
15716 workspace.show_toast(
15717 Toast::new(
15718 NotificationId::unique::<CopyPermalinkToLine>(),
15719 message,
15720 ),
15721 cx,
15722 )
15723 })
15724 .ok();
15725 }
15726 }
15727 })
15728 .detach();
15729 }
15730
15731 pub fn copy_file_location(
15732 &mut self,
15733 _: &CopyFileLocation,
15734 _: &mut Window,
15735 cx: &mut Context<Self>,
15736 ) {
15737 let selection = self.selections.newest::<Point>(cx).start.row + 1;
15738 if let Some(file) = self.target_file(cx) {
15739 if let Some(path) = file.path().to_str() {
15740 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15741 }
15742 }
15743 }
15744
15745 pub fn open_permalink_to_line(
15746 &mut self,
15747 _: &OpenPermalinkToLine,
15748 window: &mut Window,
15749 cx: &mut Context<Self>,
15750 ) {
15751 let permalink_task = self.get_permalink_to_line(cx);
15752 let workspace = self.workspace();
15753
15754 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15755 Ok(permalink) => {
15756 cx.update(|_, cx| {
15757 cx.open_url(permalink.as_ref());
15758 })
15759 .ok();
15760 }
15761 Err(err) => {
15762 let message = format!("Failed to open permalink: {err}");
15763
15764 Err::<(), anyhow::Error>(err).log_err();
15765
15766 if let Some(workspace) = workspace {
15767 workspace
15768 .update(cx, |workspace, cx| {
15769 struct OpenPermalinkToLine;
15770
15771 workspace.show_toast(
15772 Toast::new(
15773 NotificationId::unique::<OpenPermalinkToLine>(),
15774 message,
15775 ),
15776 cx,
15777 )
15778 })
15779 .ok();
15780 }
15781 }
15782 })
15783 .detach();
15784 }
15785
15786 pub fn insert_uuid_v4(
15787 &mut self,
15788 _: &InsertUuidV4,
15789 window: &mut Window,
15790 cx: &mut Context<Self>,
15791 ) {
15792 self.insert_uuid(UuidVersion::V4, window, cx);
15793 }
15794
15795 pub fn insert_uuid_v7(
15796 &mut self,
15797 _: &InsertUuidV7,
15798 window: &mut Window,
15799 cx: &mut Context<Self>,
15800 ) {
15801 self.insert_uuid(UuidVersion::V7, window, cx);
15802 }
15803
15804 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15805 self.transact(window, cx, |this, window, cx| {
15806 let edits = this
15807 .selections
15808 .all::<Point>(cx)
15809 .into_iter()
15810 .map(|selection| {
15811 let uuid = match version {
15812 UuidVersion::V4 => uuid::Uuid::new_v4(),
15813 UuidVersion::V7 => uuid::Uuid::now_v7(),
15814 };
15815
15816 (selection.range(), uuid.to_string())
15817 });
15818 this.edit(edits, cx);
15819 this.refresh_inline_completion(true, false, window, cx);
15820 });
15821 }
15822
15823 pub fn open_selections_in_multibuffer(
15824 &mut self,
15825 _: &OpenSelectionsInMultibuffer,
15826 window: &mut Window,
15827 cx: &mut Context<Self>,
15828 ) {
15829 let multibuffer = self.buffer.read(cx);
15830
15831 let Some(buffer) = multibuffer.as_singleton() else {
15832 return;
15833 };
15834
15835 let Some(workspace) = self.workspace() else {
15836 return;
15837 };
15838
15839 let locations = self
15840 .selections
15841 .disjoint_anchors()
15842 .iter()
15843 .map(|range| Location {
15844 buffer: buffer.clone(),
15845 range: range.start.text_anchor..range.end.text_anchor,
15846 })
15847 .collect::<Vec<_>>();
15848
15849 let title = multibuffer.title(cx).to_string();
15850
15851 cx.spawn_in(window, async move |_, cx| {
15852 workspace.update_in(cx, |workspace, window, cx| {
15853 Self::open_locations_in_multibuffer(
15854 workspace,
15855 locations,
15856 format!("Selections for '{title}'"),
15857 false,
15858 MultibufferSelectionMode::All,
15859 window,
15860 cx,
15861 );
15862 })
15863 })
15864 .detach();
15865 }
15866
15867 /// Adds a row highlight for the given range. If a row has multiple highlights, the
15868 /// last highlight added will be used.
15869 ///
15870 /// If the range ends at the beginning of a line, then that line will not be highlighted.
15871 pub fn highlight_rows<T: 'static>(
15872 &mut self,
15873 range: Range<Anchor>,
15874 color: Hsla,
15875 should_autoscroll: bool,
15876 cx: &mut Context<Self>,
15877 ) {
15878 let snapshot = self.buffer().read(cx).snapshot(cx);
15879 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15880 let ix = row_highlights.binary_search_by(|highlight| {
15881 Ordering::Equal
15882 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15883 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15884 });
15885
15886 if let Err(mut ix) = ix {
15887 let index = post_inc(&mut self.highlight_order);
15888
15889 // If this range intersects with the preceding highlight, then merge it with
15890 // the preceding highlight. Otherwise insert a new highlight.
15891 let mut merged = false;
15892 if ix > 0 {
15893 let prev_highlight = &mut row_highlights[ix - 1];
15894 if prev_highlight
15895 .range
15896 .end
15897 .cmp(&range.start, &snapshot)
15898 .is_ge()
15899 {
15900 ix -= 1;
15901 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15902 prev_highlight.range.end = range.end;
15903 }
15904 merged = true;
15905 prev_highlight.index = index;
15906 prev_highlight.color = color;
15907 prev_highlight.should_autoscroll = should_autoscroll;
15908 }
15909 }
15910
15911 if !merged {
15912 row_highlights.insert(
15913 ix,
15914 RowHighlight {
15915 range: range.clone(),
15916 index,
15917 color,
15918 should_autoscroll,
15919 },
15920 );
15921 }
15922
15923 // If any of the following highlights intersect with this one, merge them.
15924 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15925 let highlight = &row_highlights[ix];
15926 if next_highlight
15927 .range
15928 .start
15929 .cmp(&highlight.range.end, &snapshot)
15930 .is_le()
15931 {
15932 if next_highlight
15933 .range
15934 .end
15935 .cmp(&highlight.range.end, &snapshot)
15936 .is_gt()
15937 {
15938 row_highlights[ix].range.end = next_highlight.range.end;
15939 }
15940 row_highlights.remove(ix + 1);
15941 } else {
15942 break;
15943 }
15944 }
15945 }
15946 }
15947
15948 /// Remove any highlighted row ranges of the given type that intersect the
15949 /// given ranges.
15950 pub fn remove_highlighted_rows<T: 'static>(
15951 &mut self,
15952 ranges_to_remove: Vec<Range<Anchor>>,
15953 cx: &mut Context<Self>,
15954 ) {
15955 let snapshot = self.buffer().read(cx).snapshot(cx);
15956 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15957 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15958 row_highlights.retain(|highlight| {
15959 while let Some(range_to_remove) = ranges_to_remove.peek() {
15960 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15961 Ordering::Less | Ordering::Equal => {
15962 ranges_to_remove.next();
15963 }
15964 Ordering::Greater => {
15965 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15966 Ordering::Less | Ordering::Equal => {
15967 return false;
15968 }
15969 Ordering::Greater => break,
15970 }
15971 }
15972 }
15973 }
15974
15975 true
15976 })
15977 }
15978
15979 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15980 pub fn clear_row_highlights<T: 'static>(&mut self) {
15981 self.highlighted_rows.remove(&TypeId::of::<T>());
15982 }
15983
15984 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15985 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15986 self.highlighted_rows
15987 .get(&TypeId::of::<T>())
15988 .map_or(&[] as &[_], |vec| vec.as_slice())
15989 .iter()
15990 .map(|highlight| (highlight.range.clone(), highlight.color))
15991 }
15992
15993 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15994 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15995 /// Allows to ignore certain kinds of highlights.
15996 pub fn highlighted_display_rows(
15997 &self,
15998 window: &mut Window,
15999 cx: &mut App,
16000 ) -> BTreeMap<DisplayRow, LineHighlight> {
16001 let snapshot = self.snapshot(window, cx);
16002 let mut used_highlight_orders = HashMap::default();
16003 self.highlighted_rows
16004 .iter()
16005 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16006 .fold(
16007 BTreeMap::<DisplayRow, LineHighlight>::new(),
16008 |mut unique_rows, highlight| {
16009 let start = highlight.range.start.to_display_point(&snapshot);
16010 let end = highlight.range.end.to_display_point(&snapshot);
16011 let start_row = start.row().0;
16012 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16013 && end.column() == 0
16014 {
16015 end.row().0.saturating_sub(1)
16016 } else {
16017 end.row().0
16018 };
16019 for row in start_row..=end_row {
16020 let used_index =
16021 used_highlight_orders.entry(row).or_insert(highlight.index);
16022 if highlight.index >= *used_index {
16023 *used_index = highlight.index;
16024 unique_rows.insert(DisplayRow(row), highlight.color.into());
16025 }
16026 }
16027 unique_rows
16028 },
16029 )
16030 }
16031
16032 pub fn highlighted_display_row_for_autoscroll(
16033 &self,
16034 snapshot: &DisplaySnapshot,
16035 ) -> Option<DisplayRow> {
16036 self.highlighted_rows
16037 .values()
16038 .flat_map(|highlighted_rows| highlighted_rows.iter())
16039 .filter_map(|highlight| {
16040 if highlight.should_autoscroll {
16041 Some(highlight.range.start.to_display_point(snapshot).row())
16042 } else {
16043 None
16044 }
16045 })
16046 .min()
16047 }
16048
16049 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16050 self.highlight_background::<SearchWithinRange>(
16051 ranges,
16052 |colors| colors.editor_document_highlight_read_background,
16053 cx,
16054 )
16055 }
16056
16057 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16058 self.breadcrumb_header = Some(new_header);
16059 }
16060
16061 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16062 self.clear_background_highlights::<SearchWithinRange>(cx);
16063 }
16064
16065 pub fn highlight_background<T: 'static>(
16066 &mut self,
16067 ranges: &[Range<Anchor>],
16068 color_fetcher: fn(&ThemeColors) -> Hsla,
16069 cx: &mut Context<Self>,
16070 ) {
16071 self.background_highlights
16072 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16073 self.scrollbar_marker_state.dirty = true;
16074 cx.notify();
16075 }
16076
16077 pub fn clear_background_highlights<T: 'static>(
16078 &mut self,
16079 cx: &mut Context<Self>,
16080 ) -> Option<BackgroundHighlight> {
16081 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16082 if !text_highlights.1.is_empty() {
16083 self.scrollbar_marker_state.dirty = true;
16084 cx.notify();
16085 }
16086 Some(text_highlights)
16087 }
16088
16089 pub fn highlight_gutter<T: 'static>(
16090 &mut self,
16091 ranges: &[Range<Anchor>],
16092 color_fetcher: fn(&App) -> Hsla,
16093 cx: &mut Context<Self>,
16094 ) {
16095 self.gutter_highlights
16096 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16097 cx.notify();
16098 }
16099
16100 pub fn clear_gutter_highlights<T: 'static>(
16101 &mut self,
16102 cx: &mut Context<Self>,
16103 ) -> Option<GutterHighlight> {
16104 cx.notify();
16105 self.gutter_highlights.remove(&TypeId::of::<T>())
16106 }
16107
16108 #[cfg(feature = "test-support")]
16109 pub fn all_text_background_highlights(
16110 &self,
16111 window: &mut Window,
16112 cx: &mut Context<Self>,
16113 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16114 let snapshot = self.snapshot(window, cx);
16115 let buffer = &snapshot.buffer_snapshot;
16116 let start = buffer.anchor_before(0);
16117 let end = buffer.anchor_after(buffer.len());
16118 let theme = cx.theme().colors();
16119 self.background_highlights_in_range(start..end, &snapshot, theme)
16120 }
16121
16122 #[cfg(feature = "test-support")]
16123 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16124 let snapshot = self.buffer().read(cx).snapshot(cx);
16125
16126 let highlights = self
16127 .background_highlights
16128 .get(&TypeId::of::<items::BufferSearchHighlights>());
16129
16130 if let Some((_color, ranges)) = highlights {
16131 ranges
16132 .iter()
16133 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16134 .collect_vec()
16135 } else {
16136 vec![]
16137 }
16138 }
16139
16140 fn document_highlights_for_position<'a>(
16141 &'a self,
16142 position: Anchor,
16143 buffer: &'a MultiBufferSnapshot,
16144 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16145 let read_highlights = self
16146 .background_highlights
16147 .get(&TypeId::of::<DocumentHighlightRead>())
16148 .map(|h| &h.1);
16149 let write_highlights = self
16150 .background_highlights
16151 .get(&TypeId::of::<DocumentHighlightWrite>())
16152 .map(|h| &h.1);
16153 let left_position = position.bias_left(buffer);
16154 let right_position = position.bias_right(buffer);
16155 read_highlights
16156 .into_iter()
16157 .chain(write_highlights)
16158 .flat_map(move |ranges| {
16159 let start_ix = match ranges.binary_search_by(|probe| {
16160 let cmp = probe.end.cmp(&left_position, buffer);
16161 if cmp.is_ge() {
16162 Ordering::Greater
16163 } else {
16164 Ordering::Less
16165 }
16166 }) {
16167 Ok(i) | Err(i) => i,
16168 };
16169
16170 ranges[start_ix..]
16171 .iter()
16172 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16173 })
16174 }
16175
16176 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16177 self.background_highlights
16178 .get(&TypeId::of::<T>())
16179 .map_or(false, |(_, highlights)| !highlights.is_empty())
16180 }
16181
16182 pub fn background_highlights_in_range(
16183 &self,
16184 search_range: Range<Anchor>,
16185 display_snapshot: &DisplaySnapshot,
16186 theme: &ThemeColors,
16187 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16188 let mut results = Vec::new();
16189 for (color_fetcher, ranges) in self.background_highlights.values() {
16190 let color = color_fetcher(theme);
16191 let start_ix = match ranges.binary_search_by(|probe| {
16192 let cmp = probe
16193 .end
16194 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16195 if cmp.is_gt() {
16196 Ordering::Greater
16197 } else {
16198 Ordering::Less
16199 }
16200 }) {
16201 Ok(i) | Err(i) => i,
16202 };
16203 for range in &ranges[start_ix..] {
16204 if range
16205 .start
16206 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16207 .is_ge()
16208 {
16209 break;
16210 }
16211
16212 let start = range.start.to_display_point(display_snapshot);
16213 let end = range.end.to_display_point(display_snapshot);
16214 results.push((start..end, color))
16215 }
16216 }
16217 results
16218 }
16219
16220 pub fn background_highlight_row_ranges<T: 'static>(
16221 &self,
16222 search_range: Range<Anchor>,
16223 display_snapshot: &DisplaySnapshot,
16224 count: usize,
16225 ) -> Vec<RangeInclusive<DisplayPoint>> {
16226 let mut results = Vec::new();
16227 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16228 return vec![];
16229 };
16230
16231 let start_ix = match ranges.binary_search_by(|probe| {
16232 let cmp = probe
16233 .end
16234 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16235 if cmp.is_gt() {
16236 Ordering::Greater
16237 } else {
16238 Ordering::Less
16239 }
16240 }) {
16241 Ok(i) | Err(i) => i,
16242 };
16243 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16244 if let (Some(start_display), Some(end_display)) = (start, end) {
16245 results.push(
16246 start_display.to_display_point(display_snapshot)
16247 ..=end_display.to_display_point(display_snapshot),
16248 );
16249 }
16250 };
16251 let mut start_row: Option<Point> = None;
16252 let mut end_row: Option<Point> = None;
16253 if ranges.len() > count {
16254 return Vec::new();
16255 }
16256 for range in &ranges[start_ix..] {
16257 if range
16258 .start
16259 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16260 .is_ge()
16261 {
16262 break;
16263 }
16264 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16265 if let Some(current_row) = &end_row {
16266 if end.row == current_row.row {
16267 continue;
16268 }
16269 }
16270 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16271 if start_row.is_none() {
16272 assert_eq!(end_row, None);
16273 start_row = Some(start);
16274 end_row = Some(end);
16275 continue;
16276 }
16277 if let Some(current_end) = end_row.as_mut() {
16278 if start.row > current_end.row + 1 {
16279 push_region(start_row, end_row);
16280 start_row = Some(start);
16281 end_row = Some(end);
16282 } else {
16283 // Merge two hunks.
16284 *current_end = end;
16285 }
16286 } else {
16287 unreachable!();
16288 }
16289 }
16290 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16291 push_region(start_row, end_row);
16292 results
16293 }
16294
16295 pub fn gutter_highlights_in_range(
16296 &self,
16297 search_range: Range<Anchor>,
16298 display_snapshot: &DisplaySnapshot,
16299 cx: &App,
16300 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16301 let mut results = Vec::new();
16302 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16303 let color = color_fetcher(cx);
16304 let start_ix = match ranges.binary_search_by(|probe| {
16305 let cmp = probe
16306 .end
16307 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16308 if cmp.is_gt() {
16309 Ordering::Greater
16310 } else {
16311 Ordering::Less
16312 }
16313 }) {
16314 Ok(i) | Err(i) => i,
16315 };
16316 for range in &ranges[start_ix..] {
16317 if range
16318 .start
16319 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16320 .is_ge()
16321 {
16322 break;
16323 }
16324
16325 let start = range.start.to_display_point(display_snapshot);
16326 let end = range.end.to_display_point(display_snapshot);
16327 results.push((start..end, color))
16328 }
16329 }
16330 results
16331 }
16332
16333 /// Get the text ranges corresponding to the redaction query
16334 pub fn redacted_ranges(
16335 &self,
16336 search_range: Range<Anchor>,
16337 display_snapshot: &DisplaySnapshot,
16338 cx: &App,
16339 ) -> Vec<Range<DisplayPoint>> {
16340 display_snapshot
16341 .buffer_snapshot
16342 .redacted_ranges(search_range, |file| {
16343 if let Some(file) = file {
16344 file.is_private()
16345 && EditorSettings::get(
16346 Some(SettingsLocation {
16347 worktree_id: file.worktree_id(cx),
16348 path: file.path().as_ref(),
16349 }),
16350 cx,
16351 )
16352 .redact_private_values
16353 } else {
16354 false
16355 }
16356 })
16357 .map(|range| {
16358 range.start.to_display_point(display_snapshot)
16359 ..range.end.to_display_point(display_snapshot)
16360 })
16361 .collect()
16362 }
16363
16364 pub fn highlight_text<T: 'static>(
16365 &mut self,
16366 ranges: Vec<Range<Anchor>>,
16367 style: HighlightStyle,
16368 cx: &mut Context<Self>,
16369 ) {
16370 self.display_map.update(cx, |map, _| {
16371 map.highlight_text(TypeId::of::<T>(), ranges, style)
16372 });
16373 cx.notify();
16374 }
16375
16376 pub(crate) fn highlight_inlays<T: 'static>(
16377 &mut self,
16378 highlights: Vec<InlayHighlight>,
16379 style: HighlightStyle,
16380 cx: &mut Context<Self>,
16381 ) {
16382 self.display_map.update(cx, |map, _| {
16383 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16384 });
16385 cx.notify();
16386 }
16387
16388 pub fn text_highlights<'a, T: 'static>(
16389 &'a self,
16390 cx: &'a App,
16391 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16392 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16393 }
16394
16395 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16396 let cleared = self
16397 .display_map
16398 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16399 if cleared {
16400 cx.notify();
16401 }
16402 }
16403
16404 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16405 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16406 && self.focus_handle.is_focused(window)
16407 }
16408
16409 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16410 self.show_cursor_when_unfocused = is_enabled;
16411 cx.notify();
16412 }
16413
16414 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16415 cx.notify();
16416 }
16417
16418 fn on_buffer_event(
16419 &mut self,
16420 multibuffer: &Entity<MultiBuffer>,
16421 event: &multi_buffer::Event,
16422 window: &mut Window,
16423 cx: &mut Context<Self>,
16424 ) {
16425 match event {
16426 multi_buffer::Event::Edited {
16427 singleton_buffer_edited,
16428 edited_buffer: buffer_edited,
16429 } => {
16430 self.scrollbar_marker_state.dirty = true;
16431 self.active_indent_guides_state.dirty = true;
16432 self.refresh_active_diagnostics(cx);
16433 self.refresh_code_actions(window, cx);
16434 if self.has_active_inline_completion() {
16435 self.update_visible_inline_completion(window, cx);
16436 }
16437 if let Some(buffer) = buffer_edited {
16438 let buffer_id = buffer.read(cx).remote_id();
16439 if !self.registered_buffers.contains_key(&buffer_id) {
16440 if let Some(project) = self.project.as_ref() {
16441 project.update(cx, |project, cx| {
16442 self.registered_buffers.insert(
16443 buffer_id,
16444 project.register_buffer_with_language_servers(&buffer, cx),
16445 );
16446 })
16447 }
16448 }
16449 }
16450 cx.emit(EditorEvent::BufferEdited);
16451 cx.emit(SearchEvent::MatchesInvalidated);
16452 if *singleton_buffer_edited {
16453 if let Some(project) = &self.project {
16454 #[allow(clippy::mutable_key_type)]
16455 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16456 multibuffer
16457 .all_buffers()
16458 .into_iter()
16459 .filter_map(|buffer| {
16460 buffer.update(cx, |buffer, cx| {
16461 let language = buffer.language()?;
16462 let should_discard = project.update(cx, |project, cx| {
16463 project.is_local()
16464 && !project.has_language_servers_for(buffer, cx)
16465 });
16466 should_discard.not().then_some(language.clone())
16467 })
16468 })
16469 .collect::<HashSet<_>>()
16470 });
16471 if !languages_affected.is_empty() {
16472 self.refresh_inlay_hints(
16473 InlayHintRefreshReason::BufferEdited(languages_affected),
16474 cx,
16475 );
16476 }
16477 }
16478 }
16479
16480 let Some(project) = &self.project else { return };
16481 let (telemetry, is_via_ssh) = {
16482 let project = project.read(cx);
16483 let telemetry = project.client().telemetry().clone();
16484 let is_via_ssh = project.is_via_ssh();
16485 (telemetry, is_via_ssh)
16486 };
16487 refresh_linked_ranges(self, window, cx);
16488 telemetry.log_edit_event("editor", is_via_ssh);
16489 }
16490 multi_buffer::Event::ExcerptsAdded {
16491 buffer,
16492 predecessor,
16493 excerpts,
16494 } => {
16495 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16496 let buffer_id = buffer.read(cx).remote_id();
16497 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16498 if let Some(project) = &self.project {
16499 get_uncommitted_diff_for_buffer(
16500 project,
16501 [buffer.clone()],
16502 self.buffer.clone(),
16503 cx,
16504 )
16505 .detach();
16506 }
16507 }
16508 cx.emit(EditorEvent::ExcerptsAdded {
16509 buffer: buffer.clone(),
16510 predecessor: *predecessor,
16511 excerpts: excerpts.clone(),
16512 });
16513 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16514 }
16515 multi_buffer::Event::ExcerptsRemoved { ids } => {
16516 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16517 let buffer = self.buffer.read(cx);
16518 self.registered_buffers
16519 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16520 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16521 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16522 }
16523 multi_buffer::Event::ExcerptsEdited {
16524 excerpt_ids,
16525 buffer_ids,
16526 } => {
16527 self.display_map.update(cx, |map, cx| {
16528 map.unfold_buffers(buffer_ids.iter().copied(), cx)
16529 });
16530 cx.emit(EditorEvent::ExcerptsEdited {
16531 ids: excerpt_ids.clone(),
16532 })
16533 }
16534 multi_buffer::Event::ExcerptsExpanded { ids } => {
16535 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16536 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16537 }
16538 multi_buffer::Event::Reparsed(buffer_id) => {
16539 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16540 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16541
16542 cx.emit(EditorEvent::Reparsed(*buffer_id));
16543 }
16544 multi_buffer::Event::DiffHunksToggled => {
16545 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16546 }
16547 multi_buffer::Event::LanguageChanged(buffer_id) => {
16548 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16549 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16550 cx.emit(EditorEvent::Reparsed(*buffer_id));
16551 cx.notify();
16552 }
16553 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16554 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16555 multi_buffer::Event::FileHandleChanged
16556 | multi_buffer::Event::Reloaded
16557 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16558 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16559 multi_buffer::Event::DiagnosticsUpdated => {
16560 self.refresh_active_diagnostics(cx);
16561 self.refresh_inline_diagnostics(true, window, cx);
16562 self.scrollbar_marker_state.dirty = true;
16563 cx.notify();
16564 }
16565 _ => {}
16566 };
16567 }
16568
16569 fn on_display_map_changed(
16570 &mut self,
16571 _: Entity<DisplayMap>,
16572 _: &mut Window,
16573 cx: &mut Context<Self>,
16574 ) {
16575 cx.notify();
16576 }
16577
16578 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16579 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16580 self.update_edit_prediction_settings(cx);
16581 self.refresh_inline_completion(true, false, window, cx);
16582 self.refresh_inlay_hints(
16583 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16584 self.selections.newest_anchor().head(),
16585 &self.buffer.read(cx).snapshot(cx),
16586 cx,
16587 )),
16588 cx,
16589 );
16590
16591 let old_cursor_shape = self.cursor_shape;
16592
16593 {
16594 let editor_settings = EditorSettings::get_global(cx);
16595 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16596 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16597 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16598 }
16599
16600 if old_cursor_shape != self.cursor_shape {
16601 cx.emit(EditorEvent::CursorShapeChanged);
16602 }
16603
16604 let project_settings = ProjectSettings::get_global(cx);
16605 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16606
16607 if self.mode == EditorMode::Full {
16608 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16609 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16610 if self.show_inline_diagnostics != show_inline_diagnostics {
16611 self.show_inline_diagnostics = show_inline_diagnostics;
16612 self.refresh_inline_diagnostics(false, window, cx);
16613 }
16614
16615 if self.git_blame_inline_enabled != inline_blame_enabled {
16616 self.toggle_git_blame_inline_internal(false, window, cx);
16617 }
16618 }
16619
16620 cx.notify();
16621 }
16622
16623 pub fn set_searchable(&mut self, searchable: bool) {
16624 self.searchable = searchable;
16625 }
16626
16627 pub fn searchable(&self) -> bool {
16628 self.searchable
16629 }
16630
16631 fn open_proposed_changes_editor(
16632 &mut self,
16633 _: &OpenProposedChangesEditor,
16634 window: &mut Window,
16635 cx: &mut Context<Self>,
16636 ) {
16637 let Some(workspace) = self.workspace() else {
16638 cx.propagate();
16639 return;
16640 };
16641
16642 let selections = self.selections.all::<usize>(cx);
16643 let multi_buffer = self.buffer.read(cx);
16644 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16645 let mut new_selections_by_buffer = HashMap::default();
16646 for selection in selections {
16647 for (buffer, range, _) in
16648 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16649 {
16650 let mut range = range.to_point(buffer);
16651 range.start.column = 0;
16652 range.end.column = buffer.line_len(range.end.row);
16653 new_selections_by_buffer
16654 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16655 .or_insert(Vec::new())
16656 .push(range)
16657 }
16658 }
16659
16660 let proposed_changes_buffers = new_selections_by_buffer
16661 .into_iter()
16662 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16663 .collect::<Vec<_>>();
16664 let proposed_changes_editor = cx.new(|cx| {
16665 ProposedChangesEditor::new(
16666 "Proposed changes",
16667 proposed_changes_buffers,
16668 self.project.clone(),
16669 window,
16670 cx,
16671 )
16672 });
16673
16674 window.defer(cx, move |window, cx| {
16675 workspace.update(cx, |workspace, cx| {
16676 workspace.active_pane().update(cx, |pane, cx| {
16677 pane.add_item(
16678 Box::new(proposed_changes_editor),
16679 true,
16680 true,
16681 None,
16682 window,
16683 cx,
16684 );
16685 });
16686 });
16687 });
16688 }
16689
16690 pub fn open_excerpts_in_split(
16691 &mut self,
16692 _: &OpenExcerptsSplit,
16693 window: &mut Window,
16694 cx: &mut Context<Self>,
16695 ) {
16696 self.open_excerpts_common(None, true, window, cx)
16697 }
16698
16699 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16700 self.open_excerpts_common(None, false, window, cx)
16701 }
16702
16703 fn open_excerpts_common(
16704 &mut self,
16705 jump_data: Option<JumpData>,
16706 split: bool,
16707 window: &mut Window,
16708 cx: &mut Context<Self>,
16709 ) {
16710 let Some(workspace) = self.workspace() else {
16711 cx.propagate();
16712 return;
16713 };
16714
16715 if self.buffer.read(cx).is_singleton() {
16716 cx.propagate();
16717 return;
16718 }
16719
16720 let mut new_selections_by_buffer = HashMap::default();
16721 match &jump_data {
16722 Some(JumpData::MultiBufferPoint {
16723 excerpt_id,
16724 position,
16725 anchor,
16726 line_offset_from_top,
16727 }) => {
16728 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16729 if let Some(buffer) = multi_buffer_snapshot
16730 .buffer_id_for_excerpt(*excerpt_id)
16731 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16732 {
16733 let buffer_snapshot = buffer.read(cx).snapshot();
16734 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16735 language::ToPoint::to_point(anchor, &buffer_snapshot)
16736 } else {
16737 buffer_snapshot.clip_point(*position, Bias::Left)
16738 };
16739 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16740 new_selections_by_buffer.insert(
16741 buffer,
16742 (
16743 vec![jump_to_offset..jump_to_offset],
16744 Some(*line_offset_from_top),
16745 ),
16746 );
16747 }
16748 }
16749 Some(JumpData::MultiBufferRow {
16750 row,
16751 line_offset_from_top,
16752 }) => {
16753 let point = MultiBufferPoint::new(row.0, 0);
16754 if let Some((buffer, buffer_point, _)) =
16755 self.buffer.read(cx).point_to_buffer_point(point, cx)
16756 {
16757 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16758 new_selections_by_buffer
16759 .entry(buffer)
16760 .or_insert((Vec::new(), Some(*line_offset_from_top)))
16761 .0
16762 .push(buffer_offset..buffer_offset)
16763 }
16764 }
16765 None => {
16766 let selections = self.selections.all::<usize>(cx);
16767 let multi_buffer = self.buffer.read(cx);
16768 for selection in selections {
16769 for (snapshot, range, _, anchor) in multi_buffer
16770 .snapshot(cx)
16771 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16772 {
16773 if let Some(anchor) = anchor {
16774 // selection is in a deleted hunk
16775 let Some(buffer_id) = anchor.buffer_id else {
16776 continue;
16777 };
16778 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16779 continue;
16780 };
16781 let offset = text::ToOffset::to_offset(
16782 &anchor.text_anchor,
16783 &buffer_handle.read(cx).snapshot(),
16784 );
16785 let range = offset..offset;
16786 new_selections_by_buffer
16787 .entry(buffer_handle)
16788 .or_insert((Vec::new(), None))
16789 .0
16790 .push(range)
16791 } else {
16792 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16793 else {
16794 continue;
16795 };
16796 new_selections_by_buffer
16797 .entry(buffer_handle)
16798 .or_insert((Vec::new(), None))
16799 .0
16800 .push(range)
16801 }
16802 }
16803 }
16804 }
16805 }
16806
16807 if new_selections_by_buffer.is_empty() {
16808 return;
16809 }
16810
16811 // We defer the pane interaction because we ourselves are a workspace item
16812 // and activating a new item causes the pane to call a method on us reentrantly,
16813 // which panics if we're on the stack.
16814 window.defer(cx, move |window, cx| {
16815 workspace.update(cx, |workspace, cx| {
16816 let pane = if split {
16817 workspace.adjacent_pane(window, cx)
16818 } else {
16819 workspace.active_pane().clone()
16820 };
16821
16822 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16823 let editor = buffer
16824 .read(cx)
16825 .file()
16826 .is_none()
16827 .then(|| {
16828 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16829 // so `workspace.open_project_item` will never find them, always opening a new editor.
16830 // Instead, we try to activate the existing editor in the pane first.
16831 let (editor, pane_item_index) =
16832 pane.read(cx).items().enumerate().find_map(|(i, item)| {
16833 let editor = item.downcast::<Editor>()?;
16834 let singleton_buffer =
16835 editor.read(cx).buffer().read(cx).as_singleton()?;
16836 if singleton_buffer == buffer {
16837 Some((editor, i))
16838 } else {
16839 None
16840 }
16841 })?;
16842 pane.update(cx, |pane, cx| {
16843 pane.activate_item(pane_item_index, true, true, window, cx)
16844 });
16845 Some(editor)
16846 })
16847 .flatten()
16848 .unwrap_or_else(|| {
16849 workspace.open_project_item::<Self>(
16850 pane.clone(),
16851 buffer,
16852 true,
16853 true,
16854 window,
16855 cx,
16856 )
16857 });
16858
16859 editor.update(cx, |editor, cx| {
16860 let autoscroll = match scroll_offset {
16861 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16862 None => Autoscroll::newest(),
16863 };
16864 let nav_history = editor.nav_history.take();
16865 editor.change_selections(Some(autoscroll), window, cx, |s| {
16866 s.select_ranges(ranges);
16867 });
16868 editor.nav_history = nav_history;
16869 });
16870 }
16871 })
16872 });
16873 }
16874
16875 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16876 let snapshot = self.buffer.read(cx).read(cx);
16877 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16878 Some(
16879 ranges
16880 .iter()
16881 .map(move |range| {
16882 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16883 })
16884 .collect(),
16885 )
16886 }
16887
16888 fn selection_replacement_ranges(
16889 &self,
16890 range: Range<OffsetUtf16>,
16891 cx: &mut App,
16892 ) -> Vec<Range<OffsetUtf16>> {
16893 let selections = self.selections.all::<OffsetUtf16>(cx);
16894 let newest_selection = selections
16895 .iter()
16896 .max_by_key(|selection| selection.id)
16897 .unwrap();
16898 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16899 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16900 let snapshot = self.buffer.read(cx).read(cx);
16901 selections
16902 .into_iter()
16903 .map(|mut selection| {
16904 selection.start.0 =
16905 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16906 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16907 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16908 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16909 })
16910 .collect()
16911 }
16912
16913 fn report_editor_event(
16914 &self,
16915 event_type: &'static str,
16916 file_extension: Option<String>,
16917 cx: &App,
16918 ) {
16919 if cfg!(any(test, feature = "test-support")) {
16920 return;
16921 }
16922
16923 let Some(project) = &self.project else { return };
16924
16925 // If None, we are in a file without an extension
16926 let file = self
16927 .buffer
16928 .read(cx)
16929 .as_singleton()
16930 .and_then(|b| b.read(cx).file());
16931 let file_extension = file_extension.or(file
16932 .as_ref()
16933 .and_then(|file| Path::new(file.file_name(cx)).extension())
16934 .and_then(|e| e.to_str())
16935 .map(|a| a.to_string()));
16936
16937 let vim_mode = cx
16938 .global::<SettingsStore>()
16939 .raw_user_settings()
16940 .get("vim_mode")
16941 == Some(&serde_json::Value::Bool(true));
16942
16943 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16944 let copilot_enabled = edit_predictions_provider
16945 == language::language_settings::EditPredictionProvider::Copilot;
16946 let copilot_enabled_for_language = self
16947 .buffer
16948 .read(cx)
16949 .language_settings(cx)
16950 .show_edit_predictions;
16951
16952 let project = project.read(cx);
16953 telemetry::event!(
16954 event_type,
16955 file_extension,
16956 vim_mode,
16957 copilot_enabled,
16958 copilot_enabled_for_language,
16959 edit_predictions_provider,
16960 is_via_ssh = project.is_via_ssh(),
16961 );
16962 }
16963
16964 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16965 /// with each line being an array of {text, highlight} objects.
16966 fn copy_highlight_json(
16967 &mut self,
16968 _: &CopyHighlightJson,
16969 window: &mut Window,
16970 cx: &mut Context<Self>,
16971 ) {
16972 #[derive(Serialize)]
16973 struct Chunk<'a> {
16974 text: String,
16975 highlight: Option<&'a str>,
16976 }
16977
16978 let snapshot = self.buffer.read(cx).snapshot(cx);
16979 let range = self
16980 .selected_text_range(false, window, cx)
16981 .and_then(|selection| {
16982 if selection.range.is_empty() {
16983 None
16984 } else {
16985 Some(selection.range)
16986 }
16987 })
16988 .unwrap_or_else(|| 0..snapshot.len());
16989
16990 let chunks = snapshot.chunks(range, true);
16991 let mut lines = Vec::new();
16992 let mut line: VecDeque<Chunk> = VecDeque::new();
16993
16994 let Some(style) = self.style.as_ref() else {
16995 return;
16996 };
16997
16998 for chunk in chunks {
16999 let highlight = chunk
17000 .syntax_highlight_id
17001 .and_then(|id| id.name(&style.syntax));
17002 let mut chunk_lines = chunk.text.split('\n').peekable();
17003 while let Some(text) = chunk_lines.next() {
17004 let mut merged_with_last_token = false;
17005 if let Some(last_token) = line.back_mut() {
17006 if last_token.highlight == highlight {
17007 last_token.text.push_str(text);
17008 merged_with_last_token = true;
17009 }
17010 }
17011
17012 if !merged_with_last_token {
17013 line.push_back(Chunk {
17014 text: text.into(),
17015 highlight,
17016 });
17017 }
17018
17019 if chunk_lines.peek().is_some() {
17020 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17021 line.pop_front();
17022 }
17023 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17024 line.pop_back();
17025 }
17026
17027 lines.push(mem::take(&mut line));
17028 }
17029 }
17030 }
17031
17032 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17033 return;
17034 };
17035 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17036 }
17037
17038 pub fn open_context_menu(
17039 &mut self,
17040 _: &OpenContextMenu,
17041 window: &mut Window,
17042 cx: &mut Context<Self>,
17043 ) {
17044 self.request_autoscroll(Autoscroll::newest(), cx);
17045 let position = self.selections.newest_display(cx).start;
17046 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17047 }
17048
17049 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17050 &self.inlay_hint_cache
17051 }
17052
17053 pub fn replay_insert_event(
17054 &mut self,
17055 text: &str,
17056 relative_utf16_range: Option<Range<isize>>,
17057 window: &mut Window,
17058 cx: &mut Context<Self>,
17059 ) {
17060 if !self.input_enabled {
17061 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17062 return;
17063 }
17064 if let Some(relative_utf16_range) = relative_utf16_range {
17065 let selections = self.selections.all::<OffsetUtf16>(cx);
17066 self.change_selections(None, window, cx, |s| {
17067 let new_ranges = selections.into_iter().map(|range| {
17068 let start = OffsetUtf16(
17069 range
17070 .head()
17071 .0
17072 .saturating_add_signed(relative_utf16_range.start),
17073 );
17074 let end = OffsetUtf16(
17075 range
17076 .head()
17077 .0
17078 .saturating_add_signed(relative_utf16_range.end),
17079 );
17080 start..end
17081 });
17082 s.select_ranges(new_ranges);
17083 });
17084 }
17085
17086 self.handle_input(text, window, cx);
17087 }
17088
17089 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17090 let Some(provider) = self.semantics_provider.as_ref() else {
17091 return false;
17092 };
17093
17094 let mut supports = false;
17095 self.buffer().update(cx, |this, cx| {
17096 this.for_each_buffer(|buffer| {
17097 supports |= provider.supports_inlay_hints(buffer, cx);
17098 });
17099 });
17100
17101 supports
17102 }
17103
17104 pub fn is_focused(&self, window: &Window) -> bool {
17105 self.focus_handle.is_focused(window)
17106 }
17107
17108 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17109 cx.emit(EditorEvent::Focused);
17110
17111 if let Some(descendant) = self
17112 .last_focused_descendant
17113 .take()
17114 .and_then(|descendant| descendant.upgrade())
17115 {
17116 window.focus(&descendant);
17117 } else {
17118 if let Some(blame) = self.blame.as_ref() {
17119 blame.update(cx, GitBlame::focus)
17120 }
17121
17122 self.blink_manager.update(cx, BlinkManager::enable);
17123 self.show_cursor_names(window, cx);
17124 self.buffer.update(cx, |buffer, cx| {
17125 buffer.finalize_last_transaction(cx);
17126 if self.leader_peer_id.is_none() {
17127 buffer.set_active_selections(
17128 &self.selections.disjoint_anchors(),
17129 self.selections.line_mode,
17130 self.cursor_shape,
17131 cx,
17132 );
17133 }
17134 });
17135 }
17136 }
17137
17138 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17139 cx.emit(EditorEvent::FocusedIn)
17140 }
17141
17142 fn handle_focus_out(
17143 &mut self,
17144 event: FocusOutEvent,
17145 _window: &mut Window,
17146 cx: &mut Context<Self>,
17147 ) {
17148 if event.blurred != self.focus_handle {
17149 self.last_focused_descendant = Some(event.blurred);
17150 }
17151 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17152 }
17153
17154 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17155 self.blink_manager.update(cx, BlinkManager::disable);
17156 self.buffer
17157 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17158
17159 if let Some(blame) = self.blame.as_ref() {
17160 blame.update(cx, GitBlame::blur)
17161 }
17162 if !self.hover_state.focused(window, cx) {
17163 hide_hover(self, cx);
17164 }
17165 if !self
17166 .context_menu
17167 .borrow()
17168 .as_ref()
17169 .is_some_and(|context_menu| context_menu.focused(window, cx))
17170 {
17171 self.hide_context_menu(window, cx);
17172 }
17173 self.discard_inline_completion(false, cx);
17174 cx.emit(EditorEvent::Blurred);
17175 cx.notify();
17176 }
17177
17178 pub fn register_action<A: Action>(
17179 &mut self,
17180 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17181 ) -> Subscription {
17182 let id = self.next_editor_action_id.post_inc();
17183 let listener = Arc::new(listener);
17184 self.editor_actions.borrow_mut().insert(
17185 id,
17186 Box::new(move |window, _| {
17187 let listener = listener.clone();
17188 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17189 let action = action.downcast_ref().unwrap();
17190 if phase == DispatchPhase::Bubble {
17191 listener(action, window, cx)
17192 }
17193 })
17194 }),
17195 );
17196
17197 let editor_actions = self.editor_actions.clone();
17198 Subscription::new(move || {
17199 editor_actions.borrow_mut().remove(&id);
17200 })
17201 }
17202
17203 pub fn file_header_size(&self) -> u32 {
17204 FILE_HEADER_HEIGHT
17205 }
17206
17207 pub fn restore(
17208 &mut self,
17209 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17210 window: &mut Window,
17211 cx: &mut Context<Self>,
17212 ) {
17213 let workspace = self.workspace();
17214 let project = self.project.as_ref();
17215 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17216 let mut tasks = Vec::new();
17217 for (buffer_id, changes) in revert_changes {
17218 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17219 buffer.update(cx, |buffer, cx| {
17220 buffer.edit(
17221 changes
17222 .into_iter()
17223 .map(|(range, text)| (range, text.to_string())),
17224 None,
17225 cx,
17226 );
17227 });
17228
17229 if let Some(project) =
17230 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17231 {
17232 project.update(cx, |project, cx| {
17233 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17234 })
17235 }
17236 }
17237 }
17238 tasks
17239 });
17240 cx.spawn_in(window, async move |_, cx| {
17241 for (buffer, task) in save_tasks {
17242 let result = task.await;
17243 if result.is_err() {
17244 let Some(path) = buffer
17245 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17246 .ok()
17247 else {
17248 continue;
17249 };
17250 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17251 let Some(task) = cx
17252 .update_window_entity(&workspace, |workspace, window, cx| {
17253 workspace
17254 .open_path_preview(path, None, false, false, false, window, cx)
17255 })
17256 .ok()
17257 else {
17258 continue;
17259 };
17260 task.await.log_err();
17261 }
17262 }
17263 }
17264 })
17265 .detach();
17266 self.change_selections(None, window, cx, |selections| selections.refresh());
17267 }
17268
17269 pub fn to_pixel_point(
17270 &self,
17271 source: multi_buffer::Anchor,
17272 editor_snapshot: &EditorSnapshot,
17273 window: &mut Window,
17274 ) -> Option<gpui::Point<Pixels>> {
17275 let source_point = source.to_display_point(editor_snapshot);
17276 self.display_to_pixel_point(source_point, editor_snapshot, window)
17277 }
17278
17279 pub fn display_to_pixel_point(
17280 &self,
17281 source: DisplayPoint,
17282 editor_snapshot: &EditorSnapshot,
17283 window: &mut Window,
17284 ) -> Option<gpui::Point<Pixels>> {
17285 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17286 let text_layout_details = self.text_layout_details(window);
17287 let scroll_top = text_layout_details
17288 .scroll_anchor
17289 .scroll_position(editor_snapshot)
17290 .y;
17291
17292 if source.row().as_f32() < scroll_top.floor() {
17293 return None;
17294 }
17295 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17296 let source_y = line_height * (source.row().as_f32() - scroll_top);
17297 Some(gpui::Point::new(source_x, source_y))
17298 }
17299
17300 pub fn has_visible_completions_menu(&self) -> bool {
17301 !self.edit_prediction_preview_is_active()
17302 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17303 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17304 })
17305 }
17306
17307 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17308 self.addons
17309 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17310 }
17311
17312 pub fn unregister_addon<T: Addon>(&mut self) {
17313 self.addons.remove(&std::any::TypeId::of::<T>());
17314 }
17315
17316 pub fn addon<T: Addon>(&self) -> Option<&T> {
17317 let type_id = std::any::TypeId::of::<T>();
17318 self.addons
17319 .get(&type_id)
17320 .and_then(|item| item.to_any().downcast_ref::<T>())
17321 }
17322
17323 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17324 let text_layout_details = self.text_layout_details(window);
17325 let style = &text_layout_details.editor_style;
17326 let font_id = window.text_system().resolve_font(&style.text.font());
17327 let font_size = style.text.font_size.to_pixels(window.rem_size());
17328 let line_height = style.text.line_height_in_pixels(window.rem_size());
17329 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17330
17331 gpui::Size::new(em_width, line_height)
17332 }
17333
17334 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17335 self.load_diff_task.clone()
17336 }
17337
17338 fn read_metadata_from_db(
17339 &mut self,
17340 item_id: u64,
17341 workspace_id: WorkspaceId,
17342 window: &mut Window,
17343 cx: &mut Context<Editor>,
17344 ) {
17345 if self.is_singleton(cx)
17346 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17347 {
17348 let buffer_snapshot = OnceCell::new();
17349
17350 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17351 if !selections.is_empty() {
17352 let snapshot =
17353 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17354 self.change_selections(None, window, cx, |s| {
17355 s.select_ranges(selections.into_iter().map(|(start, end)| {
17356 snapshot.clip_offset(start, Bias::Left)
17357 ..snapshot.clip_offset(end, Bias::Right)
17358 }));
17359 });
17360 }
17361 };
17362
17363 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17364 if !folds.is_empty() {
17365 let snapshot =
17366 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17367 self.fold_ranges(
17368 folds
17369 .into_iter()
17370 .map(|(start, end)| {
17371 snapshot.clip_offset(start, Bias::Left)
17372 ..snapshot.clip_offset(end, Bias::Right)
17373 })
17374 .collect(),
17375 false,
17376 window,
17377 cx,
17378 );
17379 }
17380 }
17381 }
17382
17383 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17384 }
17385}
17386
17387fn insert_extra_newline_brackets(
17388 buffer: &MultiBufferSnapshot,
17389 range: Range<usize>,
17390 language: &language::LanguageScope,
17391) -> bool {
17392 let leading_whitespace_len = buffer
17393 .reversed_chars_at(range.start)
17394 .take_while(|c| c.is_whitespace() && *c != '\n')
17395 .map(|c| c.len_utf8())
17396 .sum::<usize>();
17397 let trailing_whitespace_len = buffer
17398 .chars_at(range.end)
17399 .take_while(|c| c.is_whitespace() && *c != '\n')
17400 .map(|c| c.len_utf8())
17401 .sum::<usize>();
17402 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17403
17404 language.brackets().any(|(pair, enabled)| {
17405 let pair_start = pair.start.trim_end();
17406 let pair_end = pair.end.trim_start();
17407
17408 enabled
17409 && pair.newline
17410 && buffer.contains_str_at(range.end, pair_end)
17411 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17412 })
17413}
17414
17415fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17416 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17417 [(buffer, range, _)] => (*buffer, range.clone()),
17418 _ => return false,
17419 };
17420 let pair = {
17421 let mut result: Option<BracketMatch> = None;
17422
17423 for pair in buffer
17424 .all_bracket_ranges(range.clone())
17425 .filter(move |pair| {
17426 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17427 })
17428 {
17429 let len = pair.close_range.end - pair.open_range.start;
17430
17431 if let Some(existing) = &result {
17432 let existing_len = existing.close_range.end - existing.open_range.start;
17433 if len > existing_len {
17434 continue;
17435 }
17436 }
17437
17438 result = Some(pair);
17439 }
17440
17441 result
17442 };
17443 let Some(pair) = pair else {
17444 return false;
17445 };
17446 pair.newline_only
17447 && buffer
17448 .chars_for_range(pair.open_range.end..range.start)
17449 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17450 .all(|c| c.is_whitespace() && c != '\n')
17451}
17452
17453fn get_uncommitted_diff_for_buffer(
17454 project: &Entity<Project>,
17455 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17456 buffer: Entity<MultiBuffer>,
17457 cx: &mut App,
17458) -> Task<()> {
17459 let mut tasks = Vec::new();
17460 project.update(cx, |project, cx| {
17461 for buffer in buffers {
17462 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17463 }
17464 });
17465 cx.spawn(async move |cx| {
17466 let diffs = future::join_all(tasks).await;
17467 buffer
17468 .update(cx, |buffer, cx| {
17469 for diff in diffs.into_iter().flatten() {
17470 buffer.add_diff(diff, cx);
17471 }
17472 })
17473 .ok();
17474 })
17475}
17476
17477fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17478 let tab_size = tab_size.get() as usize;
17479 let mut width = offset;
17480
17481 for ch in text.chars() {
17482 width += if ch == '\t' {
17483 tab_size - (width % tab_size)
17484 } else {
17485 1
17486 };
17487 }
17488
17489 width - offset
17490}
17491
17492#[cfg(test)]
17493mod tests {
17494 use super::*;
17495
17496 #[test]
17497 fn test_string_size_with_expanded_tabs() {
17498 let nz = |val| NonZeroU32::new(val).unwrap();
17499 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17500 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17501 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17502 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17503 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17504 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17505 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17506 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17507 }
17508}
17509
17510/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17511struct WordBreakingTokenizer<'a> {
17512 input: &'a str,
17513}
17514
17515impl<'a> WordBreakingTokenizer<'a> {
17516 fn new(input: &'a str) -> Self {
17517 Self { input }
17518 }
17519}
17520
17521fn is_char_ideographic(ch: char) -> bool {
17522 use unicode_script::Script::*;
17523 use unicode_script::UnicodeScript;
17524 matches!(ch.script(), Han | Tangut | Yi)
17525}
17526
17527fn is_grapheme_ideographic(text: &str) -> bool {
17528 text.chars().any(is_char_ideographic)
17529}
17530
17531fn is_grapheme_whitespace(text: &str) -> bool {
17532 text.chars().any(|x| x.is_whitespace())
17533}
17534
17535fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17536 text.chars().next().map_or(false, |ch| {
17537 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17538 })
17539}
17540
17541#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17542enum WordBreakToken<'a> {
17543 Word { token: &'a str, grapheme_len: usize },
17544 InlineWhitespace { token: &'a str, grapheme_len: usize },
17545 Newline,
17546}
17547
17548impl<'a> Iterator for WordBreakingTokenizer<'a> {
17549 /// Yields a span, the count of graphemes in the token, and whether it was
17550 /// whitespace. Note that it also breaks at word boundaries.
17551 type Item = WordBreakToken<'a>;
17552
17553 fn next(&mut self) -> Option<Self::Item> {
17554 use unicode_segmentation::UnicodeSegmentation;
17555 if self.input.is_empty() {
17556 return None;
17557 }
17558
17559 let mut iter = self.input.graphemes(true).peekable();
17560 let mut offset = 0;
17561 let mut grapheme_len = 0;
17562 if let Some(first_grapheme) = iter.next() {
17563 let is_newline = first_grapheme == "\n";
17564 let is_whitespace = is_grapheme_whitespace(first_grapheme);
17565 offset += first_grapheme.len();
17566 grapheme_len += 1;
17567 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17568 if let Some(grapheme) = iter.peek().copied() {
17569 if should_stay_with_preceding_ideograph(grapheme) {
17570 offset += grapheme.len();
17571 grapheme_len += 1;
17572 }
17573 }
17574 } else {
17575 let mut words = self.input[offset..].split_word_bound_indices().peekable();
17576 let mut next_word_bound = words.peek().copied();
17577 if next_word_bound.map_or(false, |(i, _)| i == 0) {
17578 next_word_bound = words.next();
17579 }
17580 while let Some(grapheme) = iter.peek().copied() {
17581 if next_word_bound.map_or(false, |(i, _)| i == offset) {
17582 break;
17583 };
17584 if is_grapheme_whitespace(grapheme) != is_whitespace
17585 || (grapheme == "\n") != is_newline
17586 {
17587 break;
17588 };
17589 offset += grapheme.len();
17590 grapheme_len += 1;
17591 iter.next();
17592 }
17593 }
17594 let token = &self.input[..offset];
17595 self.input = &self.input[offset..];
17596 if token == "\n" {
17597 Some(WordBreakToken::Newline)
17598 } else if is_whitespace {
17599 Some(WordBreakToken::InlineWhitespace {
17600 token,
17601 grapheme_len,
17602 })
17603 } else {
17604 Some(WordBreakToken::Word {
17605 token,
17606 grapheme_len,
17607 })
17608 }
17609 } else {
17610 None
17611 }
17612 }
17613}
17614
17615#[test]
17616fn test_word_breaking_tokenizer() {
17617 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17618 ("", &[]),
17619 (" ", &[whitespace(" ", 2)]),
17620 ("Ʒ", &[word("Ʒ", 1)]),
17621 ("Ǽ", &[word("Ǽ", 1)]),
17622 ("⋑", &[word("⋑", 1)]),
17623 ("⋑⋑", &[word("⋑⋑", 2)]),
17624 (
17625 "原理,进而",
17626 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
17627 ),
17628 (
17629 "hello world",
17630 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17631 ),
17632 (
17633 "hello, world",
17634 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17635 ),
17636 (
17637 " hello world",
17638 &[
17639 whitespace(" ", 2),
17640 word("hello", 5),
17641 whitespace(" ", 1),
17642 word("world", 5),
17643 ],
17644 ),
17645 (
17646 "这是什么 \n 钢笔",
17647 &[
17648 word("这", 1),
17649 word("是", 1),
17650 word("什", 1),
17651 word("么", 1),
17652 whitespace(" ", 1),
17653 newline(),
17654 whitespace(" ", 1),
17655 word("钢", 1),
17656 word("笔", 1),
17657 ],
17658 ),
17659 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
17660 ];
17661
17662 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17663 WordBreakToken::Word {
17664 token,
17665 grapheme_len,
17666 }
17667 }
17668
17669 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17670 WordBreakToken::InlineWhitespace {
17671 token,
17672 grapheme_len,
17673 }
17674 }
17675
17676 fn newline() -> WordBreakToken<'static> {
17677 WordBreakToken::Newline
17678 }
17679
17680 for (input, result) in tests {
17681 assert_eq!(
17682 WordBreakingTokenizer::new(input)
17683 .collect::<Vec<_>>()
17684 .as_slice(),
17685 *result,
17686 );
17687 }
17688}
17689
17690fn wrap_with_prefix(
17691 line_prefix: String,
17692 unwrapped_text: String,
17693 wrap_column: usize,
17694 tab_size: NonZeroU32,
17695 preserve_existing_whitespace: bool,
17696) -> String {
17697 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17698 let mut wrapped_text = String::new();
17699 let mut current_line = line_prefix.clone();
17700
17701 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17702 let mut current_line_len = line_prefix_len;
17703 let mut in_whitespace = false;
17704 for token in tokenizer {
17705 let have_preceding_whitespace = in_whitespace;
17706 match token {
17707 WordBreakToken::Word {
17708 token,
17709 grapheme_len,
17710 } => {
17711 in_whitespace = false;
17712 if current_line_len + grapheme_len > wrap_column
17713 && current_line_len != line_prefix_len
17714 {
17715 wrapped_text.push_str(current_line.trim_end());
17716 wrapped_text.push('\n');
17717 current_line.truncate(line_prefix.len());
17718 current_line_len = line_prefix_len;
17719 }
17720 current_line.push_str(token);
17721 current_line_len += grapheme_len;
17722 }
17723 WordBreakToken::InlineWhitespace {
17724 mut token,
17725 mut grapheme_len,
17726 } => {
17727 in_whitespace = true;
17728 if have_preceding_whitespace && !preserve_existing_whitespace {
17729 continue;
17730 }
17731 if !preserve_existing_whitespace {
17732 token = " ";
17733 grapheme_len = 1;
17734 }
17735 if current_line_len + grapheme_len > wrap_column {
17736 wrapped_text.push_str(current_line.trim_end());
17737 wrapped_text.push('\n');
17738 current_line.truncate(line_prefix.len());
17739 current_line_len = line_prefix_len;
17740 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17741 current_line.push_str(token);
17742 current_line_len += grapheme_len;
17743 }
17744 }
17745 WordBreakToken::Newline => {
17746 in_whitespace = true;
17747 if preserve_existing_whitespace {
17748 wrapped_text.push_str(current_line.trim_end());
17749 wrapped_text.push('\n');
17750 current_line.truncate(line_prefix.len());
17751 current_line_len = line_prefix_len;
17752 } else if have_preceding_whitespace {
17753 continue;
17754 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17755 {
17756 wrapped_text.push_str(current_line.trim_end());
17757 wrapped_text.push('\n');
17758 current_line.truncate(line_prefix.len());
17759 current_line_len = line_prefix_len;
17760 } else if current_line_len != line_prefix_len {
17761 current_line.push(' ');
17762 current_line_len += 1;
17763 }
17764 }
17765 }
17766 }
17767
17768 if !current_line.is_empty() {
17769 wrapped_text.push_str(¤t_line);
17770 }
17771 wrapped_text
17772}
17773
17774#[test]
17775fn test_wrap_with_prefix() {
17776 assert_eq!(
17777 wrap_with_prefix(
17778 "# ".to_string(),
17779 "abcdefg".to_string(),
17780 4,
17781 NonZeroU32::new(4).unwrap(),
17782 false,
17783 ),
17784 "# abcdefg"
17785 );
17786 assert_eq!(
17787 wrap_with_prefix(
17788 "".to_string(),
17789 "\thello world".to_string(),
17790 8,
17791 NonZeroU32::new(4).unwrap(),
17792 false,
17793 ),
17794 "hello\nworld"
17795 );
17796 assert_eq!(
17797 wrap_with_prefix(
17798 "// ".to_string(),
17799 "xx \nyy zz aa bb cc".to_string(),
17800 12,
17801 NonZeroU32::new(4).unwrap(),
17802 false,
17803 ),
17804 "// xx yy zz\n// aa bb cc"
17805 );
17806 assert_eq!(
17807 wrap_with_prefix(
17808 String::new(),
17809 "这是什么 \n 钢笔".to_string(),
17810 3,
17811 NonZeroU32::new(4).unwrap(),
17812 false,
17813 ),
17814 "这是什\n么 钢\n笔"
17815 );
17816}
17817
17818pub trait CollaborationHub {
17819 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17820 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17821 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17822}
17823
17824impl CollaborationHub for Entity<Project> {
17825 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17826 self.read(cx).collaborators()
17827 }
17828
17829 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17830 self.read(cx).user_store().read(cx).participant_indices()
17831 }
17832
17833 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17834 let this = self.read(cx);
17835 let user_ids = this.collaborators().values().map(|c| c.user_id);
17836 this.user_store().read_with(cx, |user_store, cx| {
17837 user_store.participant_names(user_ids, cx)
17838 })
17839 }
17840}
17841
17842pub trait SemanticsProvider {
17843 fn hover(
17844 &self,
17845 buffer: &Entity<Buffer>,
17846 position: text::Anchor,
17847 cx: &mut App,
17848 ) -> Option<Task<Vec<project::Hover>>>;
17849
17850 fn inlay_hints(
17851 &self,
17852 buffer_handle: Entity<Buffer>,
17853 range: Range<text::Anchor>,
17854 cx: &mut App,
17855 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17856
17857 fn resolve_inlay_hint(
17858 &self,
17859 hint: InlayHint,
17860 buffer_handle: Entity<Buffer>,
17861 server_id: LanguageServerId,
17862 cx: &mut App,
17863 ) -> Option<Task<anyhow::Result<InlayHint>>>;
17864
17865 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17866
17867 fn document_highlights(
17868 &self,
17869 buffer: &Entity<Buffer>,
17870 position: text::Anchor,
17871 cx: &mut App,
17872 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17873
17874 fn definitions(
17875 &self,
17876 buffer: &Entity<Buffer>,
17877 position: text::Anchor,
17878 kind: GotoDefinitionKind,
17879 cx: &mut App,
17880 ) -> Option<Task<Result<Vec<LocationLink>>>>;
17881
17882 fn range_for_rename(
17883 &self,
17884 buffer: &Entity<Buffer>,
17885 position: text::Anchor,
17886 cx: &mut App,
17887 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17888
17889 fn perform_rename(
17890 &self,
17891 buffer: &Entity<Buffer>,
17892 position: text::Anchor,
17893 new_name: String,
17894 cx: &mut App,
17895 ) -> Option<Task<Result<ProjectTransaction>>>;
17896}
17897
17898pub trait CompletionProvider {
17899 fn completions(
17900 &self,
17901 excerpt_id: ExcerptId,
17902 buffer: &Entity<Buffer>,
17903 buffer_position: text::Anchor,
17904 trigger: CompletionContext,
17905 window: &mut Window,
17906 cx: &mut Context<Editor>,
17907 ) -> Task<Result<Option<Vec<Completion>>>>;
17908
17909 fn resolve_completions(
17910 &self,
17911 buffer: Entity<Buffer>,
17912 completion_indices: Vec<usize>,
17913 completions: Rc<RefCell<Box<[Completion]>>>,
17914 cx: &mut Context<Editor>,
17915 ) -> Task<Result<bool>>;
17916
17917 fn apply_additional_edits_for_completion(
17918 &self,
17919 _buffer: Entity<Buffer>,
17920 _completions: Rc<RefCell<Box<[Completion]>>>,
17921 _completion_index: usize,
17922 _push_to_history: bool,
17923 _cx: &mut Context<Editor>,
17924 ) -> Task<Result<Option<language::Transaction>>> {
17925 Task::ready(Ok(None))
17926 }
17927
17928 fn is_completion_trigger(
17929 &self,
17930 buffer: &Entity<Buffer>,
17931 position: language::Anchor,
17932 text: &str,
17933 trigger_in_words: bool,
17934 cx: &mut Context<Editor>,
17935 ) -> bool;
17936
17937 fn sort_completions(&self) -> bool {
17938 true
17939 }
17940}
17941
17942pub trait CodeActionProvider {
17943 fn id(&self) -> Arc<str>;
17944
17945 fn code_actions(
17946 &self,
17947 buffer: &Entity<Buffer>,
17948 range: Range<text::Anchor>,
17949 window: &mut Window,
17950 cx: &mut App,
17951 ) -> Task<Result<Vec<CodeAction>>>;
17952
17953 fn apply_code_action(
17954 &self,
17955 buffer_handle: Entity<Buffer>,
17956 action: CodeAction,
17957 excerpt_id: ExcerptId,
17958 push_to_history: bool,
17959 window: &mut Window,
17960 cx: &mut App,
17961 ) -> Task<Result<ProjectTransaction>>;
17962}
17963
17964impl CodeActionProvider for Entity<Project> {
17965 fn id(&self) -> Arc<str> {
17966 "project".into()
17967 }
17968
17969 fn code_actions(
17970 &self,
17971 buffer: &Entity<Buffer>,
17972 range: Range<text::Anchor>,
17973 _window: &mut Window,
17974 cx: &mut App,
17975 ) -> Task<Result<Vec<CodeAction>>> {
17976 self.update(cx, |project, cx| {
17977 let code_lens = project.code_lens(buffer, range.clone(), cx);
17978 let code_actions = project.code_actions(buffer, range, None, cx);
17979 cx.background_spawn(async move {
17980 let (code_lens, code_actions) = join(code_lens, code_actions).await;
17981 Ok(code_lens
17982 .context("code lens fetch")?
17983 .into_iter()
17984 .chain(code_actions.context("code action fetch")?)
17985 .collect())
17986 })
17987 })
17988 }
17989
17990 fn apply_code_action(
17991 &self,
17992 buffer_handle: Entity<Buffer>,
17993 action: CodeAction,
17994 _excerpt_id: ExcerptId,
17995 push_to_history: bool,
17996 _window: &mut Window,
17997 cx: &mut App,
17998 ) -> Task<Result<ProjectTransaction>> {
17999 self.update(cx, |project, cx| {
18000 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18001 })
18002 }
18003}
18004
18005fn snippet_completions(
18006 project: &Project,
18007 buffer: &Entity<Buffer>,
18008 buffer_position: text::Anchor,
18009 cx: &mut App,
18010) -> Task<Result<Vec<Completion>>> {
18011 let language = buffer.read(cx).language_at(buffer_position);
18012 let language_name = language.as_ref().map(|language| language.lsp_id());
18013 let snippet_store = project.snippets().read(cx);
18014 let snippets = snippet_store.snippets_for(language_name, cx);
18015
18016 if snippets.is_empty() {
18017 return Task::ready(Ok(vec![]));
18018 }
18019 let snapshot = buffer.read(cx).text_snapshot();
18020 let chars: String = snapshot
18021 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18022 .collect();
18023
18024 let scope = language.map(|language| language.default_scope());
18025 let executor = cx.background_executor().clone();
18026
18027 cx.background_spawn(async move {
18028 let classifier = CharClassifier::new(scope).for_completion(true);
18029 let mut last_word = chars
18030 .chars()
18031 .take_while(|c| classifier.is_word(*c))
18032 .collect::<String>();
18033 last_word = last_word.chars().rev().collect();
18034
18035 if last_word.is_empty() {
18036 return Ok(vec![]);
18037 }
18038
18039 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18040 let to_lsp = |point: &text::Anchor| {
18041 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18042 point_to_lsp(end)
18043 };
18044 let lsp_end = to_lsp(&buffer_position);
18045
18046 let candidates = snippets
18047 .iter()
18048 .enumerate()
18049 .flat_map(|(ix, snippet)| {
18050 snippet
18051 .prefix
18052 .iter()
18053 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18054 })
18055 .collect::<Vec<StringMatchCandidate>>();
18056
18057 let mut matches = fuzzy::match_strings(
18058 &candidates,
18059 &last_word,
18060 last_word.chars().any(|c| c.is_uppercase()),
18061 100,
18062 &Default::default(),
18063 executor,
18064 )
18065 .await;
18066
18067 // Remove all candidates where the query's start does not match the start of any word in the candidate
18068 if let Some(query_start) = last_word.chars().next() {
18069 matches.retain(|string_match| {
18070 split_words(&string_match.string).any(|word| {
18071 // Check that the first codepoint of the word as lowercase matches the first
18072 // codepoint of the query as lowercase
18073 word.chars()
18074 .flat_map(|codepoint| codepoint.to_lowercase())
18075 .zip(query_start.to_lowercase())
18076 .all(|(word_cp, query_cp)| word_cp == query_cp)
18077 })
18078 });
18079 }
18080
18081 let matched_strings = matches
18082 .into_iter()
18083 .map(|m| m.string)
18084 .collect::<HashSet<_>>();
18085
18086 let result: Vec<Completion> = snippets
18087 .into_iter()
18088 .filter_map(|snippet| {
18089 let matching_prefix = snippet
18090 .prefix
18091 .iter()
18092 .find(|prefix| matched_strings.contains(*prefix))?;
18093 let start = as_offset - last_word.len();
18094 let start = snapshot.anchor_before(start);
18095 let range = start..buffer_position;
18096 let lsp_start = to_lsp(&start);
18097 let lsp_range = lsp::Range {
18098 start: lsp_start,
18099 end: lsp_end,
18100 };
18101 Some(Completion {
18102 old_range: range,
18103 new_text: snippet.body.clone(),
18104 source: CompletionSource::Lsp {
18105 server_id: LanguageServerId(usize::MAX),
18106 resolved: true,
18107 lsp_completion: Box::new(lsp::CompletionItem {
18108 label: snippet.prefix.first().unwrap().clone(),
18109 kind: Some(CompletionItemKind::SNIPPET),
18110 label_details: snippet.description.as_ref().map(|description| {
18111 lsp::CompletionItemLabelDetails {
18112 detail: Some(description.clone()),
18113 description: None,
18114 }
18115 }),
18116 insert_text_format: Some(InsertTextFormat::SNIPPET),
18117 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18118 lsp::InsertReplaceEdit {
18119 new_text: snippet.body.clone(),
18120 insert: lsp_range,
18121 replace: lsp_range,
18122 },
18123 )),
18124 filter_text: Some(snippet.body.clone()),
18125 sort_text: Some(char::MAX.to_string()),
18126 ..lsp::CompletionItem::default()
18127 }),
18128 lsp_defaults: None,
18129 },
18130 label: CodeLabel {
18131 text: matching_prefix.clone(),
18132 runs: Vec::new(),
18133 filter_range: 0..matching_prefix.len(),
18134 },
18135 icon_path: None,
18136 documentation: snippet
18137 .description
18138 .clone()
18139 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18140 confirm: None,
18141 })
18142 })
18143 .collect();
18144
18145 Ok(result)
18146 })
18147}
18148
18149impl CompletionProvider for Entity<Project> {
18150 fn completions(
18151 &self,
18152 _excerpt_id: ExcerptId,
18153 buffer: &Entity<Buffer>,
18154 buffer_position: text::Anchor,
18155 options: CompletionContext,
18156 _window: &mut Window,
18157 cx: &mut Context<Editor>,
18158 ) -> Task<Result<Option<Vec<Completion>>>> {
18159 self.update(cx, |project, cx| {
18160 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18161 let project_completions = project.completions(buffer, buffer_position, options, cx);
18162 cx.background_spawn(async move {
18163 let snippets_completions = snippets.await?;
18164 match project_completions.await? {
18165 Some(mut completions) => {
18166 completions.extend(snippets_completions);
18167 Ok(Some(completions))
18168 }
18169 None => {
18170 if snippets_completions.is_empty() {
18171 Ok(None)
18172 } else {
18173 Ok(Some(snippets_completions))
18174 }
18175 }
18176 }
18177 })
18178 })
18179 }
18180
18181 fn resolve_completions(
18182 &self,
18183 buffer: Entity<Buffer>,
18184 completion_indices: Vec<usize>,
18185 completions: Rc<RefCell<Box<[Completion]>>>,
18186 cx: &mut Context<Editor>,
18187 ) -> Task<Result<bool>> {
18188 self.update(cx, |project, cx| {
18189 project.lsp_store().update(cx, |lsp_store, cx| {
18190 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18191 })
18192 })
18193 }
18194
18195 fn apply_additional_edits_for_completion(
18196 &self,
18197 buffer: Entity<Buffer>,
18198 completions: Rc<RefCell<Box<[Completion]>>>,
18199 completion_index: usize,
18200 push_to_history: bool,
18201 cx: &mut Context<Editor>,
18202 ) -> Task<Result<Option<language::Transaction>>> {
18203 self.update(cx, |project, cx| {
18204 project.lsp_store().update(cx, |lsp_store, cx| {
18205 lsp_store.apply_additional_edits_for_completion(
18206 buffer,
18207 completions,
18208 completion_index,
18209 push_to_history,
18210 cx,
18211 )
18212 })
18213 })
18214 }
18215
18216 fn is_completion_trigger(
18217 &self,
18218 buffer: &Entity<Buffer>,
18219 position: language::Anchor,
18220 text: &str,
18221 trigger_in_words: bool,
18222 cx: &mut Context<Editor>,
18223 ) -> bool {
18224 let mut chars = text.chars();
18225 let char = if let Some(char) = chars.next() {
18226 char
18227 } else {
18228 return false;
18229 };
18230 if chars.next().is_some() {
18231 return false;
18232 }
18233
18234 let buffer = buffer.read(cx);
18235 let snapshot = buffer.snapshot();
18236 if !snapshot.settings_at(position, cx).show_completions_on_input {
18237 return false;
18238 }
18239 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18240 if trigger_in_words && classifier.is_word(char) {
18241 return true;
18242 }
18243
18244 buffer.completion_triggers().contains(text)
18245 }
18246}
18247
18248impl SemanticsProvider for Entity<Project> {
18249 fn hover(
18250 &self,
18251 buffer: &Entity<Buffer>,
18252 position: text::Anchor,
18253 cx: &mut App,
18254 ) -> Option<Task<Vec<project::Hover>>> {
18255 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18256 }
18257
18258 fn document_highlights(
18259 &self,
18260 buffer: &Entity<Buffer>,
18261 position: text::Anchor,
18262 cx: &mut App,
18263 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18264 Some(self.update(cx, |project, cx| {
18265 project.document_highlights(buffer, position, cx)
18266 }))
18267 }
18268
18269 fn definitions(
18270 &self,
18271 buffer: &Entity<Buffer>,
18272 position: text::Anchor,
18273 kind: GotoDefinitionKind,
18274 cx: &mut App,
18275 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18276 Some(self.update(cx, |project, cx| match kind {
18277 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18278 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18279 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18280 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18281 }))
18282 }
18283
18284 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18285 // TODO: make this work for remote projects
18286 self.update(cx, |this, cx| {
18287 buffer.update(cx, |buffer, cx| {
18288 this.any_language_server_supports_inlay_hints(buffer, cx)
18289 })
18290 })
18291 }
18292
18293 fn inlay_hints(
18294 &self,
18295 buffer_handle: Entity<Buffer>,
18296 range: Range<text::Anchor>,
18297 cx: &mut App,
18298 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18299 Some(self.update(cx, |project, cx| {
18300 project.inlay_hints(buffer_handle, range, cx)
18301 }))
18302 }
18303
18304 fn resolve_inlay_hint(
18305 &self,
18306 hint: InlayHint,
18307 buffer_handle: Entity<Buffer>,
18308 server_id: LanguageServerId,
18309 cx: &mut App,
18310 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18311 Some(self.update(cx, |project, cx| {
18312 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18313 }))
18314 }
18315
18316 fn range_for_rename(
18317 &self,
18318 buffer: &Entity<Buffer>,
18319 position: text::Anchor,
18320 cx: &mut App,
18321 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18322 Some(self.update(cx, |project, cx| {
18323 let buffer = buffer.clone();
18324 let task = project.prepare_rename(buffer.clone(), position, cx);
18325 cx.spawn(async move |_, cx| {
18326 Ok(match task.await? {
18327 PrepareRenameResponse::Success(range) => Some(range),
18328 PrepareRenameResponse::InvalidPosition => None,
18329 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18330 // Fallback on using TreeSitter info to determine identifier range
18331 buffer.update(cx, |buffer, _| {
18332 let snapshot = buffer.snapshot();
18333 let (range, kind) = snapshot.surrounding_word(position);
18334 if kind != Some(CharKind::Word) {
18335 return None;
18336 }
18337 Some(
18338 snapshot.anchor_before(range.start)
18339 ..snapshot.anchor_after(range.end),
18340 )
18341 })?
18342 }
18343 })
18344 })
18345 }))
18346 }
18347
18348 fn perform_rename(
18349 &self,
18350 buffer: &Entity<Buffer>,
18351 position: text::Anchor,
18352 new_name: String,
18353 cx: &mut App,
18354 ) -> Option<Task<Result<ProjectTransaction>>> {
18355 Some(self.update(cx, |project, cx| {
18356 project.perform_rename(buffer.clone(), position, new_name, cx)
18357 }))
18358 }
18359}
18360
18361fn inlay_hint_settings(
18362 location: Anchor,
18363 snapshot: &MultiBufferSnapshot,
18364 cx: &mut Context<Editor>,
18365) -> InlayHintSettings {
18366 let file = snapshot.file_at(location);
18367 let language = snapshot.language_at(location).map(|l| l.name());
18368 language_settings(language, file, cx).inlay_hints
18369}
18370
18371fn consume_contiguous_rows(
18372 contiguous_row_selections: &mut Vec<Selection<Point>>,
18373 selection: &Selection<Point>,
18374 display_map: &DisplaySnapshot,
18375 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18376) -> (MultiBufferRow, MultiBufferRow) {
18377 contiguous_row_selections.push(selection.clone());
18378 let start_row = MultiBufferRow(selection.start.row);
18379 let mut end_row = ending_row(selection, display_map);
18380
18381 while let Some(next_selection) = selections.peek() {
18382 if next_selection.start.row <= end_row.0 {
18383 end_row = ending_row(next_selection, display_map);
18384 contiguous_row_selections.push(selections.next().unwrap().clone());
18385 } else {
18386 break;
18387 }
18388 }
18389 (start_row, end_row)
18390}
18391
18392fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18393 if next_selection.end.column > 0 || next_selection.is_empty() {
18394 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18395 } else {
18396 MultiBufferRow(next_selection.end.row)
18397 }
18398}
18399
18400impl EditorSnapshot {
18401 pub fn remote_selections_in_range<'a>(
18402 &'a self,
18403 range: &'a Range<Anchor>,
18404 collaboration_hub: &dyn CollaborationHub,
18405 cx: &'a App,
18406 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18407 let participant_names = collaboration_hub.user_names(cx);
18408 let participant_indices = collaboration_hub.user_participant_indices(cx);
18409 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18410 let collaborators_by_replica_id = collaborators_by_peer_id
18411 .iter()
18412 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18413 .collect::<HashMap<_, _>>();
18414 self.buffer_snapshot
18415 .selections_in_range(range, false)
18416 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18417 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18418 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18419 let user_name = participant_names.get(&collaborator.user_id).cloned();
18420 Some(RemoteSelection {
18421 replica_id,
18422 selection,
18423 cursor_shape,
18424 line_mode,
18425 participant_index,
18426 peer_id: collaborator.peer_id,
18427 user_name,
18428 })
18429 })
18430 }
18431
18432 pub fn hunks_for_ranges(
18433 &self,
18434 ranges: impl IntoIterator<Item = Range<Point>>,
18435 ) -> Vec<MultiBufferDiffHunk> {
18436 let mut hunks = Vec::new();
18437 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18438 HashMap::default();
18439 for query_range in ranges {
18440 let query_rows =
18441 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18442 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18443 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18444 ) {
18445 // Include deleted hunks that are adjacent to the query range, because
18446 // otherwise they would be missed.
18447 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18448 if hunk.status().is_deleted() {
18449 intersects_range |= hunk.row_range.start == query_rows.end;
18450 intersects_range |= hunk.row_range.end == query_rows.start;
18451 }
18452 if intersects_range {
18453 if !processed_buffer_rows
18454 .entry(hunk.buffer_id)
18455 .or_default()
18456 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18457 {
18458 continue;
18459 }
18460 hunks.push(hunk);
18461 }
18462 }
18463 }
18464
18465 hunks
18466 }
18467
18468 fn display_diff_hunks_for_rows<'a>(
18469 &'a self,
18470 display_rows: Range<DisplayRow>,
18471 folded_buffers: &'a HashSet<BufferId>,
18472 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18473 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18474 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18475
18476 self.buffer_snapshot
18477 .diff_hunks_in_range(buffer_start..buffer_end)
18478 .filter_map(|hunk| {
18479 if folded_buffers.contains(&hunk.buffer_id) {
18480 return None;
18481 }
18482
18483 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18484 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18485
18486 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18487 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18488
18489 let display_hunk = if hunk_display_start.column() != 0 {
18490 DisplayDiffHunk::Folded {
18491 display_row: hunk_display_start.row(),
18492 }
18493 } else {
18494 let mut end_row = hunk_display_end.row();
18495 if hunk_display_end.column() > 0 {
18496 end_row.0 += 1;
18497 }
18498 let is_created_file = hunk.is_created_file();
18499 DisplayDiffHunk::Unfolded {
18500 status: hunk.status(),
18501 diff_base_byte_range: hunk.diff_base_byte_range,
18502 display_row_range: hunk_display_start.row()..end_row,
18503 multi_buffer_range: Anchor::range_in_buffer(
18504 hunk.excerpt_id,
18505 hunk.buffer_id,
18506 hunk.buffer_range,
18507 ),
18508 is_created_file,
18509 }
18510 };
18511
18512 Some(display_hunk)
18513 })
18514 }
18515
18516 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18517 self.display_snapshot.buffer_snapshot.language_at(position)
18518 }
18519
18520 pub fn is_focused(&self) -> bool {
18521 self.is_focused
18522 }
18523
18524 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18525 self.placeholder_text.as_ref()
18526 }
18527
18528 pub fn scroll_position(&self) -> gpui::Point<f32> {
18529 self.scroll_anchor.scroll_position(&self.display_snapshot)
18530 }
18531
18532 fn gutter_dimensions(
18533 &self,
18534 font_id: FontId,
18535 font_size: Pixels,
18536 max_line_number_width: Pixels,
18537 cx: &App,
18538 ) -> Option<GutterDimensions> {
18539 if !self.show_gutter {
18540 return None;
18541 }
18542
18543 let descent = cx.text_system().descent(font_id, font_size);
18544 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18545 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18546
18547 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18548 matches!(
18549 ProjectSettings::get_global(cx).git.git_gutter,
18550 Some(GitGutterSetting::TrackedFiles)
18551 )
18552 });
18553 let gutter_settings = EditorSettings::get_global(cx).gutter;
18554 let show_line_numbers = self
18555 .show_line_numbers
18556 .unwrap_or(gutter_settings.line_numbers);
18557 let line_gutter_width = if show_line_numbers {
18558 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18559 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18560 max_line_number_width.max(min_width_for_number_on_gutter)
18561 } else {
18562 0.0.into()
18563 };
18564
18565 let show_code_actions = self
18566 .show_code_actions
18567 .unwrap_or(gutter_settings.code_actions);
18568
18569 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18570 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18571
18572 let git_blame_entries_width =
18573 self.git_blame_gutter_max_author_length
18574 .map(|max_author_length| {
18575 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18576
18577 /// The number of characters to dedicate to gaps and margins.
18578 const SPACING_WIDTH: usize = 4;
18579
18580 let max_char_count = max_author_length
18581 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18582 + ::git::SHORT_SHA_LENGTH
18583 + MAX_RELATIVE_TIMESTAMP.len()
18584 + SPACING_WIDTH;
18585
18586 em_advance * max_char_count
18587 });
18588
18589 let is_singleton = self.buffer_snapshot.is_singleton();
18590
18591 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18592 left_padding += if !is_singleton {
18593 em_width * 4.0
18594 } else if show_code_actions || show_runnables || show_breakpoints {
18595 em_width * 3.0
18596 } else if show_git_gutter && show_line_numbers {
18597 em_width * 2.0
18598 } else if show_git_gutter || show_line_numbers {
18599 em_width
18600 } else {
18601 px(0.)
18602 };
18603
18604 let shows_folds = is_singleton && gutter_settings.folds;
18605
18606 let right_padding = if shows_folds && show_line_numbers {
18607 em_width * 4.0
18608 } else if shows_folds || (!is_singleton && show_line_numbers) {
18609 em_width * 3.0
18610 } else if show_line_numbers {
18611 em_width
18612 } else {
18613 px(0.)
18614 };
18615
18616 Some(GutterDimensions {
18617 left_padding,
18618 right_padding,
18619 width: line_gutter_width + left_padding + right_padding,
18620 margin: -descent,
18621 git_blame_entries_width,
18622 })
18623 }
18624
18625 pub fn render_crease_toggle(
18626 &self,
18627 buffer_row: MultiBufferRow,
18628 row_contains_cursor: bool,
18629 editor: Entity<Editor>,
18630 window: &mut Window,
18631 cx: &mut App,
18632 ) -> Option<AnyElement> {
18633 let folded = self.is_line_folded(buffer_row);
18634 let mut is_foldable = false;
18635
18636 if let Some(crease) = self
18637 .crease_snapshot
18638 .query_row(buffer_row, &self.buffer_snapshot)
18639 {
18640 is_foldable = true;
18641 match crease {
18642 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18643 if let Some(render_toggle) = render_toggle {
18644 let toggle_callback =
18645 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18646 if folded {
18647 editor.update(cx, |editor, cx| {
18648 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18649 });
18650 } else {
18651 editor.update(cx, |editor, cx| {
18652 editor.unfold_at(
18653 &crate::UnfoldAt { buffer_row },
18654 window,
18655 cx,
18656 )
18657 });
18658 }
18659 });
18660 return Some((render_toggle)(
18661 buffer_row,
18662 folded,
18663 toggle_callback,
18664 window,
18665 cx,
18666 ));
18667 }
18668 }
18669 }
18670 }
18671
18672 is_foldable |= self.starts_indent(buffer_row);
18673
18674 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18675 Some(
18676 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18677 .toggle_state(folded)
18678 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18679 if folded {
18680 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18681 } else {
18682 this.fold_at(&FoldAt { buffer_row }, window, cx);
18683 }
18684 }))
18685 .into_any_element(),
18686 )
18687 } else {
18688 None
18689 }
18690 }
18691
18692 pub fn render_crease_trailer(
18693 &self,
18694 buffer_row: MultiBufferRow,
18695 window: &mut Window,
18696 cx: &mut App,
18697 ) -> Option<AnyElement> {
18698 let folded = self.is_line_folded(buffer_row);
18699 if let Crease::Inline { render_trailer, .. } = self
18700 .crease_snapshot
18701 .query_row(buffer_row, &self.buffer_snapshot)?
18702 {
18703 let render_trailer = render_trailer.as_ref()?;
18704 Some(render_trailer(buffer_row, folded, window, cx))
18705 } else {
18706 None
18707 }
18708 }
18709}
18710
18711impl Deref for EditorSnapshot {
18712 type Target = DisplaySnapshot;
18713
18714 fn deref(&self) -> &Self::Target {
18715 &self.display_snapshot
18716 }
18717}
18718
18719#[derive(Clone, Debug, PartialEq, Eq)]
18720pub enum EditorEvent {
18721 InputIgnored {
18722 text: Arc<str>,
18723 },
18724 InputHandled {
18725 utf16_range_to_replace: Option<Range<isize>>,
18726 text: Arc<str>,
18727 },
18728 ExcerptsAdded {
18729 buffer: Entity<Buffer>,
18730 predecessor: ExcerptId,
18731 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18732 },
18733 ExcerptsRemoved {
18734 ids: Vec<ExcerptId>,
18735 },
18736 BufferFoldToggled {
18737 ids: Vec<ExcerptId>,
18738 folded: bool,
18739 },
18740 ExcerptsEdited {
18741 ids: Vec<ExcerptId>,
18742 },
18743 ExcerptsExpanded {
18744 ids: Vec<ExcerptId>,
18745 },
18746 BufferEdited,
18747 Edited {
18748 transaction_id: clock::Lamport,
18749 },
18750 Reparsed(BufferId),
18751 Focused,
18752 FocusedIn,
18753 Blurred,
18754 DirtyChanged,
18755 Saved,
18756 TitleChanged,
18757 DiffBaseChanged,
18758 SelectionsChanged {
18759 local: bool,
18760 },
18761 ScrollPositionChanged {
18762 local: bool,
18763 autoscroll: bool,
18764 },
18765 Closed,
18766 TransactionUndone {
18767 transaction_id: clock::Lamport,
18768 },
18769 TransactionBegun {
18770 transaction_id: clock::Lamport,
18771 },
18772 Reloaded,
18773 CursorShapeChanged,
18774 PushedToNavHistory {
18775 anchor: Anchor,
18776 is_deactivate: bool,
18777 },
18778}
18779
18780impl EventEmitter<EditorEvent> for Editor {}
18781
18782impl Focusable for Editor {
18783 fn focus_handle(&self, _cx: &App) -> FocusHandle {
18784 self.focus_handle.clone()
18785 }
18786}
18787
18788impl Render for Editor {
18789 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18790 let settings = ThemeSettings::get_global(cx);
18791
18792 let mut text_style = match self.mode {
18793 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18794 color: cx.theme().colors().editor_foreground,
18795 font_family: settings.ui_font.family.clone(),
18796 font_features: settings.ui_font.features.clone(),
18797 font_fallbacks: settings.ui_font.fallbacks.clone(),
18798 font_size: rems(0.875).into(),
18799 font_weight: settings.ui_font.weight,
18800 line_height: relative(settings.buffer_line_height.value()),
18801 ..Default::default()
18802 },
18803 EditorMode::Full => TextStyle {
18804 color: cx.theme().colors().editor_foreground,
18805 font_family: settings.buffer_font.family.clone(),
18806 font_features: settings.buffer_font.features.clone(),
18807 font_fallbacks: settings.buffer_font.fallbacks.clone(),
18808 font_size: settings.buffer_font_size(cx).into(),
18809 font_weight: settings.buffer_font.weight,
18810 line_height: relative(settings.buffer_line_height.value()),
18811 ..Default::default()
18812 },
18813 };
18814 if let Some(text_style_refinement) = &self.text_style_refinement {
18815 text_style.refine(text_style_refinement)
18816 }
18817
18818 let background = match self.mode {
18819 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18820 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18821 EditorMode::Full => cx.theme().colors().editor_background,
18822 };
18823
18824 EditorElement::new(
18825 &cx.entity(),
18826 EditorStyle {
18827 background,
18828 local_player: cx.theme().players().local(),
18829 text: text_style,
18830 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18831 syntax: cx.theme().syntax().clone(),
18832 status: cx.theme().status().clone(),
18833 inlay_hints_style: make_inlay_hints_style(cx),
18834 inline_completion_styles: make_suggestion_styles(cx),
18835 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18836 },
18837 )
18838 }
18839}
18840
18841impl EntityInputHandler for Editor {
18842 fn text_for_range(
18843 &mut self,
18844 range_utf16: Range<usize>,
18845 adjusted_range: &mut Option<Range<usize>>,
18846 _: &mut Window,
18847 cx: &mut Context<Self>,
18848 ) -> Option<String> {
18849 let snapshot = self.buffer.read(cx).read(cx);
18850 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18851 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18852 if (start.0..end.0) != range_utf16 {
18853 adjusted_range.replace(start.0..end.0);
18854 }
18855 Some(snapshot.text_for_range(start..end).collect())
18856 }
18857
18858 fn selected_text_range(
18859 &mut self,
18860 ignore_disabled_input: bool,
18861 _: &mut Window,
18862 cx: &mut Context<Self>,
18863 ) -> Option<UTF16Selection> {
18864 // Prevent the IME menu from appearing when holding down an alphabetic key
18865 // while input is disabled.
18866 if !ignore_disabled_input && !self.input_enabled {
18867 return None;
18868 }
18869
18870 let selection = self.selections.newest::<OffsetUtf16>(cx);
18871 let range = selection.range();
18872
18873 Some(UTF16Selection {
18874 range: range.start.0..range.end.0,
18875 reversed: selection.reversed,
18876 })
18877 }
18878
18879 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18880 let snapshot = self.buffer.read(cx).read(cx);
18881 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18882 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18883 }
18884
18885 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18886 self.clear_highlights::<InputComposition>(cx);
18887 self.ime_transaction.take();
18888 }
18889
18890 fn replace_text_in_range(
18891 &mut self,
18892 range_utf16: Option<Range<usize>>,
18893 text: &str,
18894 window: &mut Window,
18895 cx: &mut Context<Self>,
18896 ) {
18897 if !self.input_enabled {
18898 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18899 return;
18900 }
18901
18902 self.transact(window, cx, |this, window, cx| {
18903 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
18904 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18905 Some(this.selection_replacement_ranges(range_utf16, cx))
18906 } else {
18907 this.marked_text_ranges(cx)
18908 };
18909
18910 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
18911 let newest_selection_id = this.selections.newest_anchor().id;
18912 this.selections
18913 .all::<OffsetUtf16>(cx)
18914 .iter()
18915 .zip(ranges_to_replace.iter())
18916 .find_map(|(selection, range)| {
18917 if selection.id == newest_selection_id {
18918 Some(
18919 (range.start.0 as isize - selection.head().0 as isize)
18920 ..(range.end.0 as isize - selection.head().0 as isize),
18921 )
18922 } else {
18923 None
18924 }
18925 })
18926 });
18927
18928 cx.emit(EditorEvent::InputHandled {
18929 utf16_range_to_replace: range_to_replace,
18930 text: text.into(),
18931 });
18932
18933 if let Some(new_selected_ranges) = new_selected_ranges {
18934 this.change_selections(None, window, cx, |selections| {
18935 selections.select_ranges(new_selected_ranges)
18936 });
18937 this.backspace(&Default::default(), window, cx);
18938 }
18939
18940 this.handle_input(text, window, cx);
18941 });
18942
18943 if let Some(transaction) = self.ime_transaction {
18944 self.buffer.update(cx, |buffer, cx| {
18945 buffer.group_until_transaction(transaction, cx);
18946 });
18947 }
18948
18949 self.unmark_text(window, cx);
18950 }
18951
18952 fn replace_and_mark_text_in_range(
18953 &mut self,
18954 range_utf16: Option<Range<usize>>,
18955 text: &str,
18956 new_selected_range_utf16: Option<Range<usize>>,
18957 window: &mut Window,
18958 cx: &mut Context<Self>,
18959 ) {
18960 if !self.input_enabled {
18961 return;
18962 }
18963
18964 let transaction = self.transact(window, cx, |this, window, cx| {
18965 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18966 let snapshot = this.buffer.read(cx).read(cx);
18967 if let Some(relative_range_utf16) = range_utf16.as_ref() {
18968 for marked_range in &mut marked_ranges {
18969 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18970 marked_range.start.0 += relative_range_utf16.start;
18971 marked_range.start =
18972 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18973 marked_range.end =
18974 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18975 }
18976 }
18977 Some(marked_ranges)
18978 } else if let Some(range_utf16) = range_utf16 {
18979 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18980 Some(this.selection_replacement_ranges(range_utf16, cx))
18981 } else {
18982 None
18983 };
18984
18985 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18986 let newest_selection_id = this.selections.newest_anchor().id;
18987 this.selections
18988 .all::<OffsetUtf16>(cx)
18989 .iter()
18990 .zip(ranges_to_replace.iter())
18991 .find_map(|(selection, range)| {
18992 if selection.id == newest_selection_id {
18993 Some(
18994 (range.start.0 as isize - selection.head().0 as isize)
18995 ..(range.end.0 as isize - selection.head().0 as isize),
18996 )
18997 } else {
18998 None
18999 }
19000 })
19001 });
19002
19003 cx.emit(EditorEvent::InputHandled {
19004 utf16_range_to_replace: range_to_replace,
19005 text: text.into(),
19006 });
19007
19008 if let Some(ranges) = ranges_to_replace {
19009 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19010 }
19011
19012 let marked_ranges = {
19013 let snapshot = this.buffer.read(cx).read(cx);
19014 this.selections
19015 .disjoint_anchors()
19016 .iter()
19017 .map(|selection| {
19018 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19019 })
19020 .collect::<Vec<_>>()
19021 };
19022
19023 if text.is_empty() {
19024 this.unmark_text(window, cx);
19025 } else {
19026 this.highlight_text::<InputComposition>(
19027 marked_ranges.clone(),
19028 HighlightStyle {
19029 underline: Some(UnderlineStyle {
19030 thickness: px(1.),
19031 color: None,
19032 wavy: false,
19033 }),
19034 ..Default::default()
19035 },
19036 cx,
19037 );
19038 }
19039
19040 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19041 let use_autoclose = this.use_autoclose;
19042 let use_auto_surround = this.use_auto_surround;
19043 this.set_use_autoclose(false);
19044 this.set_use_auto_surround(false);
19045 this.handle_input(text, window, cx);
19046 this.set_use_autoclose(use_autoclose);
19047 this.set_use_auto_surround(use_auto_surround);
19048
19049 if let Some(new_selected_range) = new_selected_range_utf16 {
19050 let snapshot = this.buffer.read(cx).read(cx);
19051 let new_selected_ranges = marked_ranges
19052 .into_iter()
19053 .map(|marked_range| {
19054 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19055 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19056 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19057 snapshot.clip_offset_utf16(new_start, Bias::Left)
19058 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19059 })
19060 .collect::<Vec<_>>();
19061
19062 drop(snapshot);
19063 this.change_selections(None, window, cx, |selections| {
19064 selections.select_ranges(new_selected_ranges)
19065 });
19066 }
19067 });
19068
19069 self.ime_transaction = self.ime_transaction.or(transaction);
19070 if let Some(transaction) = self.ime_transaction {
19071 self.buffer.update(cx, |buffer, cx| {
19072 buffer.group_until_transaction(transaction, cx);
19073 });
19074 }
19075
19076 if self.text_highlights::<InputComposition>(cx).is_none() {
19077 self.ime_transaction.take();
19078 }
19079 }
19080
19081 fn bounds_for_range(
19082 &mut self,
19083 range_utf16: Range<usize>,
19084 element_bounds: gpui::Bounds<Pixels>,
19085 window: &mut Window,
19086 cx: &mut Context<Self>,
19087 ) -> Option<gpui::Bounds<Pixels>> {
19088 let text_layout_details = self.text_layout_details(window);
19089 let gpui::Size {
19090 width: em_width,
19091 height: line_height,
19092 } = self.character_size(window);
19093
19094 let snapshot = self.snapshot(window, cx);
19095 let scroll_position = snapshot.scroll_position();
19096 let scroll_left = scroll_position.x * em_width;
19097
19098 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19099 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19100 + self.gutter_dimensions.width
19101 + self.gutter_dimensions.margin;
19102 let y = line_height * (start.row().as_f32() - scroll_position.y);
19103
19104 Some(Bounds {
19105 origin: element_bounds.origin + point(x, y),
19106 size: size(em_width, line_height),
19107 })
19108 }
19109
19110 fn character_index_for_point(
19111 &mut self,
19112 point: gpui::Point<Pixels>,
19113 _window: &mut Window,
19114 _cx: &mut Context<Self>,
19115 ) -> Option<usize> {
19116 let position_map = self.last_position_map.as_ref()?;
19117 if !position_map.text_hitbox.contains(&point) {
19118 return None;
19119 }
19120 let display_point = position_map.point_for_position(point).previous_valid;
19121 let anchor = position_map
19122 .snapshot
19123 .display_point_to_anchor(display_point, Bias::Left);
19124 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19125 Some(utf16_offset.0)
19126 }
19127}
19128
19129trait SelectionExt {
19130 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19131 fn spanned_rows(
19132 &self,
19133 include_end_if_at_line_start: bool,
19134 map: &DisplaySnapshot,
19135 ) -> Range<MultiBufferRow>;
19136}
19137
19138impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19139 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19140 let start = self
19141 .start
19142 .to_point(&map.buffer_snapshot)
19143 .to_display_point(map);
19144 let end = self
19145 .end
19146 .to_point(&map.buffer_snapshot)
19147 .to_display_point(map);
19148 if self.reversed {
19149 end..start
19150 } else {
19151 start..end
19152 }
19153 }
19154
19155 fn spanned_rows(
19156 &self,
19157 include_end_if_at_line_start: bool,
19158 map: &DisplaySnapshot,
19159 ) -> Range<MultiBufferRow> {
19160 let start = self.start.to_point(&map.buffer_snapshot);
19161 let mut end = self.end.to_point(&map.buffer_snapshot);
19162 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19163 end.row -= 1;
19164 }
19165
19166 let buffer_start = map.prev_line_boundary(start).0;
19167 let buffer_end = map.next_line_boundary(end).0;
19168 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19169 }
19170}
19171
19172impl<T: InvalidationRegion> InvalidationStack<T> {
19173 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19174 where
19175 S: Clone + ToOffset,
19176 {
19177 while let Some(region) = self.last() {
19178 let all_selections_inside_invalidation_ranges =
19179 if selections.len() == region.ranges().len() {
19180 selections
19181 .iter()
19182 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19183 .all(|(selection, invalidation_range)| {
19184 let head = selection.head().to_offset(buffer);
19185 invalidation_range.start <= head && invalidation_range.end >= head
19186 })
19187 } else {
19188 false
19189 };
19190
19191 if all_selections_inside_invalidation_ranges {
19192 break;
19193 } else {
19194 self.pop();
19195 }
19196 }
19197 }
19198}
19199
19200impl<T> Default for InvalidationStack<T> {
19201 fn default() -> Self {
19202 Self(Default::default())
19203 }
19204}
19205
19206impl<T> Deref for InvalidationStack<T> {
19207 type Target = Vec<T>;
19208
19209 fn deref(&self) -> &Self::Target {
19210 &self.0
19211 }
19212}
19213
19214impl<T> DerefMut for InvalidationStack<T> {
19215 fn deref_mut(&mut self) -> &mut Self::Target {
19216 &mut self.0
19217 }
19218}
19219
19220impl InvalidationRegion for SnippetState {
19221 fn ranges(&self) -> &[Range<Anchor>] {
19222 &self.ranges[self.active_index]
19223 }
19224}
19225
19226pub fn diagnostic_block_renderer(
19227 diagnostic: Diagnostic,
19228 max_message_rows: Option<u8>,
19229 allow_closing: bool,
19230) -> RenderBlock {
19231 let (text_without_backticks, code_ranges) =
19232 highlight_diagnostic_message(&diagnostic, max_message_rows);
19233
19234 Arc::new(move |cx: &mut BlockContext| {
19235 let group_id: SharedString = cx.block_id.to_string().into();
19236
19237 let mut text_style = cx.window.text_style().clone();
19238 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19239 let theme_settings = ThemeSettings::get_global(cx);
19240 text_style.font_family = theme_settings.buffer_font.family.clone();
19241 text_style.font_style = theme_settings.buffer_font.style;
19242 text_style.font_features = theme_settings.buffer_font.features.clone();
19243 text_style.font_weight = theme_settings.buffer_font.weight;
19244
19245 let multi_line_diagnostic = diagnostic.message.contains('\n');
19246
19247 let buttons = |diagnostic: &Diagnostic| {
19248 if multi_line_diagnostic {
19249 v_flex()
19250 } else {
19251 h_flex()
19252 }
19253 .when(allow_closing, |div| {
19254 div.children(diagnostic.is_primary.then(|| {
19255 IconButton::new("close-block", IconName::XCircle)
19256 .icon_color(Color::Muted)
19257 .size(ButtonSize::Compact)
19258 .style(ButtonStyle::Transparent)
19259 .visible_on_hover(group_id.clone())
19260 .on_click(move |_click, window, cx| {
19261 window.dispatch_action(Box::new(Cancel), cx)
19262 })
19263 .tooltip(|window, cx| {
19264 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19265 })
19266 }))
19267 })
19268 .child(
19269 IconButton::new("copy-block", IconName::Copy)
19270 .icon_color(Color::Muted)
19271 .size(ButtonSize::Compact)
19272 .style(ButtonStyle::Transparent)
19273 .visible_on_hover(group_id.clone())
19274 .on_click({
19275 let message = diagnostic.message.clone();
19276 move |_click, _, cx| {
19277 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19278 }
19279 })
19280 .tooltip(Tooltip::text("Copy diagnostic message")),
19281 )
19282 };
19283
19284 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19285 AvailableSpace::min_size(),
19286 cx.window,
19287 cx.app,
19288 );
19289
19290 h_flex()
19291 .id(cx.block_id)
19292 .group(group_id.clone())
19293 .relative()
19294 .size_full()
19295 .block_mouse_down()
19296 .pl(cx.gutter_dimensions.width)
19297 .w(cx.max_width - cx.gutter_dimensions.full_width())
19298 .child(
19299 div()
19300 .flex()
19301 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19302 .flex_shrink(),
19303 )
19304 .child(buttons(&diagnostic))
19305 .child(div().flex().flex_shrink_0().child(
19306 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19307 &text_style,
19308 code_ranges.iter().map(|range| {
19309 (
19310 range.clone(),
19311 HighlightStyle {
19312 font_weight: Some(FontWeight::BOLD),
19313 ..Default::default()
19314 },
19315 )
19316 }),
19317 ),
19318 ))
19319 .into_any_element()
19320 })
19321}
19322
19323fn inline_completion_edit_text(
19324 current_snapshot: &BufferSnapshot,
19325 edits: &[(Range<Anchor>, String)],
19326 edit_preview: &EditPreview,
19327 include_deletions: bool,
19328 cx: &App,
19329) -> HighlightedText {
19330 let edits = edits
19331 .iter()
19332 .map(|(anchor, text)| {
19333 (
19334 anchor.start.text_anchor..anchor.end.text_anchor,
19335 text.clone(),
19336 )
19337 })
19338 .collect::<Vec<_>>();
19339
19340 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19341}
19342
19343pub fn highlight_diagnostic_message(
19344 diagnostic: &Diagnostic,
19345 mut max_message_rows: Option<u8>,
19346) -> (SharedString, Vec<Range<usize>>) {
19347 let mut text_without_backticks = String::new();
19348 let mut code_ranges = Vec::new();
19349
19350 if let Some(source) = &diagnostic.source {
19351 text_without_backticks.push_str(source);
19352 code_ranges.push(0..source.len());
19353 text_without_backticks.push_str(": ");
19354 }
19355
19356 let mut prev_offset = 0;
19357 let mut in_code_block = false;
19358 let has_row_limit = max_message_rows.is_some();
19359 let mut newline_indices = diagnostic
19360 .message
19361 .match_indices('\n')
19362 .filter(|_| has_row_limit)
19363 .map(|(ix, _)| ix)
19364 .fuse()
19365 .peekable();
19366
19367 for (quote_ix, _) in diagnostic
19368 .message
19369 .match_indices('`')
19370 .chain([(diagnostic.message.len(), "")])
19371 {
19372 let mut first_newline_ix = None;
19373 let mut last_newline_ix = None;
19374 while let Some(newline_ix) = newline_indices.peek() {
19375 if *newline_ix < quote_ix {
19376 if first_newline_ix.is_none() {
19377 first_newline_ix = Some(*newline_ix);
19378 }
19379 last_newline_ix = Some(*newline_ix);
19380
19381 if let Some(rows_left) = &mut max_message_rows {
19382 if *rows_left == 0 {
19383 break;
19384 } else {
19385 *rows_left -= 1;
19386 }
19387 }
19388 let _ = newline_indices.next();
19389 } else {
19390 break;
19391 }
19392 }
19393 let prev_len = text_without_backticks.len();
19394 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19395 text_without_backticks.push_str(new_text);
19396 if in_code_block {
19397 code_ranges.push(prev_len..text_without_backticks.len());
19398 }
19399 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19400 in_code_block = !in_code_block;
19401 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19402 text_without_backticks.push_str("...");
19403 break;
19404 }
19405 }
19406
19407 (text_without_backticks.into(), code_ranges)
19408}
19409
19410fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19411 match severity {
19412 DiagnosticSeverity::ERROR => colors.error,
19413 DiagnosticSeverity::WARNING => colors.warning,
19414 DiagnosticSeverity::INFORMATION => colors.info,
19415 DiagnosticSeverity::HINT => colors.info,
19416 _ => colors.ignored,
19417 }
19418}
19419
19420pub fn styled_runs_for_code_label<'a>(
19421 label: &'a CodeLabel,
19422 syntax_theme: &'a theme::SyntaxTheme,
19423) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19424 let fade_out = HighlightStyle {
19425 fade_out: Some(0.35),
19426 ..Default::default()
19427 };
19428
19429 let mut prev_end = label.filter_range.end;
19430 label
19431 .runs
19432 .iter()
19433 .enumerate()
19434 .flat_map(move |(ix, (range, highlight_id))| {
19435 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19436 style
19437 } else {
19438 return Default::default();
19439 };
19440 let mut muted_style = style;
19441 muted_style.highlight(fade_out);
19442
19443 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19444 if range.start >= label.filter_range.end {
19445 if range.start > prev_end {
19446 runs.push((prev_end..range.start, fade_out));
19447 }
19448 runs.push((range.clone(), muted_style));
19449 } else if range.end <= label.filter_range.end {
19450 runs.push((range.clone(), style));
19451 } else {
19452 runs.push((range.start..label.filter_range.end, style));
19453 runs.push((label.filter_range.end..range.end, muted_style));
19454 }
19455 prev_end = cmp::max(prev_end, range.end);
19456
19457 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19458 runs.push((prev_end..label.text.len(), fade_out));
19459 }
19460
19461 runs
19462 })
19463}
19464
19465pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19466 let mut prev_index = 0;
19467 let mut prev_codepoint: Option<char> = None;
19468 text.char_indices()
19469 .chain([(text.len(), '\0')])
19470 .filter_map(move |(index, codepoint)| {
19471 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19472 let is_boundary = index == text.len()
19473 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19474 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19475 if is_boundary {
19476 let chunk = &text[prev_index..index];
19477 prev_index = index;
19478 Some(chunk)
19479 } else {
19480 None
19481 }
19482 })
19483}
19484
19485pub trait RangeToAnchorExt: Sized {
19486 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19487
19488 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19489 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19490 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19491 }
19492}
19493
19494impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19495 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19496 let start_offset = self.start.to_offset(snapshot);
19497 let end_offset = self.end.to_offset(snapshot);
19498 if start_offset == end_offset {
19499 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19500 } else {
19501 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19502 }
19503 }
19504}
19505
19506pub trait RowExt {
19507 fn as_f32(&self) -> f32;
19508
19509 fn next_row(&self) -> Self;
19510
19511 fn previous_row(&self) -> Self;
19512
19513 fn minus(&self, other: Self) -> u32;
19514}
19515
19516impl RowExt for DisplayRow {
19517 fn as_f32(&self) -> f32 {
19518 self.0 as f32
19519 }
19520
19521 fn next_row(&self) -> Self {
19522 Self(self.0 + 1)
19523 }
19524
19525 fn previous_row(&self) -> Self {
19526 Self(self.0.saturating_sub(1))
19527 }
19528
19529 fn minus(&self, other: Self) -> u32 {
19530 self.0 - other.0
19531 }
19532}
19533
19534impl RowExt for MultiBufferRow {
19535 fn as_f32(&self) -> f32 {
19536 self.0 as f32
19537 }
19538
19539 fn next_row(&self) -> Self {
19540 Self(self.0 + 1)
19541 }
19542
19543 fn previous_row(&self) -> Self {
19544 Self(self.0.saturating_sub(1))
19545 }
19546
19547 fn minus(&self, other: Self) -> u32 {
19548 self.0 - other.0
19549 }
19550}
19551
19552trait RowRangeExt {
19553 type Row;
19554
19555 fn len(&self) -> usize;
19556
19557 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19558}
19559
19560impl RowRangeExt for Range<MultiBufferRow> {
19561 type Row = MultiBufferRow;
19562
19563 fn len(&self) -> usize {
19564 (self.end.0 - self.start.0) as usize
19565 }
19566
19567 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19568 (self.start.0..self.end.0).map(MultiBufferRow)
19569 }
19570}
19571
19572impl RowRangeExt for Range<DisplayRow> {
19573 type Row = DisplayRow;
19574
19575 fn len(&self) -> usize {
19576 (self.end.0 - self.start.0) as usize
19577 }
19578
19579 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19580 (self.start.0..self.end.0).map(DisplayRow)
19581 }
19582}
19583
19584/// If select range has more than one line, we
19585/// just point the cursor to range.start.
19586fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19587 if range.start.row == range.end.row {
19588 range
19589 } else {
19590 range.start..range.start
19591 }
19592}
19593pub struct KillRing(ClipboardItem);
19594impl Global for KillRing {}
19595
19596const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19597
19598struct BreakpointPromptEditor {
19599 pub(crate) prompt: Entity<Editor>,
19600 editor: WeakEntity<Editor>,
19601 breakpoint_anchor: Anchor,
19602 kind: BreakpointKind,
19603 block_ids: HashSet<CustomBlockId>,
19604 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19605 _subscriptions: Vec<Subscription>,
19606}
19607
19608impl BreakpointPromptEditor {
19609 const MAX_LINES: u8 = 4;
19610
19611 fn new(
19612 editor: WeakEntity<Editor>,
19613 breakpoint_anchor: Anchor,
19614 kind: BreakpointKind,
19615 window: &mut Window,
19616 cx: &mut Context<Self>,
19617 ) -> Self {
19618 let buffer = cx.new(|cx| {
19619 Buffer::local(
19620 kind.log_message()
19621 .map(|msg| msg.to_string())
19622 .unwrap_or_default(),
19623 cx,
19624 )
19625 });
19626 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19627
19628 let prompt = cx.new(|cx| {
19629 let mut prompt = Editor::new(
19630 EditorMode::AutoHeight {
19631 max_lines: Self::MAX_LINES as usize,
19632 },
19633 buffer,
19634 None,
19635 window,
19636 cx,
19637 );
19638 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19639 prompt.set_show_cursor_when_unfocused(false, cx);
19640 prompt.set_placeholder_text(
19641 "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19642 cx,
19643 );
19644
19645 prompt
19646 });
19647
19648 Self {
19649 prompt,
19650 editor,
19651 breakpoint_anchor,
19652 kind,
19653 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19654 block_ids: Default::default(),
19655 _subscriptions: vec![],
19656 }
19657 }
19658
19659 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19660 self.block_ids.extend(block_ids)
19661 }
19662
19663 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19664 if let Some(editor) = self.editor.upgrade() {
19665 let log_message = self
19666 .prompt
19667 .read(cx)
19668 .buffer
19669 .read(cx)
19670 .as_singleton()
19671 .expect("A multi buffer in breakpoint prompt isn't possible")
19672 .read(cx)
19673 .as_rope()
19674 .to_string();
19675
19676 editor.update(cx, |editor, cx| {
19677 editor.edit_breakpoint_at_anchor(
19678 self.breakpoint_anchor,
19679 self.kind.clone(),
19680 BreakpointEditAction::EditLogMessage(log_message.into()),
19681 cx,
19682 );
19683
19684 editor.remove_blocks(self.block_ids.clone(), None, cx);
19685 cx.focus_self(window);
19686 });
19687 }
19688 }
19689
19690 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19691 self.editor
19692 .update(cx, |editor, cx| {
19693 editor.remove_blocks(self.block_ids.clone(), None, cx);
19694 window.focus(&editor.focus_handle);
19695 })
19696 .log_err();
19697 }
19698
19699 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19700 let settings = ThemeSettings::get_global(cx);
19701 let text_style = TextStyle {
19702 color: if self.prompt.read(cx).read_only(cx) {
19703 cx.theme().colors().text_disabled
19704 } else {
19705 cx.theme().colors().text
19706 },
19707 font_family: settings.buffer_font.family.clone(),
19708 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19709 font_size: settings.buffer_font_size(cx).into(),
19710 font_weight: settings.buffer_font.weight,
19711 line_height: relative(settings.buffer_line_height.value()),
19712 ..Default::default()
19713 };
19714 EditorElement::new(
19715 &self.prompt,
19716 EditorStyle {
19717 background: cx.theme().colors().editor_background,
19718 local_player: cx.theme().players().local(),
19719 text: text_style,
19720 ..Default::default()
19721 },
19722 )
19723 }
19724}
19725
19726impl Render for BreakpointPromptEditor {
19727 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19728 let gutter_dimensions = *self.gutter_dimensions.lock();
19729 h_flex()
19730 .key_context("Editor")
19731 .bg(cx.theme().colors().editor_background)
19732 .border_y_1()
19733 .border_color(cx.theme().status().info_border)
19734 .size_full()
19735 .py(window.line_height() / 2.5)
19736 .on_action(cx.listener(Self::confirm))
19737 .on_action(cx.listener(Self::cancel))
19738 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19739 .child(div().flex_1().child(self.render_prompt_editor(cx)))
19740 }
19741}
19742
19743impl Focusable for BreakpointPromptEditor {
19744 fn focus_handle(&self, cx: &App) -> FocusHandle {
19745 self.prompt.focus_handle(cx)
19746 }
19747}
19748
19749fn all_edits_insertions_or_deletions(
19750 edits: &Vec<(Range<Anchor>, String)>,
19751 snapshot: &MultiBufferSnapshot,
19752) -> bool {
19753 let mut all_insertions = true;
19754 let mut all_deletions = true;
19755
19756 for (range, new_text) in edits.iter() {
19757 let range_is_empty = range.to_offset(&snapshot).is_empty();
19758 let text_is_empty = new_text.is_empty();
19759
19760 if range_is_empty != text_is_empty {
19761 if range_is_empty {
19762 all_deletions = false;
19763 } else {
19764 all_insertions = false;
19765 }
19766 } else {
19767 return false;
19768 }
19769
19770 if !all_insertions && !all_deletions {
19771 return false;
19772 }
19773 }
19774 all_insertions || all_deletions
19775}
19776
19777struct MissingEditPredictionKeybindingTooltip;
19778
19779impl Render for MissingEditPredictionKeybindingTooltip {
19780 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
19781 ui::tooltip_container(window, cx, |container, _, cx| {
19782 container
19783 .flex_shrink_0()
19784 .max_w_80()
19785 .min_h(rems_from_px(124.))
19786 .justify_between()
19787 .child(
19788 v_flex()
19789 .flex_1()
19790 .text_ui_sm(cx)
19791 .child(Label::new("Conflict with Accept Keybinding"))
19792 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19793 )
19794 .child(
19795 h_flex()
19796 .pb_1()
19797 .gap_1()
19798 .items_end()
19799 .w_full()
19800 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19801 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19802 }))
19803 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19804 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19805 })),
19806 )
19807 })
19808 }
19809}
19810
19811#[derive(Debug, Clone, Copy, PartialEq)]
19812pub struct LineHighlight {
19813 pub background: Background,
19814 pub border: Option<gpui::Hsla>,
19815}
19816
19817impl From<Hsla> for LineHighlight {
19818 fn from(hsla: Hsla) -> Self {
19819 Self {
19820 background: hsla.into(),
19821 border: None,
19822 }
19823 }
19824}
19825
19826impl From<Background> for LineHighlight {
19827 fn from(background: Background) -> Self {
19828 Self {
19829 background,
19830 border: None,
19831 }
19832 }
19833}