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.highlight_rows::<T>(
12648 start..end,
12649 highlight_color
12650 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12651 false,
12652 cx,
12653 );
12654 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
12655 }
12656
12657 pub fn go_to_definition(
12658 &mut self,
12659 _: &GoToDefinition,
12660 window: &mut Window,
12661 cx: &mut Context<Self>,
12662 ) -> Task<Result<Navigated>> {
12663 let definition =
12664 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12665 cx.spawn_in(window, async move |editor, cx| {
12666 if definition.await? == Navigated::Yes {
12667 return Ok(Navigated::Yes);
12668 }
12669 match editor.update_in(cx, |editor, window, cx| {
12670 editor.find_all_references(&FindAllReferences, window, cx)
12671 })? {
12672 Some(references) => references.await,
12673 None => Ok(Navigated::No),
12674 }
12675 })
12676 }
12677
12678 pub fn go_to_declaration(
12679 &mut self,
12680 _: &GoToDeclaration,
12681 window: &mut Window,
12682 cx: &mut Context<Self>,
12683 ) -> Task<Result<Navigated>> {
12684 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12685 }
12686
12687 pub fn go_to_declaration_split(
12688 &mut self,
12689 _: &GoToDeclaration,
12690 window: &mut Window,
12691 cx: &mut Context<Self>,
12692 ) -> Task<Result<Navigated>> {
12693 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12694 }
12695
12696 pub fn go_to_implementation(
12697 &mut self,
12698 _: &GoToImplementation,
12699 window: &mut Window,
12700 cx: &mut Context<Self>,
12701 ) -> Task<Result<Navigated>> {
12702 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12703 }
12704
12705 pub fn go_to_implementation_split(
12706 &mut self,
12707 _: &GoToImplementationSplit,
12708 window: &mut Window,
12709 cx: &mut Context<Self>,
12710 ) -> Task<Result<Navigated>> {
12711 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12712 }
12713
12714 pub fn go_to_type_definition(
12715 &mut self,
12716 _: &GoToTypeDefinition,
12717 window: &mut Window,
12718 cx: &mut Context<Self>,
12719 ) -> Task<Result<Navigated>> {
12720 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12721 }
12722
12723 pub fn go_to_definition_split(
12724 &mut self,
12725 _: &GoToDefinitionSplit,
12726 window: &mut Window,
12727 cx: &mut Context<Self>,
12728 ) -> Task<Result<Navigated>> {
12729 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12730 }
12731
12732 pub fn go_to_type_definition_split(
12733 &mut self,
12734 _: &GoToTypeDefinitionSplit,
12735 window: &mut Window,
12736 cx: &mut Context<Self>,
12737 ) -> Task<Result<Navigated>> {
12738 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12739 }
12740
12741 fn go_to_definition_of_kind(
12742 &mut self,
12743 kind: GotoDefinitionKind,
12744 split: bool,
12745 window: &mut Window,
12746 cx: &mut Context<Self>,
12747 ) -> Task<Result<Navigated>> {
12748 let Some(provider) = self.semantics_provider.clone() else {
12749 return Task::ready(Ok(Navigated::No));
12750 };
12751 let head = self.selections.newest::<usize>(cx).head();
12752 let buffer = self.buffer.read(cx);
12753 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12754 text_anchor
12755 } else {
12756 return Task::ready(Ok(Navigated::No));
12757 };
12758
12759 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12760 return Task::ready(Ok(Navigated::No));
12761 };
12762
12763 cx.spawn_in(window, async move |editor, cx| {
12764 let definitions = definitions.await?;
12765 let navigated = editor
12766 .update_in(cx, |editor, window, cx| {
12767 editor.navigate_to_hover_links(
12768 Some(kind),
12769 definitions
12770 .into_iter()
12771 .filter(|location| {
12772 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12773 })
12774 .map(HoverLink::Text)
12775 .collect::<Vec<_>>(),
12776 split,
12777 window,
12778 cx,
12779 )
12780 })?
12781 .await?;
12782 anyhow::Ok(navigated)
12783 })
12784 }
12785
12786 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12787 let selection = self.selections.newest_anchor();
12788 let head = selection.head();
12789 let tail = selection.tail();
12790
12791 let Some((buffer, start_position)) =
12792 self.buffer.read(cx).text_anchor_for_position(head, cx)
12793 else {
12794 return;
12795 };
12796
12797 let end_position = if head != tail {
12798 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12799 return;
12800 };
12801 Some(pos)
12802 } else {
12803 None
12804 };
12805
12806 let url_finder = cx.spawn_in(window, async move |editor, cx| {
12807 let url = if let Some(end_pos) = end_position {
12808 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12809 } else {
12810 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12811 };
12812
12813 if let Some(url) = url {
12814 editor.update(cx, |_, cx| {
12815 cx.open_url(&url);
12816 })
12817 } else {
12818 Ok(())
12819 }
12820 });
12821
12822 url_finder.detach();
12823 }
12824
12825 pub fn open_selected_filename(
12826 &mut self,
12827 _: &OpenSelectedFilename,
12828 window: &mut Window,
12829 cx: &mut Context<Self>,
12830 ) {
12831 let Some(workspace) = self.workspace() else {
12832 return;
12833 };
12834
12835 let position = self.selections.newest_anchor().head();
12836
12837 let Some((buffer, buffer_position)) =
12838 self.buffer.read(cx).text_anchor_for_position(position, cx)
12839 else {
12840 return;
12841 };
12842
12843 let project = self.project.clone();
12844
12845 cx.spawn_in(window, async move |_, cx| {
12846 let result = find_file(&buffer, project, buffer_position, cx).await;
12847
12848 if let Some((_, path)) = result {
12849 workspace
12850 .update_in(cx, |workspace, window, cx| {
12851 workspace.open_resolved_path(path, window, cx)
12852 })?
12853 .await?;
12854 }
12855 anyhow::Ok(())
12856 })
12857 .detach();
12858 }
12859
12860 pub(crate) fn navigate_to_hover_links(
12861 &mut self,
12862 kind: Option<GotoDefinitionKind>,
12863 mut definitions: Vec<HoverLink>,
12864 split: bool,
12865 window: &mut Window,
12866 cx: &mut Context<Editor>,
12867 ) -> Task<Result<Navigated>> {
12868 // If there is one definition, just open it directly
12869 if definitions.len() == 1 {
12870 let definition = definitions.pop().unwrap();
12871
12872 enum TargetTaskResult {
12873 Location(Option<Location>),
12874 AlreadyNavigated,
12875 }
12876
12877 let target_task = match definition {
12878 HoverLink::Text(link) => {
12879 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12880 }
12881 HoverLink::InlayHint(lsp_location, server_id) => {
12882 let computation =
12883 self.compute_target_location(lsp_location, server_id, window, cx);
12884 cx.background_spawn(async move {
12885 let location = computation.await?;
12886 Ok(TargetTaskResult::Location(location))
12887 })
12888 }
12889 HoverLink::Url(url) => {
12890 cx.open_url(&url);
12891 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12892 }
12893 HoverLink::File(path) => {
12894 if let Some(workspace) = self.workspace() {
12895 cx.spawn_in(window, async move |_, cx| {
12896 workspace
12897 .update_in(cx, |workspace, window, cx| {
12898 workspace.open_resolved_path(path, window, cx)
12899 })?
12900 .await
12901 .map(|_| TargetTaskResult::AlreadyNavigated)
12902 })
12903 } else {
12904 Task::ready(Ok(TargetTaskResult::Location(None)))
12905 }
12906 }
12907 };
12908 cx.spawn_in(window, async move |editor, cx| {
12909 let target = match target_task.await.context("target resolution task")? {
12910 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12911 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12912 TargetTaskResult::Location(Some(target)) => target,
12913 };
12914
12915 editor.update_in(cx, |editor, window, cx| {
12916 let Some(workspace) = editor.workspace() else {
12917 return Navigated::No;
12918 };
12919 let pane = workspace.read(cx).active_pane().clone();
12920
12921 let range = target.range.to_point(target.buffer.read(cx));
12922 let range = editor.range_for_match(&range);
12923 let range = collapse_multiline_range(range);
12924
12925 if !split
12926 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12927 {
12928 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12929 } else {
12930 window.defer(cx, move |window, cx| {
12931 let target_editor: Entity<Self> =
12932 workspace.update(cx, |workspace, cx| {
12933 let pane = if split {
12934 workspace.adjacent_pane(window, cx)
12935 } else {
12936 workspace.active_pane().clone()
12937 };
12938
12939 workspace.open_project_item(
12940 pane,
12941 target.buffer.clone(),
12942 true,
12943 true,
12944 window,
12945 cx,
12946 )
12947 });
12948 target_editor.update(cx, |target_editor, cx| {
12949 // When selecting a definition in a different buffer, disable the nav history
12950 // to avoid creating a history entry at the previous cursor location.
12951 pane.update(cx, |pane, _| pane.disable_history());
12952 target_editor.go_to_singleton_buffer_range(range, window, cx);
12953 pane.update(cx, |pane, _| pane.enable_history());
12954 });
12955 });
12956 }
12957 Navigated::Yes
12958 })
12959 })
12960 } else if !definitions.is_empty() {
12961 cx.spawn_in(window, async move |editor, cx| {
12962 let (title, location_tasks, workspace) = editor
12963 .update_in(cx, |editor, window, cx| {
12964 let tab_kind = match kind {
12965 Some(GotoDefinitionKind::Implementation) => "Implementations",
12966 _ => "Definitions",
12967 };
12968 let title = definitions
12969 .iter()
12970 .find_map(|definition| match definition {
12971 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12972 let buffer = origin.buffer.read(cx);
12973 format!(
12974 "{} for {}",
12975 tab_kind,
12976 buffer
12977 .text_for_range(origin.range.clone())
12978 .collect::<String>()
12979 )
12980 }),
12981 HoverLink::InlayHint(_, _) => None,
12982 HoverLink::Url(_) => None,
12983 HoverLink::File(_) => None,
12984 })
12985 .unwrap_or(tab_kind.to_string());
12986 let location_tasks = definitions
12987 .into_iter()
12988 .map(|definition| match definition {
12989 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12990 HoverLink::InlayHint(lsp_location, server_id) => editor
12991 .compute_target_location(lsp_location, server_id, window, cx),
12992 HoverLink::Url(_) => Task::ready(Ok(None)),
12993 HoverLink::File(_) => Task::ready(Ok(None)),
12994 })
12995 .collect::<Vec<_>>();
12996 (title, location_tasks, editor.workspace().clone())
12997 })
12998 .context("location tasks preparation")?;
12999
13000 let locations = future::join_all(location_tasks)
13001 .await
13002 .into_iter()
13003 .filter_map(|location| location.transpose())
13004 .collect::<Result<_>>()
13005 .context("location tasks")?;
13006
13007 let Some(workspace) = workspace else {
13008 return Ok(Navigated::No);
13009 };
13010 let opened = workspace
13011 .update_in(cx, |workspace, window, cx| {
13012 Self::open_locations_in_multibuffer(
13013 workspace,
13014 locations,
13015 title,
13016 split,
13017 MultibufferSelectionMode::First,
13018 window,
13019 cx,
13020 )
13021 })
13022 .ok();
13023
13024 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13025 })
13026 } else {
13027 Task::ready(Ok(Navigated::No))
13028 }
13029 }
13030
13031 fn compute_target_location(
13032 &self,
13033 lsp_location: lsp::Location,
13034 server_id: LanguageServerId,
13035 window: &mut Window,
13036 cx: &mut Context<Self>,
13037 ) -> Task<anyhow::Result<Option<Location>>> {
13038 let Some(project) = self.project.clone() else {
13039 return Task::ready(Ok(None));
13040 };
13041
13042 cx.spawn_in(window, async move |editor, cx| {
13043 let location_task = editor.update(cx, |_, cx| {
13044 project.update(cx, |project, cx| {
13045 let language_server_name = project
13046 .language_server_statuses(cx)
13047 .find(|(id, _)| server_id == *id)
13048 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13049 language_server_name.map(|language_server_name| {
13050 project.open_local_buffer_via_lsp(
13051 lsp_location.uri.clone(),
13052 server_id,
13053 language_server_name,
13054 cx,
13055 )
13056 })
13057 })
13058 })?;
13059 let location = match location_task {
13060 Some(task) => Some({
13061 let target_buffer_handle = task.await.context("open local buffer")?;
13062 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13063 let target_start = target_buffer
13064 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13065 let target_end = target_buffer
13066 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13067 target_buffer.anchor_after(target_start)
13068 ..target_buffer.anchor_before(target_end)
13069 })?;
13070 Location {
13071 buffer: target_buffer_handle,
13072 range,
13073 }
13074 }),
13075 None => None,
13076 };
13077 Ok(location)
13078 })
13079 }
13080
13081 pub fn find_all_references(
13082 &mut self,
13083 _: &FindAllReferences,
13084 window: &mut Window,
13085 cx: &mut Context<Self>,
13086 ) -> Option<Task<Result<Navigated>>> {
13087 let selection = self.selections.newest::<usize>(cx);
13088 let multi_buffer = self.buffer.read(cx);
13089 let head = selection.head();
13090
13091 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13092 let head_anchor = multi_buffer_snapshot.anchor_at(
13093 head,
13094 if head < selection.tail() {
13095 Bias::Right
13096 } else {
13097 Bias::Left
13098 },
13099 );
13100
13101 match self
13102 .find_all_references_task_sources
13103 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13104 {
13105 Ok(_) => {
13106 log::info!(
13107 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13108 );
13109 return None;
13110 }
13111 Err(i) => {
13112 self.find_all_references_task_sources.insert(i, head_anchor);
13113 }
13114 }
13115
13116 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13117 let workspace = self.workspace()?;
13118 let project = workspace.read(cx).project().clone();
13119 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13120 Some(cx.spawn_in(window, async move |editor, cx| {
13121 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13122 if let Ok(i) = editor
13123 .find_all_references_task_sources
13124 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13125 {
13126 editor.find_all_references_task_sources.remove(i);
13127 }
13128 });
13129
13130 let locations = references.await?;
13131 if locations.is_empty() {
13132 return anyhow::Ok(Navigated::No);
13133 }
13134
13135 workspace.update_in(cx, |workspace, window, cx| {
13136 let title = locations
13137 .first()
13138 .as_ref()
13139 .map(|location| {
13140 let buffer = location.buffer.read(cx);
13141 format!(
13142 "References to `{}`",
13143 buffer
13144 .text_for_range(location.range.clone())
13145 .collect::<String>()
13146 )
13147 })
13148 .unwrap();
13149 Self::open_locations_in_multibuffer(
13150 workspace,
13151 locations,
13152 title,
13153 false,
13154 MultibufferSelectionMode::First,
13155 window,
13156 cx,
13157 );
13158 Navigated::Yes
13159 })
13160 }))
13161 }
13162
13163 /// Opens a multibuffer with the given project locations in it
13164 pub fn open_locations_in_multibuffer(
13165 workspace: &mut Workspace,
13166 mut locations: Vec<Location>,
13167 title: String,
13168 split: bool,
13169 multibuffer_selection_mode: MultibufferSelectionMode,
13170 window: &mut Window,
13171 cx: &mut Context<Workspace>,
13172 ) {
13173 // If there are multiple definitions, open them in a multibuffer
13174 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13175 let mut locations = locations.into_iter().peekable();
13176 let mut ranges = Vec::new();
13177 let capability = workspace.project().read(cx).capability();
13178
13179 let excerpt_buffer = cx.new(|cx| {
13180 let mut multibuffer = MultiBuffer::new(capability);
13181 while let Some(location) = locations.next() {
13182 let buffer = location.buffer.read(cx);
13183 let mut ranges_for_buffer = Vec::new();
13184 let range = location.range.to_offset(buffer);
13185 ranges_for_buffer.push(range.clone());
13186
13187 while let Some(next_location) = locations.peek() {
13188 if next_location.buffer == location.buffer {
13189 ranges_for_buffer.push(next_location.range.to_offset(buffer));
13190 locations.next();
13191 } else {
13192 break;
13193 }
13194 }
13195
13196 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13197 ranges.extend(multibuffer.push_excerpts_with_context_lines(
13198 location.buffer.clone(),
13199 ranges_for_buffer,
13200 DEFAULT_MULTIBUFFER_CONTEXT,
13201 cx,
13202 ))
13203 }
13204
13205 multibuffer.with_title(title)
13206 });
13207
13208 let editor = cx.new(|cx| {
13209 Editor::for_multibuffer(
13210 excerpt_buffer,
13211 Some(workspace.project().clone()),
13212 window,
13213 cx,
13214 )
13215 });
13216 editor.update(cx, |editor, cx| {
13217 match multibuffer_selection_mode {
13218 MultibufferSelectionMode::First => {
13219 if let Some(first_range) = ranges.first() {
13220 editor.change_selections(None, window, cx, |selections| {
13221 selections.clear_disjoint();
13222 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13223 });
13224 }
13225 editor.highlight_background::<Self>(
13226 &ranges,
13227 |theme| theme.editor_highlighted_line_background,
13228 cx,
13229 );
13230 }
13231 MultibufferSelectionMode::All => {
13232 editor.change_selections(None, window, cx, |selections| {
13233 selections.clear_disjoint();
13234 selections.select_anchor_ranges(ranges);
13235 });
13236 }
13237 }
13238 editor.register_buffers_with_language_servers(cx);
13239 });
13240
13241 let item = Box::new(editor);
13242 let item_id = item.item_id();
13243
13244 if split {
13245 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13246 } else {
13247 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13248 let (preview_item_id, preview_item_idx) =
13249 workspace.active_pane().update(cx, |pane, _| {
13250 (pane.preview_item_id(), pane.preview_item_idx())
13251 });
13252
13253 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13254
13255 if let Some(preview_item_id) = preview_item_id {
13256 workspace.active_pane().update(cx, |pane, cx| {
13257 pane.remove_item(preview_item_id, false, false, window, cx);
13258 });
13259 }
13260 } else {
13261 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13262 }
13263 }
13264 workspace.active_pane().update(cx, |pane, cx| {
13265 pane.set_preview_item_id(Some(item_id), cx);
13266 });
13267 }
13268
13269 pub fn rename(
13270 &mut self,
13271 _: &Rename,
13272 window: &mut Window,
13273 cx: &mut Context<Self>,
13274 ) -> Option<Task<Result<()>>> {
13275 use language::ToOffset as _;
13276
13277 let provider = self.semantics_provider.clone()?;
13278 let selection = self.selections.newest_anchor().clone();
13279 let (cursor_buffer, cursor_buffer_position) = self
13280 .buffer
13281 .read(cx)
13282 .text_anchor_for_position(selection.head(), cx)?;
13283 let (tail_buffer, cursor_buffer_position_end) = self
13284 .buffer
13285 .read(cx)
13286 .text_anchor_for_position(selection.tail(), cx)?;
13287 if tail_buffer != cursor_buffer {
13288 return None;
13289 }
13290
13291 let snapshot = cursor_buffer.read(cx).snapshot();
13292 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13293 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13294 let prepare_rename = provider
13295 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13296 .unwrap_or_else(|| Task::ready(Ok(None)));
13297 drop(snapshot);
13298
13299 Some(cx.spawn_in(window, async move |this, cx| {
13300 let rename_range = if let Some(range) = prepare_rename.await? {
13301 Some(range)
13302 } else {
13303 this.update(cx, |this, cx| {
13304 let buffer = this.buffer.read(cx).snapshot(cx);
13305 let mut buffer_highlights = this
13306 .document_highlights_for_position(selection.head(), &buffer)
13307 .filter(|highlight| {
13308 highlight.start.excerpt_id == selection.head().excerpt_id
13309 && highlight.end.excerpt_id == selection.head().excerpt_id
13310 });
13311 buffer_highlights
13312 .next()
13313 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13314 })?
13315 };
13316 if let Some(rename_range) = rename_range {
13317 this.update_in(cx, |this, window, cx| {
13318 let snapshot = cursor_buffer.read(cx).snapshot();
13319 let rename_buffer_range = rename_range.to_offset(&snapshot);
13320 let cursor_offset_in_rename_range =
13321 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13322 let cursor_offset_in_rename_range_end =
13323 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13324
13325 this.take_rename(false, window, cx);
13326 let buffer = this.buffer.read(cx).read(cx);
13327 let cursor_offset = selection.head().to_offset(&buffer);
13328 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13329 let rename_end = rename_start + rename_buffer_range.len();
13330 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13331 let mut old_highlight_id = None;
13332 let old_name: Arc<str> = buffer
13333 .chunks(rename_start..rename_end, true)
13334 .map(|chunk| {
13335 if old_highlight_id.is_none() {
13336 old_highlight_id = chunk.syntax_highlight_id;
13337 }
13338 chunk.text
13339 })
13340 .collect::<String>()
13341 .into();
13342
13343 drop(buffer);
13344
13345 // Position the selection in the rename editor so that it matches the current selection.
13346 this.show_local_selections = false;
13347 let rename_editor = cx.new(|cx| {
13348 let mut editor = Editor::single_line(window, cx);
13349 editor.buffer.update(cx, |buffer, cx| {
13350 buffer.edit([(0..0, old_name.clone())], None, cx)
13351 });
13352 let rename_selection_range = match cursor_offset_in_rename_range
13353 .cmp(&cursor_offset_in_rename_range_end)
13354 {
13355 Ordering::Equal => {
13356 editor.select_all(&SelectAll, window, cx);
13357 return editor;
13358 }
13359 Ordering::Less => {
13360 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13361 }
13362 Ordering::Greater => {
13363 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13364 }
13365 };
13366 if rename_selection_range.end > old_name.len() {
13367 editor.select_all(&SelectAll, window, cx);
13368 } else {
13369 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13370 s.select_ranges([rename_selection_range]);
13371 });
13372 }
13373 editor
13374 });
13375 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13376 if e == &EditorEvent::Focused {
13377 cx.emit(EditorEvent::FocusedIn)
13378 }
13379 })
13380 .detach();
13381
13382 let write_highlights =
13383 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13384 let read_highlights =
13385 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13386 let ranges = write_highlights
13387 .iter()
13388 .flat_map(|(_, ranges)| ranges.iter())
13389 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13390 .cloned()
13391 .collect();
13392
13393 this.highlight_text::<Rename>(
13394 ranges,
13395 HighlightStyle {
13396 fade_out: Some(0.6),
13397 ..Default::default()
13398 },
13399 cx,
13400 );
13401 let rename_focus_handle = rename_editor.focus_handle(cx);
13402 window.focus(&rename_focus_handle);
13403 let block_id = this.insert_blocks(
13404 [BlockProperties {
13405 style: BlockStyle::Flex,
13406 placement: BlockPlacement::Below(range.start),
13407 height: 1,
13408 render: Arc::new({
13409 let rename_editor = rename_editor.clone();
13410 move |cx: &mut BlockContext| {
13411 let mut text_style = cx.editor_style.text.clone();
13412 if let Some(highlight_style) = old_highlight_id
13413 .and_then(|h| h.style(&cx.editor_style.syntax))
13414 {
13415 text_style = text_style.highlight(highlight_style);
13416 }
13417 div()
13418 .block_mouse_down()
13419 .pl(cx.anchor_x)
13420 .child(EditorElement::new(
13421 &rename_editor,
13422 EditorStyle {
13423 background: cx.theme().system().transparent,
13424 local_player: cx.editor_style.local_player,
13425 text: text_style,
13426 scrollbar_width: cx.editor_style.scrollbar_width,
13427 syntax: cx.editor_style.syntax.clone(),
13428 status: cx.editor_style.status.clone(),
13429 inlay_hints_style: HighlightStyle {
13430 font_weight: Some(FontWeight::BOLD),
13431 ..make_inlay_hints_style(cx.app)
13432 },
13433 inline_completion_styles: make_suggestion_styles(
13434 cx.app,
13435 ),
13436 ..EditorStyle::default()
13437 },
13438 ))
13439 .into_any_element()
13440 }
13441 }),
13442 priority: 0,
13443 }],
13444 Some(Autoscroll::fit()),
13445 cx,
13446 )[0];
13447 this.pending_rename = Some(RenameState {
13448 range,
13449 old_name,
13450 editor: rename_editor,
13451 block_id,
13452 });
13453 })?;
13454 }
13455
13456 Ok(())
13457 }))
13458 }
13459
13460 pub fn confirm_rename(
13461 &mut self,
13462 _: &ConfirmRename,
13463 window: &mut Window,
13464 cx: &mut Context<Self>,
13465 ) -> Option<Task<Result<()>>> {
13466 let rename = self.take_rename(false, window, cx)?;
13467 let workspace = self.workspace()?.downgrade();
13468 let (buffer, start) = self
13469 .buffer
13470 .read(cx)
13471 .text_anchor_for_position(rename.range.start, cx)?;
13472 let (end_buffer, _) = self
13473 .buffer
13474 .read(cx)
13475 .text_anchor_for_position(rename.range.end, cx)?;
13476 if buffer != end_buffer {
13477 return None;
13478 }
13479
13480 let old_name = rename.old_name;
13481 let new_name = rename.editor.read(cx).text(cx);
13482
13483 let rename = self.semantics_provider.as_ref()?.perform_rename(
13484 &buffer,
13485 start,
13486 new_name.clone(),
13487 cx,
13488 )?;
13489
13490 Some(cx.spawn_in(window, async move |editor, cx| {
13491 let project_transaction = rename.await?;
13492 Self::open_project_transaction(
13493 &editor,
13494 workspace,
13495 project_transaction,
13496 format!("Rename: {} → {}", old_name, new_name),
13497 cx,
13498 )
13499 .await?;
13500
13501 editor.update(cx, |editor, cx| {
13502 editor.refresh_document_highlights(cx);
13503 })?;
13504 Ok(())
13505 }))
13506 }
13507
13508 fn take_rename(
13509 &mut self,
13510 moving_cursor: bool,
13511 window: &mut Window,
13512 cx: &mut Context<Self>,
13513 ) -> Option<RenameState> {
13514 let rename = self.pending_rename.take()?;
13515 if rename.editor.focus_handle(cx).is_focused(window) {
13516 window.focus(&self.focus_handle);
13517 }
13518
13519 self.remove_blocks(
13520 [rename.block_id].into_iter().collect(),
13521 Some(Autoscroll::fit()),
13522 cx,
13523 );
13524 self.clear_highlights::<Rename>(cx);
13525 self.show_local_selections = true;
13526
13527 if moving_cursor {
13528 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13529 editor.selections.newest::<usize>(cx).head()
13530 });
13531
13532 // Update the selection to match the position of the selection inside
13533 // the rename editor.
13534 let snapshot = self.buffer.read(cx).read(cx);
13535 let rename_range = rename.range.to_offset(&snapshot);
13536 let cursor_in_editor = snapshot
13537 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13538 .min(rename_range.end);
13539 drop(snapshot);
13540
13541 self.change_selections(None, window, cx, |s| {
13542 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13543 });
13544 } else {
13545 self.refresh_document_highlights(cx);
13546 }
13547
13548 Some(rename)
13549 }
13550
13551 pub fn pending_rename(&self) -> Option<&RenameState> {
13552 self.pending_rename.as_ref()
13553 }
13554
13555 fn format(
13556 &mut self,
13557 _: &Format,
13558 window: &mut Window,
13559 cx: &mut Context<Self>,
13560 ) -> Option<Task<Result<()>>> {
13561 let project = match &self.project {
13562 Some(project) => project.clone(),
13563 None => return None,
13564 };
13565
13566 Some(self.perform_format(
13567 project,
13568 FormatTrigger::Manual,
13569 FormatTarget::Buffers,
13570 window,
13571 cx,
13572 ))
13573 }
13574
13575 fn format_selections(
13576 &mut self,
13577 _: &FormatSelections,
13578 window: &mut Window,
13579 cx: &mut Context<Self>,
13580 ) -> Option<Task<Result<()>>> {
13581 let project = match &self.project {
13582 Some(project) => project.clone(),
13583 None => return None,
13584 };
13585
13586 let ranges = self
13587 .selections
13588 .all_adjusted(cx)
13589 .into_iter()
13590 .map(|selection| selection.range())
13591 .collect_vec();
13592
13593 Some(self.perform_format(
13594 project,
13595 FormatTrigger::Manual,
13596 FormatTarget::Ranges(ranges),
13597 window,
13598 cx,
13599 ))
13600 }
13601
13602 fn perform_format(
13603 &mut self,
13604 project: Entity<Project>,
13605 trigger: FormatTrigger,
13606 target: FormatTarget,
13607 window: &mut Window,
13608 cx: &mut Context<Self>,
13609 ) -> Task<Result<()>> {
13610 let buffer = self.buffer.clone();
13611 let (buffers, target) = match target {
13612 FormatTarget::Buffers => {
13613 let mut buffers = buffer.read(cx).all_buffers();
13614 if trigger == FormatTrigger::Save {
13615 buffers.retain(|buffer| buffer.read(cx).is_dirty());
13616 }
13617 (buffers, LspFormatTarget::Buffers)
13618 }
13619 FormatTarget::Ranges(selection_ranges) => {
13620 let multi_buffer = buffer.read(cx);
13621 let snapshot = multi_buffer.read(cx);
13622 let mut buffers = HashSet::default();
13623 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13624 BTreeMap::new();
13625 for selection_range in selection_ranges {
13626 for (buffer, buffer_range, _) in
13627 snapshot.range_to_buffer_ranges(selection_range)
13628 {
13629 let buffer_id = buffer.remote_id();
13630 let start = buffer.anchor_before(buffer_range.start);
13631 let end = buffer.anchor_after(buffer_range.end);
13632 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13633 buffer_id_to_ranges
13634 .entry(buffer_id)
13635 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13636 .or_insert_with(|| vec![start..end]);
13637 }
13638 }
13639 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13640 }
13641 };
13642
13643 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13644 let format = project.update(cx, |project, cx| {
13645 project.format(buffers, target, true, trigger, cx)
13646 });
13647
13648 cx.spawn_in(window, async move |_, cx| {
13649 let transaction = futures::select_biased! {
13650 transaction = format.log_err().fuse() => transaction,
13651 () = timeout => {
13652 log::warn!("timed out waiting for formatting");
13653 None
13654 }
13655 };
13656
13657 buffer
13658 .update(cx, |buffer, cx| {
13659 if let Some(transaction) = transaction {
13660 if !buffer.is_singleton() {
13661 buffer.push_transaction(&transaction.0, cx);
13662 }
13663 }
13664 cx.notify();
13665 })
13666 .ok();
13667
13668 Ok(())
13669 })
13670 }
13671
13672 fn organize_imports(
13673 &mut self,
13674 _: &OrganizeImports,
13675 window: &mut Window,
13676 cx: &mut Context<Self>,
13677 ) -> Option<Task<Result<()>>> {
13678 let project = match &self.project {
13679 Some(project) => project.clone(),
13680 None => return None,
13681 };
13682 Some(self.perform_code_action_kind(
13683 project,
13684 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13685 window,
13686 cx,
13687 ))
13688 }
13689
13690 fn perform_code_action_kind(
13691 &mut self,
13692 project: Entity<Project>,
13693 kind: CodeActionKind,
13694 window: &mut Window,
13695 cx: &mut Context<Self>,
13696 ) -> Task<Result<()>> {
13697 let buffer = self.buffer.clone();
13698 let buffers = buffer.read(cx).all_buffers();
13699 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13700 let apply_action = project.update(cx, |project, cx| {
13701 project.apply_code_action_kind(buffers, kind, true, cx)
13702 });
13703 cx.spawn_in(window, async move |_, cx| {
13704 let transaction = futures::select_biased! {
13705 () = timeout => {
13706 log::warn!("timed out waiting for executing code action");
13707 None
13708 }
13709 transaction = apply_action.log_err().fuse() => transaction,
13710 };
13711 buffer
13712 .update(cx, |buffer, cx| {
13713 // check if we need this
13714 if let Some(transaction) = transaction {
13715 if !buffer.is_singleton() {
13716 buffer.push_transaction(&transaction.0, cx);
13717 }
13718 }
13719 cx.notify();
13720 })
13721 .ok();
13722 Ok(())
13723 })
13724 }
13725
13726 fn restart_language_server(
13727 &mut self,
13728 _: &RestartLanguageServer,
13729 _: &mut Window,
13730 cx: &mut Context<Self>,
13731 ) {
13732 if let Some(project) = self.project.clone() {
13733 self.buffer.update(cx, |multi_buffer, cx| {
13734 project.update(cx, |project, cx| {
13735 project.restart_language_servers_for_buffers(
13736 multi_buffer.all_buffers().into_iter().collect(),
13737 cx,
13738 );
13739 });
13740 })
13741 }
13742 }
13743
13744 fn cancel_language_server_work(
13745 workspace: &mut Workspace,
13746 _: &actions::CancelLanguageServerWork,
13747 _: &mut Window,
13748 cx: &mut Context<Workspace>,
13749 ) {
13750 let project = workspace.project();
13751 let buffers = workspace
13752 .active_item(cx)
13753 .and_then(|item| item.act_as::<Editor>(cx))
13754 .map_or(HashSet::default(), |editor| {
13755 editor.read(cx).buffer.read(cx).all_buffers()
13756 });
13757 project.update(cx, |project, cx| {
13758 project.cancel_language_server_work_for_buffers(buffers, cx);
13759 });
13760 }
13761
13762 fn show_character_palette(
13763 &mut self,
13764 _: &ShowCharacterPalette,
13765 window: &mut Window,
13766 _: &mut Context<Self>,
13767 ) {
13768 window.show_character_palette();
13769 }
13770
13771 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13772 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13773 let buffer = self.buffer.read(cx).snapshot(cx);
13774 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13775 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13776 let is_valid = buffer
13777 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13778 .any(|entry| {
13779 entry.diagnostic.is_primary
13780 && !entry.range.is_empty()
13781 && entry.range.start == primary_range_start
13782 && entry.diagnostic.message == active_diagnostics.primary_message
13783 });
13784
13785 if is_valid != active_diagnostics.is_valid {
13786 active_diagnostics.is_valid = is_valid;
13787 if is_valid {
13788 let mut new_styles = HashMap::default();
13789 for (block_id, diagnostic) in &active_diagnostics.blocks {
13790 new_styles.insert(
13791 *block_id,
13792 diagnostic_block_renderer(diagnostic.clone(), None, true),
13793 );
13794 }
13795 self.display_map.update(cx, |display_map, _cx| {
13796 display_map.replace_blocks(new_styles);
13797 });
13798 } else {
13799 self.dismiss_diagnostics(cx);
13800 }
13801 }
13802 }
13803 }
13804
13805 fn activate_diagnostics(
13806 &mut self,
13807 buffer_id: BufferId,
13808 group_id: usize,
13809 window: &mut Window,
13810 cx: &mut Context<Self>,
13811 ) {
13812 self.dismiss_diagnostics(cx);
13813 let snapshot = self.snapshot(window, cx);
13814 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13815 let buffer = self.buffer.read(cx).snapshot(cx);
13816
13817 let mut primary_range = None;
13818 let mut primary_message = None;
13819 let diagnostic_group = buffer
13820 .diagnostic_group(buffer_id, group_id)
13821 .filter_map(|entry| {
13822 let start = entry.range.start;
13823 let end = entry.range.end;
13824 if snapshot.is_line_folded(MultiBufferRow(start.row))
13825 && (start.row == end.row
13826 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13827 {
13828 return None;
13829 }
13830 if entry.diagnostic.is_primary {
13831 primary_range = Some(entry.range.clone());
13832 primary_message = Some(entry.diagnostic.message.clone());
13833 }
13834 Some(entry)
13835 })
13836 .collect::<Vec<_>>();
13837 let primary_range = primary_range?;
13838 let primary_message = primary_message?;
13839
13840 let blocks = display_map
13841 .insert_blocks(
13842 diagnostic_group.iter().map(|entry| {
13843 let diagnostic = entry.diagnostic.clone();
13844 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13845 BlockProperties {
13846 style: BlockStyle::Fixed,
13847 placement: BlockPlacement::Below(
13848 buffer.anchor_after(entry.range.start),
13849 ),
13850 height: message_height,
13851 render: diagnostic_block_renderer(diagnostic, None, true),
13852 priority: 0,
13853 }
13854 }),
13855 cx,
13856 )
13857 .into_iter()
13858 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13859 .collect();
13860
13861 Some(ActiveDiagnosticGroup {
13862 primary_range: buffer.anchor_before(primary_range.start)
13863 ..buffer.anchor_after(primary_range.end),
13864 primary_message,
13865 group_id,
13866 blocks,
13867 is_valid: true,
13868 })
13869 });
13870 }
13871
13872 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13873 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13874 self.display_map.update(cx, |display_map, cx| {
13875 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13876 });
13877 cx.notify();
13878 }
13879 }
13880
13881 /// Disable inline diagnostics rendering for this editor.
13882 pub fn disable_inline_diagnostics(&mut self) {
13883 self.inline_diagnostics_enabled = false;
13884 self.inline_diagnostics_update = Task::ready(());
13885 self.inline_diagnostics.clear();
13886 }
13887
13888 pub fn inline_diagnostics_enabled(&self) -> bool {
13889 self.inline_diagnostics_enabled
13890 }
13891
13892 pub fn show_inline_diagnostics(&self) -> bool {
13893 self.show_inline_diagnostics
13894 }
13895
13896 pub fn toggle_inline_diagnostics(
13897 &mut self,
13898 _: &ToggleInlineDiagnostics,
13899 window: &mut Window,
13900 cx: &mut Context<'_, Editor>,
13901 ) {
13902 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13903 self.refresh_inline_diagnostics(false, window, cx);
13904 }
13905
13906 fn refresh_inline_diagnostics(
13907 &mut self,
13908 debounce: bool,
13909 window: &mut Window,
13910 cx: &mut Context<Self>,
13911 ) {
13912 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13913 self.inline_diagnostics_update = Task::ready(());
13914 self.inline_diagnostics.clear();
13915 return;
13916 }
13917
13918 let debounce_ms = ProjectSettings::get_global(cx)
13919 .diagnostics
13920 .inline
13921 .update_debounce_ms;
13922 let debounce = if debounce && debounce_ms > 0 {
13923 Some(Duration::from_millis(debounce_ms))
13924 } else {
13925 None
13926 };
13927 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
13928 if let Some(debounce) = debounce {
13929 cx.background_executor().timer(debounce).await;
13930 }
13931 let Some(snapshot) = editor
13932 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13933 .ok()
13934 else {
13935 return;
13936 };
13937
13938 let new_inline_diagnostics = cx
13939 .background_spawn(async move {
13940 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13941 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13942 let message = diagnostic_entry
13943 .diagnostic
13944 .message
13945 .split_once('\n')
13946 .map(|(line, _)| line)
13947 .map(SharedString::new)
13948 .unwrap_or_else(|| {
13949 SharedString::from(diagnostic_entry.diagnostic.message)
13950 });
13951 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13952 let (Ok(i) | Err(i)) = inline_diagnostics
13953 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13954 inline_diagnostics.insert(
13955 i,
13956 (
13957 start_anchor,
13958 InlineDiagnostic {
13959 message,
13960 group_id: diagnostic_entry.diagnostic.group_id,
13961 start: diagnostic_entry.range.start.to_point(&snapshot),
13962 is_primary: diagnostic_entry.diagnostic.is_primary,
13963 severity: diagnostic_entry.diagnostic.severity,
13964 },
13965 ),
13966 );
13967 }
13968 inline_diagnostics
13969 })
13970 .await;
13971
13972 editor
13973 .update(cx, |editor, cx| {
13974 editor.inline_diagnostics = new_inline_diagnostics;
13975 cx.notify();
13976 })
13977 .ok();
13978 });
13979 }
13980
13981 pub fn set_selections_from_remote(
13982 &mut self,
13983 selections: Vec<Selection<Anchor>>,
13984 pending_selection: Option<Selection<Anchor>>,
13985 window: &mut Window,
13986 cx: &mut Context<Self>,
13987 ) {
13988 let old_cursor_position = self.selections.newest_anchor().head();
13989 self.selections.change_with(cx, |s| {
13990 s.select_anchors(selections);
13991 if let Some(pending_selection) = pending_selection {
13992 s.set_pending(pending_selection, SelectMode::Character);
13993 } else {
13994 s.clear_pending();
13995 }
13996 });
13997 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13998 }
13999
14000 fn push_to_selection_history(&mut self) {
14001 self.selection_history.push(SelectionHistoryEntry {
14002 selections: self.selections.disjoint_anchors(),
14003 select_next_state: self.select_next_state.clone(),
14004 select_prev_state: self.select_prev_state.clone(),
14005 add_selections_state: self.add_selections_state.clone(),
14006 });
14007 }
14008
14009 pub fn transact(
14010 &mut self,
14011 window: &mut Window,
14012 cx: &mut Context<Self>,
14013 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14014 ) -> Option<TransactionId> {
14015 self.start_transaction_at(Instant::now(), window, cx);
14016 update(self, window, cx);
14017 self.end_transaction_at(Instant::now(), cx)
14018 }
14019
14020 pub fn start_transaction_at(
14021 &mut self,
14022 now: Instant,
14023 window: &mut Window,
14024 cx: &mut Context<Self>,
14025 ) {
14026 self.end_selection(window, cx);
14027 if let Some(tx_id) = self
14028 .buffer
14029 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14030 {
14031 self.selection_history
14032 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14033 cx.emit(EditorEvent::TransactionBegun {
14034 transaction_id: tx_id,
14035 })
14036 }
14037 }
14038
14039 pub fn end_transaction_at(
14040 &mut self,
14041 now: Instant,
14042 cx: &mut Context<Self>,
14043 ) -> Option<TransactionId> {
14044 if let Some(transaction_id) = self
14045 .buffer
14046 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14047 {
14048 if let Some((_, end_selections)) =
14049 self.selection_history.transaction_mut(transaction_id)
14050 {
14051 *end_selections = Some(self.selections.disjoint_anchors());
14052 } else {
14053 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14054 }
14055
14056 cx.emit(EditorEvent::Edited { transaction_id });
14057 Some(transaction_id)
14058 } else {
14059 None
14060 }
14061 }
14062
14063 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14064 if self.selection_mark_mode {
14065 self.change_selections(None, window, cx, |s| {
14066 s.move_with(|_, sel| {
14067 sel.collapse_to(sel.head(), SelectionGoal::None);
14068 });
14069 })
14070 }
14071 self.selection_mark_mode = true;
14072 cx.notify();
14073 }
14074
14075 pub fn swap_selection_ends(
14076 &mut self,
14077 _: &actions::SwapSelectionEnds,
14078 window: &mut Window,
14079 cx: &mut Context<Self>,
14080 ) {
14081 self.change_selections(None, window, cx, |s| {
14082 s.move_with(|_, sel| {
14083 if sel.start != sel.end {
14084 sel.reversed = !sel.reversed
14085 }
14086 });
14087 });
14088 self.request_autoscroll(Autoscroll::newest(), cx);
14089 cx.notify();
14090 }
14091
14092 pub fn toggle_fold(
14093 &mut self,
14094 _: &actions::ToggleFold,
14095 window: &mut Window,
14096 cx: &mut Context<Self>,
14097 ) {
14098 if self.is_singleton(cx) {
14099 let selection = self.selections.newest::<Point>(cx);
14100
14101 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14102 let range = if selection.is_empty() {
14103 let point = selection.head().to_display_point(&display_map);
14104 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14105 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14106 .to_point(&display_map);
14107 start..end
14108 } else {
14109 selection.range()
14110 };
14111 if display_map.folds_in_range(range).next().is_some() {
14112 self.unfold_lines(&Default::default(), window, cx)
14113 } else {
14114 self.fold(&Default::default(), window, cx)
14115 }
14116 } else {
14117 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14118 let buffer_ids: HashSet<_> = self
14119 .selections
14120 .disjoint_anchor_ranges()
14121 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14122 .collect();
14123
14124 let should_unfold = buffer_ids
14125 .iter()
14126 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14127
14128 for buffer_id in buffer_ids {
14129 if should_unfold {
14130 self.unfold_buffer(buffer_id, cx);
14131 } else {
14132 self.fold_buffer(buffer_id, cx);
14133 }
14134 }
14135 }
14136 }
14137
14138 pub fn toggle_fold_recursive(
14139 &mut self,
14140 _: &actions::ToggleFoldRecursive,
14141 window: &mut Window,
14142 cx: &mut Context<Self>,
14143 ) {
14144 let selection = self.selections.newest::<Point>(cx);
14145
14146 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14147 let range = if selection.is_empty() {
14148 let point = selection.head().to_display_point(&display_map);
14149 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14150 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14151 .to_point(&display_map);
14152 start..end
14153 } else {
14154 selection.range()
14155 };
14156 if display_map.folds_in_range(range).next().is_some() {
14157 self.unfold_recursive(&Default::default(), window, cx)
14158 } else {
14159 self.fold_recursive(&Default::default(), window, cx)
14160 }
14161 }
14162
14163 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14164 if self.is_singleton(cx) {
14165 let mut to_fold = Vec::new();
14166 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14167 let selections = self.selections.all_adjusted(cx);
14168
14169 for selection in selections {
14170 let range = selection.range().sorted();
14171 let buffer_start_row = range.start.row;
14172
14173 if range.start.row != range.end.row {
14174 let mut found = false;
14175 let mut row = range.start.row;
14176 while row <= range.end.row {
14177 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14178 {
14179 found = true;
14180 row = crease.range().end.row + 1;
14181 to_fold.push(crease);
14182 } else {
14183 row += 1
14184 }
14185 }
14186 if found {
14187 continue;
14188 }
14189 }
14190
14191 for row in (0..=range.start.row).rev() {
14192 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14193 if crease.range().end.row >= buffer_start_row {
14194 to_fold.push(crease);
14195 if row <= range.start.row {
14196 break;
14197 }
14198 }
14199 }
14200 }
14201 }
14202
14203 self.fold_creases(to_fold, true, window, cx);
14204 } else {
14205 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14206 let buffer_ids = self
14207 .selections
14208 .disjoint_anchor_ranges()
14209 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14210 .collect::<HashSet<_>>();
14211 for buffer_id in buffer_ids {
14212 self.fold_buffer(buffer_id, cx);
14213 }
14214 }
14215 }
14216
14217 fn fold_at_level(
14218 &mut self,
14219 fold_at: &FoldAtLevel,
14220 window: &mut Window,
14221 cx: &mut Context<Self>,
14222 ) {
14223 if !self.buffer.read(cx).is_singleton() {
14224 return;
14225 }
14226
14227 let fold_at_level = fold_at.0;
14228 let snapshot = self.buffer.read(cx).snapshot(cx);
14229 let mut to_fold = Vec::new();
14230 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14231
14232 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14233 while start_row < end_row {
14234 match self
14235 .snapshot(window, cx)
14236 .crease_for_buffer_row(MultiBufferRow(start_row))
14237 {
14238 Some(crease) => {
14239 let nested_start_row = crease.range().start.row + 1;
14240 let nested_end_row = crease.range().end.row;
14241
14242 if current_level < fold_at_level {
14243 stack.push((nested_start_row, nested_end_row, current_level + 1));
14244 } else if current_level == fold_at_level {
14245 to_fold.push(crease);
14246 }
14247
14248 start_row = nested_end_row + 1;
14249 }
14250 None => start_row += 1,
14251 }
14252 }
14253 }
14254
14255 self.fold_creases(to_fold, true, window, cx);
14256 }
14257
14258 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14259 if self.buffer.read(cx).is_singleton() {
14260 let mut fold_ranges = Vec::new();
14261 let snapshot = self.buffer.read(cx).snapshot(cx);
14262
14263 for row in 0..snapshot.max_row().0 {
14264 if let Some(foldable_range) = self
14265 .snapshot(window, cx)
14266 .crease_for_buffer_row(MultiBufferRow(row))
14267 {
14268 fold_ranges.push(foldable_range);
14269 }
14270 }
14271
14272 self.fold_creases(fold_ranges, true, window, cx);
14273 } else {
14274 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14275 editor
14276 .update_in(cx, |editor, _, cx| {
14277 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14278 editor.fold_buffer(buffer_id, cx);
14279 }
14280 })
14281 .ok();
14282 });
14283 }
14284 }
14285
14286 pub fn fold_function_bodies(
14287 &mut self,
14288 _: &actions::FoldFunctionBodies,
14289 window: &mut Window,
14290 cx: &mut Context<Self>,
14291 ) {
14292 let snapshot = self.buffer.read(cx).snapshot(cx);
14293
14294 let ranges = snapshot
14295 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14296 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14297 .collect::<Vec<_>>();
14298
14299 let creases = ranges
14300 .into_iter()
14301 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14302 .collect();
14303
14304 self.fold_creases(creases, true, window, cx);
14305 }
14306
14307 pub fn fold_recursive(
14308 &mut self,
14309 _: &actions::FoldRecursive,
14310 window: &mut Window,
14311 cx: &mut Context<Self>,
14312 ) {
14313 let mut to_fold = Vec::new();
14314 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14315 let selections = self.selections.all_adjusted(cx);
14316
14317 for selection in selections {
14318 let range = selection.range().sorted();
14319 let buffer_start_row = range.start.row;
14320
14321 if range.start.row != range.end.row {
14322 let mut found = false;
14323 for row in range.start.row..=range.end.row {
14324 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14325 found = true;
14326 to_fold.push(crease);
14327 }
14328 }
14329 if found {
14330 continue;
14331 }
14332 }
14333
14334 for row in (0..=range.start.row).rev() {
14335 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14336 if crease.range().end.row >= buffer_start_row {
14337 to_fold.push(crease);
14338 } else {
14339 break;
14340 }
14341 }
14342 }
14343 }
14344
14345 self.fold_creases(to_fold, true, window, cx);
14346 }
14347
14348 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14349 let buffer_row = fold_at.buffer_row;
14350 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14351
14352 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14353 let autoscroll = self
14354 .selections
14355 .all::<Point>(cx)
14356 .iter()
14357 .any(|selection| crease.range().overlaps(&selection.range()));
14358
14359 self.fold_creases(vec![crease], autoscroll, window, cx);
14360 }
14361 }
14362
14363 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14364 if self.is_singleton(cx) {
14365 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14366 let buffer = &display_map.buffer_snapshot;
14367 let selections = self.selections.all::<Point>(cx);
14368 let ranges = selections
14369 .iter()
14370 .map(|s| {
14371 let range = s.display_range(&display_map).sorted();
14372 let mut start = range.start.to_point(&display_map);
14373 let mut end = range.end.to_point(&display_map);
14374 start.column = 0;
14375 end.column = buffer.line_len(MultiBufferRow(end.row));
14376 start..end
14377 })
14378 .collect::<Vec<_>>();
14379
14380 self.unfold_ranges(&ranges, true, true, cx);
14381 } else {
14382 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14383 let buffer_ids = self
14384 .selections
14385 .disjoint_anchor_ranges()
14386 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14387 .collect::<HashSet<_>>();
14388 for buffer_id in buffer_ids {
14389 self.unfold_buffer(buffer_id, cx);
14390 }
14391 }
14392 }
14393
14394 pub fn unfold_recursive(
14395 &mut self,
14396 _: &UnfoldRecursive,
14397 _window: &mut Window,
14398 cx: &mut Context<Self>,
14399 ) {
14400 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14401 let selections = self.selections.all::<Point>(cx);
14402 let ranges = selections
14403 .iter()
14404 .map(|s| {
14405 let mut range = s.display_range(&display_map).sorted();
14406 *range.start.column_mut() = 0;
14407 *range.end.column_mut() = display_map.line_len(range.end.row());
14408 let start = range.start.to_point(&display_map);
14409 let end = range.end.to_point(&display_map);
14410 start..end
14411 })
14412 .collect::<Vec<_>>();
14413
14414 self.unfold_ranges(&ranges, true, true, cx);
14415 }
14416
14417 pub fn unfold_at(
14418 &mut self,
14419 unfold_at: &UnfoldAt,
14420 _window: &mut Window,
14421 cx: &mut Context<Self>,
14422 ) {
14423 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14424
14425 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14426 ..Point::new(
14427 unfold_at.buffer_row.0,
14428 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14429 );
14430
14431 let autoscroll = self
14432 .selections
14433 .all::<Point>(cx)
14434 .iter()
14435 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14436
14437 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14438 }
14439
14440 pub fn unfold_all(
14441 &mut self,
14442 _: &actions::UnfoldAll,
14443 _window: &mut Window,
14444 cx: &mut Context<Self>,
14445 ) {
14446 if self.buffer.read(cx).is_singleton() {
14447 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14448 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14449 } else {
14450 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14451 editor
14452 .update(cx, |editor, cx| {
14453 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14454 editor.unfold_buffer(buffer_id, cx);
14455 }
14456 })
14457 .ok();
14458 });
14459 }
14460 }
14461
14462 pub fn fold_selected_ranges(
14463 &mut self,
14464 _: &FoldSelectedRanges,
14465 window: &mut Window,
14466 cx: &mut Context<Self>,
14467 ) {
14468 let selections = self.selections.all::<Point>(cx);
14469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14470 let line_mode = self.selections.line_mode;
14471 let ranges = selections
14472 .into_iter()
14473 .map(|s| {
14474 if line_mode {
14475 let start = Point::new(s.start.row, 0);
14476 let end = Point::new(
14477 s.end.row,
14478 display_map
14479 .buffer_snapshot
14480 .line_len(MultiBufferRow(s.end.row)),
14481 );
14482 Crease::simple(start..end, display_map.fold_placeholder.clone())
14483 } else {
14484 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14485 }
14486 })
14487 .collect::<Vec<_>>();
14488 self.fold_creases(ranges, true, window, cx);
14489 }
14490
14491 pub fn fold_ranges<T: ToOffset + Clone>(
14492 &mut self,
14493 ranges: Vec<Range<T>>,
14494 auto_scroll: bool,
14495 window: &mut Window,
14496 cx: &mut Context<Self>,
14497 ) {
14498 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14499 let ranges = ranges
14500 .into_iter()
14501 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14502 .collect::<Vec<_>>();
14503 self.fold_creases(ranges, auto_scroll, window, cx);
14504 }
14505
14506 pub fn fold_creases<T: ToOffset + Clone>(
14507 &mut self,
14508 creases: Vec<Crease<T>>,
14509 auto_scroll: bool,
14510 window: &mut Window,
14511 cx: &mut Context<Self>,
14512 ) {
14513 if creases.is_empty() {
14514 return;
14515 }
14516
14517 let mut buffers_affected = HashSet::default();
14518 let multi_buffer = self.buffer().read(cx);
14519 for crease in &creases {
14520 if let Some((_, buffer, _)) =
14521 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14522 {
14523 buffers_affected.insert(buffer.read(cx).remote_id());
14524 };
14525 }
14526
14527 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14528
14529 if auto_scroll {
14530 self.request_autoscroll(Autoscroll::fit(), cx);
14531 }
14532
14533 cx.notify();
14534
14535 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14536 // Clear diagnostics block when folding a range that contains it.
14537 let snapshot = self.snapshot(window, cx);
14538 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14539 drop(snapshot);
14540 self.active_diagnostics = Some(active_diagnostics);
14541 self.dismiss_diagnostics(cx);
14542 } else {
14543 self.active_diagnostics = Some(active_diagnostics);
14544 }
14545 }
14546
14547 self.scrollbar_marker_state.dirty = true;
14548 self.folds_did_change(cx);
14549 }
14550
14551 /// Removes any folds whose ranges intersect any of the given ranges.
14552 pub fn unfold_ranges<T: ToOffset + Clone>(
14553 &mut self,
14554 ranges: &[Range<T>],
14555 inclusive: bool,
14556 auto_scroll: bool,
14557 cx: &mut Context<Self>,
14558 ) {
14559 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14560 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14561 });
14562 self.folds_did_change(cx);
14563 }
14564
14565 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14566 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14567 return;
14568 }
14569 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14570 self.display_map.update(cx, |display_map, cx| {
14571 display_map.fold_buffers([buffer_id], cx)
14572 });
14573 cx.emit(EditorEvent::BufferFoldToggled {
14574 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14575 folded: true,
14576 });
14577 cx.notify();
14578 }
14579
14580 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14581 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14582 return;
14583 }
14584 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14585 self.display_map.update(cx, |display_map, cx| {
14586 display_map.unfold_buffers([buffer_id], cx);
14587 });
14588 cx.emit(EditorEvent::BufferFoldToggled {
14589 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14590 folded: false,
14591 });
14592 cx.notify();
14593 }
14594
14595 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14596 self.display_map.read(cx).is_buffer_folded(buffer)
14597 }
14598
14599 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14600 self.display_map.read(cx).folded_buffers()
14601 }
14602
14603 /// Removes any folds with the given ranges.
14604 pub fn remove_folds_with_type<T: ToOffset + Clone>(
14605 &mut self,
14606 ranges: &[Range<T>],
14607 type_id: TypeId,
14608 auto_scroll: bool,
14609 cx: &mut Context<Self>,
14610 ) {
14611 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14612 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14613 });
14614 self.folds_did_change(cx);
14615 }
14616
14617 fn remove_folds_with<T: ToOffset + Clone>(
14618 &mut self,
14619 ranges: &[Range<T>],
14620 auto_scroll: bool,
14621 cx: &mut Context<Self>,
14622 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14623 ) {
14624 if ranges.is_empty() {
14625 return;
14626 }
14627
14628 let mut buffers_affected = HashSet::default();
14629 let multi_buffer = self.buffer().read(cx);
14630 for range in ranges {
14631 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14632 buffers_affected.insert(buffer.read(cx).remote_id());
14633 };
14634 }
14635
14636 self.display_map.update(cx, update);
14637
14638 if auto_scroll {
14639 self.request_autoscroll(Autoscroll::fit(), cx);
14640 }
14641
14642 cx.notify();
14643 self.scrollbar_marker_state.dirty = true;
14644 self.active_indent_guides_state.dirty = true;
14645 }
14646
14647 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14648 self.display_map.read(cx).fold_placeholder.clone()
14649 }
14650
14651 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14652 self.buffer.update(cx, |buffer, cx| {
14653 buffer.set_all_diff_hunks_expanded(cx);
14654 });
14655 }
14656
14657 pub fn expand_all_diff_hunks(
14658 &mut self,
14659 _: &ExpandAllDiffHunks,
14660 _window: &mut Window,
14661 cx: &mut Context<Self>,
14662 ) {
14663 self.buffer.update(cx, |buffer, cx| {
14664 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14665 });
14666 }
14667
14668 pub fn toggle_selected_diff_hunks(
14669 &mut self,
14670 _: &ToggleSelectedDiffHunks,
14671 _window: &mut Window,
14672 cx: &mut Context<Self>,
14673 ) {
14674 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14675 self.toggle_diff_hunks_in_ranges(ranges, cx);
14676 }
14677
14678 pub fn diff_hunks_in_ranges<'a>(
14679 &'a self,
14680 ranges: &'a [Range<Anchor>],
14681 buffer: &'a MultiBufferSnapshot,
14682 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14683 ranges.iter().flat_map(move |range| {
14684 let end_excerpt_id = range.end.excerpt_id;
14685 let range = range.to_point(buffer);
14686 let mut peek_end = range.end;
14687 if range.end.row < buffer.max_row().0 {
14688 peek_end = Point::new(range.end.row + 1, 0);
14689 }
14690 buffer
14691 .diff_hunks_in_range(range.start..peek_end)
14692 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14693 })
14694 }
14695
14696 pub fn has_stageable_diff_hunks_in_ranges(
14697 &self,
14698 ranges: &[Range<Anchor>],
14699 snapshot: &MultiBufferSnapshot,
14700 ) -> bool {
14701 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14702 hunks.any(|hunk| hunk.status().has_secondary_hunk())
14703 }
14704
14705 pub fn toggle_staged_selected_diff_hunks(
14706 &mut self,
14707 _: &::git::ToggleStaged,
14708 _: &mut Window,
14709 cx: &mut Context<Self>,
14710 ) {
14711 let snapshot = self.buffer.read(cx).snapshot(cx);
14712 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14713 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14714 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14715 }
14716
14717 pub fn stage_and_next(
14718 &mut self,
14719 _: &::git::StageAndNext,
14720 window: &mut Window,
14721 cx: &mut Context<Self>,
14722 ) {
14723 self.do_stage_or_unstage_and_next(true, window, cx);
14724 }
14725
14726 pub fn unstage_and_next(
14727 &mut self,
14728 _: &::git::UnstageAndNext,
14729 window: &mut Window,
14730 cx: &mut Context<Self>,
14731 ) {
14732 self.do_stage_or_unstage_and_next(false, window, cx);
14733 }
14734
14735 pub fn stage_or_unstage_diff_hunks(
14736 &mut self,
14737 stage: bool,
14738 ranges: Vec<Range<Anchor>>,
14739 cx: &mut Context<Self>,
14740 ) {
14741 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14742 cx.spawn(async move |this, cx| {
14743 task.await?;
14744 this.update(cx, |this, cx| {
14745 let snapshot = this.buffer.read(cx).snapshot(cx);
14746 let chunk_by = this
14747 .diff_hunks_in_ranges(&ranges, &snapshot)
14748 .chunk_by(|hunk| hunk.buffer_id);
14749 for (buffer_id, hunks) in &chunk_by {
14750 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14751 }
14752 })
14753 })
14754 .detach_and_log_err(cx);
14755 }
14756
14757 fn save_buffers_for_ranges_if_needed(
14758 &mut self,
14759 ranges: &[Range<Anchor>],
14760 cx: &mut Context<'_, Editor>,
14761 ) -> Task<Result<()>> {
14762 let multibuffer = self.buffer.read(cx);
14763 let snapshot = multibuffer.read(cx);
14764 let buffer_ids: HashSet<_> = ranges
14765 .iter()
14766 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14767 .collect();
14768 drop(snapshot);
14769
14770 let mut buffers = HashSet::default();
14771 for buffer_id in buffer_ids {
14772 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14773 let buffer = buffer_entity.read(cx);
14774 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14775 {
14776 buffers.insert(buffer_entity);
14777 }
14778 }
14779 }
14780
14781 if let Some(project) = &self.project {
14782 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14783 } else {
14784 Task::ready(Ok(()))
14785 }
14786 }
14787
14788 fn do_stage_or_unstage_and_next(
14789 &mut self,
14790 stage: bool,
14791 window: &mut Window,
14792 cx: &mut Context<Self>,
14793 ) {
14794 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14795
14796 if ranges.iter().any(|range| range.start != range.end) {
14797 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14798 return;
14799 }
14800
14801 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14802 let snapshot = self.snapshot(window, cx);
14803 let position = self.selections.newest::<Point>(cx).head();
14804 let mut row = snapshot
14805 .buffer_snapshot
14806 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14807 .find(|hunk| hunk.row_range.start.0 > position.row)
14808 .map(|hunk| hunk.row_range.start);
14809
14810 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14811 // Outside of the project diff editor, wrap around to the beginning.
14812 if !all_diff_hunks_expanded {
14813 row = row.or_else(|| {
14814 snapshot
14815 .buffer_snapshot
14816 .diff_hunks_in_range(Point::zero()..position)
14817 .find(|hunk| hunk.row_range.end.0 < position.row)
14818 .map(|hunk| hunk.row_range.start)
14819 });
14820 }
14821
14822 if let Some(row) = row {
14823 let destination = Point::new(row.0, 0);
14824 let autoscroll = Autoscroll::center();
14825
14826 self.unfold_ranges(&[destination..destination], false, false, cx);
14827 self.change_selections(Some(autoscroll), window, cx, |s| {
14828 s.select_ranges([destination..destination]);
14829 });
14830 }
14831 }
14832
14833 fn do_stage_or_unstage(
14834 &self,
14835 stage: bool,
14836 buffer_id: BufferId,
14837 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14838 cx: &mut App,
14839 ) -> Option<()> {
14840 let project = self.project.as_ref()?;
14841 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14842 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14843 let buffer_snapshot = buffer.read(cx).snapshot();
14844 let file_exists = buffer_snapshot
14845 .file()
14846 .is_some_and(|file| file.disk_state().exists());
14847 diff.update(cx, |diff, cx| {
14848 diff.stage_or_unstage_hunks(
14849 stage,
14850 &hunks
14851 .map(|hunk| buffer_diff::DiffHunk {
14852 buffer_range: hunk.buffer_range,
14853 diff_base_byte_range: hunk.diff_base_byte_range,
14854 secondary_status: hunk.secondary_status,
14855 range: Point::zero()..Point::zero(), // unused
14856 })
14857 .collect::<Vec<_>>(),
14858 &buffer_snapshot,
14859 file_exists,
14860 cx,
14861 )
14862 });
14863 None
14864 }
14865
14866 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14867 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14868 self.buffer
14869 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14870 }
14871
14872 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14873 self.buffer.update(cx, |buffer, cx| {
14874 let ranges = vec![Anchor::min()..Anchor::max()];
14875 if !buffer.all_diff_hunks_expanded()
14876 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14877 {
14878 buffer.collapse_diff_hunks(ranges, cx);
14879 true
14880 } else {
14881 false
14882 }
14883 })
14884 }
14885
14886 fn toggle_diff_hunks_in_ranges(
14887 &mut self,
14888 ranges: Vec<Range<Anchor>>,
14889 cx: &mut Context<'_, Editor>,
14890 ) {
14891 self.buffer.update(cx, |buffer, cx| {
14892 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14893 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14894 })
14895 }
14896
14897 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14898 self.buffer.update(cx, |buffer, cx| {
14899 let snapshot = buffer.snapshot(cx);
14900 let excerpt_id = range.end.excerpt_id;
14901 let point_range = range.to_point(&snapshot);
14902 let expand = !buffer.single_hunk_is_expanded(range, cx);
14903 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14904 })
14905 }
14906
14907 pub(crate) fn apply_all_diff_hunks(
14908 &mut self,
14909 _: &ApplyAllDiffHunks,
14910 window: &mut Window,
14911 cx: &mut Context<Self>,
14912 ) {
14913 let buffers = self.buffer.read(cx).all_buffers();
14914 for branch_buffer in buffers {
14915 branch_buffer.update(cx, |branch_buffer, cx| {
14916 branch_buffer.merge_into_base(Vec::new(), cx);
14917 });
14918 }
14919
14920 if let Some(project) = self.project.clone() {
14921 self.save(true, project, window, cx).detach_and_log_err(cx);
14922 }
14923 }
14924
14925 pub(crate) fn apply_selected_diff_hunks(
14926 &mut self,
14927 _: &ApplyDiffHunk,
14928 window: &mut Window,
14929 cx: &mut Context<Self>,
14930 ) {
14931 let snapshot = self.snapshot(window, cx);
14932 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14933 let mut ranges_by_buffer = HashMap::default();
14934 self.transact(window, cx, |editor, _window, cx| {
14935 for hunk in hunks {
14936 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14937 ranges_by_buffer
14938 .entry(buffer.clone())
14939 .or_insert_with(Vec::new)
14940 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14941 }
14942 }
14943
14944 for (buffer, ranges) in ranges_by_buffer {
14945 buffer.update(cx, |buffer, cx| {
14946 buffer.merge_into_base(ranges, cx);
14947 });
14948 }
14949 });
14950
14951 if let Some(project) = self.project.clone() {
14952 self.save(true, project, window, cx).detach_and_log_err(cx);
14953 }
14954 }
14955
14956 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14957 if hovered != self.gutter_hovered {
14958 self.gutter_hovered = hovered;
14959 cx.notify();
14960 }
14961 }
14962
14963 pub fn insert_blocks(
14964 &mut self,
14965 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14966 autoscroll: Option<Autoscroll>,
14967 cx: &mut Context<Self>,
14968 ) -> Vec<CustomBlockId> {
14969 let blocks = self
14970 .display_map
14971 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14972 if let Some(autoscroll) = autoscroll {
14973 self.request_autoscroll(autoscroll, cx);
14974 }
14975 cx.notify();
14976 blocks
14977 }
14978
14979 pub fn resize_blocks(
14980 &mut self,
14981 heights: HashMap<CustomBlockId, u32>,
14982 autoscroll: Option<Autoscroll>,
14983 cx: &mut Context<Self>,
14984 ) {
14985 self.display_map
14986 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14987 if let Some(autoscroll) = autoscroll {
14988 self.request_autoscroll(autoscroll, cx);
14989 }
14990 cx.notify();
14991 }
14992
14993 pub fn replace_blocks(
14994 &mut self,
14995 renderers: HashMap<CustomBlockId, RenderBlock>,
14996 autoscroll: Option<Autoscroll>,
14997 cx: &mut Context<Self>,
14998 ) {
14999 self.display_map
15000 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15001 if let Some(autoscroll) = autoscroll {
15002 self.request_autoscroll(autoscroll, cx);
15003 }
15004 cx.notify();
15005 }
15006
15007 pub fn remove_blocks(
15008 &mut self,
15009 block_ids: HashSet<CustomBlockId>,
15010 autoscroll: Option<Autoscroll>,
15011 cx: &mut Context<Self>,
15012 ) {
15013 self.display_map.update(cx, |display_map, cx| {
15014 display_map.remove_blocks(block_ids, cx)
15015 });
15016 if let Some(autoscroll) = autoscroll {
15017 self.request_autoscroll(autoscroll, cx);
15018 }
15019 cx.notify();
15020 }
15021
15022 pub fn row_for_block(
15023 &self,
15024 block_id: CustomBlockId,
15025 cx: &mut Context<Self>,
15026 ) -> Option<DisplayRow> {
15027 self.display_map
15028 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15029 }
15030
15031 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15032 self.focused_block = Some(focused_block);
15033 }
15034
15035 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15036 self.focused_block.take()
15037 }
15038
15039 pub fn insert_creases(
15040 &mut self,
15041 creases: impl IntoIterator<Item = Crease<Anchor>>,
15042 cx: &mut Context<Self>,
15043 ) -> Vec<CreaseId> {
15044 self.display_map
15045 .update(cx, |map, cx| map.insert_creases(creases, cx))
15046 }
15047
15048 pub fn remove_creases(
15049 &mut self,
15050 ids: impl IntoIterator<Item = CreaseId>,
15051 cx: &mut Context<Self>,
15052 ) {
15053 self.display_map
15054 .update(cx, |map, cx| map.remove_creases(ids, cx));
15055 }
15056
15057 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15058 self.display_map
15059 .update(cx, |map, cx| map.snapshot(cx))
15060 .longest_row()
15061 }
15062
15063 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15064 self.display_map
15065 .update(cx, |map, cx| map.snapshot(cx))
15066 .max_point()
15067 }
15068
15069 pub fn text(&self, cx: &App) -> String {
15070 self.buffer.read(cx).read(cx).text()
15071 }
15072
15073 pub fn is_empty(&self, cx: &App) -> bool {
15074 self.buffer.read(cx).read(cx).is_empty()
15075 }
15076
15077 pub fn text_option(&self, cx: &App) -> Option<String> {
15078 let text = self.text(cx);
15079 let text = text.trim();
15080
15081 if text.is_empty() {
15082 return None;
15083 }
15084
15085 Some(text.to_string())
15086 }
15087
15088 pub fn set_text(
15089 &mut self,
15090 text: impl Into<Arc<str>>,
15091 window: &mut Window,
15092 cx: &mut Context<Self>,
15093 ) {
15094 self.transact(window, cx, |this, _, cx| {
15095 this.buffer
15096 .read(cx)
15097 .as_singleton()
15098 .expect("you can only call set_text on editors for singleton buffers")
15099 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15100 });
15101 }
15102
15103 pub fn display_text(&self, cx: &mut App) -> String {
15104 self.display_map
15105 .update(cx, |map, cx| map.snapshot(cx))
15106 .text()
15107 }
15108
15109 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15110 let mut wrap_guides = smallvec::smallvec![];
15111
15112 if self.show_wrap_guides == Some(false) {
15113 return wrap_guides;
15114 }
15115
15116 let settings = self.buffer.read(cx).language_settings(cx);
15117 if settings.show_wrap_guides {
15118 match self.soft_wrap_mode(cx) {
15119 SoftWrap::Column(soft_wrap) => {
15120 wrap_guides.push((soft_wrap as usize, true));
15121 }
15122 SoftWrap::Bounded(soft_wrap) => {
15123 wrap_guides.push((soft_wrap as usize, true));
15124 }
15125 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15126 }
15127 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15128 }
15129
15130 wrap_guides
15131 }
15132
15133 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15134 let settings = self.buffer.read(cx).language_settings(cx);
15135 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15136 match mode {
15137 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15138 SoftWrap::None
15139 }
15140 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15141 language_settings::SoftWrap::PreferredLineLength => {
15142 SoftWrap::Column(settings.preferred_line_length)
15143 }
15144 language_settings::SoftWrap::Bounded => {
15145 SoftWrap::Bounded(settings.preferred_line_length)
15146 }
15147 }
15148 }
15149
15150 pub fn set_soft_wrap_mode(
15151 &mut self,
15152 mode: language_settings::SoftWrap,
15153
15154 cx: &mut Context<Self>,
15155 ) {
15156 self.soft_wrap_mode_override = Some(mode);
15157 cx.notify();
15158 }
15159
15160 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15161 self.hard_wrap = hard_wrap;
15162 cx.notify();
15163 }
15164
15165 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15166 self.text_style_refinement = Some(style);
15167 }
15168
15169 /// called by the Element so we know what style we were most recently rendered with.
15170 pub(crate) fn set_style(
15171 &mut self,
15172 style: EditorStyle,
15173 window: &mut Window,
15174 cx: &mut Context<Self>,
15175 ) {
15176 let rem_size = window.rem_size();
15177 self.display_map.update(cx, |map, cx| {
15178 map.set_font(
15179 style.text.font(),
15180 style.text.font_size.to_pixels(rem_size),
15181 cx,
15182 )
15183 });
15184 self.style = Some(style);
15185 }
15186
15187 pub fn style(&self) -> Option<&EditorStyle> {
15188 self.style.as_ref()
15189 }
15190
15191 // Called by the element. This method is not designed to be called outside of the editor
15192 // element's layout code because it does not notify when rewrapping is computed synchronously.
15193 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15194 self.display_map
15195 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15196 }
15197
15198 pub fn set_soft_wrap(&mut self) {
15199 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15200 }
15201
15202 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15203 if self.soft_wrap_mode_override.is_some() {
15204 self.soft_wrap_mode_override.take();
15205 } else {
15206 let soft_wrap = match self.soft_wrap_mode(cx) {
15207 SoftWrap::GitDiff => return,
15208 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15209 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15210 language_settings::SoftWrap::None
15211 }
15212 };
15213 self.soft_wrap_mode_override = Some(soft_wrap);
15214 }
15215 cx.notify();
15216 }
15217
15218 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15219 let Some(workspace) = self.workspace() else {
15220 return;
15221 };
15222 let fs = workspace.read(cx).app_state().fs.clone();
15223 let current_show = TabBarSettings::get_global(cx).show;
15224 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15225 setting.show = Some(!current_show);
15226 });
15227 }
15228
15229 pub fn toggle_indent_guides(
15230 &mut self,
15231 _: &ToggleIndentGuides,
15232 _: &mut Window,
15233 cx: &mut Context<Self>,
15234 ) {
15235 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15236 self.buffer
15237 .read(cx)
15238 .language_settings(cx)
15239 .indent_guides
15240 .enabled
15241 });
15242 self.show_indent_guides = Some(!currently_enabled);
15243 cx.notify();
15244 }
15245
15246 fn should_show_indent_guides(&self) -> Option<bool> {
15247 self.show_indent_guides
15248 }
15249
15250 pub fn toggle_line_numbers(
15251 &mut self,
15252 _: &ToggleLineNumbers,
15253 _: &mut Window,
15254 cx: &mut Context<Self>,
15255 ) {
15256 let mut editor_settings = EditorSettings::get_global(cx).clone();
15257 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15258 EditorSettings::override_global(editor_settings, cx);
15259 }
15260
15261 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15262 if let Some(show_line_numbers) = self.show_line_numbers {
15263 return show_line_numbers;
15264 }
15265 EditorSettings::get_global(cx).gutter.line_numbers
15266 }
15267
15268 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15269 self.use_relative_line_numbers
15270 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15271 }
15272
15273 pub fn toggle_relative_line_numbers(
15274 &mut self,
15275 _: &ToggleRelativeLineNumbers,
15276 _: &mut Window,
15277 cx: &mut Context<Self>,
15278 ) {
15279 let is_relative = self.should_use_relative_line_numbers(cx);
15280 self.set_relative_line_number(Some(!is_relative), cx)
15281 }
15282
15283 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15284 self.use_relative_line_numbers = is_relative;
15285 cx.notify();
15286 }
15287
15288 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15289 self.show_gutter = show_gutter;
15290 cx.notify();
15291 }
15292
15293 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15294 self.show_scrollbars = show_scrollbars;
15295 cx.notify();
15296 }
15297
15298 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15299 self.show_line_numbers = Some(show_line_numbers);
15300 cx.notify();
15301 }
15302
15303 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15304 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15305 cx.notify();
15306 }
15307
15308 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15309 self.show_code_actions = Some(show_code_actions);
15310 cx.notify();
15311 }
15312
15313 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15314 self.show_runnables = Some(show_runnables);
15315 cx.notify();
15316 }
15317
15318 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15319 self.show_breakpoints = Some(show_breakpoints);
15320 cx.notify();
15321 }
15322
15323 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15324 if self.display_map.read(cx).masked != masked {
15325 self.display_map.update(cx, |map, _| map.masked = masked);
15326 }
15327 cx.notify()
15328 }
15329
15330 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15331 self.show_wrap_guides = Some(show_wrap_guides);
15332 cx.notify();
15333 }
15334
15335 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15336 self.show_indent_guides = Some(show_indent_guides);
15337 cx.notify();
15338 }
15339
15340 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15341 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15342 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15343 if let Some(dir) = file.abs_path(cx).parent() {
15344 return Some(dir.to_owned());
15345 }
15346 }
15347
15348 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15349 return Some(project_path.path.to_path_buf());
15350 }
15351 }
15352
15353 None
15354 }
15355
15356 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15357 self.active_excerpt(cx)?
15358 .1
15359 .read(cx)
15360 .file()
15361 .and_then(|f| f.as_local())
15362 }
15363
15364 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15365 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15366 let buffer = buffer.read(cx);
15367 if let Some(project_path) = buffer.project_path(cx) {
15368 let project = self.project.as_ref()?.read(cx);
15369 project.absolute_path(&project_path, cx)
15370 } else {
15371 buffer
15372 .file()
15373 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15374 }
15375 })
15376 }
15377
15378 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15379 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15380 let project_path = buffer.read(cx).project_path(cx)?;
15381 let project = self.project.as_ref()?.read(cx);
15382 let entry = project.entry_for_path(&project_path, cx)?;
15383 let path = entry.path.to_path_buf();
15384 Some(path)
15385 })
15386 }
15387
15388 pub fn reveal_in_finder(
15389 &mut self,
15390 _: &RevealInFileManager,
15391 _window: &mut Window,
15392 cx: &mut Context<Self>,
15393 ) {
15394 if let Some(target) = self.target_file(cx) {
15395 cx.reveal_path(&target.abs_path(cx));
15396 }
15397 }
15398
15399 pub fn copy_path(
15400 &mut self,
15401 _: &zed_actions::workspace::CopyPath,
15402 _window: &mut Window,
15403 cx: &mut Context<Self>,
15404 ) {
15405 if let Some(path) = self.target_file_abs_path(cx) {
15406 if let Some(path) = path.to_str() {
15407 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15408 }
15409 }
15410 }
15411
15412 pub fn copy_relative_path(
15413 &mut self,
15414 _: &zed_actions::workspace::CopyRelativePath,
15415 _window: &mut Window,
15416 cx: &mut Context<Self>,
15417 ) {
15418 if let Some(path) = self.target_file_path(cx) {
15419 if let Some(path) = path.to_str() {
15420 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15421 }
15422 }
15423 }
15424
15425 pub fn project_path(&self, cx: &mut Context<Self>) -> Option<ProjectPath> {
15426 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15427 buffer.read_with(cx, |buffer, cx| buffer.project_path(cx))
15428 } else {
15429 None
15430 }
15431 }
15432
15433 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15434 let _ = maybe!({
15435 let breakpoint_store = self.breakpoint_store.as_ref()?;
15436
15437 let Some((_, _, active_position)) =
15438 breakpoint_store.read(cx).active_position().cloned()
15439 else {
15440 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15441 return None;
15442 };
15443
15444 let snapshot = self
15445 .project
15446 .as_ref()?
15447 .read(cx)
15448 .buffer_for_id(active_position.buffer_id?, cx)?
15449 .read(cx)
15450 .snapshot();
15451
15452 for (id, ExcerptRange { context, .. }) in self
15453 .buffer
15454 .read(cx)
15455 .excerpts_for_buffer(active_position.buffer_id?, cx)
15456 {
15457 if context.start.cmp(&active_position, &snapshot).is_ge()
15458 || context.end.cmp(&active_position, &snapshot).is_lt()
15459 {
15460 continue;
15461 }
15462 let snapshot = self.buffer.read(cx).snapshot(cx);
15463 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15464
15465 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15466 self.go_to_line::<DebugCurrentRowHighlight>(
15467 multibuffer_anchor,
15468 Some(cx.theme().colors().editor_debugger_active_line_background),
15469 window,
15470 cx,
15471 );
15472
15473 cx.notify();
15474 }
15475
15476 Some(())
15477 });
15478 }
15479
15480 pub fn copy_file_name_without_extension(
15481 &mut self,
15482 _: &CopyFileNameWithoutExtension,
15483 _: &mut Window,
15484 cx: &mut Context<Self>,
15485 ) {
15486 if let Some(file) = self.target_file(cx) {
15487 if let Some(file_stem) = file.path().file_stem() {
15488 if let Some(name) = file_stem.to_str() {
15489 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15490 }
15491 }
15492 }
15493 }
15494
15495 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15496 if let Some(file) = self.target_file(cx) {
15497 if let Some(file_name) = file.path().file_name() {
15498 if let Some(name) = file_name.to_str() {
15499 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15500 }
15501 }
15502 }
15503 }
15504
15505 pub fn toggle_git_blame(
15506 &mut self,
15507 _: &::git::Blame,
15508 window: &mut Window,
15509 cx: &mut Context<Self>,
15510 ) {
15511 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15512
15513 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15514 self.start_git_blame(true, window, cx);
15515 }
15516
15517 cx.notify();
15518 }
15519
15520 pub fn toggle_git_blame_inline(
15521 &mut self,
15522 _: &ToggleGitBlameInline,
15523 window: &mut Window,
15524 cx: &mut Context<Self>,
15525 ) {
15526 self.toggle_git_blame_inline_internal(true, window, cx);
15527 cx.notify();
15528 }
15529
15530 pub fn git_blame_inline_enabled(&self) -> bool {
15531 self.git_blame_inline_enabled
15532 }
15533
15534 pub fn toggle_selection_menu(
15535 &mut self,
15536 _: &ToggleSelectionMenu,
15537 _: &mut Window,
15538 cx: &mut Context<Self>,
15539 ) {
15540 self.show_selection_menu = self
15541 .show_selection_menu
15542 .map(|show_selections_menu| !show_selections_menu)
15543 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15544
15545 cx.notify();
15546 }
15547
15548 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15549 self.show_selection_menu
15550 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15551 }
15552
15553 fn start_git_blame(
15554 &mut self,
15555 user_triggered: bool,
15556 window: &mut Window,
15557 cx: &mut Context<Self>,
15558 ) {
15559 if let Some(project) = self.project.as_ref() {
15560 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15561 return;
15562 };
15563
15564 if buffer.read(cx).file().is_none() {
15565 return;
15566 }
15567
15568 let focused = self.focus_handle(cx).contains_focused(window, cx);
15569
15570 let project = project.clone();
15571 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15572 self.blame_subscription =
15573 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15574 self.blame = Some(blame);
15575 }
15576 }
15577
15578 fn toggle_git_blame_inline_internal(
15579 &mut self,
15580 user_triggered: bool,
15581 window: &mut Window,
15582 cx: &mut Context<Self>,
15583 ) {
15584 if self.git_blame_inline_enabled {
15585 self.git_blame_inline_enabled = false;
15586 self.show_git_blame_inline = false;
15587 self.show_git_blame_inline_delay_task.take();
15588 } else {
15589 self.git_blame_inline_enabled = true;
15590 self.start_git_blame_inline(user_triggered, window, cx);
15591 }
15592
15593 cx.notify();
15594 }
15595
15596 fn start_git_blame_inline(
15597 &mut self,
15598 user_triggered: bool,
15599 window: &mut Window,
15600 cx: &mut Context<Self>,
15601 ) {
15602 self.start_git_blame(user_triggered, window, cx);
15603
15604 if ProjectSettings::get_global(cx)
15605 .git
15606 .inline_blame_delay()
15607 .is_some()
15608 {
15609 self.start_inline_blame_timer(window, cx);
15610 } else {
15611 self.show_git_blame_inline = true
15612 }
15613 }
15614
15615 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15616 self.blame.as_ref()
15617 }
15618
15619 pub fn show_git_blame_gutter(&self) -> bool {
15620 self.show_git_blame_gutter
15621 }
15622
15623 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15624 self.show_git_blame_gutter && self.has_blame_entries(cx)
15625 }
15626
15627 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15628 self.show_git_blame_inline
15629 && (self.focus_handle.is_focused(window)
15630 || self
15631 .git_blame_inline_tooltip
15632 .as_ref()
15633 .and_then(|t| t.upgrade())
15634 .is_some())
15635 && !self.newest_selection_head_on_empty_line(cx)
15636 && self.has_blame_entries(cx)
15637 }
15638
15639 fn has_blame_entries(&self, cx: &App) -> bool {
15640 self.blame()
15641 .map_or(false, |blame| blame.read(cx).has_generated_entries())
15642 }
15643
15644 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15645 let cursor_anchor = self.selections.newest_anchor().head();
15646
15647 let snapshot = self.buffer.read(cx).snapshot(cx);
15648 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15649
15650 snapshot.line_len(buffer_row) == 0
15651 }
15652
15653 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15654 let buffer_and_selection = maybe!({
15655 let selection = self.selections.newest::<Point>(cx);
15656 let selection_range = selection.range();
15657
15658 let multi_buffer = self.buffer().read(cx);
15659 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15660 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15661
15662 let (buffer, range, _) = if selection.reversed {
15663 buffer_ranges.first()
15664 } else {
15665 buffer_ranges.last()
15666 }?;
15667
15668 let selection = text::ToPoint::to_point(&range.start, &buffer).row
15669 ..text::ToPoint::to_point(&range.end, &buffer).row;
15670 Some((
15671 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15672 selection,
15673 ))
15674 });
15675
15676 let Some((buffer, selection)) = buffer_and_selection else {
15677 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15678 };
15679
15680 let Some(project) = self.project.as_ref() else {
15681 return Task::ready(Err(anyhow!("editor does not have project")));
15682 };
15683
15684 project.update(cx, |project, cx| {
15685 project.get_permalink_to_line(&buffer, selection, cx)
15686 })
15687 }
15688
15689 pub fn copy_permalink_to_line(
15690 &mut self,
15691 _: &CopyPermalinkToLine,
15692 window: &mut Window,
15693 cx: &mut Context<Self>,
15694 ) {
15695 let permalink_task = self.get_permalink_to_line(cx);
15696 let workspace = self.workspace();
15697
15698 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15699 Ok(permalink) => {
15700 cx.update(|_, cx| {
15701 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15702 })
15703 .ok();
15704 }
15705 Err(err) => {
15706 let message = format!("Failed to copy permalink: {err}");
15707
15708 Err::<(), anyhow::Error>(err).log_err();
15709
15710 if let Some(workspace) = workspace {
15711 workspace
15712 .update_in(cx, |workspace, _, cx| {
15713 struct CopyPermalinkToLine;
15714
15715 workspace.show_toast(
15716 Toast::new(
15717 NotificationId::unique::<CopyPermalinkToLine>(),
15718 message,
15719 ),
15720 cx,
15721 )
15722 })
15723 .ok();
15724 }
15725 }
15726 })
15727 .detach();
15728 }
15729
15730 pub fn copy_file_location(
15731 &mut self,
15732 _: &CopyFileLocation,
15733 _: &mut Window,
15734 cx: &mut Context<Self>,
15735 ) {
15736 let selection = self.selections.newest::<Point>(cx).start.row + 1;
15737 if let Some(file) = self.target_file(cx) {
15738 if let Some(path) = file.path().to_str() {
15739 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15740 }
15741 }
15742 }
15743
15744 pub fn open_permalink_to_line(
15745 &mut self,
15746 _: &OpenPermalinkToLine,
15747 window: &mut Window,
15748 cx: &mut Context<Self>,
15749 ) {
15750 let permalink_task = self.get_permalink_to_line(cx);
15751 let workspace = self.workspace();
15752
15753 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15754 Ok(permalink) => {
15755 cx.update(|_, cx| {
15756 cx.open_url(permalink.as_ref());
15757 })
15758 .ok();
15759 }
15760 Err(err) => {
15761 let message = format!("Failed to open permalink: {err}");
15762
15763 Err::<(), anyhow::Error>(err).log_err();
15764
15765 if let Some(workspace) = workspace {
15766 workspace
15767 .update(cx, |workspace, cx| {
15768 struct OpenPermalinkToLine;
15769
15770 workspace.show_toast(
15771 Toast::new(
15772 NotificationId::unique::<OpenPermalinkToLine>(),
15773 message,
15774 ),
15775 cx,
15776 )
15777 })
15778 .ok();
15779 }
15780 }
15781 })
15782 .detach();
15783 }
15784
15785 pub fn insert_uuid_v4(
15786 &mut self,
15787 _: &InsertUuidV4,
15788 window: &mut Window,
15789 cx: &mut Context<Self>,
15790 ) {
15791 self.insert_uuid(UuidVersion::V4, window, cx);
15792 }
15793
15794 pub fn insert_uuid_v7(
15795 &mut self,
15796 _: &InsertUuidV7,
15797 window: &mut Window,
15798 cx: &mut Context<Self>,
15799 ) {
15800 self.insert_uuid(UuidVersion::V7, window, cx);
15801 }
15802
15803 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15804 self.transact(window, cx, |this, window, cx| {
15805 let edits = this
15806 .selections
15807 .all::<Point>(cx)
15808 .into_iter()
15809 .map(|selection| {
15810 let uuid = match version {
15811 UuidVersion::V4 => uuid::Uuid::new_v4(),
15812 UuidVersion::V7 => uuid::Uuid::now_v7(),
15813 };
15814
15815 (selection.range(), uuid.to_string())
15816 });
15817 this.edit(edits, cx);
15818 this.refresh_inline_completion(true, false, window, cx);
15819 });
15820 }
15821
15822 pub fn open_selections_in_multibuffer(
15823 &mut self,
15824 _: &OpenSelectionsInMultibuffer,
15825 window: &mut Window,
15826 cx: &mut Context<Self>,
15827 ) {
15828 let multibuffer = self.buffer.read(cx);
15829
15830 let Some(buffer) = multibuffer.as_singleton() else {
15831 return;
15832 };
15833
15834 let Some(workspace) = self.workspace() else {
15835 return;
15836 };
15837
15838 let locations = self
15839 .selections
15840 .disjoint_anchors()
15841 .iter()
15842 .map(|range| Location {
15843 buffer: buffer.clone(),
15844 range: range.start.text_anchor..range.end.text_anchor,
15845 })
15846 .collect::<Vec<_>>();
15847
15848 let title = multibuffer.title(cx).to_string();
15849
15850 cx.spawn_in(window, async move |_, cx| {
15851 workspace.update_in(cx, |workspace, window, cx| {
15852 Self::open_locations_in_multibuffer(
15853 workspace,
15854 locations,
15855 format!("Selections for '{title}'"),
15856 false,
15857 MultibufferSelectionMode::All,
15858 window,
15859 cx,
15860 );
15861 })
15862 })
15863 .detach();
15864 }
15865
15866 /// Adds a row highlight for the given range. If a row has multiple highlights, the
15867 /// last highlight added will be used.
15868 ///
15869 /// If the range ends at the beginning of a line, then that line will not be highlighted.
15870 pub fn highlight_rows<T: 'static>(
15871 &mut self,
15872 range: Range<Anchor>,
15873 color: Hsla,
15874 should_autoscroll: bool,
15875 cx: &mut Context<Self>,
15876 ) {
15877 let snapshot = self.buffer().read(cx).snapshot(cx);
15878 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15879 let ix = row_highlights.binary_search_by(|highlight| {
15880 Ordering::Equal
15881 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15882 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15883 });
15884
15885 if let Err(mut ix) = ix {
15886 let index = post_inc(&mut self.highlight_order);
15887
15888 // If this range intersects with the preceding highlight, then merge it with
15889 // the preceding highlight. Otherwise insert a new highlight.
15890 let mut merged = false;
15891 if ix > 0 {
15892 let prev_highlight = &mut row_highlights[ix - 1];
15893 if prev_highlight
15894 .range
15895 .end
15896 .cmp(&range.start, &snapshot)
15897 .is_ge()
15898 {
15899 ix -= 1;
15900 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15901 prev_highlight.range.end = range.end;
15902 }
15903 merged = true;
15904 prev_highlight.index = index;
15905 prev_highlight.color = color;
15906 prev_highlight.should_autoscroll = should_autoscroll;
15907 }
15908 }
15909
15910 if !merged {
15911 row_highlights.insert(
15912 ix,
15913 RowHighlight {
15914 range: range.clone(),
15915 index,
15916 color,
15917 should_autoscroll,
15918 },
15919 );
15920 }
15921
15922 // If any of the following highlights intersect with this one, merge them.
15923 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15924 let highlight = &row_highlights[ix];
15925 if next_highlight
15926 .range
15927 .start
15928 .cmp(&highlight.range.end, &snapshot)
15929 .is_le()
15930 {
15931 if next_highlight
15932 .range
15933 .end
15934 .cmp(&highlight.range.end, &snapshot)
15935 .is_gt()
15936 {
15937 row_highlights[ix].range.end = next_highlight.range.end;
15938 }
15939 row_highlights.remove(ix + 1);
15940 } else {
15941 break;
15942 }
15943 }
15944 }
15945 }
15946
15947 /// Remove any highlighted row ranges of the given type that intersect the
15948 /// given ranges.
15949 pub fn remove_highlighted_rows<T: 'static>(
15950 &mut self,
15951 ranges_to_remove: Vec<Range<Anchor>>,
15952 cx: &mut Context<Self>,
15953 ) {
15954 let snapshot = self.buffer().read(cx).snapshot(cx);
15955 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15956 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15957 row_highlights.retain(|highlight| {
15958 while let Some(range_to_remove) = ranges_to_remove.peek() {
15959 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15960 Ordering::Less | Ordering::Equal => {
15961 ranges_to_remove.next();
15962 }
15963 Ordering::Greater => {
15964 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15965 Ordering::Less | Ordering::Equal => {
15966 return false;
15967 }
15968 Ordering::Greater => break,
15969 }
15970 }
15971 }
15972 }
15973
15974 true
15975 })
15976 }
15977
15978 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15979 pub fn clear_row_highlights<T: 'static>(&mut self) {
15980 self.highlighted_rows.remove(&TypeId::of::<T>());
15981 }
15982
15983 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15984 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15985 self.highlighted_rows
15986 .get(&TypeId::of::<T>())
15987 .map_or(&[] as &[_], |vec| vec.as_slice())
15988 .iter()
15989 .map(|highlight| (highlight.range.clone(), highlight.color))
15990 }
15991
15992 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15993 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15994 /// Allows to ignore certain kinds of highlights.
15995 pub fn highlighted_display_rows(
15996 &self,
15997 window: &mut Window,
15998 cx: &mut App,
15999 ) -> BTreeMap<DisplayRow, LineHighlight> {
16000 let snapshot = self.snapshot(window, cx);
16001 let mut used_highlight_orders = HashMap::default();
16002 self.highlighted_rows
16003 .iter()
16004 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16005 .fold(
16006 BTreeMap::<DisplayRow, LineHighlight>::new(),
16007 |mut unique_rows, highlight| {
16008 let start = highlight.range.start.to_display_point(&snapshot);
16009 let end = highlight.range.end.to_display_point(&snapshot);
16010 let start_row = start.row().0;
16011 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16012 && end.column() == 0
16013 {
16014 end.row().0.saturating_sub(1)
16015 } else {
16016 end.row().0
16017 };
16018 for row in start_row..=end_row {
16019 let used_index =
16020 used_highlight_orders.entry(row).or_insert(highlight.index);
16021 if highlight.index >= *used_index {
16022 *used_index = highlight.index;
16023 unique_rows.insert(DisplayRow(row), highlight.color.into());
16024 }
16025 }
16026 unique_rows
16027 },
16028 )
16029 }
16030
16031 pub fn highlighted_display_row_for_autoscroll(
16032 &self,
16033 snapshot: &DisplaySnapshot,
16034 ) -> Option<DisplayRow> {
16035 self.highlighted_rows
16036 .values()
16037 .flat_map(|highlighted_rows| highlighted_rows.iter())
16038 .filter_map(|highlight| {
16039 if highlight.should_autoscroll {
16040 Some(highlight.range.start.to_display_point(snapshot).row())
16041 } else {
16042 None
16043 }
16044 })
16045 .min()
16046 }
16047
16048 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16049 self.highlight_background::<SearchWithinRange>(
16050 ranges,
16051 |colors| colors.editor_document_highlight_read_background,
16052 cx,
16053 )
16054 }
16055
16056 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16057 self.breadcrumb_header = Some(new_header);
16058 }
16059
16060 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16061 self.clear_background_highlights::<SearchWithinRange>(cx);
16062 }
16063
16064 pub fn highlight_background<T: 'static>(
16065 &mut self,
16066 ranges: &[Range<Anchor>],
16067 color_fetcher: fn(&ThemeColors) -> Hsla,
16068 cx: &mut Context<Self>,
16069 ) {
16070 self.background_highlights
16071 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16072 self.scrollbar_marker_state.dirty = true;
16073 cx.notify();
16074 }
16075
16076 pub fn clear_background_highlights<T: 'static>(
16077 &mut self,
16078 cx: &mut Context<Self>,
16079 ) -> Option<BackgroundHighlight> {
16080 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16081 if !text_highlights.1.is_empty() {
16082 self.scrollbar_marker_state.dirty = true;
16083 cx.notify();
16084 }
16085 Some(text_highlights)
16086 }
16087
16088 pub fn highlight_gutter<T: 'static>(
16089 &mut self,
16090 ranges: &[Range<Anchor>],
16091 color_fetcher: fn(&App) -> Hsla,
16092 cx: &mut Context<Self>,
16093 ) {
16094 self.gutter_highlights
16095 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16096 cx.notify();
16097 }
16098
16099 pub fn clear_gutter_highlights<T: 'static>(
16100 &mut self,
16101 cx: &mut Context<Self>,
16102 ) -> Option<GutterHighlight> {
16103 cx.notify();
16104 self.gutter_highlights.remove(&TypeId::of::<T>())
16105 }
16106
16107 #[cfg(feature = "test-support")]
16108 pub fn all_text_background_highlights(
16109 &self,
16110 window: &mut Window,
16111 cx: &mut Context<Self>,
16112 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16113 let snapshot = self.snapshot(window, cx);
16114 let buffer = &snapshot.buffer_snapshot;
16115 let start = buffer.anchor_before(0);
16116 let end = buffer.anchor_after(buffer.len());
16117 let theme = cx.theme().colors();
16118 self.background_highlights_in_range(start..end, &snapshot, theme)
16119 }
16120
16121 #[cfg(feature = "test-support")]
16122 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16123 let snapshot = self.buffer().read(cx).snapshot(cx);
16124
16125 let highlights = self
16126 .background_highlights
16127 .get(&TypeId::of::<items::BufferSearchHighlights>());
16128
16129 if let Some((_color, ranges)) = highlights {
16130 ranges
16131 .iter()
16132 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16133 .collect_vec()
16134 } else {
16135 vec![]
16136 }
16137 }
16138
16139 fn document_highlights_for_position<'a>(
16140 &'a self,
16141 position: Anchor,
16142 buffer: &'a MultiBufferSnapshot,
16143 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16144 let read_highlights = self
16145 .background_highlights
16146 .get(&TypeId::of::<DocumentHighlightRead>())
16147 .map(|h| &h.1);
16148 let write_highlights = self
16149 .background_highlights
16150 .get(&TypeId::of::<DocumentHighlightWrite>())
16151 .map(|h| &h.1);
16152 let left_position = position.bias_left(buffer);
16153 let right_position = position.bias_right(buffer);
16154 read_highlights
16155 .into_iter()
16156 .chain(write_highlights)
16157 .flat_map(move |ranges| {
16158 let start_ix = match ranges.binary_search_by(|probe| {
16159 let cmp = probe.end.cmp(&left_position, buffer);
16160 if cmp.is_ge() {
16161 Ordering::Greater
16162 } else {
16163 Ordering::Less
16164 }
16165 }) {
16166 Ok(i) | Err(i) => i,
16167 };
16168
16169 ranges[start_ix..]
16170 .iter()
16171 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16172 })
16173 }
16174
16175 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16176 self.background_highlights
16177 .get(&TypeId::of::<T>())
16178 .map_or(false, |(_, highlights)| !highlights.is_empty())
16179 }
16180
16181 pub fn background_highlights_in_range(
16182 &self,
16183 search_range: Range<Anchor>,
16184 display_snapshot: &DisplaySnapshot,
16185 theme: &ThemeColors,
16186 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16187 let mut results = Vec::new();
16188 for (color_fetcher, ranges) in self.background_highlights.values() {
16189 let color = color_fetcher(theme);
16190 let start_ix = match ranges.binary_search_by(|probe| {
16191 let cmp = probe
16192 .end
16193 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16194 if cmp.is_gt() {
16195 Ordering::Greater
16196 } else {
16197 Ordering::Less
16198 }
16199 }) {
16200 Ok(i) | Err(i) => i,
16201 };
16202 for range in &ranges[start_ix..] {
16203 if range
16204 .start
16205 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16206 .is_ge()
16207 {
16208 break;
16209 }
16210
16211 let start = range.start.to_display_point(display_snapshot);
16212 let end = range.end.to_display_point(display_snapshot);
16213 results.push((start..end, color))
16214 }
16215 }
16216 results
16217 }
16218
16219 pub fn background_highlight_row_ranges<T: 'static>(
16220 &self,
16221 search_range: Range<Anchor>,
16222 display_snapshot: &DisplaySnapshot,
16223 count: usize,
16224 ) -> Vec<RangeInclusive<DisplayPoint>> {
16225 let mut results = Vec::new();
16226 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16227 return vec![];
16228 };
16229
16230 let start_ix = match ranges.binary_search_by(|probe| {
16231 let cmp = probe
16232 .end
16233 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16234 if cmp.is_gt() {
16235 Ordering::Greater
16236 } else {
16237 Ordering::Less
16238 }
16239 }) {
16240 Ok(i) | Err(i) => i,
16241 };
16242 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16243 if let (Some(start_display), Some(end_display)) = (start, end) {
16244 results.push(
16245 start_display.to_display_point(display_snapshot)
16246 ..=end_display.to_display_point(display_snapshot),
16247 );
16248 }
16249 };
16250 let mut start_row: Option<Point> = None;
16251 let mut end_row: Option<Point> = None;
16252 if ranges.len() > count {
16253 return Vec::new();
16254 }
16255 for range in &ranges[start_ix..] {
16256 if range
16257 .start
16258 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16259 .is_ge()
16260 {
16261 break;
16262 }
16263 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16264 if let Some(current_row) = &end_row {
16265 if end.row == current_row.row {
16266 continue;
16267 }
16268 }
16269 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16270 if start_row.is_none() {
16271 assert_eq!(end_row, None);
16272 start_row = Some(start);
16273 end_row = Some(end);
16274 continue;
16275 }
16276 if let Some(current_end) = end_row.as_mut() {
16277 if start.row > current_end.row + 1 {
16278 push_region(start_row, end_row);
16279 start_row = Some(start);
16280 end_row = Some(end);
16281 } else {
16282 // Merge two hunks.
16283 *current_end = end;
16284 }
16285 } else {
16286 unreachable!();
16287 }
16288 }
16289 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16290 push_region(start_row, end_row);
16291 results
16292 }
16293
16294 pub fn gutter_highlights_in_range(
16295 &self,
16296 search_range: Range<Anchor>,
16297 display_snapshot: &DisplaySnapshot,
16298 cx: &App,
16299 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16300 let mut results = Vec::new();
16301 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16302 let color = color_fetcher(cx);
16303 let start_ix = match ranges.binary_search_by(|probe| {
16304 let cmp = probe
16305 .end
16306 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16307 if cmp.is_gt() {
16308 Ordering::Greater
16309 } else {
16310 Ordering::Less
16311 }
16312 }) {
16313 Ok(i) | Err(i) => i,
16314 };
16315 for range in &ranges[start_ix..] {
16316 if range
16317 .start
16318 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16319 .is_ge()
16320 {
16321 break;
16322 }
16323
16324 let start = range.start.to_display_point(display_snapshot);
16325 let end = range.end.to_display_point(display_snapshot);
16326 results.push((start..end, color))
16327 }
16328 }
16329 results
16330 }
16331
16332 /// Get the text ranges corresponding to the redaction query
16333 pub fn redacted_ranges(
16334 &self,
16335 search_range: Range<Anchor>,
16336 display_snapshot: &DisplaySnapshot,
16337 cx: &App,
16338 ) -> Vec<Range<DisplayPoint>> {
16339 display_snapshot
16340 .buffer_snapshot
16341 .redacted_ranges(search_range, |file| {
16342 if let Some(file) = file {
16343 file.is_private()
16344 && EditorSettings::get(
16345 Some(SettingsLocation {
16346 worktree_id: file.worktree_id(cx),
16347 path: file.path().as_ref(),
16348 }),
16349 cx,
16350 )
16351 .redact_private_values
16352 } else {
16353 false
16354 }
16355 })
16356 .map(|range| {
16357 range.start.to_display_point(display_snapshot)
16358 ..range.end.to_display_point(display_snapshot)
16359 })
16360 .collect()
16361 }
16362
16363 pub fn highlight_text<T: 'static>(
16364 &mut self,
16365 ranges: Vec<Range<Anchor>>,
16366 style: HighlightStyle,
16367 cx: &mut Context<Self>,
16368 ) {
16369 self.display_map.update(cx, |map, _| {
16370 map.highlight_text(TypeId::of::<T>(), ranges, style)
16371 });
16372 cx.notify();
16373 }
16374
16375 pub(crate) fn highlight_inlays<T: 'static>(
16376 &mut self,
16377 highlights: Vec<InlayHighlight>,
16378 style: HighlightStyle,
16379 cx: &mut Context<Self>,
16380 ) {
16381 self.display_map.update(cx, |map, _| {
16382 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16383 });
16384 cx.notify();
16385 }
16386
16387 pub fn text_highlights<'a, T: 'static>(
16388 &'a self,
16389 cx: &'a App,
16390 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16391 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16392 }
16393
16394 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16395 let cleared = self
16396 .display_map
16397 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16398 if cleared {
16399 cx.notify();
16400 }
16401 }
16402
16403 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16404 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16405 && self.focus_handle.is_focused(window)
16406 }
16407
16408 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16409 self.show_cursor_when_unfocused = is_enabled;
16410 cx.notify();
16411 }
16412
16413 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16414 cx.notify();
16415 }
16416
16417 fn on_buffer_event(
16418 &mut self,
16419 multibuffer: &Entity<MultiBuffer>,
16420 event: &multi_buffer::Event,
16421 window: &mut Window,
16422 cx: &mut Context<Self>,
16423 ) {
16424 match event {
16425 multi_buffer::Event::Edited {
16426 singleton_buffer_edited,
16427 edited_buffer: buffer_edited,
16428 } => {
16429 self.scrollbar_marker_state.dirty = true;
16430 self.active_indent_guides_state.dirty = true;
16431 self.refresh_active_diagnostics(cx);
16432 self.refresh_code_actions(window, cx);
16433 if self.has_active_inline_completion() {
16434 self.update_visible_inline_completion(window, cx);
16435 }
16436 if let Some(buffer) = buffer_edited {
16437 let buffer_id = buffer.read(cx).remote_id();
16438 if !self.registered_buffers.contains_key(&buffer_id) {
16439 if let Some(project) = self.project.as_ref() {
16440 project.update(cx, |project, cx| {
16441 self.registered_buffers.insert(
16442 buffer_id,
16443 project.register_buffer_with_language_servers(&buffer, cx),
16444 );
16445 })
16446 }
16447 }
16448 }
16449 cx.emit(EditorEvent::BufferEdited);
16450 cx.emit(SearchEvent::MatchesInvalidated);
16451 if *singleton_buffer_edited {
16452 if let Some(project) = &self.project {
16453 #[allow(clippy::mutable_key_type)]
16454 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16455 multibuffer
16456 .all_buffers()
16457 .into_iter()
16458 .filter_map(|buffer| {
16459 buffer.update(cx, |buffer, cx| {
16460 let language = buffer.language()?;
16461 let should_discard = project.update(cx, |project, cx| {
16462 project.is_local()
16463 && !project.has_language_servers_for(buffer, cx)
16464 });
16465 should_discard.not().then_some(language.clone())
16466 })
16467 })
16468 .collect::<HashSet<_>>()
16469 });
16470 if !languages_affected.is_empty() {
16471 self.refresh_inlay_hints(
16472 InlayHintRefreshReason::BufferEdited(languages_affected),
16473 cx,
16474 );
16475 }
16476 }
16477 }
16478
16479 let Some(project) = &self.project else { return };
16480 let (telemetry, is_via_ssh) = {
16481 let project = project.read(cx);
16482 let telemetry = project.client().telemetry().clone();
16483 let is_via_ssh = project.is_via_ssh();
16484 (telemetry, is_via_ssh)
16485 };
16486 refresh_linked_ranges(self, window, cx);
16487 telemetry.log_edit_event("editor", is_via_ssh);
16488 }
16489 multi_buffer::Event::ExcerptsAdded {
16490 buffer,
16491 predecessor,
16492 excerpts,
16493 } => {
16494 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16495 let buffer_id = buffer.read(cx).remote_id();
16496 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16497 if let Some(project) = &self.project {
16498 get_uncommitted_diff_for_buffer(
16499 project,
16500 [buffer.clone()],
16501 self.buffer.clone(),
16502 cx,
16503 )
16504 .detach();
16505 }
16506 }
16507 cx.emit(EditorEvent::ExcerptsAdded {
16508 buffer: buffer.clone(),
16509 predecessor: *predecessor,
16510 excerpts: excerpts.clone(),
16511 });
16512 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16513 }
16514 multi_buffer::Event::ExcerptsRemoved { ids } => {
16515 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16516 let buffer = self.buffer.read(cx);
16517 self.registered_buffers
16518 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16519 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16520 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16521 }
16522 multi_buffer::Event::ExcerptsEdited {
16523 excerpt_ids,
16524 buffer_ids,
16525 } => {
16526 self.display_map.update(cx, |map, cx| {
16527 map.unfold_buffers(buffer_ids.iter().copied(), cx)
16528 });
16529 cx.emit(EditorEvent::ExcerptsEdited {
16530 ids: excerpt_ids.clone(),
16531 })
16532 }
16533 multi_buffer::Event::ExcerptsExpanded { ids } => {
16534 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16535 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16536 }
16537 multi_buffer::Event::Reparsed(buffer_id) => {
16538 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16539 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16540
16541 cx.emit(EditorEvent::Reparsed(*buffer_id));
16542 }
16543 multi_buffer::Event::DiffHunksToggled => {
16544 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16545 }
16546 multi_buffer::Event::LanguageChanged(buffer_id) => {
16547 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16548 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16549 cx.emit(EditorEvent::Reparsed(*buffer_id));
16550 cx.notify();
16551 }
16552 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16553 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16554 multi_buffer::Event::FileHandleChanged
16555 | multi_buffer::Event::Reloaded
16556 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16557 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16558 multi_buffer::Event::DiagnosticsUpdated => {
16559 self.refresh_active_diagnostics(cx);
16560 self.refresh_inline_diagnostics(true, window, cx);
16561 self.scrollbar_marker_state.dirty = true;
16562 cx.notify();
16563 }
16564 _ => {}
16565 };
16566 }
16567
16568 fn on_display_map_changed(
16569 &mut self,
16570 _: Entity<DisplayMap>,
16571 _: &mut Window,
16572 cx: &mut Context<Self>,
16573 ) {
16574 cx.notify();
16575 }
16576
16577 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16578 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16579 self.update_edit_prediction_settings(cx);
16580 self.refresh_inline_completion(true, false, window, cx);
16581 self.refresh_inlay_hints(
16582 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16583 self.selections.newest_anchor().head(),
16584 &self.buffer.read(cx).snapshot(cx),
16585 cx,
16586 )),
16587 cx,
16588 );
16589
16590 let old_cursor_shape = self.cursor_shape;
16591
16592 {
16593 let editor_settings = EditorSettings::get_global(cx);
16594 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16595 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16596 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16597 }
16598
16599 if old_cursor_shape != self.cursor_shape {
16600 cx.emit(EditorEvent::CursorShapeChanged);
16601 }
16602
16603 let project_settings = ProjectSettings::get_global(cx);
16604 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16605
16606 if self.mode == EditorMode::Full {
16607 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16608 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16609 if self.show_inline_diagnostics != show_inline_diagnostics {
16610 self.show_inline_diagnostics = show_inline_diagnostics;
16611 self.refresh_inline_diagnostics(false, window, cx);
16612 }
16613
16614 if self.git_blame_inline_enabled != inline_blame_enabled {
16615 self.toggle_git_blame_inline_internal(false, window, cx);
16616 }
16617 }
16618
16619 cx.notify();
16620 }
16621
16622 pub fn set_searchable(&mut self, searchable: bool) {
16623 self.searchable = searchable;
16624 }
16625
16626 pub fn searchable(&self) -> bool {
16627 self.searchable
16628 }
16629
16630 fn open_proposed_changes_editor(
16631 &mut self,
16632 _: &OpenProposedChangesEditor,
16633 window: &mut Window,
16634 cx: &mut Context<Self>,
16635 ) {
16636 let Some(workspace) = self.workspace() else {
16637 cx.propagate();
16638 return;
16639 };
16640
16641 let selections = self.selections.all::<usize>(cx);
16642 let multi_buffer = self.buffer.read(cx);
16643 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16644 let mut new_selections_by_buffer = HashMap::default();
16645 for selection in selections {
16646 for (buffer, range, _) in
16647 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16648 {
16649 let mut range = range.to_point(buffer);
16650 range.start.column = 0;
16651 range.end.column = buffer.line_len(range.end.row);
16652 new_selections_by_buffer
16653 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16654 .or_insert(Vec::new())
16655 .push(range)
16656 }
16657 }
16658
16659 let proposed_changes_buffers = new_selections_by_buffer
16660 .into_iter()
16661 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16662 .collect::<Vec<_>>();
16663 let proposed_changes_editor = cx.new(|cx| {
16664 ProposedChangesEditor::new(
16665 "Proposed changes",
16666 proposed_changes_buffers,
16667 self.project.clone(),
16668 window,
16669 cx,
16670 )
16671 });
16672
16673 window.defer(cx, move |window, cx| {
16674 workspace.update(cx, |workspace, cx| {
16675 workspace.active_pane().update(cx, |pane, cx| {
16676 pane.add_item(
16677 Box::new(proposed_changes_editor),
16678 true,
16679 true,
16680 None,
16681 window,
16682 cx,
16683 );
16684 });
16685 });
16686 });
16687 }
16688
16689 pub fn open_excerpts_in_split(
16690 &mut self,
16691 _: &OpenExcerptsSplit,
16692 window: &mut Window,
16693 cx: &mut Context<Self>,
16694 ) {
16695 self.open_excerpts_common(None, true, window, cx)
16696 }
16697
16698 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16699 self.open_excerpts_common(None, false, window, cx)
16700 }
16701
16702 fn open_excerpts_common(
16703 &mut self,
16704 jump_data: Option<JumpData>,
16705 split: bool,
16706 window: &mut Window,
16707 cx: &mut Context<Self>,
16708 ) {
16709 let Some(workspace) = self.workspace() else {
16710 cx.propagate();
16711 return;
16712 };
16713
16714 if self.buffer.read(cx).is_singleton() {
16715 cx.propagate();
16716 return;
16717 }
16718
16719 let mut new_selections_by_buffer = HashMap::default();
16720 match &jump_data {
16721 Some(JumpData::MultiBufferPoint {
16722 excerpt_id,
16723 position,
16724 anchor,
16725 line_offset_from_top,
16726 }) => {
16727 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16728 if let Some(buffer) = multi_buffer_snapshot
16729 .buffer_id_for_excerpt(*excerpt_id)
16730 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16731 {
16732 let buffer_snapshot = buffer.read(cx).snapshot();
16733 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16734 language::ToPoint::to_point(anchor, &buffer_snapshot)
16735 } else {
16736 buffer_snapshot.clip_point(*position, Bias::Left)
16737 };
16738 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16739 new_selections_by_buffer.insert(
16740 buffer,
16741 (
16742 vec![jump_to_offset..jump_to_offset],
16743 Some(*line_offset_from_top),
16744 ),
16745 );
16746 }
16747 }
16748 Some(JumpData::MultiBufferRow {
16749 row,
16750 line_offset_from_top,
16751 }) => {
16752 let point = MultiBufferPoint::new(row.0, 0);
16753 if let Some((buffer, buffer_point, _)) =
16754 self.buffer.read(cx).point_to_buffer_point(point, cx)
16755 {
16756 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16757 new_selections_by_buffer
16758 .entry(buffer)
16759 .or_insert((Vec::new(), Some(*line_offset_from_top)))
16760 .0
16761 .push(buffer_offset..buffer_offset)
16762 }
16763 }
16764 None => {
16765 let selections = self.selections.all::<usize>(cx);
16766 let multi_buffer = self.buffer.read(cx);
16767 for selection in selections {
16768 for (snapshot, range, _, anchor) in multi_buffer
16769 .snapshot(cx)
16770 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16771 {
16772 if let Some(anchor) = anchor {
16773 // selection is in a deleted hunk
16774 let Some(buffer_id) = anchor.buffer_id else {
16775 continue;
16776 };
16777 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16778 continue;
16779 };
16780 let offset = text::ToOffset::to_offset(
16781 &anchor.text_anchor,
16782 &buffer_handle.read(cx).snapshot(),
16783 );
16784 let range = offset..offset;
16785 new_selections_by_buffer
16786 .entry(buffer_handle)
16787 .or_insert((Vec::new(), None))
16788 .0
16789 .push(range)
16790 } else {
16791 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16792 else {
16793 continue;
16794 };
16795 new_selections_by_buffer
16796 .entry(buffer_handle)
16797 .or_insert((Vec::new(), None))
16798 .0
16799 .push(range)
16800 }
16801 }
16802 }
16803 }
16804 }
16805
16806 if new_selections_by_buffer.is_empty() {
16807 return;
16808 }
16809
16810 // We defer the pane interaction because we ourselves are a workspace item
16811 // and activating a new item causes the pane to call a method on us reentrantly,
16812 // which panics if we're on the stack.
16813 window.defer(cx, move |window, cx| {
16814 workspace.update(cx, |workspace, cx| {
16815 let pane = if split {
16816 workspace.adjacent_pane(window, cx)
16817 } else {
16818 workspace.active_pane().clone()
16819 };
16820
16821 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16822 let editor = buffer
16823 .read(cx)
16824 .file()
16825 .is_none()
16826 .then(|| {
16827 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16828 // so `workspace.open_project_item` will never find them, always opening a new editor.
16829 // Instead, we try to activate the existing editor in the pane first.
16830 let (editor, pane_item_index) =
16831 pane.read(cx).items().enumerate().find_map(|(i, item)| {
16832 let editor = item.downcast::<Editor>()?;
16833 let singleton_buffer =
16834 editor.read(cx).buffer().read(cx).as_singleton()?;
16835 if singleton_buffer == buffer {
16836 Some((editor, i))
16837 } else {
16838 None
16839 }
16840 })?;
16841 pane.update(cx, |pane, cx| {
16842 pane.activate_item(pane_item_index, true, true, window, cx)
16843 });
16844 Some(editor)
16845 })
16846 .flatten()
16847 .unwrap_or_else(|| {
16848 workspace.open_project_item::<Self>(
16849 pane.clone(),
16850 buffer,
16851 true,
16852 true,
16853 window,
16854 cx,
16855 )
16856 });
16857
16858 editor.update(cx, |editor, cx| {
16859 let autoscroll = match scroll_offset {
16860 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16861 None => Autoscroll::newest(),
16862 };
16863 let nav_history = editor.nav_history.take();
16864 editor.change_selections(Some(autoscroll), window, cx, |s| {
16865 s.select_ranges(ranges);
16866 });
16867 editor.nav_history = nav_history;
16868 });
16869 }
16870 })
16871 });
16872 }
16873
16874 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16875 let snapshot = self.buffer.read(cx).read(cx);
16876 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16877 Some(
16878 ranges
16879 .iter()
16880 .map(move |range| {
16881 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16882 })
16883 .collect(),
16884 )
16885 }
16886
16887 fn selection_replacement_ranges(
16888 &self,
16889 range: Range<OffsetUtf16>,
16890 cx: &mut App,
16891 ) -> Vec<Range<OffsetUtf16>> {
16892 let selections = self.selections.all::<OffsetUtf16>(cx);
16893 let newest_selection = selections
16894 .iter()
16895 .max_by_key(|selection| selection.id)
16896 .unwrap();
16897 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16898 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16899 let snapshot = self.buffer.read(cx).read(cx);
16900 selections
16901 .into_iter()
16902 .map(|mut selection| {
16903 selection.start.0 =
16904 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16905 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16906 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16907 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16908 })
16909 .collect()
16910 }
16911
16912 fn report_editor_event(
16913 &self,
16914 event_type: &'static str,
16915 file_extension: Option<String>,
16916 cx: &App,
16917 ) {
16918 if cfg!(any(test, feature = "test-support")) {
16919 return;
16920 }
16921
16922 let Some(project) = &self.project else { return };
16923
16924 // If None, we are in a file without an extension
16925 let file = self
16926 .buffer
16927 .read(cx)
16928 .as_singleton()
16929 .and_then(|b| b.read(cx).file());
16930 let file_extension = file_extension.or(file
16931 .as_ref()
16932 .and_then(|file| Path::new(file.file_name(cx)).extension())
16933 .and_then(|e| e.to_str())
16934 .map(|a| a.to_string()));
16935
16936 let vim_mode = cx
16937 .global::<SettingsStore>()
16938 .raw_user_settings()
16939 .get("vim_mode")
16940 == Some(&serde_json::Value::Bool(true));
16941
16942 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16943 let copilot_enabled = edit_predictions_provider
16944 == language::language_settings::EditPredictionProvider::Copilot;
16945 let copilot_enabled_for_language = self
16946 .buffer
16947 .read(cx)
16948 .language_settings(cx)
16949 .show_edit_predictions;
16950
16951 let project = project.read(cx);
16952 telemetry::event!(
16953 event_type,
16954 file_extension,
16955 vim_mode,
16956 copilot_enabled,
16957 copilot_enabled_for_language,
16958 edit_predictions_provider,
16959 is_via_ssh = project.is_via_ssh(),
16960 );
16961 }
16962
16963 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16964 /// with each line being an array of {text, highlight} objects.
16965 fn copy_highlight_json(
16966 &mut self,
16967 _: &CopyHighlightJson,
16968 window: &mut Window,
16969 cx: &mut Context<Self>,
16970 ) {
16971 #[derive(Serialize)]
16972 struct Chunk<'a> {
16973 text: String,
16974 highlight: Option<&'a str>,
16975 }
16976
16977 let snapshot = self.buffer.read(cx).snapshot(cx);
16978 let range = self
16979 .selected_text_range(false, window, cx)
16980 .and_then(|selection| {
16981 if selection.range.is_empty() {
16982 None
16983 } else {
16984 Some(selection.range)
16985 }
16986 })
16987 .unwrap_or_else(|| 0..snapshot.len());
16988
16989 let chunks = snapshot.chunks(range, true);
16990 let mut lines = Vec::new();
16991 let mut line: VecDeque<Chunk> = VecDeque::new();
16992
16993 let Some(style) = self.style.as_ref() else {
16994 return;
16995 };
16996
16997 for chunk in chunks {
16998 let highlight = chunk
16999 .syntax_highlight_id
17000 .and_then(|id| id.name(&style.syntax));
17001 let mut chunk_lines = chunk.text.split('\n').peekable();
17002 while let Some(text) = chunk_lines.next() {
17003 let mut merged_with_last_token = false;
17004 if let Some(last_token) = line.back_mut() {
17005 if last_token.highlight == highlight {
17006 last_token.text.push_str(text);
17007 merged_with_last_token = true;
17008 }
17009 }
17010
17011 if !merged_with_last_token {
17012 line.push_back(Chunk {
17013 text: text.into(),
17014 highlight,
17015 });
17016 }
17017
17018 if chunk_lines.peek().is_some() {
17019 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17020 line.pop_front();
17021 }
17022 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17023 line.pop_back();
17024 }
17025
17026 lines.push(mem::take(&mut line));
17027 }
17028 }
17029 }
17030
17031 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17032 return;
17033 };
17034 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17035 }
17036
17037 pub fn open_context_menu(
17038 &mut self,
17039 _: &OpenContextMenu,
17040 window: &mut Window,
17041 cx: &mut Context<Self>,
17042 ) {
17043 self.request_autoscroll(Autoscroll::newest(), cx);
17044 let position = self.selections.newest_display(cx).start;
17045 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17046 }
17047
17048 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17049 &self.inlay_hint_cache
17050 }
17051
17052 pub fn replay_insert_event(
17053 &mut self,
17054 text: &str,
17055 relative_utf16_range: Option<Range<isize>>,
17056 window: &mut Window,
17057 cx: &mut Context<Self>,
17058 ) {
17059 if !self.input_enabled {
17060 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17061 return;
17062 }
17063 if let Some(relative_utf16_range) = relative_utf16_range {
17064 let selections = self.selections.all::<OffsetUtf16>(cx);
17065 self.change_selections(None, window, cx, |s| {
17066 let new_ranges = selections.into_iter().map(|range| {
17067 let start = OffsetUtf16(
17068 range
17069 .head()
17070 .0
17071 .saturating_add_signed(relative_utf16_range.start),
17072 );
17073 let end = OffsetUtf16(
17074 range
17075 .head()
17076 .0
17077 .saturating_add_signed(relative_utf16_range.end),
17078 );
17079 start..end
17080 });
17081 s.select_ranges(new_ranges);
17082 });
17083 }
17084
17085 self.handle_input(text, window, cx);
17086 }
17087
17088 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17089 let Some(provider) = self.semantics_provider.as_ref() else {
17090 return false;
17091 };
17092
17093 let mut supports = false;
17094 self.buffer().update(cx, |this, cx| {
17095 this.for_each_buffer(|buffer| {
17096 supports |= provider.supports_inlay_hints(buffer, cx);
17097 });
17098 });
17099
17100 supports
17101 }
17102
17103 pub fn is_focused(&self, window: &Window) -> bool {
17104 self.focus_handle.is_focused(window)
17105 }
17106
17107 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17108 cx.emit(EditorEvent::Focused);
17109
17110 if let Some(descendant) = self
17111 .last_focused_descendant
17112 .take()
17113 .and_then(|descendant| descendant.upgrade())
17114 {
17115 window.focus(&descendant);
17116 } else {
17117 if let Some(blame) = self.blame.as_ref() {
17118 blame.update(cx, GitBlame::focus)
17119 }
17120
17121 self.blink_manager.update(cx, BlinkManager::enable);
17122 self.show_cursor_names(window, cx);
17123 self.buffer.update(cx, |buffer, cx| {
17124 buffer.finalize_last_transaction(cx);
17125 if self.leader_peer_id.is_none() {
17126 buffer.set_active_selections(
17127 &self.selections.disjoint_anchors(),
17128 self.selections.line_mode,
17129 self.cursor_shape,
17130 cx,
17131 );
17132 }
17133 });
17134 }
17135 }
17136
17137 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17138 cx.emit(EditorEvent::FocusedIn)
17139 }
17140
17141 fn handle_focus_out(
17142 &mut self,
17143 event: FocusOutEvent,
17144 _window: &mut Window,
17145 cx: &mut Context<Self>,
17146 ) {
17147 if event.blurred != self.focus_handle {
17148 self.last_focused_descendant = Some(event.blurred);
17149 }
17150 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17151 }
17152
17153 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17154 self.blink_manager.update(cx, BlinkManager::disable);
17155 self.buffer
17156 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17157
17158 if let Some(blame) = self.blame.as_ref() {
17159 blame.update(cx, GitBlame::blur)
17160 }
17161 if !self.hover_state.focused(window, cx) {
17162 hide_hover(self, cx);
17163 }
17164 if !self
17165 .context_menu
17166 .borrow()
17167 .as_ref()
17168 .is_some_and(|context_menu| context_menu.focused(window, cx))
17169 {
17170 self.hide_context_menu(window, cx);
17171 }
17172 self.discard_inline_completion(false, cx);
17173 cx.emit(EditorEvent::Blurred);
17174 cx.notify();
17175 }
17176
17177 pub fn register_action<A: Action>(
17178 &mut self,
17179 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17180 ) -> Subscription {
17181 let id = self.next_editor_action_id.post_inc();
17182 let listener = Arc::new(listener);
17183 self.editor_actions.borrow_mut().insert(
17184 id,
17185 Box::new(move |window, _| {
17186 let listener = listener.clone();
17187 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17188 let action = action.downcast_ref().unwrap();
17189 if phase == DispatchPhase::Bubble {
17190 listener(action, window, cx)
17191 }
17192 })
17193 }),
17194 );
17195
17196 let editor_actions = self.editor_actions.clone();
17197 Subscription::new(move || {
17198 editor_actions.borrow_mut().remove(&id);
17199 })
17200 }
17201
17202 pub fn file_header_size(&self) -> u32 {
17203 FILE_HEADER_HEIGHT
17204 }
17205
17206 pub fn restore(
17207 &mut self,
17208 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17209 window: &mut Window,
17210 cx: &mut Context<Self>,
17211 ) {
17212 let workspace = self.workspace();
17213 let project = self.project.as_ref();
17214 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17215 let mut tasks = Vec::new();
17216 for (buffer_id, changes) in revert_changes {
17217 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17218 buffer.update(cx, |buffer, cx| {
17219 buffer.edit(
17220 changes
17221 .into_iter()
17222 .map(|(range, text)| (range, text.to_string())),
17223 None,
17224 cx,
17225 );
17226 });
17227
17228 if let Some(project) =
17229 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17230 {
17231 project.update(cx, |project, cx| {
17232 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17233 })
17234 }
17235 }
17236 }
17237 tasks
17238 });
17239 cx.spawn_in(window, async move |_, cx| {
17240 for (buffer, task) in save_tasks {
17241 let result = task.await;
17242 if result.is_err() {
17243 let Some(path) = buffer
17244 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17245 .ok()
17246 else {
17247 continue;
17248 };
17249 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17250 let Some(task) = cx
17251 .update_window_entity(&workspace, |workspace, window, cx| {
17252 workspace
17253 .open_path_preview(path, None, false, false, false, window, cx)
17254 })
17255 .ok()
17256 else {
17257 continue;
17258 };
17259 task.await.log_err();
17260 }
17261 }
17262 }
17263 })
17264 .detach();
17265 self.change_selections(None, window, cx, |selections| selections.refresh());
17266 }
17267
17268 pub fn to_pixel_point(
17269 &self,
17270 source: multi_buffer::Anchor,
17271 editor_snapshot: &EditorSnapshot,
17272 window: &mut Window,
17273 ) -> Option<gpui::Point<Pixels>> {
17274 let source_point = source.to_display_point(editor_snapshot);
17275 self.display_to_pixel_point(source_point, editor_snapshot, window)
17276 }
17277
17278 pub fn display_to_pixel_point(
17279 &self,
17280 source: DisplayPoint,
17281 editor_snapshot: &EditorSnapshot,
17282 window: &mut Window,
17283 ) -> Option<gpui::Point<Pixels>> {
17284 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17285 let text_layout_details = self.text_layout_details(window);
17286 let scroll_top = text_layout_details
17287 .scroll_anchor
17288 .scroll_position(editor_snapshot)
17289 .y;
17290
17291 if source.row().as_f32() < scroll_top.floor() {
17292 return None;
17293 }
17294 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17295 let source_y = line_height * (source.row().as_f32() - scroll_top);
17296 Some(gpui::Point::new(source_x, source_y))
17297 }
17298
17299 pub fn has_visible_completions_menu(&self) -> bool {
17300 !self.edit_prediction_preview_is_active()
17301 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17302 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17303 })
17304 }
17305
17306 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17307 self.addons
17308 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17309 }
17310
17311 pub fn unregister_addon<T: Addon>(&mut self) {
17312 self.addons.remove(&std::any::TypeId::of::<T>());
17313 }
17314
17315 pub fn addon<T: Addon>(&self) -> Option<&T> {
17316 let type_id = std::any::TypeId::of::<T>();
17317 self.addons
17318 .get(&type_id)
17319 .and_then(|item| item.to_any().downcast_ref::<T>())
17320 }
17321
17322 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17323 let text_layout_details = self.text_layout_details(window);
17324 let style = &text_layout_details.editor_style;
17325 let font_id = window.text_system().resolve_font(&style.text.font());
17326 let font_size = style.text.font_size.to_pixels(window.rem_size());
17327 let line_height = style.text.line_height_in_pixels(window.rem_size());
17328 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17329
17330 gpui::Size::new(em_width, line_height)
17331 }
17332
17333 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17334 self.load_diff_task.clone()
17335 }
17336
17337 fn read_metadata_from_db(
17338 &mut self,
17339 item_id: u64,
17340 workspace_id: WorkspaceId,
17341 window: &mut Window,
17342 cx: &mut Context<Editor>,
17343 ) {
17344 if self.is_singleton(cx)
17345 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17346 {
17347 let buffer_snapshot = OnceCell::new();
17348
17349 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17350 if !selections.is_empty() {
17351 let snapshot =
17352 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17353 self.change_selections(None, window, cx, |s| {
17354 s.select_ranges(selections.into_iter().map(|(start, end)| {
17355 snapshot.clip_offset(start, Bias::Left)
17356 ..snapshot.clip_offset(end, Bias::Right)
17357 }));
17358 });
17359 }
17360 };
17361
17362 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17363 if !folds.is_empty() {
17364 let snapshot =
17365 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17366 self.fold_ranges(
17367 folds
17368 .into_iter()
17369 .map(|(start, end)| {
17370 snapshot.clip_offset(start, Bias::Left)
17371 ..snapshot.clip_offset(end, Bias::Right)
17372 })
17373 .collect(),
17374 false,
17375 window,
17376 cx,
17377 );
17378 }
17379 }
17380 }
17381
17382 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17383 }
17384}
17385
17386fn insert_extra_newline_brackets(
17387 buffer: &MultiBufferSnapshot,
17388 range: Range<usize>,
17389 language: &language::LanguageScope,
17390) -> bool {
17391 let leading_whitespace_len = buffer
17392 .reversed_chars_at(range.start)
17393 .take_while(|c| c.is_whitespace() && *c != '\n')
17394 .map(|c| c.len_utf8())
17395 .sum::<usize>();
17396 let trailing_whitespace_len = buffer
17397 .chars_at(range.end)
17398 .take_while(|c| c.is_whitespace() && *c != '\n')
17399 .map(|c| c.len_utf8())
17400 .sum::<usize>();
17401 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17402
17403 language.brackets().any(|(pair, enabled)| {
17404 let pair_start = pair.start.trim_end();
17405 let pair_end = pair.end.trim_start();
17406
17407 enabled
17408 && pair.newline
17409 && buffer.contains_str_at(range.end, pair_end)
17410 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17411 })
17412}
17413
17414fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17415 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17416 [(buffer, range, _)] => (*buffer, range.clone()),
17417 _ => return false,
17418 };
17419 let pair = {
17420 let mut result: Option<BracketMatch> = None;
17421
17422 for pair in buffer
17423 .all_bracket_ranges(range.clone())
17424 .filter(move |pair| {
17425 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17426 })
17427 {
17428 let len = pair.close_range.end - pair.open_range.start;
17429
17430 if let Some(existing) = &result {
17431 let existing_len = existing.close_range.end - existing.open_range.start;
17432 if len > existing_len {
17433 continue;
17434 }
17435 }
17436
17437 result = Some(pair);
17438 }
17439
17440 result
17441 };
17442 let Some(pair) = pair else {
17443 return false;
17444 };
17445 pair.newline_only
17446 && buffer
17447 .chars_for_range(pair.open_range.end..range.start)
17448 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17449 .all(|c| c.is_whitespace() && c != '\n')
17450}
17451
17452fn get_uncommitted_diff_for_buffer(
17453 project: &Entity<Project>,
17454 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17455 buffer: Entity<MultiBuffer>,
17456 cx: &mut App,
17457) -> Task<()> {
17458 let mut tasks = Vec::new();
17459 project.update(cx, |project, cx| {
17460 for buffer in buffers {
17461 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17462 }
17463 });
17464 cx.spawn(async move |cx| {
17465 let diffs = future::join_all(tasks).await;
17466 buffer
17467 .update(cx, |buffer, cx| {
17468 for diff in diffs.into_iter().flatten() {
17469 buffer.add_diff(diff, cx);
17470 }
17471 })
17472 .ok();
17473 })
17474}
17475
17476fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17477 let tab_size = tab_size.get() as usize;
17478 let mut width = offset;
17479
17480 for ch in text.chars() {
17481 width += if ch == '\t' {
17482 tab_size - (width % tab_size)
17483 } else {
17484 1
17485 };
17486 }
17487
17488 width - offset
17489}
17490
17491#[cfg(test)]
17492mod tests {
17493 use super::*;
17494
17495 #[test]
17496 fn test_string_size_with_expanded_tabs() {
17497 let nz = |val| NonZeroU32::new(val).unwrap();
17498 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17499 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17500 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17501 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17502 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17503 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17504 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17505 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17506 }
17507}
17508
17509/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17510struct WordBreakingTokenizer<'a> {
17511 input: &'a str,
17512}
17513
17514impl<'a> WordBreakingTokenizer<'a> {
17515 fn new(input: &'a str) -> Self {
17516 Self { input }
17517 }
17518}
17519
17520fn is_char_ideographic(ch: char) -> bool {
17521 use unicode_script::Script::*;
17522 use unicode_script::UnicodeScript;
17523 matches!(ch.script(), Han | Tangut | Yi)
17524}
17525
17526fn is_grapheme_ideographic(text: &str) -> bool {
17527 text.chars().any(is_char_ideographic)
17528}
17529
17530fn is_grapheme_whitespace(text: &str) -> bool {
17531 text.chars().any(|x| x.is_whitespace())
17532}
17533
17534fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17535 text.chars().next().map_or(false, |ch| {
17536 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17537 })
17538}
17539
17540#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17541enum WordBreakToken<'a> {
17542 Word { token: &'a str, grapheme_len: usize },
17543 InlineWhitespace { token: &'a str, grapheme_len: usize },
17544 Newline,
17545}
17546
17547impl<'a> Iterator for WordBreakingTokenizer<'a> {
17548 /// Yields a span, the count of graphemes in the token, and whether it was
17549 /// whitespace. Note that it also breaks at word boundaries.
17550 type Item = WordBreakToken<'a>;
17551
17552 fn next(&mut self) -> Option<Self::Item> {
17553 use unicode_segmentation::UnicodeSegmentation;
17554 if self.input.is_empty() {
17555 return None;
17556 }
17557
17558 let mut iter = self.input.graphemes(true).peekable();
17559 let mut offset = 0;
17560 let mut grapheme_len = 0;
17561 if let Some(first_grapheme) = iter.next() {
17562 let is_newline = first_grapheme == "\n";
17563 let is_whitespace = is_grapheme_whitespace(first_grapheme);
17564 offset += first_grapheme.len();
17565 grapheme_len += 1;
17566 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17567 if let Some(grapheme) = iter.peek().copied() {
17568 if should_stay_with_preceding_ideograph(grapheme) {
17569 offset += grapheme.len();
17570 grapheme_len += 1;
17571 }
17572 }
17573 } else {
17574 let mut words = self.input[offset..].split_word_bound_indices().peekable();
17575 let mut next_word_bound = words.peek().copied();
17576 if next_word_bound.map_or(false, |(i, _)| i == 0) {
17577 next_word_bound = words.next();
17578 }
17579 while let Some(grapheme) = iter.peek().copied() {
17580 if next_word_bound.map_or(false, |(i, _)| i == offset) {
17581 break;
17582 };
17583 if is_grapheme_whitespace(grapheme) != is_whitespace
17584 || (grapheme == "\n") != is_newline
17585 {
17586 break;
17587 };
17588 offset += grapheme.len();
17589 grapheme_len += 1;
17590 iter.next();
17591 }
17592 }
17593 let token = &self.input[..offset];
17594 self.input = &self.input[offset..];
17595 if token == "\n" {
17596 Some(WordBreakToken::Newline)
17597 } else if is_whitespace {
17598 Some(WordBreakToken::InlineWhitespace {
17599 token,
17600 grapheme_len,
17601 })
17602 } else {
17603 Some(WordBreakToken::Word {
17604 token,
17605 grapheme_len,
17606 })
17607 }
17608 } else {
17609 None
17610 }
17611 }
17612}
17613
17614#[test]
17615fn test_word_breaking_tokenizer() {
17616 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17617 ("", &[]),
17618 (" ", &[whitespace(" ", 2)]),
17619 ("Ʒ", &[word("Ʒ", 1)]),
17620 ("Ǽ", &[word("Ǽ", 1)]),
17621 ("⋑", &[word("⋑", 1)]),
17622 ("⋑⋑", &[word("⋑⋑", 2)]),
17623 (
17624 "原理,进而",
17625 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
17626 ),
17627 (
17628 "hello world",
17629 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17630 ),
17631 (
17632 "hello, world",
17633 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17634 ),
17635 (
17636 " hello world",
17637 &[
17638 whitespace(" ", 2),
17639 word("hello", 5),
17640 whitespace(" ", 1),
17641 word("world", 5),
17642 ],
17643 ),
17644 (
17645 "这是什么 \n 钢笔",
17646 &[
17647 word("这", 1),
17648 word("是", 1),
17649 word("什", 1),
17650 word("么", 1),
17651 whitespace(" ", 1),
17652 newline(),
17653 whitespace(" ", 1),
17654 word("钢", 1),
17655 word("笔", 1),
17656 ],
17657 ),
17658 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
17659 ];
17660
17661 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17662 WordBreakToken::Word {
17663 token,
17664 grapheme_len,
17665 }
17666 }
17667
17668 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17669 WordBreakToken::InlineWhitespace {
17670 token,
17671 grapheme_len,
17672 }
17673 }
17674
17675 fn newline() -> WordBreakToken<'static> {
17676 WordBreakToken::Newline
17677 }
17678
17679 for (input, result) in tests {
17680 assert_eq!(
17681 WordBreakingTokenizer::new(input)
17682 .collect::<Vec<_>>()
17683 .as_slice(),
17684 *result,
17685 );
17686 }
17687}
17688
17689fn wrap_with_prefix(
17690 line_prefix: String,
17691 unwrapped_text: String,
17692 wrap_column: usize,
17693 tab_size: NonZeroU32,
17694 preserve_existing_whitespace: bool,
17695) -> String {
17696 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17697 let mut wrapped_text = String::new();
17698 let mut current_line = line_prefix.clone();
17699
17700 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17701 let mut current_line_len = line_prefix_len;
17702 let mut in_whitespace = false;
17703 for token in tokenizer {
17704 let have_preceding_whitespace = in_whitespace;
17705 match token {
17706 WordBreakToken::Word {
17707 token,
17708 grapheme_len,
17709 } => {
17710 in_whitespace = false;
17711 if current_line_len + grapheme_len > wrap_column
17712 && current_line_len != line_prefix_len
17713 {
17714 wrapped_text.push_str(current_line.trim_end());
17715 wrapped_text.push('\n');
17716 current_line.truncate(line_prefix.len());
17717 current_line_len = line_prefix_len;
17718 }
17719 current_line.push_str(token);
17720 current_line_len += grapheme_len;
17721 }
17722 WordBreakToken::InlineWhitespace {
17723 mut token,
17724 mut grapheme_len,
17725 } => {
17726 in_whitespace = true;
17727 if have_preceding_whitespace && !preserve_existing_whitespace {
17728 continue;
17729 }
17730 if !preserve_existing_whitespace {
17731 token = " ";
17732 grapheme_len = 1;
17733 }
17734 if current_line_len + grapheme_len > wrap_column {
17735 wrapped_text.push_str(current_line.trim_end());
17736 wrapped_text.push('\n');
17737 current_line.truncate(line_prefix.len());
17738 current_line_len = line_prefix_len;
17739 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17740 current_line.push_str(token);
17741 current_line_len += grapheme_len;
17742 }
17743 }
17744 WordBreakToken::Newline => {
17745 in_whitespace = true;
17746 if preserve_existing_whitespace {
17747 wrapped_text.push_str(current_line.trim_end());
17748 wrapped_text.push('\n');
17749 current_line.truncate(line_prefix.len());
17750 current_line_len = line_prefix_len;
17751 } else if have_preceding_whitespace {
17752 continue;
17753 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17754 {
17755 wrapped_text.push_str(current_line.trim_end());
17756 wrapped_text.push('\n');
17757 current_line.truncate(line_prefix.len());
17758 current_line_len = line_prefix_len;
17759 } else if current_line_len != line_prefix_len {
17760 current_line.push(' ');
17761 current_line_len += 1;
17762 }
17763 }
17764 }
17765 }
17766
17767 if !current_line.is_empty() {
17768 wrapped_text.push_str(¤t_line);
17769 }
17770 wrapped_text
17771}
17772
17773#[test]
17774fn test_wrap_with_prefix() {
17775 assert_eq!(
17776 wrap_with_prefix(
17777 "# ".to_string(),
17778 "abcdefg".to_string(),
17779 4,
17780 NonZeroU32::new(4).unwrap(),
17781 false,
17782 ),
17783 "# abcdefg"
17784 );
17785 assert_eq!(
17786 wrap_with_prefix(
17787 "".to_string(),
17788 "\thello world".to_string(),
17789 8,
17790 NonZeroU32::new(4).unwrap(),
17791 false,
17792 ),
17793 "hello\nworld"
17794 );
17795 assert_eq!(
17796 wrap_with_prefix(
17797 "// ".to_string(),
17798 "xx \nyy zz aa bb cc".to_string(),
17799 12,
17800 NonZeroU32::new(4).unwrap(),
17801 false,
17802 ),
17803 "// xx yy zz\n// aa bb cc"
17804 );
17805 assert_eq!(
17806 wrap_with_prefix(
17807 String::new(),
17808 "这是什么 \n 钢笔".to_string(),
17809 3,
17810 NonZeroU32::new(4).unwrap(),
17811 false,
17812 ),
17813 "这是什\n么 钢\n笔"
17814 );
17815}
17816
17817pub trait CollaborationHub {
17818 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17819 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17820 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17821}
17822
17823impl CollaborationHub for Entity<Project> {
17824 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17825 self.read(cx).collaborators()
17826 }
17827
17828 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17829 self.read(cx).user_store().read(cx).participant_indices()
17830 }
17831
17832 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17833 let this = self.read(cx);
17834 let user_ids = this.collaborators().values().map(|c| c.user_id);
17835 this.user_store().read_with(cx, |user_store, cx| {
17836 user_store.participant_names(user_ids, cx)
17837 })
17838 }
17839}
17840
17841pub trait SemanticsProvider {
17842 fn hover(
17843 &self,
17844 buffer: &Entity<Buffer>,
17845 position: text::Anchor,
17846 cx: &mut App,
17847 ) -> Option<Task<Vec<project::Hover>>>;
17848
17849 fn inlay_hints(
17850 &self,
17851 buffer_handle: Entity<Buffer>,
17852 range: Range<text::Anchor>,
17853 cx: &mut App,
17854 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17855
17856 fn resolve_inlay_hint(
17857 &self,
17858 hint: InlayHint,
17859 buffer_handle: Entity<Buffer>,
17860 server_id: LanguageServerId,
17861 cx: &mut App,
17862 ) -> Option<Task<anyhow::Result<InlayHint>>>;
17863
17864 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17865
17866 fn document_highlights(
17867 &self,
17868 buffer: &Entity<Buffer>,
17869 position: text::Anchor,
17870 cx: &mut App,
17871 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17872
17873 fn definitions(
17874 &self,
17875 buffer: &Entity<Buffer>,
17876 position: text::Anchor,
17877 kind: GotoDefinitionKind,
17878 cx: &mut App,
17879 ) -> Option<Task<Result<Vec<LocationLink>>>>;
17880
17881 fn range_for_rename(
17882 &self,
17883 buffer: &Entity<Buffer>,
17884 position: text::Anchor,
17885 cx: &mut App,
17886 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17887
17888 fn perform_rename(
17889 &self,
17890 buffer: &Entity<Buffer>,
17891 position: text::Anchor,
17892 new_name: String,
17893 cx: &mut App,
17894 ) -> Option<Task<Result<ProjectTransaction>>>;
17895}
17896
17897pub trait CompletionProvider {
17898 fn completions(
17899 &self,
17900 excerpt_id: ExcerptId,
17901 buffer: &Entity<Buffer>,
17902 buffer_position: text::Anchor,
17903 trigger: CompletionContext,
17904 window: &mut Window,
17905 cx: &mut Context<Editor>,
17906 ) -> Task<Result<Option<Vec<Completion>>>>;
17907
17908 fn resolve_completions(
17909 &self,
17910 buffer: Entity<Buffer>,
17911 completion_indices: Vec<usize>,
17912 completions: Rc<RefCell<Box<[Completion]>>>,
17913 cx: &mut Context<Editor>,
17914 ) -> Task<Result<bool>>;
17915
17916 fn apply_additional_edits_for_completion(
17917 &self,
17918 _buffer: Entity<Buffer>,
17919 _completions: Rc<RefCell<Box<[Completion]>>>,
17920 _completion_index: usize,
17921 _push_to_history: bool,
17922 _cx: &mut Context<Editor>,
17923 ) -> Task<Result<Option<language::Transaction>>> {
17924 Task::ready(Ok(None))
17925 }
17926
17927 fn is_completion_trigger(
17928 &self,
17929 buffer: &Entity<Buffer>,
17930 position: language::Anchor,
17931 text: &str,
17932 trigger_in_words: bool,
17933 cx: &mut Context<Editor>,
17934 ) -> bool;
17935
17936 fn sort_completions(&self) -> bool {
17937 true
17938 }
17939}
17940
17941pub trait CodeActionProvider {
17942 fn id(&self) -> Arc<str>;
17943
17944 fn code_actions(
17945 &self,
17946 buffer: &Entity<Buffer>,
17947 range: Range<text::Anchor>,
17948 window: &mut Window,
17949 cx: &mut App,
17950 ) -> Task<Result<Vec<CodeAction>>>;
17951
17952 fn apply_code_action(
17953 &self,
17954 buffer_handle: Entity<Buffer>,
17955 action: CodeAction,
17956 excerpt_id: ExcerptId,
17957 push_to_history: bool,
17958 window: &mut Window,
17959 cx: &mut App,
17960 ) -> Task<Result<ProjectTransaction>>;
17961}
17962
17963impl CodeActionProvider for Entity<Project> {
17964 fn id(&self) -> Arc<str> {
17965 "project".into()
17966 }
17967
17968 fn code_actions(
17969 &self,
17970 buffer: &Entity<Buffer>,
17971 range: Range<text::Anchor>,
17972 _window: &mut Window,
17973 cx: &mut App,
17974 ) -> Task<Result<Vec<CodeAction>>> {
17975 self.update(cx, |project, cx| {
17976 let code_lens = project.code_lens(buffer, range.clone(), cx);
17977 let code_actions = project.code_actions(buffer, range, None, cx);
17978 cx.background_spawn(async move {
17979 let (code_lens, code_actions) = join(code_lens, code_actions).await;
17980 Ok(code_lens
17981 .context("code lens fetch")?
17982 .into_iter()
17983 .chain(code_actions.context("code action fetch")?)
17984 .collect())
17985 })
17986 })
17987 }
17988
17989 fn apply_code_action(
17990 &self,
17991 buffer_handle: Entity<Buffer>,
17992 action: CodeAction,
17993 _excerpt_id: ExcerptId,
17994 push_to_history: bool,
17995 _window: &mut Window,
17996 cx: &mut App,
17997 ) -> Task<Result<ProjectTransaction>> {
17998 self.update(cx, |project, cx| {
17999 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18000 })
18001 }
18002}
18003
18004fn snippet_completions(
18005 project: &Project,
18006 buffer: &Entity<Buffer>,
18007 buffer_position: text::Anchor,
18008 cx: &mut App,
18009) -> Task<Result<Vec<Completion>>> {
18010 let language = buffer.read(cx).language_at(buffer_position);
18011 let language_name = language.as_ref().map(|language| language.lsp_id());
18012 let snippet_store = project.snippets().read(cx);
18013 let snippets = snippet_store.snippets_for(language_name, cx);
18014
18015 if snippets.is_empty() {
18016 return Task::ready(Ok(vec![]));
18017 }
18018 let snapshot = buffer.read(cx).text_snapshot();
18019 let chars: String = snapshot
18020 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18021 .collect();
18022
18023 let scope = language.map(|language| language.default_scope());
18024 let executor = cx.background_executor().clone();
18025
18026 cx.background_spawn(async move {
18027 let classifier = CharClassifier::new(scope).for_completion(true);
18028 let mut last_word = chars
18029 .chars()
18030 .take_while(|c| classifier.is_word(*c))
18031 .collect::<String>();
18032 last_word = last_word.chars().rev().collect();
18033
18034 if last_word.is_empty() {
18035 return Ok(vec![]);
18036 }
18037
18038 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18039 let to_lsp = |point: &text::Anchor| {
18040 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18041 point_to_lsp(end)
18042 };
18043 let lsp_end = to_lsp(&buffer_position);
18044
18045 let candidates = snippets
18046 .iter()
18047 .enumerate()
18048 .flat_map(|(ix, snippet)| {
18049 snippet
18050 .prefix
18051 .iter()
18052 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18053 })
18054 .collect::<Vec<StringMatchCandidate>>();
18055
18056 let mut matches = fuzzy::match_strings(
18057 &candidates,
18058 &last_word,
18059 last_word.chars().any(|c| c.is_uppercase()),
18060 100,
18061 &Default::default(),
18062 executor,
18063 )
18064 .await;
18065
18066 // Remove all candidates where the query's start does not match the start of any word in the candidate
18067 if let Some(query_start) = last_word.chars().next() {
18068 matches.retain(|string_match| {
18069 split_words(&string_match.string).any(|word| {
18070 // Check that the first codepoint of the word as lowercase matches the first
18071 // codepoint of the query as lowercase
18072 word.chars()
18073 .flat_map(|codepoint| codepoint.to_lowercase())
18074 .zip(query_start.to_lowercase())
18075 .all(|(word_cp, query_cp)| word_cp == query_cp)
18076 })
18077 });
18078 }
18079
18080 let matched_strings = matches
18081 .into_iter()
18082 .map(|m| m.string)
18083 .collect::<HashSet<_>>();
18084
18085 let result: Vec<Completion> = snippets
18086 .into_iter()
18087 .filter_map(|snippet| {
18088 let matching_prefix = snippet
18089 .prefix
18090 .iter()
18091 .find(|prefix| matched_strings.contains(*prefix))?;
18092 let start = as_offset - last_word.len();
18093 let start = snapshot.anchor_before(start);
18094 let range = start..buffer_position;
18095 let lsp_start = to_lsp(&start);
18096 let lsp_range = lsp::Range {
18097 start: lsp_start,
18098 end: lsp_end,
18099 };
18100 Some(Completion {
18101 old_range: range,
18102 new_text: snippet.body.clone(),
18103 source: CompletionSource::Lsp {
18104 server_id: LanguageServerId(usize::MAX),
18105 resolved: true,
18106 lsp_completion: Box::new(lsp::CompletionItem {
18107 label: snippet.prefix.first().unwrap().clone(),
18108 kind: Some(CompletionItemKind::SNIPPET),
18109 label_details: snippet.description.as_ref().map(|description| {
18110 lsp::CompletionItemLabelDetails {
18111 detail: Some(description.clone()),
18112 description: None,
18113 }
18114 }),
18115 insert_text_format: Some(InsertTextFormat::SNIPPET),
18116 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18117 lsp::InsertReplaceEdit {
18118 new_text: snippet.body.clone(),
18119 insert: lsp_range,
18120 replace: lsp_range,
18121 },
18122 )),
18123 filter_text: Some(snippet.body.clone()),
18124 sort_text: Some(char::MAX.to_string()),
18125 ..lsp::CompletionItem::default()
18126 }),
18127 lsp_defaults: None,
18128 },
18129 label: CodeLabel {
18130 text: matching_prefix.clone(),
18131 runs: Vec::new(),
18132 filter_range: 0..matching_prefix.len(),
18133 },
18134 icon_path: None,
18135 documentation: snippet
18136 .description
18137 .clone()
18138 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18139 confirm: None,
18140 })
18141 })
18142 .collect();
18143
18144 Ok(result)
18145 })
18146}
18147
18148impl CompletionProvider for Entity<Project> {
18149 fn completions(
18150 &self,
18151 _excerpt_id: ExcerptId,
18152 buffer: &Entity<Buffer>,
18153 buffer_position: text::Anchor,
18154 options: CompletionContext,
18155 _window: &mut Window,
18156 cx: &mut Context<Editor>,
18157 ) -> Task<Result<Option<Vec<Completion>>>> {
18158 self.update(cx, |project, cx| {
18159 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18160 let project_completions = project.completions(buffer, buffer_position, options, cx);
18161 cx.background_spawn(async move {
18162 let snippets_completions = snippets.await?;
18163 match project_completions.await? {
18164 Some(mut completions) => {
18165 completions.extend(snippets_completions);
18166 Ok(Some(completions))
18167 }
18168 None => {
18169 if snippets_completions.is_empty() {
18170 Ok(None)
18171 } else {
18172 Ok(Some(snippets_completions))
18173 }
18174 }
18175 }
18176 })
18177 })
18178 }
18179
18180 fn resolve_completions(
18181 &self,
18182 buffer: Entity<Buffer>,
18183 completion_indices: Vec<usize>,
18184 completions: Rc<RefCell<Box<[Completion]>>>,
18185 cx: &mut Context<Editor>,
18186 ) -> Task<Result<bool>> {
18187 self.update(cx, |project, cx| {
18188 project.lsp_store().update(cx, |lsp_store, cx| {
18189 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18190 })
18191 })
18192 }
18193
18194 fn apply_additional_edits_for_completion(
18195 &self,
18196 buffer: Entity<Buffer>,
18197 completions: Rc<RefCell<Box<[Completion]>>>,
18198 completion_index: usize,
18199 push_to_history: bool,
18200 cx: &mut Context<Editor>,
18201 ) -> Task<Result<Option<language::Transaction>>> {
18202 self.update(cx, |project, cx| {
18203 project.lsp_store().update(cx, |lsp_store, cx| {
18204 lsp_store.apply_additional_edits_for_completion(
18205 buffer,
18206 completions,
18207 completion_index,
18208 push_to_history,
18209 cx,
18210 )
18211 })
18212 })
18213 }
18214
18215 fn is_completion_trigger(
18216 &self,
18217 buffer: &Entity<Buffer>,
18218 position: language::Anchor,
18219 text: &str,
18220 trigger_in_words: bool,
18221 cx: &mut Context<Editor>,
18222 ) -> bool {
18223 let mut chars = text.chars();
18224 let char = if let Some(char) = chars.next() {
18225 char
18226 } else {
18227 return false;
18228 };
18229 if chars.next().is_some() {
18230 return false;
18231 }
18232
18233 let buffer = buffer.read(cx);
18234 let snapshot = buffer.snapshot();
18235 if !snapshot.settings_at(position, cx).show_completions_on_input {
18236 return false;
18237 }
18238 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18239 if trigger_in_words && classifier.is_word(char) {
18240 return true;
18241 }
18242
18243 buffer.completion_triggers().contains(text)
18244 }
18245}
18246
18247impl SemanticsProvider for Entity<Project> {
18248 fn hover(
18249 &self,
18250 buffer: &Entity<Buffer>,
18251 position: text::Anchor,
18252 cx: &mut App,
18253 ) -> Option<Task<Vec<project::Hover>>> {
18254 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18255 }
18256
18257 fn document_highlights(
18258 &self,
18259 buffer: &Entity<Buffer>,
18260 position: text::Anchor,
18261 cx: &mut App,
18262 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18263 Some(self.update(cx, |project, cx| {
18264 project.document_highlights(buffer, position, cx)
18265 }))
18266 }
18267
18268 fn definitions(
18269 &self,
18270 buffer: &Entity<Buffer>,
18271 position: text::Anchor,
18272 kind: GotoDefinitionKind,
18273 cx: &mut App,
18274 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18275 Some(self.update(cx, |project, cx| match kind {
18276 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18277 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18278 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18279 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18280 }))
18281 }
18282
18283 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18284 // TODO: make this work for remote projects
18285 self.update(cx, |this, cx| {
18286 buffer.update(cx, |buffer, cx| {
18287 this.any_language_server_supports_inlay_hints(buffer, cx)
18288 })
18289 })
18290 }
18291
18292 fn inlay_hints(
18293 &self,
18294 buffer_handle: Entity<Buffer>,
18295 range: Range<text::Anchor>,
18296 cx: &mut App,
18297 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18298 Some(self.update(cx, |project, cx| {
18299 project.inlay_hints(buffer_handle, range, cx)
18300 }))
18301 }
18302
18303 fn resolve_inlay_hint(
18304 &self,
18305 hint: InlayHint,
18306 buffer_handle: Entity<Buffer>,
18307 server_id: LanguageServerId,
18308 cx: &mut App,
18309 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18310 Some(self.update(cx, |project, cx| {
18311 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18312 }))
18313 }
18314
18315 fn range_for_rename(
18316 &self,
18317 buffer: &Entity<Buffer>,
18318 position: text::Anchor,
18319 cx: &mut App,
18320 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18321 Some(self.update(cx, |project, cx| {
18322 let buffer = buffer.clone();
18323 let task = project.prepare_rename(buffer.clone(), position, cx);
18324 cx.spawn(async move |_, cx| {
18325 Ok(match task.await? {
18326 PrepareRenameResponse::Success(range) => Some(range),
18327 PrepareRenameResponse::InvalidPosition => None,
18328 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18329 // Fallback on using TreeSitter info to determine identifier range
18330 buffer.update(cx, |buffer, _| {
18331 let snapshot = buffer.snapshot();
18332 let (range, kind) = snapshot.surrounding_word(position);
18333 if kind != Some(CharKind::Word) {
18334 return None;
18335 }
18336 Some(
18337 snapshot.anchor_before(range.start)
18338 ..snapshot.anchor_after(range.end),
18339 )
18340 })?
18341 }
18342 })
18343 })
18344 }))
18345 }
18346
18347 fn perform_rename(
18348 &self,
18349 buffer: &Entity<Buffer>,
18350 position: text::Anchor,
18351 new_name: String,
18352 cx: &mut App,
18353 ) -> Option<Task<Result<ProjectTransaction>>> {
18354 Some(self.update(cx, |project, cx| {
18355 project.perform_rename(buffer.clone(), position, new_name, cx)
18356 }))
18357 }
18358}
18359
18360fn inlay_hint_settings(
18361 location: Anchor,
18362 snapshot: &MultiBufferSnapshot,
18363 cx: &mut Context<Editor>,
18364) -> InlayHintSettings {
18365 let file = snapshot.file_at(location);
18366 let language = snapshot.language_at(location).map(|l| l.name());
18367 language_settings(language, file, cx).inlay_hints
18368}
18369
18370fn consume_contiguous_rows(
18371 contiguous_row_selections: &mut Vec<Selection<Point>>,
18372 selection: &Selection<Point>,
18373 display_map: &DisplaySnapshot,
18374 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18375) -> (MultiBufferRow, MultiBufferRow) {
18376 contiguous_row_selections.push(selection.clone());
18377 let start_row = MultiBufferRow(selection.start.row);
18378 let mut end_row = ending_row(selection, display_map);
18379
18380 while let Some(next_selection) = selections.peek() {
18381 if next_selection.start.row <= end_row.0 {
18382 end_row = ending_row(next_selection, display_map);
18383 contiguous_row_selections.push(selections.next().unwrap().clone());
18384 } else {
18385 break;
18386 }
18387 }
18388 (start_row, end_row)
18389}
18390
18391fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18392 if next_selection.end.column > 0 || next_selection.is_empty() {
18393 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18394 } else {
18395 MultiBufferRow(next_selection.end.row)
18396 }
18397}
18398
18399impl EditorSnapshot {
18400 pub fn remote_selections_in_range<'a>(
18401 &'a self,
18402 range: &'a Range<Anchor>,
18403 collaboration_hub: &dyn CollaborationHub,
18404 cx: &'a App,
18405 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18406 let participant_names = collaboration_hub.user_names(cx);
18407 let participant_indices = collaboration_hub.user_participant_indices(cx);
18408 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18409 let collaborators_by_replica_id = collaborators_by_peer_id
18410 .iter()
18411 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18412 .collect::<HashMap<_, _>>();
18413 self.buffer_snapshot
18414 .selections_in_range(range, false)
18415 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18416 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18417 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18418 let user_name = participant_names.get(&collaborator.user_id).cloned();
18419 Some(RemoteSelection {
18420 replica_id,
18421 selection,
18422 cursor_shape,
18423 line_mode,
18424 participant_index,
18425 peer_id: collaborator.peer_id,
18426 user_name,
18427 })
18428 })
18429 }
18430
18431 pub fn hunks_for_ranges(
18432 &self,
18433 ranges: impl IntoIterator<Item = Range<Point>>,
18434 ) -> Vec<MultiBufferDiffHunk> {
18435 let mut hunks = Vec::new();
18436 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18437 HashMap::default();
18438 for query_range in ranges {
18439 let query_rows =
18440 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18441 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18442 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18443 ) {
18444 // Include deleted hunks that are adjacent to the query range, because
18445 // otherwise they would be missed.
18446 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18447 if hunk.status().is_deleted() {
18448 intersects_range |= hunk.row_range.start == query_rows.end;
18449 intersects_range |= hunk.row_range.end == query_rows.start;
18450 }
18451 if intersects_range {
18452 if !processed_buffer_rows
18453 .entry(hunk.buffer_id)
18454 .or_default()
18455 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18456 {
18457 continue;
18458 }
18459 hunks.push(hunk);
18460 }
18461 }
18462 }
18463
18464 hunks
18465 }
18466
18467 fn display_diff_hunks_for_rows<'a>(
18468 &'a self,
18469 display_rows: Range<DisplayRow>,
18470 folded_buffers: &'a HashSet<BufferId>,
18471 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18472 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18473 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18474
18475 self.buffer_snapshot
18476 .diff_hunks_in_range(buffer_start..buffer_end)
18477 .filter_map(|hunk| {
18478 if folded_buffers.contains(&hunk.buffer_id) {
18479 return None;
18480 }
18481
18482 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18483 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18484
18485 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18486 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18487
18488 let display_hunk = if hunk_display_start.column() != 0 {
18489 DisplayDiffHunk::Folded {
18490 display_row: hunk_display_start.row(),
18491 }
18492 } else {
18493 let mut end_row = hunk_display_end.row();
18494 if hunk_display_end.column() > 0 {
18495 end_row.0 += 1;
18496 }
18497 let is_created_file = hunk.is_created_file();
18498 DisplayDiffHunk::Unfolded {
18499 status: hunk.status(),
18500 diff_base_byte_range: hunk.diff_base_byte_range,
18501 display_row_range: hunk_display_start.row()..end_row,
18502 multi_buffer_range: Anchor::range_in_buffer(
18503 hunk.excerpt_id,
18504 hunk.buffer_id,
18505 hunk.buffer_range,
18506 ),
18507 is_created_file,
18508 }
18509 };
18510
18511 Some(display_hunk)
18512 })
18513 }
18514
18515 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18516 self.display_snapshot.buffer_snapshot.language_at(position)
18517 }
18518
18519 pub fn is_focused(&self) -> bool {
18520 self.is_focused
18521 }
18522
18523 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18524 self.placeholder_text.as_ref()
18525 }
18526
18527 pub fn scroll_position(&self) -> gpui::Point<f32> {
18528 self.scroll_anchor.scroll_position(&self.display_snapshot)
18529 }
18530
18531 fn gutter_dimensions(
18532 &self,
18533 font_id: FontId,
18534 font_size: Pixels,
18535 max_line_number_width: Pixels,
18536 cx: &App,
18537 ) -> Option<GutterDimensions> {
18538 if !self.show_gutter {
18539 return None;
18540 }
18541
18542 let descent = cx.text_system().descent(font_id, font_size);
18543 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18544 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18545
18546 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18547 matches!(
18548 ProjectSettings::get_global(cx).git.git_gutter,
18549 Some(GitGutterSetting::TrackedFiles)
18550 )
18551 });
18552 let gutter_settings = EditorSettings::get_global(cx).gutter;
18553 let show_line_numbers = self
18554 .show_line_numbers
18555 .unwrap_or(gutter_settings.line_numbers);
18556 let line_gutter_width = if show_line_numbers {
18557 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18558 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18559 max_line_number_width.max(min_width_for_number_on_gutter)
18560 } else {
18561 0.0.into()
18562 };
18563
18564 let show_code_actions = self
18565 .show_code_actions
18566 .unwrap_or(gutter_settings.code_actions);
18567
18568 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18569 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18570
18571 let git_blame_entries_width =
18572 self.git_blame_gutter_max_author_length
18573 .map(|max_author_length| {
18574 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18575
18576 /// The number of characters to dedicate to gaps and margins.
18577 const SPACING_WIDTH: usize = 4;
18578
18579 let max_char_count = max_author_length
18580 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18581 + ::git::SHORT_SHA_LENGTH
18582 + MAX_RELATIVE_TIMESTAMP.len()
18583 + SPACING_WIDTH;
18584
18585 em_advance * max_char_count
18586 });
18587
18588 let is_singleton = self.buffer_snapshot.is_singleton();
18589
18590 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18591 left_padding += if !is_singleton {
18592 em_width * 4.0
18593 } else if show_code_actions || show_runnables || show_breakpoints {
18594 em_width * 3.0
18595 } else if show_git_gutter && show_line_numbers {
18596 em_width * 2.0
18597 } else if show_git_gutter || show_line_numbers {
18598 em_width
18599 } else {
18600 px(0.)
18601 };
18602
18603 let shows_folds = is_singleton && gutter_settings.folds;
18604
18605 let right_padding = if shows_folds && show_line_numbers {
18606 em_width * 4.0
18607 } else if shows_folds || (!is_singleton && show_line_numbers) {
18608 em_width * 3.0
18609 } else if show_line_numbers {
18610 em_width
18611 } else {
18612 px(0.)
18613 };
18614
18615 Some(GutterDimensions {
18616 left_padding,
18617 right_padding,
18618 width: line_gutter_width + left_padding + right_padding,
18619 margin: -descent,
18620 git_blame_entries_width,
18621 })
18622 }
18623
18624 pub fn render_crease_toggle(
18625 &self,
18626 buffer_row: MultiBufferRow,
18627 row_contains_cursor: bool,
18628 editor: Entity<Editor>,
18629 window: &mut Window,
18630 cx: &mut App,
18631 ) -> Option<AnyElement> {
18632 let folded = self.is_line_folded(buffer_row);
18633 let mut is_foldable = false;
18634
18635 if let Some(crease) = self
18636 .crease_snapshot
18637 .query_row(buffer_row, &self.buffer_snapshot)
18638 {
18639 is_foldable = true;
18640 match crease {
18641 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18642 if let Some(render_toggle) = render_toggle {
18643 let toggle_callback =
18644 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18645 if folded {
18646 editor.update(cx, |editor, cx| {
18647 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18648 });
18649 } else {
18650 editor.update(cx, |editor, cx| {
18651 editor.unfold_at(
18652 &crate::UnfoldAt { buffer_row },
18653 window,
18654 cx,
18655 )
18656 });
18657 }
18658 });
18659 return Some((render_toggle)(
18660 buffer_row,
18661 folded,
18662 toggle_callback,
18663 window,
18664 cx,
18665 ));
18666 }
18667 }
18668 }
18669 }
18670
18671 is_foldable |= self.starts_indent(buffer_row);
18672
18673 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18674 Some(
18675 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18676 .toggle_state(folded)
18677 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18678 if folded {
18679 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18680 } else {
18681 this.fold_at(&FoldAt { buffer_row }, window, cx);
18682 }
18683 }))
18684 .into_any_element(),
18685 )
18686 } else {
18687 None
18688 }
18689 }
18690
18691 pub fn render_crease_trailer(
18692 &self,
18693 buffer_row: MultiBufferRow,
18694 window: &mut Window,
18695 cx: &mut App,
18696 ) -> Option<AnyElement> {
18697 let folded = self.is_line_folded(buffer_row);
18698 if let Crease::Inline { render_trailer, .. } = self
18699 .crease_snapshot
18700 .query_row(buffer_row, &self.buffer_snapshot)?
18701 {
18702 let render_trailer = render_trailer.as_ref()?;
18703 Some(render_trailer(buffer_row, folded, window, cx))
18704 } else {
18705 None
18706 }
18707 }
18708}
18709
18710impl Deref for EditorSnapshot {
18711 type Target = DisplaySnapshot;
18712
18713 fn deref(&self) -> &Self::Target {
18714 &self.display_snapshot
18715 }
18716}
18717
18718#[derive(Clone, Debug, PartialEq, Eq)]
18719pub enum EditorEvent {
18720 InputIgnored {
18721 text: Arc<str>,
18722 },
18723 InputHandled {
18724 utf16_range_to_replace: Option<Range<isize>>,
18725 text: Arc<str>,
18726 },
18727 ExcerptsAdded {
18728 buffer: Entity<Buffer>,
18729 predecessor: ExcerptId,
18730 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18731 },
18732 ExcerptsRemoved {
18733 ids: Vec<ExcerptId>,
18734 },
18735 BufferFoldToggled {
18736 ids: Vec<ExcerptId>,
18737 folded: bool,
18738 },
18739 ExcerptsEdited {
18740 ids: Vec<ExcerptId>,
18741 },
18742 ExcerptsExpanded {
18743 ids: Vec<ExcerptId>,
18744 },
18745 BufferEdited,
18746 Edited {
18747 transaction_id: clock::Lamport,
18748 },
18749 Reparsed(BufferId),
18750 Focused,
18751 FocusedIn,
18752 Blurred,
18753 DirtyChanged,
18754 Saved,
18755 TitleChanged,
18756 DiffBaseChanged,
18757 SelectionsChanged {
18758 local: bool,
18759 },
18760 ScrollPositionChanged {
18761 local: bool,
18762 autoscroll: bool,
18763 },
18764 Closed,
18765 TransactionUndone {
18766 transaction_id: clock::Lamport,
18767 },
18768 TransactionBegun {
18769 transaction_id: clock::Lamport,
18770 },
18771 Reloaded,
18772 CursorShapeChanged,
18773 PushedToNavHistory {
18774 anchor: Anchor,
18775 is_deactivate: bool,
18776 },
18777}
18778
18779impl EventEmitter<EditorEvent> for Editor {}
18780
18781impl Focusable for Editor {
18782 fn focus_handle(&self, _cx: &App) -> FocusHandle {
18783 self.focus_handle.clone()
18784 }
18785}
18786
18787impl Render for Editor {
18788 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18789 let settings = ThemeSettings::get_global(cx);
18790
18791 let mut text_style = match self.mode {
18792 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18793 color: cx.theme().colors().editor_foreground,
18794 font_family: settings.ui_font.family.clone(),
18795 font_features: settings.ui_font.features.clone(),
18796 font_fallbacks: settings.ui_font.fallbacks.clone(),
18797 font_size: rems(0.875).into(),
18798 font_weight: settings.ui_font.weight,
18799 line_height: relative(settings.buffer_line_height.value()),
18800 ..Default::default()
18801 },
18802 EditorMode::Full => TextStyle {
18803 color: cx.theme().colors().editor_foreground,
18804 font_family: settings.buffer_font.family.clone(),
18805 font_features: settings.buffer_font.features.clone(),
18806 font_fallbacks: settings.buffer_font.fallbacks.clone(),
18807 font_size: settings.buffer_font_size(cx).into(),
18808 font_weight: settings.buffer_font.weight,
18809 line_height: relative(settings.buffer_line_height.value()),
18810 ..Default::default()
18811 },
18812 };
18813 if let Some(text_style_refinement) = &self.text_style_refinement {
18814 text_style.refine(text_style_refinement)
18815 }
18816
18817 let background = match self.mode {
18818 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18819 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18820 EditorMode::Full => cx.theme().colors().editor_background,
18821 };
18822
18823 EditorElement::new(
18824 &cx.entity(),
18825 EditorStyle {
18826 background,
18827 local_player: cx.theme().players().local(),
18828 text: text_style,
18829 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18830 syntax: cx.theme().syntax().clone(),
18831 status: cx.theme().status().clone(),
18832 inlay_hints_style: make_inlay_hints_style(cx),
18833 inline_completion_styles: make_suggestion_styles(cx),
18834 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18835 },
18836 )
18837 }
18838}
18839
18840impl EntityInputHandler for Editor {
18841 fn text_for_range(
18842 &mut self,
18843 range_utf16: Range<usize>,
18844 adjusted_range: &mut Option<Range<usize>>,
18845 _: &mut Window,
18846 cx: &mut Context<Self>,
18847 ) -> Option<String> {
18848 let snapshot = self.buffer.read(cx).read(cx);
18849 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18850 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18851 if (start.0..end.0) != range_utf16 {
18852 adjusted_range.replace(start.0..end.0);
18853 }
18854 Some(snapshot.text_for_range(start..end).collect())
18855 }
18856
18857 fn selected_text_range(
18858 &mut self,
18859 ignore_disabled_input: bool,
18860 _: &mut Window,
18861 cx: &mut Context<Self>,
18862 ) -> Option<UTF16Selection> {
18863 // Prevent the IME menu from appearing when holding down an alphabetic key
18864 // while input is disabled.
18865 if !ignore_disabled_input && !self.input_enabled {
18866 return None;
18867 }
18868
18869 let selection = self.selections.newest::<OffsetUtf16>(cx);
18870 let range = selection.range();
18871
18872 Some(UTF16Selection {
18873 range: range.start.0..range.end.0,
18874 reversed: selection.reversed,
18875 })
18876 }
18877
18878 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18879 let snapshot = self.buffer.read(cx).read(cx);
18880 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18881 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18882 }
18883
18884 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18885 self.clear_highlights::<InputComposition>(cx);
18886 self.ime_transaction.take();
18887 }
18888
18889 fn replace_text_in_range(
18890 &mut self,
18891 range_utf16: Option<Range<usize>>,
18892 text: &str,
18893 window: &mut Window,
18894 cx: &mut Context<Self>,
18895 ) {
18896 if !self.input_enabled {
18897 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18898 return;
18899 }
18900
18901 self.transact(window, cx, |this, window, cx| {
18902 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
18903 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18904 Some(this.selection_replacement_ranges(range_utf16, cx))
18905 } else {
18906 this.marked_text_ranges(cx)
18907 };
18908
18909 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
18910 let newest_selection_id = this.selections.newest_anchor().id;
18911 this.selections
18912 .all::<OffsetUtf16>(cx)
18913 .iter()
18914 .zip(ranges_to_replace.iter())
18915 .find_map(|(selection, range)| {
18916 if selection.id == newest_selection_id {
18917 Some(
18918 (range.start.0 as isize - selection.head().0 as isize)
18919 ..(range.end.0 as isize - selection.head().0 as isize),
18920 )
18921 } else {
18922 None
18923 }
18924 })
18925 });
18926
18927 cx.emit(EditorEvent::InputHandled {
18928 utf16_range_to_replace: range_to_replace,
18929 text: text.into(),
18930 });
18931
18932 if let Some(new_selected_ranges) = new_selected_ranges {
18933 this.change_selections(None, window, cx, |selections| {
18934 selections.select_ranges(new_selected_ranges)
18935 });
18936 this.backspace(&Default::default(), window, cx);
18937 }
18938
18939 this.handle_input(text, window, cx);
18940 });
18941
18942 if let Some(transaction) = self.ime_transaction {
18943 self.buffer.update(cx, |buffer, cx| {
18944 buffer.group_until_transaction(transaction, cx);
18945 });
18946 }
18947
18948 self.unmark_text(window, cx);
18949 }
18950
18951 fn replace_and_mark_text_in_range(
18952 &mut self,
18953 range_utf16: Option<Range<usize>>,
18954 text: &str,
18955 new_selected_range_utf16: Option<Range<usize>>,
18956 window: &mut Window,
18957 cx: &mut Context<Self>,
18958 ) {
18959 if !self.input_enabled {
18960 return;
18961 }
18962
18963 let transaction = self.transact(window, cx, |this, window, cx| {
18964 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18965 let snapshot = this.buffer.read(cx).read(cx);
18966 if let Some(relative_range_utf16) = range_utf16.as_ref() {
18967 for marked_range in &mut marked_ranges {
18968 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18969 marked_range.start.0 += relative_range_utf16.start;
18970 marked_range.start =
18971 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18972 marked_range.end =
18973 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18974 }
18975 }
18976 Some(marked_ranges)
18977 } else if let Some(range_utf16) = range_utf16 {
18978 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18979 Some(this.selection_replacement_ranges(range_utf16, cx))
18980 } else {
18981 None
18982 };
18983
18984 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18985 let newest_selection_id = this.selections.newest_anchor().id;
18986 this.selections
18987 .all::<OffsetUtf16>(cx)
18988 .iter()
18989 .zip(ranges_to_replace.iter())
18990 .find_map(|(selection, range)| {
18991 if selection.id == newest_selection_id {
18992 Some(
18993 (range.start.0 as isize - selection.head().0 as isize)
18994 ..(range.end.0 as isize - selection.head().0 as isize),
18995 )
18996 } else {
18997 None
18998 }
18999 })
19000 });
19001
19002 cx.emit(EditorEvent::InputHandled {
19003 utf16_range_to_replace: range_to_replace,
19004 text: text.into(),
19005 });
19006
19007 if let Some(ranges) = ranges_to_replace {
19008 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19009 }
19010
19011 let marked_ranges = {
19012 let snapshot = this.buffer.read(cx).read(cx);
19013 this.selections
19014 .disjoint_anchors()
19015 .iter()
19016 .map(|selection| {
19017 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19018 })
19019 .collect::<Vec<_>>()
19020 };
19021
19022 if text.is_empty() {
19023 this.unmark_text(window, cx);
19024 } else {
19025 this.highlight_text::<InputComposition>(
19026 marked_ranges.clone(),
19027 HighlightStyle {
19028 underline: Some(UnderlineStyle {
19029 thickness: px(1.),
19030 color: None,
19031 wavy: false,
19032 }),
19033 ..Default::default()
19034 },
19035 cx,
19036 );
19037 }
19038
19039 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19040 let use_autoclose = this.use_autoclose;
19041 let use_auto_surround = this.use_auto_surround;
19042 this.set_use_autoclose(false);
19043 this.set_use_auto_surround(false);
19044 this.handle_input(text, window, cx);
19045 this.set_use_autoclose(use_autoclose);
19046 this.set_use_auto_surround(use_auto_surround);
19047
19048 if let Some(new_selected_range) = new_selected_range_utf16 {
19049 let snapshot = this.buffer.read(cx).read(cx);
19050 let new_selected_ranges = marked_ranges
19051 .into_iter()
19052 .map(|marked_range| {
19053 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19054 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19055 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19056 snapshot.clip_offset_utf16(new_start, Bias::Left)
19057 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19058 })
19059 .collect::<Vec<_>>();
19060
19061 drop(snapshot);
19062 this.change_selections(None, window, cx, |selections| {
19063 selections.select_ranges(new_selected_ranges)
19064 });
19065 }
19066 });
19067
19068 self.ime_transaction = self.ime_transaction.or(transaction);
19069 if let Some(transaction) = self.ime_transaction {
19070 self.buffer.update(cx, |buffer, cx| {
19071 buffer.group_until_transaction(transaction, cx);
19072 });
19073 }
19074
19075 if self.text_highlights::<InputComposition>(cx).is_none() {
19076 self.ime_transaction.take();
19077 }
19078 }
19079
19080 fn bounds_for_range(
19081 &mut self,
19082 range_utf16: Range<usize>,
19083 element_bounds: gpui::Bounds<Pixels>,
19084 window: &mut Window,
19085 cx: &mut Context<Self>,
19086 ) -> Option<gpui::Bounds<Pixels>> {
19087 let text_layout_details = self.text_layout_details(window);
19088 let gpui::Size {
19089 width: em_width,
19090 height: line_height,
19091 } = self.character_size(window);
19092
19093 let snapshot = self.snapshot(window, cx);
19094 let scroll_position = snapshot.scroll_position();
19095 let scroll_left = scroll_position.x * em_width;
19096
19097 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19098 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19099 + self.gutter_dimensions.width
19100 + self.gutter_dimensions.margin;
19101 let y = line_height * (start.row().as_f32() - scroll_position.y);
19102
19103 Some(Bounds {
19104 origin: element_bounds.origin + point(x, y),
19105 size: size(em_width, line_height),
19106 })
19107 }
19108
19109 fn character_index_for_point(
19110 &mut self,
19111 point: gpui::Point<Pixels>,
19112 _window: &mut Window,
19113 _cx: &mut Context<Self>,
19114 ) -> Option<usize> {
19115 let position_map = self.last_position_map.as_ref()?;
19116 if !position_map.text_hitbox.contains(&point) {
19117 return None;
19118 }
19119 let display_point = position_map.point_for_position(point).previous_valid;
19120 let anchor = position_map
19121 .snapshot
19122 .display_point_to_anchor(display_point, Bias::Left);
19123 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19124 Some(utf16_offset.0)
19125 }
19126}
19127
19128trait SelectionExt {
19129 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19130 fn spanned_rows(
19131 &self,
19132 include_end_if_at_line_start: bool,
19133 map: &DisplaySnapshot,
19134 ) -> Range<MultiBufferRow>;
19135}
19136
19137impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19138 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19139 let start = self
19140 .start
19141 .to_point(&map.buffer_snapshot)
19142 .to_display_point(map);
19143 let end = self
19144 .end
19145 .to_point(&map.buffer_snapshot)
19146 .to_display_point(map);
19147 if self.reversed {
19148 end..start
19149 } else {
19150 start..end
19151 }
19152 }
19153
19154 fn spanned_rows(
19155 &self,
19156 include_end_if_at_line_start: bool,
19157 map: &DisplaySnapshot,
19158 ) -> Range<MultiBufferRow> {
19159 let start = self.start.to_point(&map.buffer_snapshot);
19160 let mut end = self.end.to_point(&map.buffer_snapshot);
19161 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19162 end.row -= 1;
19163 }
19164
19165 let buffer_start = map.prev_line_boundary(start).0;
19166 let buffer_end = map.next_line_boundary(end).0;
19167 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19168 }
19169}
19170
19171impl<T: InvalidationRegion> InvalidationStack<T> {
19172 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19173 where
19174 S: Clone + ToOffset,
19175 {
19176 while let Some(region) = self.last() {
19177 let all_selections_inside_invalidation_ranges =
19178 if selections.len() == region.ranges().len() {
19179 selections
19180 .iter()
19181 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19182 .all(|(selection, invalidation_range)| {
19183 let head = selection.head().to_offset(buffer);
19184 invalidation_range.start <= head && invalidation_range.end >= head
19185 })
19186 } else {
19187 false
19188 };
19189
19190 if all_selections_inside_invalidation_ranges {
19191 break;
19192 } else {
19193 self.pop();
19194 }
19195 }
19196 }
19197}
19198
19199impl<T> Default for InvalidationStack<T> {
19200 fn default() -> Self {
19201 Self(Default::default())
19202 }
19203}
19204
19205impl<T> Deref for InvalidationStack<T> {
19206 type Target = Vec<T>;
19207
19208 fn deref(&self) -> &Self::Target {
19209 &self.0
19210 }
19211}
19212
19213impl<T> DerefMut for InvalidationStack<T> {
19214 fn deref_mut(&mut self) -> &mut Self::Target {
19215 &mut self.0
19216 }
19217}
19218
19219impl InvalidationRegion for SnippetState {
19220 fn ranges(&self) -> &[Range<Anchor>] {
19221 &self.ranges[self.active_index]
19222 }
19223}
19224
19225pub fn diagnostic_block_renderer(
19226 diagnostic: Diagnostic,
19227 max_message_rows: Option<u8>,
19228 allow_closing: bool,
19229) -> RenderBlock {
19230 let (text_without_backticks, code_ranges) =
19231 highlight_diagnostic_message(&diagnostic, max_message_rows);
19232
19233 Arc::new(move |cx: &mut BlockContext| {
19234 let group_id: SharedString = cx.block_id.to_string().into();
19235
19236 let mut text_style = cx.window.text_style().clone();
19237 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19238 let theme_settings = ThemeSettings::get_global(cx);
19239 text_style.font_family = theme_settings.buffer_font.family.clone();
19240 text_style.font_style = theme_settings.buffer_font.style;
19241 text_style.font_features = theme_settings.buffer_font.features.clone();
19242 text_style.font_weight = theme_settings.buffer_font.weight;
19243
19244 let multi_line_diagnostic = diagnostic.message.contains('\n');
19245
19246 let buttons = |diagnostic: &Diagnostic| {
19247 if multi_line_diagnostic {
19248 v_flex()
19249 } else {
19250 h_flex()
19251 }
19252 .when(allow_closing, |div| {
19253 div.children(diagnostic.is_primary.then(|| {
19254 IconButton::new("close-block", IconName::XCircle)
19255 .icon_color(Color::Muted)
19256 .size(ButtonSize::Compact)
19257 .style(ButtonStyle::Transparent)
19258 .visible_on_hover(group_id.clone())
19259 .on_click(move |_click, window, cx| {
19260 window.dispatch_action(Box::new(Cancel), cx)
19261 })
19262 .tooltip(|window, cx| {
19263 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19264 })
19265 }))
19266 })
19267 .child(
19268 IconButton::new("copy-block", IconName::Copy)
19269 .icon_color(Color::Muted)
19270 .size(ButtonSize::Compact)
19271 .style(ButtonStyle::Transparent)
19272 .visible_on_hover(group_id.clone())
19273 .on_click({
19274 let message = diagnostic.message.clone();
19275 move |_click, _, cx| {
19276 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19277 }
19278 })
19279 .tooltip(Tooltip::text("Copy diagnostic message")),
19280 )
19281 };
19282
19283 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19284 AvailableSpace::min_size(),
19285 cx.window,
19286 cx.app,
19287 );
19288
19289 h_flex()
19290 .id(cx.block_id)
19291 .group(group_id.clone())
19292 .relative()
19293 .size_full()
19294 .block_mouse_down()
19295 .pl(cx.gutter_dimensions.width)
19296 .w(cx.max_width - cx.gutter_dimensions.full_width())
19297 .child(
19298 div()
19299 .flex()
19300 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19301 .flex_shrink(),
19302 )
19303 .child(buttons(&diagnostic))
19304 .child(div().flex().flex_shrink_0().child(
19305 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19306 &text_style,
19307 code_ranges.iter().map(|range| {
19308 (
19309 range.clone(),
19310 HighlightStyle {
19311 font_weight: Some(FontWeight::BOLD),
19312 ..Default::default()
19313 },
19314 )
19315 }),
19316 ),
19317 ))
19318 .into_any_element()
19319 })
19320}
19321
19322fn inline_completion_edit_text(
19323 current_snapshot: &BufferSnapshot,
19324 edits: &[(Range<Anchor>, String)],
19325 edit_preview: &EditPreview,
19326 include_deletions: bool,
19327 cx: &App,
19328) -> HighlightedText {
19329 let edits = edits
19330 .iter()
19331 .map(|(anchor, text)| {
19332 (
19333 anchor.start.text_anchor..anchor.end.text_anchor,
19334 text.clone(),
19335 )
19336 })
19337 .collect::<Vec<_>>();
19338
19339 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19340}
19341
19342pub fn highlight_diagnostic_message(
19343 diagnostic: &Diagnostic,
19344 mut max_message_rows: Option<u8>,
19345) -> (SharedString, Vec<Range<usize>>) {
19346 let mut text_without_backticks = String::new();
19347 let mut code_ranges = Vec::new();
19348
19349 if let Some(source) = &diagnostic.source {
19350 text_without_backticks.push_str(source);
19351 code_ranges.push(0..source.len());
19352 text_without_backticks.push_str(": ");
19353 }
19354
19355 let mut prev_offset = 0;
19356 let mut in_code_block = false;
19357 let has_row_limit = max_message_rows.is_some();
19358 let mut newline_indices = diagnostic
19359 .message
19360 .match_indices('\n')
19361 .filter(|_| has_row_limit)
19362 .map(|(ix, _)| ix)
19363 .fuse()
19364 .peekable();
19365
19366 for (quote_ix, _) in diagnostic
19367 .message
19368 .match_indices('`')
19369 .chain([(diagnostic.message.len(), "")])
19370 {
19371 let mut first_newline_ix = None;
19372 let mut last_newline_ix = None;
19373 while let Some(newline_ix) = newline_indices.peek() {
19374 if *newline_ix < quote_ix {
19375 if first_newline_ix.is_none() {
19376 first_newline_ix = Some(*newline_ix);
19377 }
19378 last_newline_ix = Some(*newline_ix);
19379
19380 if let Some(rows_left) = &mut max_message_rows {
19381 if *rows_left == 0 {
19382 break;
19383 } else {
19384 *rows_left -= 1;
19385 }
19386 }
19387 let _ = newline_indices.next();
19388 } else {
19389 break;
19390 }
19391 }
19392 let prev_len = text_without_backticks.len();
19393 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19394 text_without_backticks.push_str(new_text);
19395 if in_code_block {
19396 code_ranges.push(prev_len..text_without_backticks.len());
19397 }
19398 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19399 in_code_block = !in_code_block;
19400 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19401 text_without_backticks.push_str("...");
19402 break;
19403 }
19404 }
19405
19406 (text_without_backticks.into(), code_ranges)
19407}
19408
19409fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19410 match severity {
19411 DiagnosticSeverity::ERROR => colors.error,
19412 DiagnosticSeverity::WARNING => colors.warning,
19413 DiagnosticSeverity::INFORMATION => colors.info,
19414 DiagnosticSeverity::HINT => colors.info,
19415 _ => colors.ignored,
19416 }
19417}
19418
19419pub fn styled_runs_for_code_label<'a>(
19420 label: &'a CodeLabel,
19421 syntax_theme: &'a theme::SyntaxTheme,
19422) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19423 let fade_out = HighlightStyle {
19424 fade_out: Some(0.35),
19425 ..Default::default()
19426 };
19427
19428 let mut prev_end = label.filter_range.end;
19429 label
19430 .runs
19431 .iter()
19432 .enumerate()
19433 .flat_map(move |(ix, (range, highlight_id))| {
19434 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19435 style
19436 } else {
19437 return Default::default();
19438 };
19439 let mut muted_style = style;
19440 muted_style.highlight(fade_out);
19441
19442 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19443 if range.start >= label.filter_range.end {
19444 if range.start > prev_end {
19445 runs.push((prev_end..range.start, fade_out));
19446 }
19447 runs.push((range.clone(), muted_style));
19448 } else if range.end <= label.filter_range.end {
19449 runs.push((range.clone(), style));
19450 } else {
19451 runs.push((range.start..label.filter_range.end, style));
19452 runs.push((label.filter_range.end..range.end, muted_style));
19453 }
19454 prev_end = cmp::max(prev_end, range.end);
19455
19456 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19457 runs.push((prev_end..label.text.len(), fade_out));
19458 }
19459
19460 runs
19461 })
19462}
19463
19464pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19465 let mut prev_index = 0;
19466 let mut prev_codepoint: Option<char> = None;
19467 text.char_indices()
19468 .chain([(text.len(), '\0')])
19469 .filter_map(move |(index, codepoint)| {
19470 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19471 let is_boundary = index == text.len()
19472 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19473 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19474 if is_boundary {
19475 let chunk = &text[prev_index..index];
19476 prev_index = index;
19477 Some(chunk)
19478 } else {
19479 None
19480 }
19481 })
19482}
19483
19484pub trait RangeToAnchorExt: Sized {
19485 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19486
19487 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19488 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19489 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19490 }
19491}
19492
19493impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19494 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19495 let start_offset = self.start.to_offset(snapshot);
19496 let end_offset = self.end.to_offset(snapshot);
19497 if start_offset == end_offset {
19498 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19499 } else {
19500 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19501 }
19502 }
19503}
19504
19505pub trait RowExt {
19506 fn as_f32(&self) -> f32;
19507
19508 fn next_row(&self) -> Self;
19509
19510 fn previous_row(&self) -> Self;
19511
19512 fn minus(&self, other: Self) -> u32;
19513}
19514
19515impl RowExt for DisplayRow {
19516 fn as_f32(&self) -> f32 {
19517 self.0 as f32
19518 }
19519
19520 fn next_row(&self) -> Self {
19521 Self(self.0 + 1)
19522 }
19523
19524 fn previous_row(&self) -> Self {
19525 Self(self.0.saturating_sub(1))
19526 }
19527
19528 fn minus(&self, other: Self) -> u32 {
19529 self.0 - other.0
19530 }
19531}
19532
19533impl RowExt for MultiBufferRow {
19534 fn as_f32(&self) -> f32 {
19535 self.0 as f32
19536 }
19537
19538 fn next_row(&self) -> Self {
19539 Self(self.0 + 1)
19540 }
19541
19542 fn previous_row(&self) -> Self {
19543 Self(self.0.saturating_sub(1))
19544 }
19545
19546 fn minus(&self, other: Self) -> u32 {
19547 self.0 - other.0
19548 }
19549}
19550
19551trait RowRangeExt {
19552 type Row;
19553
19554 fn len(&self) -> usize;
19555
19556 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19557}
19558
19559impl RowRangeExt for Range<MultiBufferRow> {
19560 type Row = MultiBufferRow;
19561
19562 fn len(&self) -> usize {
19563 (self.end.0 - self.start.0) as usize
19564 }
19565
19566 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19567 (self.start.0..self.end.0).map(MultiBufferRow)
19568 }
19569}
19570
19571impl RowRangeExt for Range<DisplayRow> {
19572 type Row = DisplayRow;
19573
19574 fn len(&self) -> usize {
19575 (self.end.0 - self.start.0) as usize
19576 }
19577
19578 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19579 (self.start.0..self.end.0).map(DisplayRow)
19580 }
19581}
19582
19583/// If select range has more than one line, we
19584/// just point the cursor to range.start.
19585fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19586 if range.start.row == range.end.row {
19587 range
19588 } else {
19589 range.start..range.start
19590 }
19591}
19592pub struct KillRing(ClipboardItem);
19593impl Global for KillRing {}
19594
19595const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19596
19597struct BreakpointPromptEditor {
19598 pub(crate) prompt: Entity<Editor>,
19599 editor: WeakEntity<Editor>,
19600 breakpoint_anchor: Anchor,
19601 kind: BreakpointKind,
19602 block_ids: HashSet<CustomBlockId>,
19603 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19604 _subscriptions: Vec<Subscription>,
19605}
19606
19607impl BreakpointPromptEditor {
19608 const MAX_LINES: u8 = 4;
19609
19610 fn new(
19611 editor: WeakEntity<Editor>,
19612 breakpoint_anchor: Anchor,
19613 kind: BreakpointKind,
19614 window: &mut Window,
19615 cx: &mut Context<Self>,
19616 ) -> Self {
19617 let buffer = cx.new(|cx| {
19618 Buffer::local(
19619 kind.log_message()
19620 .map(|msg| msg.to_string())
19621 .unwrap_or_default(),
19622 cx,
19623 )
19624 });
19625 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19626
19627 let prompt = cx.new(|cx| {
19628 let mut prompt = Editor::new(
19629 EditorMode::AutoHeight {
19630 max_lines: Self::MAX_LINES as usize,
19631 },
19632 buffer,
19633 None,
19634 window,
19635 cx,
19636 );
19637 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19638 prompt.set_show_cursor_when_unfocused(false, cx);
19639 prompt.set_placeholder_text(
19640 "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19641 cx,
19642 );
19643
19644 prompt
19645 });
19646
19647 Self {
19648 prompt,
19649 editor,
19650 breakpoint_anchor,
19651 kind,
19652 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19653 block_ids: Default::default(),
19654 _subscriptions: vec![],
19655 }
19656 }
19657
19658 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19659 self.block_ids.extend(block_ids)
19660 }
19661
19662 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19663 if let Some(editor) = self.editor.upgrade() {
19664 let log_message = self
19665 .prompt
19666 .read(cx)
19667 .buffer
19668 .read(cx)
19669 .as_singleton()
19670 .expect("A multi buffer in breakpoint prompt isn't possible")
19671 .read(cx)
19672 .as_rope()
19673 .to_string();
19674
19675 editor.update(cx, |editor, cx| {
19676 editor.edit_breakpoint_at_anchor(
19677 self.breakpoint_anchor,
19678 self.kind.clone(),
19679 BreakpointEditAction::EditLogMessage(log_message.into()),
19680 cx,
19681 );
19682
19683 editor.remove_blocks(self.block_ids.clone(), None, cx);
19684 cx.focus_self(window);
19685 });
19686 }
19687 }
19688
19689 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19690 self.editor
19691 .update(cx, |editor, cx| {
19692 editor.remove_blocks(self.block_ids.clone(), None, cx);
19693 window.focus(&editor.focus_handle);
19694 })
19695 .log_err();
19696 }
19697
19698 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19699 let settings = ThemeSettings::get_global(cx);
19700 let text_style = TextStyle {
19701 color: if self.prompt.read(cx).read_only(cx) {
19702 cx.theme().colors().text_disabled
19703 } else {
19704 cx.theme().colors().text
19705 },
19706 font_family: settings.buffer_font.family.clone(),
19707 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19708 font_size: settings.buffer_font_size(cx).into(),
19709 font_weight: settings.buffer_font.weight,
19710 line_height: relative(settings.buffer_line_height.value()),
19711 ..Default::default()
19712 };
19713 EditorElement::new(
19714 &self.prompt,
19715 EditorStyle {
19716 background: cx.theme().colors().editor_background,
19717 local_player: cx.theme().players().local(),
19718 text: text_style,
19719 ..Default::default()
19720 },
19721 )
19722 }
19723}
19724
19725impl Render for BreakpointPromptEditor {
19726 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19727 let gutter_dimensions = *self.gutter_dimensions.lock();
19728 h_flex()
19729 .key_context("Editor")
19730 .bg(cx.theme().colors().editor_background)
19731 .border_y_1()
19732 .border_color(cx.theme().status().info_border)
19733 .size_full()
19734 .py(window.line_height() / 2.5)
19735 .on_action(cx.listener(Self::confirm))
19736 .on_action(cx.listener(Self::cancel))
19737 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19738 .child(div().flex_1().child(self.render_prompt_editor(cx)))
19739 }
19740}
19741
19742impl Focusable for BreakpointPromptEditor {
19743 fn focus_handle(&self, cx: &App) -> FocusHandle {
19744 self.prompt.focus_handle(cx)
19745 }
19746}
19747
19748fn all_edits_insertions_or_deletions(
19749 edits: &Vec<(Range<Anchor>, String)>,
19750 snapshot: &MultiBufferSnapshot,
19751) -> bool {
19752 let mut all_insertions = true;
19753 let mut all_deletions = true;
19754
19755 for (range, new_text) in edits.iter() {
19756 let range_is_empty = range.to_offset(&snapshot).is_empty();
19757 let text_is_empty = new_text.is_empty();
19758
19759 if range_is_empty != text_is_empty {
19760 if range_is_empty {
19761 all_deletions = false;
19762 } else {
19763 all_insertions = false;
19764 }
19765 } else {
19766 return false;
19767 }
19768
19769 if !all_insertions && !all_deletions {
19770 return false;
19771 }
19772 }
19773 all_insertions || all_deletions
19774}
19775
19776struct MissingEditPredictionKeybindingTooltip;
19777
19778impl Render for MissingEditPredictionKeybindingTooltip {
19779 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
19780 ui::tooltip_container(window, cx, |container, _, cx| {
19781 container
19782 .flex_shrink_0()
19783 .max_w_80()
19784 .min_h(rems_from_px(124.))
19785 .justify_between()
19786 .child(
19787 v_flex()
19788 .flex_1()
19789 .text_ui_sm(cx)
19790 .child(Label::new("Conflict with Accept Keybinding"))
19791 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19792 )
19793 .child(
19794 h_flex()
19795 .pb_1()
19796 .gap_1()
19797 .items_end()
19798 .w_full()
19799 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19800 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19801 }))
19802 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19803 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19804 })),
19805 )
19806 })
19807 }
19808}
19809
19810#[derive(Debug, Clone, Copy, PartialEq)]
19811pub struct LineHighlight {
19812 pub background: Background,
19813 pub border: Option<gpui::Hsla>,
19814}
19815
19816impl From<Hsla> for LineHighlight {
19817 fn from(hsla: Hsla) -> Self {
19818 Self {
19819 background: hsla.into(),
19820 border: None,
19821 }
19822 }
19823}
19824
19825impl From<Background> for LineHighlight {
19826 fn from(background: Background) -> Self {
19827 Self {
19828 background,
19829 border: None,
19830 }
19831 }
19832}