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};
63use editor_settings::GoToDefinitionFallback;
64pub use editor_settings::{
65 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
66};
67pub use editor_settings_controls::*;
68use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
69pub use element::{
70 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
71};
72use feature_flags::{Debugger, FeatureFlagAppExt};
73use futures::{
74 future::{self, join, Shared},
75 FutureExt,
76};
77use fuzzy::StringMatchCandidate;
78
79use ::git::Restore;
80use code_context_menus::{
81 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
82 CompletionsMenu, ContextMenuOrigin,
83};
84use git::blame::GitBlame;
85use gpui::{
86 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
87 AnimationExt, AnyElement, App, AppContext, AsyncWindowContext, AvailableSpace, Background,
88 Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
89 EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
90 Global, HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
91 ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
92 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
93 WeakEntity, WeakFocusHandle, Window,
94};
95use highlight_matching_bracket::refresh_matching_bracket_highlights;
96use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
97use hover_popover::{hide_hover, HoverState};
98use indent_guides::ActiveIndentGuidesState;
99use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
100pub use inline_completion::Direction;
101use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
102pub use items::MAX_TAB_TITLE_LEN;
103use itertools::Itertools;
104use language::{
105 language_settings::{
106 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
107 WordsCompletionMode,
108 },
109 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
110 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
111 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
112 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
113};
114use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
115use linked_editing_ranges::refresh_linked_ranges;
116use mouse_context_menu::MouseContextMenu;
117use persistence::DB;
118use project::{
119 debugger::breakpoint_store::{
120 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
121 },
122 ProjectPath,
123};
124
125pub use proposed_changes_editor::{
126 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
127};
128use smallvec::smallvec;
129use std::{cell::OnceCell, iter::Peekable};
130use task::{ResolvedTask, TaskTemplate, TaskVariables};
131
132pub use lsp::CompletionContext;
133use lsp::{
134 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
135 InsertTextFormat, LanguageServerId, LanguageServerName,
136};
137
138use language::BufferSnapshot;
139use movement::TextLayoutDetails;
140pub use multi_buffer::{
141 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
142 ToOffset, ToPoint,
143};
144use multi_buffer::{
145 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
146 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
147};
148use parking_lot::Mutex;
149use project::{
150 debugger::breakpoint_store::{Breakpoint, BreakpointKind},
151 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
152 project_settings::{GitGutterSetting, ProjectSettings},
153 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
154 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
155 TaskSourceKind,
156};
157use rand::prelude::*;
158use rpc::{proto::*, ErrorExt};
159use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
160use selections_collection::{
161 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
162};
163use serde::{Deserialize, Serialize};
164use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
165use smallvec::SmallVec;
166use snippet::Snippet;
167use std::sync::Arc;
168use std::{
169 any::TypeId,
170 borrow::Cow,
171 cell::RefCell,
172 cmp::{self, Ordering, Reverse},
173 mem,
174 num::NonZeroU32,
175 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
176 path::{Path, PathBuf},
177 rc::Rc,
178 time::{Duration, Instant},
179};
180pub use sum_tree::Bias;
181use sum_tree::TreeMap;
182use text::{BufferId, OffsetUtf16, Rope};
183use theme::{
184 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
185 ThemeColors, ThemeSettings,
186};
187use ui::{
188 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconButtonShape, IconName,
189 IconSize, Key, Tooltip,
190};
191use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
192use workspace::{
193 item::{ItemHandle, PreviewTabsSettings},
194 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
195 searchable::SearchEvent,
196 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
197 RestoreOnStartupBehavior, SplitDirection, TabBarSettings, Toast, ViewId, Workspace,
198 WorkspaceId, WorkspaceSettings, SERIALIZATION_THROTTLE_TIME,
199};
200
201use crate::hover_links::{find_url, find_url_from_range};
202use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
203
204pub const FILE_HEADER_HEIGHT: u32 = 2;
205pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
206pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
207const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
208const MAX_LINE_LEN: usize = 1024;
209const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
210const MAX_SELECTION_HISTORY_LEN: usize = 1024;
211pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
212#[doc(hidden)]
213pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
214
215pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
216pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
217pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
218
219pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
220pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
221pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
222
223pub type RenderDiffHunkControlsFn = Arc<
224 dyn Fn(
225 u32,
226 &DiffHunkStatus,
227 Range<Anchor>,
228 bool,
229 Pixels,
230 &Entity<Editor>,
231 &mut App,
232 ) -> AnyElement,
233>;
234
235const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
236 alt: true,
237 shift: true,
238 control: false,
239 platform: false,
240 function: false,
241};
242
243#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
244pub enum InlayId {
245 InlineCompletion(usize),
246 Hint(usize),
247}
248
249impl InlayId {
250 fn id(&self) -> usize {
251 match self {
252 Self::InlineCompletion(id) => *id,
253 Self::Hint(id) => *id,
254 }
255 }
256}
257
258pub enum DebugCurrentRowHighlight {}
259enum DocumentHighlightRead {}
260enum DocumentHighlightWrite {}
261enum InputComposition {}
262enum SelectedTextHighlight {}
263
264#[derive(Debug, Copy, Clone, PartialEq, Eq)]
265pub enum Navigated {
266 Yes,
267 No,
268}
269
270impl Navigated {
271 pub fn from_bool(yes: bool) -> Navigated {
272 if yes {
273 Navigated::Yes
274 } else {
275 Navigated::No
276 }
277 }
278}
279
280#[derive(Debug, Clone, PartialEq, Eq)]
281enum DisplayDiffHunk {
282 Folded {
283 display_row: DisplayRow,
284 },
285 Unfolded {
286 is_created_file: bool,
287 diff_base_byte_range: Range<usize>,
288 display_row_range: Range<DisplayRow>,
289 multi_buffer_range: Range<Anchor>,
290 status: DiffHunkStatus,
291 },
292}
293
294pub fn init_settings(cx: &mut App) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut App) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new(
306 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 workspace.register_action(Editor::cancel_language_server_work);
311 },
312 )
313 .detach();
314
315 cx.on_action(move |_: &workspace::NewFile, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(
319 Default::default(),
320 app_state,
321 cx,
322 |workspace, window, cx| {
323 Editor::new_file(workspace, &Default::default(), window, cx)
324 },
325 )
326 .detach();
327 }
328 });
329 cx.on_action(move |_: &workspace::NewWindow, cx| {
330 let app_state = workspace::AppState::global(cx);
331 if let Some(app_state) = app_state.upgrade() {
332 workspace::open_new(
333 Default::default(),
334 app_state,
335 cx,
336 |workspace, window, cx| {
337 cx.activate(true);
338 Editor::new_file(workspace, &Default::default(), window, cx)
339 },
340 )
341 .detach();
342 }
343 });
344}
345
346pub struct SearchWithinRange;
347
348trait InvalidationRegion {
349 fn ranges(&self) -> &[Range<Anchor>];
350}
351
352#[derive(Clone, Debug, PartialEq)]
353pub enum SelectPhase {
354 Begin {
355 position: DisplayPoint,
356 add: bool,
357 click_count: usize,
358 },
359 BeginColumnar {
360 position: DisplayPoint,
361 reset: bool,
362 goal_column: u32,
363 },
364 Extend {
365 position: DisplayPoint,
366 click_count: usize,
367 },
368 Update {
369 position: DisplayPoint,
370 goal_column: u32,
371 scroll_delta: gpui::Point<f32>,
372 },
373 End,
374}
375
376#[derive(Clone, Debug)]
377pub enum SelectMode {
378 Character,
379 Word(Range<Anchor>),
380 Line(Range<Anchor>),
381 All,
382}
383
384#[derive(Copy, Clone, PartialEq, Eq, Debug)]
385pub enum EditorMode {
386 SingleLine { auto_width: bool },
387 AutoHeight { max_lines: usize },
388 Full,
389}
390
391#[derive(Copy, Clone, Debug)]
392pub enum SoftWrap {
393 /// Prefer not to wrap at all.
394 ///
395 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
396 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
397 GitDiff,
398 /// Prefer a single line generally, unless an overly long line is encountered.
399 None,
400 /// Soft wrap lines that exceed the editor width.
401 EditorWidth,
402 /// Soft wrap lines at the preferred line length.
403 Column(u32),
404 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
405 Bounded(u32),
406}
407
408#[derive(Clone)]
409pub struct EditorStyle {
410 pub background: Hsla,
411 pub local_player: PlayerColor,
412 pub text: TextStyle,
413 pub scrollbar_width: Pixels,
414 pub syntax: Arc<SyntaxTheme>,
415 pub status: StatusColors,
416 pub inlay_hints_style: HighlightStyle,
417 pub inline_completion_styles: InlineCompletionStyles,
418 pub unnecessary_code_fade: f32,
419}
420
421impl Default for EditorStyle {
422 fn default() -> Self {
423 Self {
424 background: Hsla::default(),
425 local_player: PlayerColor::default(),
426 text: TextStyle::default(),
427 scrollbar_width: Pixels::default(),
428 syntax: Default::default(),
429 // HACK: Status colors don't have a real default.
430 // We should look into removing the status colors from the editor
431 // style and retrieve them directly from the theme.
432 status: StatusColors::dark(),
433 inlay_hints_style: HighlightStyle::default(),
434 inline_completion_styles: InlineCompletionStyles {
435 insertion: HighlightStyle::default(),
436 whitespace: HighlightStyle::default(),
437 },
438 unnecessary_code_fade: Default::default(),
439 }
440 }
441}
442
443pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
444 let show_background = language_settings::language_settings(None, None, cx)
445 .inlay_hints
446 .show_background;
447
448 HighlightStyle {
449 color: Some(cx.theme().status().hint),
450 background_color: show_background.then(|| cx.theme().status().hint_background),
451 ..HighlightStyle::default()
452 }
453}
454
455pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
456 InlineCompletionStyles {
457 insertion: HighlightStyle {
458 color: Some(cx.theme().status().predictive),
459 ..HighlightStyle::default()
460 },
461 whitespace: HighlightStyle {
462 background_color: Some(cx.theme().status().created_background),
463 ..HighlightStyle::default()
464 },
465 }
466}
467
468type CompletionId = usize;
469
470pub(crate) enum EditDisplayMode {
471 TabAccept,
472 DiffPopover,
473 Inline,
474}
475
476enum InlineCompletion {
477 Edit {
478 edits: Vec<(Range<Anchor>, String)>,
479 edit_preview: Option<EditPreview>,
480 display_mode: EditDisplayMode,
481 snapshot: BufferSnapshot,
482 },
483 Move {
484 target: Anchor,
485 snapshot: BufferSnapshot,
486 },
487}
488
489struct InlineCompletionState {
490 inlay_ids: Vec<InlayId>,
491 completion: InlineCompletion,
492 completion_id: Option<SharedString>,
493 invalidation_range: Range<Anchor>,
494}
495
496enum EditPredictionSettings {
497 Disabled,
498 Enabled {
499 show_in_menu: bool,
500 preview_requires_modifier: bool,
501 },
502}
503
504enum InlineCompletionHighlight {}
505
506#[derive(Debug, Clone)]
507struct InlineDiagnostic {
508 message: SharedString,
509 group_id: usize,
510 is_primary: bool,
511 start: Point,
512 severity: DiagnosticSeverity,
513}
514
515pub enum MenuInlineCompletionsPolicy {
516 Never,
517 ByProvider,
518}
519
520pub enum EditPredictionPreview {
521 /// Modifier is not pressed
522 Inactive { released_too_fast: bool },
523 /// Modifier pressed
524 Active {
525 since: Instant,
526 previous_scroll_position: Option<ScrollAnchor>,
527 },
528}
529
530impl EditPredictionPreview {
531 pub fn released_too_fast(&self) -> bool {
532 match self {
533 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
534 EditPredictionPreview::Active { .. } => false,
535 }
536 }
537
538 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
539 if let EditPredictionPreview::Active {
540 previous_scroll_position,
541 ..
542 } = self
543 {
544 *previous_scroll_position = scroll_position;
545 }
546 }
547}
548
549pub struct ContextMenuOptions {
550 pub min_entries_visible: usize,
551 pub max_entries_visible: usize,
552 pub placement: Option<ContextMenuPlacement>,
553}
554
555#[derive(Debug, Clone, PartialEq, Eq)]
556pub enum ContextMenuPlacement {
557 Above,
558 Below,
559}
560
561#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
562struct EditorActionId(usize);
563
564impl EditorActionId {
565 pub fn post_inc(&mut self) -> Self {
566 let answer = self.0;
567
568 *self = Self(answer + 1);
569
570 Self(answer)
571 }
572}
573
574// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
575// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
576
577type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
578type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
579
580#[derive(Default)]
581struct ScrollbarMarkerState {
582 scrollbar_size: Size<Pixels>,
583 dirty: bool,
584 markers: Arc<[PaintQuad]>,
585 pending_refresh: Option<Task<Result<()>>>,
586}
587
588impl ScrollbarMarkerState {
589 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
590 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
591 }
592}
593
594#[derive(Clone, Debug)]
595struct RunnableTasks {
596 templates: Vec<(TaskSourceKind, TaskTemplate)>,
597 offset: multi_buffer::Anchor,
598 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
599 column: u32,
600 // Values of all named captures, including those starting with '_'
601 extra_variables: HashMap<String, String>,
602 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
603 context_range: Range<BufferOffset>,
604}
605
606impl RunnableTasks {
607 fn resolve<'a>(
608 &'a self,
609 cx: &'a task::TaskContext,
610 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
611 self.templates.iter().filter_map(|(kind, template)| {
612 template
613 .resolve_task(&kind.to_id_base(), cx)
614 .map(|task| (kind.clone(), task))
615 })
616 }
617}
618
619#[derive(Clone)]
620struct ResolvedTasks {
621 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
622 position: Anchor,
623}
624
625#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
626struct BufferOffset(usize);
627
628// Addons allow storing per-editor state in other crates (e.g. Vim)
629pub trait Addon: 'static {
630 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
631
632 fn render_buffer_header_controls(
633 &self,
634 _: &ExcerptInfo,
635 _: &Window,
636 _: &App,
637 ) -> Option<AnyElement> {
638 None
639 }
640
641 fn to_any(&self) -> &dyn std::any::Any;
642}
643
644/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
645///
646/// See the [module level documentation](self) for more information.
647pub struct Editor {
648 focus_handle: FocusHandle,
649 last_focused_descendant: Option<WeakFocusHandle>,
650 /// The text buffer being edited
651 buffer: Entity<MultiBuffer>,
652 /// Map of how text in the buffer should be displayed.
653 /// Handles soft wraps, folds, fake inlay text insertions, etc.
654 pub display_map: Entity<DisplayMap>,
655 pub selections: SelectionsCollection,
656 pub scroll_manager: ScrollManager,
657 /// When inline assist editors are linked, they all render cursors because
658 /// typing enters text into each of them, even the ones that aren't focused.
659 pub(crate) show_cursor_when_unfocused: bool,
660 columnar_selection_tail: Option<Anchor>,
661 add_selections_state: Option<AddSelectionsState>,
662 select_next_state: Option<SelectNextState>,
663 select_prev_state: Option<SelectNextState>,
664 selection_history: SelectionHistory,
665 autoclose_regions: Vec<AutocloseRegion>,
666 snippet_stack: InvalidationStack<SnippetState>,
667 select_syntax_node_history: SelectSyntaxNodeHistory,
668 ime_transaction: Option<TransactionId>,
669 active_diagnostics: Option<ActiveDiagnosticGroup>,
670 show_inline_diagnostics: bool,
671 inline_diagnostics_update: Task<()>,
672 inline_diagnostics_enabled: bool,
673 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
674 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
675 hard_wrap: Option<usize>,
676
677 // TODO: make this a access method
678 pub project: Option<Entity<Project>>,
679 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
680 completion_provider: Option<Box<dyn CompletionProvider>>,
681 collaboration_hub: Option<Box<dyn CollaborationHub>>,
682 blink_manager: Entity<BlinkManager>,
683 show_cursor_names: bool,
684 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
685 pub show_local_selections: bool,
686 mode: EditorMode,
687 show_breadcrumbs: bool,
688 show_gutter: bool,
689 show_scrollbars: bool,
690 show_line_numbers: Option<bool>,
691 use_relative_line_numbers: Option<bool>,
692 show_git_diff_gutter: Option<bool>,
693 show_code_actions: Option<bool>,
694 show_runnables: Option<bool>,
695 show_breakpoints: Option<bool>,
696 show_wrap_guides: Option<bool>,
697 show_indent_guides: Option<bool>,
698 placeholder_text: Option<Arc<str>>,
699 highlight_order: usize,
700 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
701 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
702 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
703 scrollbar_marker_state: ScrollbarMarkerState,
704 active_indent_guides_state: ActiveIndentGuidesState,
705 nav_history: Option<ItemNavHistory>,
706 context_menu: RefCell<Option<CodeContextMenu>>,
707 context_menu_options: Option<ContextMenuOptions>,
708 mouse_context_menu: Option<MouseContextMenu>,
709 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
710 signature_help_state: SignatureHelpState,
711 auto_signature_help: Option<bool>,
712 find_all_references_task_sources: Vec<Anchor>,
713 next_completion_id: CompletionId,
714 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
715 code_actions_task: Option<Task<Result<()>>>,
716 selection_highlight_task: Option<Task<()>>,
717 document_highlights_task: Option<Task<()>>,
718 linked_editing_range_task: Option<Task<Option<()>>>,
719 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
720 pending_rename: Option<RenameState>,
721 searchable: bool,
722 cursor_shape: CursorShape,
723 current_line_highlight: Option<CurrentLineHighlight>,
724 collapse_matches: bool,
725 autoindent_mode: Option<AutoindentMode>,
726 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
727 input_enabled: bool,
728 use_modal_editing: bool,
729 read_only: bool,
730 leader_peer_id: Option<PeerId>,
731 remote_id: Option<ViewId>,
732 hover_state: HoverState,
733 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
734 gutter_hovered: bool,
735 hovered_link_state: Option<HoveredLinkState>,
736 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
737 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
738 active_inline_completion: Option<InlineCompletionState>,
739 /// Used to prevent flickering as the user types while the menu is open
740 stale_inline_completion_in_menu: Option<InlineCompletionState>,
741 edit_prediction_settings: EditPredictionSettings,
742 inline_completions_hidden_for_vim_mode: bool,
743 show_inline_completions_override: Option<bool>,
744 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
745 edit_prediction_preview: EditPredictionPreview,
746 edit_prediction_indent_conflict: bool,
747 edit_prediction_requires_modifier_in_indent_conflict: bool,
748 inlay_hint_cache: InlayHintCache,
749 next_inlay_id: usize,
750 _subscriptions: Vec<Subscription>,
751 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
752 gutter_dimensions: GutterDimensions,
753 style: Option<EditorStyle>,
754 text_style_refinement: Option<TextStyleRefinement>,
755 next_editor_action_id: EditorActionId,
756 editor_actions:
757 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
758 use_autoclose: bool,
759 use_auto_surround: bool,
760 auto_replace_emoji_shortcode: bool,
761 jsx_tag_auto_close_enabled_in_any_buffer: bool,
762 show_git_blame_gutter: bool,
763 show_git_blame_inline: bool,
764 show_git_blame_inline_delay_task: Option<Task<()>>,
765 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
766 git_blame_inline_enabled: bool,
767 render_diff_hunk_controls: RenderDiffHunkControlsFn,
768 serialize_dirty_buffers: bool,
769 show_selection_menu: Option<bool>,
770 blame: Option<Entity<GitBlame>>,
771 blame_subscription: Option<Subscription>,
772 custom_context_menu: Option<
773 Box<
774 dyn 'static
775 + Fn(
776 &mut Self,
777 DisplayPoint,
778 &mut Window,
779 &mut Context<Self>,
780 ) -> Option<Entity<ui::ContextMenu>>,
781 >,
782 >,
783 last_bounds: Option<Bounds<Pixels>>,
784 last_position_map: Option<Rc<PositionMap>>,
785 expect_bounds_change: Option<Bounds<Pixels>>,
786 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
787 tasks_update_task: Option<Task<()>>,
788 pub breakpoint_store: Option<Entity<BreakpointStore>>,
789 /// Allow's a user to create a breakpoint by selecting this indicator
790 /// It should be None while a user is not hovering over the gutter
791 /// Otherwise it represents the point that the breakpoint will be shown
792 pub gutter_breakpoint_indicator: Option<DisplayPoint>,
793 in_project_search: bool,
794 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
795 breadcrumb_header: Option<String>,
796 focused_block: Option<FocusedBlock>,
797 next_scroll_position: NextScrollCursorCenterTopBottom,
798 addons: HashMap<TypeId, Box<dyn Addon>>,
799 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
800 load_diff_task: Option<Shared<Task<()>>>,
801 selection_mark_mode: bool,
802 toggle_fold_multiple_buffers: Task<()>,
803 _scroll_cursor_center_top_bottom_task: Task<()>,
804 serialize_selections: Task<()>,
805 serialize_folds: Task<()>,
806 mouse_cursor_hidden: bool,
807 hide_mouse_while_typing: bool,
808}
809
810#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
811enum NextScrollCursorCenterTopBottom {
812 #[default]
813 Center,
814 Top,
815 Bottom,
816}
817
818impl NextScrollCursorCenterTopBottom {
819 fn next(&self) -> Self {
820 match self {
821 Self::Center => Self::Top,
822 Self::Top => Self::Bottom,
823 Self::Bottom => Self::Center,
824 }
825 }
826}
827
828#[derive(Clone)]
829pub struct EditorSnapshot {
830 pub mode: EditorMode,
831 show_gutter: bool,
832 show_line_numbers: Option<bool>,
833 show_git_diff_gutter: Option<bool>,
834 show_code_actions: Option<bool>,
835 show_runnables: Option<bool>,
836 show_breakpoints: Option<bool>,
837 git_blame_gutter_max_author_length: Option<usize>,
838 pub display_snapshot: DisplaySnapshot,
839 pub placeholder_text: Option<Arc<str>>,
840 is_focused: bool,
841 scroll_anchor: ScrollAnchor,
842 ongoing_scroll: OngoingScroll,
843 current_line_highlight: CurrentLineHighlight,
844 gutter_hovered: bool,
845}
846
847const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
848
849#[derive(Default, Debug, Clone, Copy)]
850pub struct GutterDimensions {
851 pub left_padding: Pixels,
852 pub right_padding: Pixels,
853 pub width: Pixels,
854 pub margin: Pixels,
855 pub git_blame_entries_width: Option<Pixels>,
856}
857
858impl GutterDimensions {
859 /// The full width of the space taken up by the gutter.
860 pub fn full_width(&self) -> Pixels {
861 self.margin + self.width
862 }
863
864 /// The width of the space reserved for the fold indicators,
865 /// use alongside 'justify_end' and `gutter_width` to
866 /// right align content with the line numbers
867 pub fn fold_area_width(&self) -> Pixels {
868 self.margin + self.right_padding
869 }
870}
871
872#[derive(Debug)]
873pub struct RemoteSelection {
874 pub replica_id: ReplicaId,
875 pub selection: Selection<Anchor>,
876 pub cursor_shape: CursorShape,
877 pub peer_id: PeerId,
878 pub line_mode: bool,
879 pub participant_index: Option<ParticipantIndex>,
880 pub user_name: Option<SharedString>,
881}
882
883#[derive(Clone, Debug)]
884struct SelectionHistoryEntry {
885 selections: Arc<[Selection<Anchor>]>,
886 select_next_state: Option<SelectNextState>,
887 select_prev_state: Option<SelectNextState>,
888 add_selections_state: Option<AddSelectionsState>,
889}
890
891enum SelectionHistoryMode {
892 Normal,
893 Undoing,
894 Redoing,
895}
896
897#[derive(Clone, PartialEq, Eq, Hash)]
898struct HoveredCursor {
899 replica_id: u16,
900 selection_id: usize,
901}
902
903impl Default for SelectionHistoryMode {
904 fn default() -> Self {
905 Self::Normal
906 }
907}
908
909#[derive(Default)]
910struct SelectionHistory {
911 #[allow(clippy::type_complexity)]
912 selections_by_transaction:
913 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
914 mode: SelectionHistoryMode,
915 undo_stack: VecDeque<SelectionHistoryEntry>,
916 redo_stack: VecDeque<SelectionHistoryEntry>,
917}
918
919impl SelectionHistory {
920 fn insert_transaction(
921 &mut self,
922 transaction_id: TransactionId,
923 selections: Arc<[Selection<Anchor>]>,
924 ) {
925 self.selections_by_transaction
926 .insert(transaction_id, (selections, None));
927 }
928
929 #[allow(clippy::type_complexity)]
930 fn transaction(
931 &self,
932 transaction_id: TransactionId,
933 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
934 self.selections_by_transaction.get(&transaction_id)
935 }
936
937 #[allow(clippy::type_complexity)]
938 fn transaction_mut(
939 &mut self,
940 transaction_id: TransactionId,
941 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
942 self.selections_by_transaction.get_mut(&transaction_id)
943 }
944
945 fn push(&mut self, entry: SelectionHistoryEntry) {
946 if !entry.selections.is_empty() {
947 match self.mode {
948 SelectionHistoryMode::Normal => {
949 self.push_undo(entry);
950 self.redo_stack.clear();
951 }
952 SelectionHistoryMode::Undoing => self.push_redo(entry),
953 SelectionHistoryMode::Redoing => self.push_undo(entry),
954 }
955 }
956 }
957
958 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
959 if self
960 .undo_stack
961 .back()
962 .map_or(true, |e| e.selections != entry.selections)
963 {
964 self.undo_stack.push_back(entry);
965 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
966 self.undo_stack.pop_front();
967 }
968 }
969 }
970
971 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
972 if self
973 .redo_stack
974 .back()
975 .map_or(true, |e| e.selections != entry.selections)
976 {
977 self.redo_stack.push_back(entry);
978 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
979 self.redo_stack.pop_front();
980 }
981 }
982 }
983}
984
985struct RowHighlight {
986 index: usize,
987 range: Range<Anchor>,
988 color: Hsla,
989 should_autoscroll: bool,
990}
991
992#[derive(Clone, Debug)]
993struct AddSelectionsState {
994 above: bool,
995 stack: Vec<usize>,
996}
997
998#[derive(Clone)]
999struct SelectNextState {
1000 query: AhoCorasick,
1001 wordwise: bool,
1002 done: bool,
1003}
1004
1005impl std::fmt::Debug for SelectNextState {
1006 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1007 f.debug_struct(std::any::type_name::<Self>())
1008 .field("wordwise", &self.wordwise)
1009 .field("done", &self.done)
1010 .finish()
1011 }
1012}
1013
1014#[derive(Debug)]
1015struct AutocloseRegion {
1016 selection_id: usize,
1017 range: Range<Anchor>,
1018 pair: BracketPair,
1019}
1020
1021#[derive(Debug)]
1022struct SnippetState {
1023 ranges: Vec<Vec<Range<Anchor>>>,
1024 active_index: usize,
1025 choices: Vec<Option<Vec<String>>>,
1026}
1027
1028#[doc(hidden)]
1029pub struct RenameState {
1030 pub range: Range<Anchor>,
1031 pub old_name: Arc<str>,
1032 pub editor: Entity<Editor>,
1033 block_id: CustomBlockId,
1034}
1035
1036struct InvalidationStack<T>(Vec<T>);
1037
1038struct RegisteredInlineCompletionProvider {
1039 provider: Arc<dyn InlineCompletionProviderHandle>,
1040 _subscription: Subscription,
1041}
1042
1043#[derive(Debug, PartialEq, Eq)]
1044struct ActiveDiagnosticGroup {
1045 primary_range: Range<Anchor>,
1046 primary_message: String,
1047 group_id: usize,
1048 blocks: HashMap<CustomBlockId, Diagnostic>,
1049 is_valid: bool,
1050}
1051
1052#[derive(Serialize, Deserialize, Clone, Debug)]
1053pub struct ClipboardSelection {
1054 /// The number of bytes in this selection.
1055 pub len: usize,
1056 /// Whether this was a full-line selection.
1057 pub is_entire_line: bool,
1058 /// The indentation of the first line when this content was originally copied.
1059 pub first_line_indent: u32,
1060}
1061
1062// selections, scroll behavior, was newest selection reversed
1063type SelectSyntaxNodeHistoryState = (
1064 Box<[Selection<usize>]>,
1065 SelectSyntaxNodeScrollBehavior,
1066 bool,
1067);
1068
1069#[derive(Default)]
1070struct SelectSyntaxNodeHistory {
1071 stack: Vec<SelectSyntaxNodeHistoryState>,
1072 // disable temporarily to allow changing selections without losing the stack
1073 pub disable_clearing: bool,
1074}
1075
1076impl SelectSyntaxNodeHistory {
1077 pub fn try_clear(&mut self) {
1078 if !self.disable_clearing {
1079 self.stack.clear();
1080 }
1081 }
1082
1083 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1084 self.stack.push(selection);
1085 }
1086
1087 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1088 self.stack.pop()
1089 }
1090}
1091
1092enum SelectSyntaxNodeScrollBehavior {
1093 CursorTop,
1094 CenterSelection,
1095 CursorBottom,
1096}
1097
1098#[derive(Debug)]
1099pub(crate) struct NavigationData {
1100 cursor_anchor: Anchor,
1101 cursor_position: Point,
1102 scroll_anchor: ScrollAnchor,
1103 scroll_top_row: u32,
1104}
1105
1106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1107pub enum GotoDefinitionKind {
1108 Symbol,
1109 Declaration,
1110 Type,
1111 Implementation,
1112}
1113
1114#[derive(Debug, Clone)]
1115enum InlayHintRefreshReason {
1116 ModifiersChanged(bool),
1117 Toggle(bool),
1118 SettingsChange(InlayHintSettings),
1119 NewLinesShown,
1120 BufferEdited(HashSet<Arc<Language>>),
1121 RefreshRequested,
1122 ExcerptsRemoved(Vec<ExcerptId>),
1123}
1124
1125impl InlayHintRefreshReason {
1126 fn description(&self) -> &'static str {
1127 match self {
1128 Self::ModifiersChanged(_) => "modifiers changed",
1129 Self::Toggle(_) => "toggle",
1130 Self::SettingsChange(_) => "settings change",
1131 Self::NewLinesShown => "new lines shown",
1132 Self::BufferEdited(_) => "buffer edited",
1133 Self::RefreshRequested => "refresh requested",
1134 Self::ExcerptsRemoved(_) => "excerpts removed",
1135 }
1136 }
1137}
1138
1139pub enum FormatTarget {
1140 Buffers,
1141 Ranges(Vec<Range<MultiBufferPoint>>),
1142}
1143
1144pub(crate) struct FocusedBlock {
1145 id: BlockId,
1146 focus_handle: WeakFocusHandle,
1147}
1148
1149#[derive(Clone)]
1150enum JumpData {
1151 MultiBufferRow {
1152 row: MultiBufferRow,
1153 line_offset_from_top: u32,
1154 },
1155 MultiBufferPoint {
1156 excerpt_id: ExcerptId,
1157 position: Point,
1158 anchor: text::Anchor,
1159 line_offset_from_top: u32,
1160 },
1161}
1162
1163pub enum MultibufferSelectionMode {
1164 First,
1165 All,
1166}
1167
1168#[derive(Clone, Copy, Debug, Default)]
1169pub struct RewrapOptions {
1170 pub override_language_settings: bool,
1171 pub preserve_existing_whitespace: bool,
1172}
1173
1174impl Editor {
1175 pub fn single_line(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: false },
1180 buffer,
1181 None,
1182 window,
1183 cx,
1184 )
1185 }
1186
1187 pub fn multi_line(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(EditorMode::Full, buffer, None, window, cx)
1191 }
1192
1193 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1194 let buffer = cx.new(|cx| Buffer::local("", cx));
1195 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1196 Self::new(
1197 EditorMode::SingleLine { auto_width: true },
1198 buffer,
1199 None,
1200 window,
1201 cx,
1202 )
1203 }
1204
1205 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1206 let buffer = cx.new(|cx| Buffer::local("", cx));
1207 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1208 Self::new(
1209 EditorMode::AutoHeight { max_lines },
1210 buffer,
1211 None,
1212 window,
1213 cx,
1214 )
1215 }
1216
1217 pub fn for_buffer(
1218 buffer: Entity<Buffer>,
1219 project: Option<Entity<Project>>,
1220 window: &mut Window,
1221 cx: &mut Context<Self>,
1222 ) -> Self {
1223 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1224 Self::new(EditorMode::Full, buffer, project, window, cx)
1225 }
1226
1227 pub fn for_multibuffer(
1228 buffer: Entity<MultiBuffer>,
1229 project: Option<Entity<Project>>,
1230 window: &mut Window,
1231 cx: &mut Context<Self>,
1232 ) -> Self {
1233 Self::new(EditorMode::Full, buffer, project, window, cx)
1234 }
1235
1236 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1237 let mut clone = Self::new(
1238 self.mode,
1239 self.buffer.clone(),
1240 self.project.clone(),
1241 window,
1242 cx,
1243 );
1244 self.display_map.update(cx, |display_map, cx| {
1245 let snapshot = display_map.snapshot(cx);
1246 clone.display_map.update(cx, |display_map, cx| {
1247 display_map.set_state(&snapshot, cx);
1248 });
1249 });
1250 clone.folds_did_change(cx);
1251 clone.selections.clone_state(&self.selections);
1252 clone.scroll_manager.clone_state(&self.scroll_manager);
1253 clone.searchable = self.searchable;
1254 clone
1255 }
1256
1257 pub fn new(
1258 mode: EditorMode,
1259 buffer: Entity<MultiBuffer>,
1260 project: Option<Entity<Project>>,
1261 window: &mut Window,
1262 cx: &mut Context<Self>,
1263 ) -> Self {
1264 let style = window.text_style();
1265 let font_size = style.font_size.to_pixels(window.rem_size());
1266 let editor = cx.entity().downgrade();
1267 let fold_placeholder = FoldPlaceholder {
1268 constrain_width: true,
1269 render: Arc::new(move |fold_id, fold_range, cx| {
1270 let editor = editor.clone();
1271 div()
1272 .id(fold_id)
1273 .bg(cx.theme().colors().ghost_element_background)
1274 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1275 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1276 .rounded_xs()
1277 .size_full()
1278 .cursor_pointer()
1279 .child("⋯")
1280 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1281 .on_click(move |_, _window, cx| {
1282 editor
1283 .update(cx, |editor, cx| {
1284 editor.unfold_ranges(
1285 &[fold_range.start..fold_range.end],
1286 true,
1287 false,
1288 cx,
1289 );
1290 cx.stop_propagation();
1291 })
1292 .ok();
1293 })
1294 .into_any()
1295 }),
1296 merge_adjacent: true,
1297 ..Default::default()
1298 };
1299 let display_map = cx.new(|cx| {
1300 DisplayMap::new(
1301 buffer.clone(),
1302 style.font(),
1303 font_size,
1304 None,
1305 FILE_HEADER_HEIGHT,
1306 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1307 fold_placeholder,
1308 cx,
1309 )
1310 });
1311
1312 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1313
1314 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1315
1316 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1317 .then(|| language_settings::SoftWrap::None);
1318
1319 let mut project_subscriptions = Vec::new();
1320 if mode == EditorMode::Full {
1321 if let Some(project) = project.as_ref() {
1322 project_subscriptions.push(cx.subscribe_in(
1323 project,
1324 window,
1325 |editor, _, event, window, cx| match event {
1326 project::Event::RefreshCodeLens => {
1327 // we always query lens with actions, without storing them, always refreshing them
1328 }
1329 project::Event::RefreshInlayHints => {
1330 editor
1331 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1332 }
1333 project::Event::SnippetEdit(id, snippet_edits) => {
1334 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1335 let focus_handle = editor.focus_handle(cx);
1336 if focus_handle.is_focused(window) {
1337 let snapshot = buffer.read(cx).snapshot();
1338 for (range, snippet) in snippet_edits {
1339 let editor_range =
1340 language::range_from_lsp(*range).to_offset(&snapshot);
1341 editor
1342 .insert_snippet(
1343 &[editor_range],
1344 snippet.clone(),
1345 window,
1346 cx,
1347 )
1348 .ok();
1349 }
1350 }
1351 }
1352 }
1353 _ => {}
1354 },
1355 ));
1356 if let Some(task_inventory) = project
1357 .read(cx)
1358 .task_store()
1359 .read(cx)
1360 .task_inventory()
1361 .cloned()
1362 {
1363 project_subscriptions.push(cx.observe_in(
1364 &task_inventory,
1365 window,
1366 |editor, _, window, cx| {
1367 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1368 },
1369 ));
1370 };
1371
1372 project_subscriptions.push(cx.subscribe_in(
1373 &project.read(cx).breakpoint_store(),
1374 window,
1375 |editor, _, event, window, cx| match event {
1376 BreakpointStoreEvent::ActiveDebugLineChanged => {
1377 editor.go_to_active_debug_line(window, cx);
1378 }
1379 _ => {}
1380 },
1381 ));
1382 }
1383 }
1384
1385 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1386
1387 let inlay_hint_settings =
1388 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1389 let focus_handle = cx.focus_handle();
1390 cx.on_focus(&focus_handle, window, Self::handle_focus)
1391 .detach();
1392 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1393 .detach();
1394 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1395 .detach();
1396 cx.on_blur(&focus_handle, window, Self::handle_blur)
1397 .detach();
1398
1399 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1400 Some(false)
1401 } else {
1402 None
1403 };
1404
1405 let breakpoint_store = match (mode, project.as_ref()) {
1406 (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
1407 _ => None,
1408 };
1409
1410 let mut code_action_providers = Vec::new();
1411 let mut load_uncommitted_diff = None;
1412 if let Some(project) = project.clone() {
1413 load_uncommitted_diff = Some(
1414 get_uncommitted_diff_for_buffer(
1415 &project,
1416 buffer.read(cx).all_buffers(),
1417 buffer.clone(),
1418 cx,
1419 )
1420 .shared(),
1421 );
1422 code_action_providers.push(Rc::new(project) as Rc<_>);
1423 }
1424
1425 let mut this = Self {
1426 focus_handle,
1427 show_cursor_when_unfocused: false,
1428 last_focused_descendant: None,
1429 buffer: buffer.clone(),
1430 display_map: display_map.clone(),
1431 selections,
1432 scroll_manager: ScrollManager::new(cx),
1433 columnar_selection_tail: None,
1434 add_selections_state: None,
1435 select_next_state: None,
1436 select_prev_state: None,
1437 selection_history: Default::default(),
1438 autoclose_regions: Default::default(),
1439 snippet_stack: Default::default(),
1440 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1441 ime_transaction: Default::default(),
1442 active_diagnostics: None,
1443 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1444 inline_diagnostics_update: Task::ready(()),
1445 inline_diagnostics: Vec::new(),
1446 soft_wrap_mode_override,
1447 hard_wrap: None,
1448 completion_provider: project.clone().map(|project| Box::new(project) as _),
1449 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1450 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1451 project,
1452 blink_manager: blink_manager.clone(),
1453 show_local_selections: true,
1454 show_scrollbars: true,
1455 mode,
1456 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1457 show_gutter: mode == EditorMode::Full,
1458 show_line_numbers: None,
1459 use_relative_line_numbers: None,
1460 show_git_diff_gutter: None,
1461 show_code_actions: None,
1462 show_runnables: None,
1463 show_breakpoints: None,
1464 show_wrap_guides: None,
1465 show_indent_guides,
1466 placeholder_text: None,
1467 highlight_order: 0,
1468 highlighted_rows: HashMap::default(),
1469 background_highlights: Default::default(),
1470 gutter_highlights: TreeMap::default(),
1471 scrollbar_marker_state: ScrollbarMarkerState::default(),
1472 active_indent_guides_state: ActiveIndentGuidesState::default(),
1473 nav_history: None,
1474 context_menu: RefCell::new(None),
1475 context_menu_options: None,
1476 mouse_context_menu: None,
1477 completion_tasks: Default::default(),
1478 signature_help_state: SignatureHelpState::default(),
1479 auto_signature_help: None,
1480 find_all_references_task_sources: Vec::new(),
1481 next_completion_id: 0,
1482 next_inlay_id: 0,
1483 code_action_providers,
1484 available_code_actions: Default::default(),
1485 code_actions_task: Default::default(),
1486 selection_highlight_task: Default::default(),
1487 document_highlights_task: Default::default(),
1488 linked_editing_range_task: Default::default(),
1489 pending_rename: Default::default(),
1490 searchable: true,
1491 cursor_shape: EditorSettings::get_global(cx)
1492 .cursor_shape
1493 .unwrap_or_default(),
1494 current_line_highlight: None,
1495 autoindent_mode: Some(AutoindentMode::EachLine),
1496 collapse_matches: false,
1497 workspace: None,
1498 input_enabled: true,
1499 use_modal_editing: mode == EditorMode::Full,
1500 read_only: false,
1501 use_autoclose: true,
1502 use_auto_surround: true,
1503 auto_replace_emoji_shortcode: false,
1504 jsx_tag_auto_close_enabled_in_any_buffer: false,
1505 leader_peer_id: None,
1506 remote_id: None,
1507 hover_state: Default::default(),
1508 pending_mouse_down: None,
1509 hovered_link_state: Default::default(),
1510 edit_prediction_provider: None,
1511 active_inline_completion: None,
1512 stale_inline_completion_in_menu: None,
1513 edit_prediction_preview: EditPredictionPreview::Inactive {
1514 released_too_fast: false,
1515 },
1516 inline_diagnostics_enabled: mode == EditorMode::Full,
1517 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1518
1519 gutter_hovered: false,
1520 pixel_position_of_newest_cursor: None,
1521 last_bounds: None,
1522 last_position_map: None,
1523 expect_bounds_change: None,
1524 gutter_dimensions: GutterDimensions::default(),
1525 style: None,
1526 show_cursor_names: false,
1527 hovered_cursors: Default::default(),
1528 next_editor_action_id: EditorActionId::default(),
1529 editor_actions: Rc::default(),
1530 inline_completions_hidden_for_vim_mode: false,
1531 show_inline_completions_override: None,
1532 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1533 edit_prediction_settings: EditPredictionSettings::Disabled,
1534 edit_prediction_indent_conflict: false,
1535 edit_prediction_requires_modifier_in_indent_conflict: true,
1536 custom_context_menu: None,
1537 show_git_blame_gutter: false,
1538 show_git_blame_inline: false,
1539 show_selection_menu: None,
1540 show_git_blame_inline_delay_task: None,
1541 git_blame_inline_tooltip: None,
1542 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1543 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1544 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1545 .session
1546 .restore_unsaved_buffers,
1547 blame: None,
1548 blame_subscription: None,
1549 tasks: Default::default(),
1550
1551 breakpoint_store,
1552 gutter_breakpoint_indicator: None,
1553 _subscriptions: vec![
1554 cx.observe(&buffer, Self::on_buffer_changed),
1555 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1556 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1557 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1558 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1559 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1560 cx.observe_window_activation(window, |editor, window, cx| {
1561 let active = window.is_window_active();
1562 editor.blink_manager.update(cx, |blink_manager, cx| {
1563 if active {
1564 blink_manager.enable(cx);
1565 } else {
1566 blink_manager.disable(cx);
1567 }
1568 });
1569 }),
1570 ],
1571 tasks_update_task: None,
1572 linked_edit_ranges: Default::default(),
1573 in_project_search: false,
1574 previous_search_ranges: None,
1575 breadcrumb_header: None,
1576 focused_block: None,
1577 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1578 addons: HashMap::default(),
1579 registered_buffers: HashMap::default(),
1580 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1581 selection_mark_mode: false,
1582 toggle_fold_multiple_buffers: Task::ready(()),
1583 serialize_selections: Task::ready(()),
1584 serialize_folds: Task::ready(()),
1585 text_style_refinement: None,
1586 load_diff_task: load_uncommitted_diff,
1587 mouse_cursor_hidden: false,
1588 hide_mouse_while_typing: EditorSettings::get_global(cx)
1589 .hide_mouse_while_typing
1590 .unwrap_or(true),
1591 };
1592 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1593 this._subscriptions
1594 .push(cx.observe(breakpoints, |_, _, cx| {
1595 cx.notify();
1596 }));
1597 }
1598 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1599 this._subscriptions.extend(project_subscriptions);
1600
1601 this.end_selection(window, cx);
1602 this.scroll_manager.show_scrollbars(window, cx);
1603 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1604
1605 if mode == EditorMode::Full {
1606 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1607 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1608
1609 if this.git_blame_inline_enabled {
1610 this.git_blame_inline_enabled = true;
1611 this.start_git_blame_inline(false, window, cx);
1612 }
1613
1614 this.go_to_active_debug_line(window, cx);
1615
1616 if let Some(buffer) = buffer.read(cx).as_singleton() {
1617 if let Some(project) = this.project.as_ref() {
1618 let handle = project.update(cx, |project, cx| {
1619 project.register_buffer_with_language_servers(&buffer, cx)
1620 });
1621 this.registered_buffers
1622 .insert(buffer.read(cx).remote_id(), handle);
1623 }
1624 }
1625 }
1626
1627 this.report_editor_event("Editor Opened", None, cx);
1628 this
1629 }
1630
1631 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1632 self.mouse_context_menu
1633 .as_ref()
1634 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1635 }
1636
1637 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1638 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1639 }
1640
1641 fn key_context_internal(
1642 &self,
1643 has_active_edit_prediction: bool,
1644 window: &Window,
1645 cx: &App,
1646 ) -> KeyContext {
1647 let mut key_context = KeyContext::new_with_defaults();
1648 key_context.add("Editor");
1649 let mode = match self.mode {
1650 EditorMode::SingleLine { .. } => "single_line",
1651 EditorMode::AutoHeight { .. } => "auto_height",
1652 EditorMode::Full => "full",
1653 };
1654
1655 if EditorSettings::jupyter_enabled(cx) {
1656 key_context.add("jupyter");
1657 }
1658
1659 key_context.set("mode", mode);
1660 if self.pending_rename.is_some() {
1661 key_context.add("renaming");
1662 }
1663
1664 match self.context_menu.borrow().as_ref() {
1665 Some(CodeContextMenu::Completions(_)) => {
1666 key_context.add("menu");
1667 key_context.add("showing_completions");
1668 }
1669 Some(CodeContextMenu::CodeActions(_)) => {
1670 key_context.add("menu");
1671 key_context.add("showing_code_actions")
1672 }
1673 None => {}
1674 }
1675
1676 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1677 if !self.focus_handle(cx).contains_focused(window, cx)
1678 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1679 {
1680 for addon in self.addons.values() {
1681 addon.extend_key_context(&mut key_context, cx)
1682 }
1683 }
1684
1685 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1686 if let Some(extension) = singleton_buffer
1687 .read(cx)
1688 .file()
1689 .and_then(|file| file.path().extension()?.to_str())
1690 {
1691 key_context.set("extension", extension.to_string());
1692 }
1693 } else {
1694 key_context.add("multibuffer");
1695 }
1696
1697 if has_active_edit_prediction {
1698 if self.edit_prediction_in_conflict() {
1699 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1700 } else {
1701 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1702 key_context.add("copilot_suggestion");
1703 }
1704 }
1705
1706 if self.selection_mark_mode {
1707 key_context.add("selection_mode");
1708 }
1709
1710 key_context
1711 }
1712
1713 pub fn edit_prediction_in_conflict(&self) -> bool {
1714 if !self.show_edit_predictions_in_menu() {
1715 return false;
1716 }
1717
1718 let showing_completions = self
1719 .context_menu
1720 .borrow()
1721 .as_ref()
1722 .map_or(false, |context| {
1723 matches!(context, CodeContextMenu::Completions(_))
1724 });
1725
1726 showing_completions
1727 || self.edit_prediction_requires_modifier()
1728 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1729 // bindings to insert tab characters.
1730 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1731 }
1732
1733 pub fn accept_edit_prediction_keybind(
1734 &self,
1735 window: &Window,
1736 cx: &App,
1737 ) -> AcceptEditPredictionBinding {
1738 let key_context = self.key_context_internal(true, window, cx);
1739 let in_conflict = self.edit_prediction_in_conflict();
1740
1741 AcceptEditPredictionBinding(
1742 window
1743 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1744 .into_iter()
1745 .filter(|binding| {
1746 !in_conflict
1747 || binding
1748 .keystrokes()
1749 .first()
1750 .map_or(false, |keystroke| keystroke.modifiers.modified())
1751 })
1752 .rev()
1753 .min_by_key(|binding| {
1754 binding
1755 .keystrokes()
1756 .first()
1757 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1758 }),
1759 )
1760 }
1761
1762 pub fn new_file(
1763 workspace: &mut Workspace,
1764 _: &workspace::NewFile,
1765 window: &mut Window,
1766 cx: &mut Context<Workspace>,
1767 ) {
1768 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1769 "Failed to create buffer",
1770 window,
1771 cx,
1772 |e, _, _| match e.error_code() {
1773 ErrorCode::RemoteUpgradeRequired => Some(format!(
1774 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1775 e.error_tag("required").unwrap_or("the latest version")
1776 )),
1777 _ => None,
1778 },
1779 );
1780 }
1781
1782 pub fn new_in_workspace(
1783 workspace: &mut Workspace,
1784 window: &mut Window,
1785 cx: &mut Context<Workspace>,
1786 ) -> Task<Result<Entity<Editor>>> {
1787 let project = workspace.project().clone();
1788 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1789
1790 cx.spawn_in(window, async move |workspace, cx| {
1791 let buffer = create.await?;
1792 workspace.update_in(cx, |workspace, window, cx| {
1793 let editor =
1794 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1795 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1796 editor
1797 })
1798 })
1799 }
1800
1801 fn new_file_vertical(
1802 workspace: &mut Workspace,
1803 _: &workspace::NewFileSplitVertical,
1804 window: &mut Window,
1805 cx: &mut Context<Workspace>,
1806 ) {
1807 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1808 }
1809
1810 fn new_file_horizontal(
1811 workspace: &mut Workspace,
1812 _: &workspace::NewFileSplitHorizontal,
1813 window: &mut Window,
1814 cx: &mut Context<Workspace>,
1815 ) {
1816 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1817 }
1818
1819 fn new_file_in_direction(
1820 workspace: &mut Workspace,
1821 direction: SplitDirection,
1822 window: &mut Window,
1823 cx: &mut Context<Workspace>,
1824 ) {
1825 let project = workspace.project().clone();
1826 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1827
1828 cx.spawn_in(window, async move |workspace, cx| {
1829 let buffer = create.await?;
1830 workspace.update_in(cx, move |workspace, window, cx| {
1831 workspace.split_item(
1832 direction,
1833 Box::new(
1834 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1835 ),
1836 window,
1837 cx,
1838 )
1839 })?;
1840 anyhow::Ok(())
1841 })
1842 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1843 match e.error_code() {
1844 ErrorCode::RemoteUpgradeRequired => Some(format!(
1845 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1846 e.error_tag("required").unwrap_or("the latest version")
1847 )),
1848 _ => None,
1849 }
1850 });
1851 }
1852
1853 pub fn leader_peer_id(&self) -> Option<PeerId> {
1854 self.leader_peer_id
1855 }
1856
1857 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1858 &self.buffer
1859 }
1860
1861 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1862 self.workspace.as_ref()?.0.upgrade()
1863 }
1864
1865 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1866 self.buffer().read(cx).title(cx)
1867 }
1868
1869 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1870 let git_blame_gutter_max_author_length = self
1871 .render_git_blame_gutter(cx)
1872 .then(|| {
1873 if let Some(blame) = self.blame.as_ref() {
1874 let max_author_length =
1875 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1876 Some(max_author_length)
1877 } else {
1878 None
1879 }
1880 })
1881 .flatten();
1882
1883 EditorSnapshot {
1884 mode: self.mode,
1885 show_gutter: self.show_gutter,
1886 show_line_numbers: self.show_line_numbers,
1887 show_git_diff_gutter: self.show_git_diff_gutter,
1888 show_code_actions: self.show_code_actions,
1889 show_runnables: self.show_runnables,
1890 show_breakpoints: self.show_breakpoints,
1891 git_blame_gutter_max_author_length,
1892 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1893 scroll_anchor: self.scroll_manager.anchor(),
1894 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1895 placeholder_text: self.placeholder_text.clone(),
1896 is_focused: self.focus_handle.is_focused(window),
1897 current_line_highlight: self
1898 .current_line_highlight
1899 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1900 gutter_hovered: self.gutter_hovered,
1901 }
1902 }
1903
1904 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1905 self.buffer.read(cx).language_at(point, cx)
1906 }
1907
1908 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1909 self.buffer.read(cx).read(cx).file_at(point).cloned()
1910 }
1911
1912 pub fn active_excerpt(
1913 &self,
1914 cx: &App,
1915 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1916 self.buffer
1917 .read(cx)
1918 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1919 }
1920
1921 pub fn mode(&self) -> EditorMode {
1922 self.mode
1923 }
1924
1925 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1926 self.collaboration_hub.as_deref()
1927 }
1928
1929 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1930 self.collaboration_hub = Some(hub);
1931 }
1932
1933 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1934 self.in_project_search = in_project_search;
1935 }
1936
1937 pub fn set_custom_context_menu(
1938 &mut self,
1939 f: impl 'static
1940 + Fn(
1941 &mut Self,
1942 DisplayPoint,
1943 &mut Window,
1944 &mut Context<Self>,
1945 ) -> Option<Entity<ui::ContextMenu>>,
1946 ) {
1947 self.custom_context_menu = Some(Box::new(f))
1948 }
1949
1950 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1951 self.completion_provider = provider;
1952 }
1953
1954 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1955 self.semantics_provider.clone()
1956 }
1957
1958 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1959 self.semantics_provider = provider;
1960 }
1961
1962 pub fn set_edit_prediction_provider<T>(
1963 &mut self,
1964 provider: Option<Entity<T>>,
1965 window: &mut Window,
1966 cx: &mut Context<Self>,
1967 ) where
1968 T: EditPredictionProvider,
1969 {
1970 self.edit_prediction_provider =
1971 provider.map(|provider| RegisteredInlineCompletionProvider {
1972 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1973 if this.focus_handle.is_focused(window) {
1974 this.update_visible_inline_completion(window, cx);
1975 }
1976 }),
1977 provider: Arc::new(provider),
1978 });
1979 self.update_edit_prediction_settings(cx);
1980 self.refresh_inline_completion(false, false, window, cx);
1981 }
1982
1983 pub fn placeholder_text(&self) -> Option<&str> {
1984 self.placeholder_text.as_deref()
1985 }
1986
1987 pub fn set_placeholder_text(
1988 &mut self,
1989 placeholder_text: impl Into<Arc<str>>,
1990 cx: &mut Context<Self>,
1991 ) {
1992 let placeholder_text = Some(placeholder_text.into());
1993 if self.placeholder_text != placeholder_text {
1994 self.placeholder_text = placeholder_text;
1995 cx.notify();
1996 }
1997 }
1998
1999 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2000 self.cursor_shape = cursor_shape;
2001
2002 // Disrupt blink for immediate user feedback that the cursor shape has changed
2003 self.blink_manager.update(cx, BlinkManager::show_cursor);
2004
2005 cx.notify();
2006 }
2007
2008 pub fn set_current_line_highlight(
2009 &mut self,
2010 current_line_highlight: Option<CurrentLineHighlight>,
2011 ) {
2012 self.current_line_highlight = current_line_highlight;
2013 }
2014
2015 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2016 self.collapse_matches = collapse_matches;
2017 }
2018
2019 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2020 let buffers = self.buffer.read(cx).all_buffers();
2021 let Some(project) = self.project.as_ref() else {
2022 return;
2023 };
2024 project.update(cx, |project, cx| {
2025 for buffer in buffers {
2026 self.registered_buffers
2027 .entry(buffer.read(cx).remote_id())
2028 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2029 }
2030 })
2031 }
2032
2033 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2034 if self.collapse_matches {
2035 return range.start..range.start;
2036 }
2037 range.clone()
2038 }
2039
2040 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2041 if self.display_map.read(cx).clip_at_line_ends != clip {
2042 self.display_map
2043 .update(cx, |map, _| map.clip_at_line_ends = clip);
2044 }
2045 }
2046
2047 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2048 self.input_enabled = input_enabled;
2049 }
2050
2051 pub fn set_inline_completions_hidden_for_vim_mode(
2052 &mut self,
2053 hidden: bool,
2054 window: &mut Window,
2055 cx: &mut Context<Self>,
2056 ) {
2057 if hidden != self.inline_completions_hidden_for_vim_mode {
2058 self.inline_completions_hidden_for_vim_mode = hidden;
2059 if hidden {
2060 self.update_visible_inline_completion(window, cx);
2061 } else {
2062 self.refresh_inline_completion(true, false, window, cx);
2063 }
2064 }
2065 }
2066
2067 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2068 self.menu_inline_completions_policy = value;
2069 }
2070
2071 pub fn set_autoindent(&mut self, autoindent: bool) {
2072 if autoindent {
2073 self.autoindent_mode = Some(AutoindentMode::EachLine);
2074 } else {
2075 self.autoindent_mode = None;
2076 }
2077 }
2078
2079 pub fn read_only(&self, cx: &App) -> bool {
2080 self.read_only || self.buffer.read(cx).read_only()
2081 }
2082
2083 pub fn set_read_only(&mut self, read_only: bool) {
2084 self.read_only = read_only;
2085 }
2086
2087 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2088 self.use_autoclose = autoclose;
2089 }
2090
2091 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2092 self.use_auto_surround = auto_surround;
2093 }
2094
2095 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2096 self.auto_replace_emoji_shortcode = auto_replace;
2097 }
2098
2099 pub fn toggle_edit_predictions(
2100 &mut self,
2101 _: &ToggleEditPrediction,
2102 window: &mut Window,
2103 cx: &mut Context<Self>,
2104 ) {
2105 if self.show_inline_completions_override.is_some() {
2106 self.set_show_edit_predictions(None, window, cx);
2107 } else {
2108 let show_edit_predictions = !self.edit_predictions_enabled();
2109 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2110 }
2111 }
2112
2113 pub fn set_show_edit_predictions(
2114 &mut self,
2115 show_edit_predictions: Option<bool>,
2116 window: &mut Window,
2117 cx: &mut Context<Self>,
2118 ) {
2119 self.show_inline_completions_override = show_edit_predictions;
2120 self.update_edit_prediction_settings(cx);
2121
2122 if let Some(false) = show_edit_predictions {
2123 self.discard_inline_completion(false, cx);
2124 } else {
2125 self.refresh_inline_completion(false, true, window, cx);
2126 }
2127 }
2128
2129 fn inline_completions_disabled_in_scope(
2130 &self,
2131 buffer: &Entity<Buffer>,
2132 buffer_position: language::Anchor,
2133 cx: &App,
2134 ) -> bool {
2135 let snapshot = buffer.read(cx).snapshot();
2136 let settings = snapshot.settings_at(buffer_position, cx);
2137
2138 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2139 return false;
2140 };
2141
2142 scope.override_name().map_or(false, |scope_name| {
2143 settings
2144 .edit_predictions_disabled_in
2145 .iter()
2146 .any(|s| s == scope_name)
2147 })
2148 }
2149
2150 pub fn set_use_modal_editing(&mut self, to: bool) {
2151 self.use_modal_editing = to;
2152 }
2153
2154 pub fn use_modal_editing(&self) -> bool {
2155 self.use_modal_editing
2156 }
2157
2158 fn selections_did_change(
2159 &mut self,
2160 local: bool,
2161 old_cursor_position: &Anchor,
2162 show_completions: bool,
2163 window: &mut Window,
2164 cx: &mut Context<Self>,
2165 ) {
2166 window.invalidate_character_coordinates();
2167
2168 // Copy selections to primary selection buffer
2169 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2170 if local {
2171 let selections = self.selections.all::<usize>(cx);
2172 let buffer_handle = self.buffer.read(cx).read(cx);
2173
2174 let mut text = String::new();
2175 for (index, selection) in selections.iter().enumerate() {
2176 let text_for_selection = buffer_handle
2177 .text_for_range(selection.start..selection.end)
2178 .collect::<String>();
2179
2180 text.push_str(&text_for_selection);
2181 if index != selections.len() - 1 {
2182 text.push('\n');
2183 }
2184 }
2185
2186 if !text.is_empty() {
2187 cx.write_to_primary(ClipboardItem::new_string(text));
2188 }
2189 }
2190
2191 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2192 self.buffer.update(cx, |buffer, cx| {
2193 buffer.set_active_selections(
2194 &self.selections.disjoint_anchors(),
2195 self.selections.line_mode,
2196 self.cursor_shape,
2197 cx,
2198 )
2199 });
2200 }
2201 let display_map = self
2202 .display_map
2203 .update(cx, |display_map, cx| display_map.snapshot(cx));
2204 let buffer = &display_map.buffer_snapshot;
2205 self.add_selections_state = None;
2206 self.select_next_state = None;
2207 self.select_prev_state = None;
2208 self.select_syntax_node_history.try_clear();
2209 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2210 self.snippet_stack
2211 .invalidate(&self.selections.disjoint_anchors(), buffer);
2212 self.take_rename(false, window, cx);
2213
2214 let new_cursor_position = self.selections.newest_anchor().head();
2215
2216 self.push_to_nav_history(
2217 *old_cursor_position,
2218 Some(new_cursor_position.to_point(buffer)),
2219 false,
2220 cx,
2221 );
2222
2223 if local {
2224 let new_cursor_position = self.selections.newest_anchor().head();
2225 let mut context_menu = self.context_menu.borrow_mut();
2226 let completion_menu = match context_menu.as_ref() {
2227 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2228 _ => {
2229 *context_menu = None;
2230 None
2231 }
2232 };
2233 if let Some(buffer_id) = new_cursor_position.buffer_id {
2234 if !self.registered_buffers.contains_key(&buffer_id) {
2235 if let Some(project) = self.project.as_ref() {
2236 project.update(cx, |project, cx| {
2237 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2238 return;
2239 };
2240 self.registered_buffers.insert(
2241 buffer_id,
2242 project.register_buffer_with_language_servers(&buffer, cx),
2243 );
2244 })
2245 }
2246 }
2247 }
2248
2249 if let Some(completion_menu) = completion_menu {
2250 let cursor_position = new_cursor_position.to_offset(buffer);
2251 let (word_range, kind) =
2252 buffer.surrounding_word(completion_menu.initial_position, true);
2253 if kind == Some(CharKind::Word)
2254 && word_range.to_inclusive().contains(&cursor_position)
2255 {
2256 let mut completion_menu = completion_menu.clone();
2257 drop(context_menu);
2258
2259 let query = Self::completion_query(buffer, cursor_position);
2260 cx.spawn(async move |this, cx| {
2261 completion_menu
2262 .filter(query.as_deref(), cx.background_executor().clone())
2263 .await;
2264
2265 this.update(cx, |this, cx| {
2266 let mut context_menu = this.context_menu.borrow_mut();
2267 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2268 else {
2269 return;
2270 };
2271
2272 if menu.id > completion_menu.id {
2273 return;
2274 }
2275
2276 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2277 drop(context_menu);
2278 cx.notify();
2279 })
2280 })
2281 .detach();
2282
2283 if show_completions {
2284 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2285 }
2286 } else {
2287 drop(context_menu);
2288 self.hide_context_menu(window, cx);
2289 }
2290 } else {
2291 drop(context_menu);
2292 }
2293
2294 hide_hover(self, cx);
2295
2296 if old_cursor_position.to_display_point(&display_map).row()
2297 != new_cursor_position.to_display_point(&display_map).row()
2298 {
2299 self.available_code_actions.take();
2300 }
2301 self.refresh_code_actions(window, cx);
2302 self.refresh_document_highlights(cx);
2303 self.refresh_selected_text_highlights(window, cx);
2304 refresh_matching_bracket_highlights(self, window, cx);
2305 self.update_visible_inline_completion(window, cx);
2306 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2307 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2308 if self.git_blame_inline_enabled {
2309 self.start_inline_blame_timer(window, cx);
2310 }
2311 }
2312
2313 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2314 cx.emit(EditorEvent::SelectionsChanged { local });
2315
2316 let selections = &self.selections.disjoint;
2317 if selections.len() == 1 {
2318 cx.emit(SearchEvent::ActiveMatchChanged)
2319 }
2320 if local
2321 && self.is_singleton(cx)
2322 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2323 {
2324 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2325 let background_executor = cx.background_executor().clone();
2326 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2327 let snapshot = self.buffer().read(cx).snapshot(cx);
2328 let selections = selections.clone();
2329 self.serialize_selections = cx.background_spawn(async move {
2330 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2331 let selections = selections
2332 .iter()
2333 .map(|selection| {
2334 (
2335 selection.start.to_offset(&snapshot),
2336 selection.end.to_offset(&snapshot),
2337 )
2338 })
2339 .collect();
2340
2341 DB.save_editor_selections(editor_id, workspace_id, selections)
2342 .await
2343 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2344 .log_err();
2345 });
2346 }
2347 }
2348
2349 cx.notify();
2350 }
2351
2352 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2353 if !self.is_singleton(cx)
2354 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
2355 {
2356 return;
2357 }
2358
2359 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2360 return;
2361 };
2362 let background_executor = cx.background_executor().clone();
2363 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2364 let snapshot = self.buffer().read(cx).snapshot(cx);
2365 let folds = self.display_map.update(cx, |display_map, cx| {
2366 display_map
2367 .snapshot(cx)
2368 .folds_in_range(0..snapshot.len())
2369 .map(|fold| {
2370 (
2371 fold.range.start.to_offset(&snapshot),
2372 fold.range.end.to_offset(&snapshot),
2373 )
2374 })
2375 .collect()
2376 });
2377 self.serialize_folds = cx.background_spawn(async move {
2378 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2379 DB.save_editor_folds(editor_id, workspace_id, folds)
2380 .await
2381 .with_context(|| format!("persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"))
2382 .log_err();
2383 });
2384 }
2385
2386 pub fn sync_selections(
2387 &mut self,
2388 other: Entity<Editor>,
2389 cx: &mut Context<Self>,
2390 ) -> gpui::Subscription {
2391 let other_selections = other.read(cx).selections.disjoint.to_vec();
2392 self.selections.change_with(cx, |selections| {
2393 selections.select_anchors(other_selections);
2394 });
2395
2396 let other_subscription =
2397 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2398 EditorEvent::SelectionsChanged { local: true } => {
2399 let other_selections = other.read(cx).selections.disjoint.to_vec();
2400 if other_selections.is_empty() {
2401 return;
2402 }
2403 this.selections.change_with(cx, |selections| {
2404 selections.select_anchors(other_selections);
2405 });
2406 }
2407 _ => {}
2408 });
2409
2410 let this_subscription =
2411 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2412 EditorEvent::SelectionsChanged { local: true } => {
2413 let these_selections = this.selections.disjoint.to_vec();
2414 if these_selections.is_empty() {
2415 return;
2416 }
2417 other.update(cx, |other_editor, cx| {
2418 other_editor.selections.change_with(cx, |selections| {
2419 selections.select_anchors(these_selections);
2420 })
2421 });
2422 }
2423 _ => {}
2424 });
2425
2426 Subscription::join(other_subscription, this_subscription)
2427 }
2428
2429 pub fn change_selections<R>(
2430 &mut self,
2431 autoscroll: Option<Autoscroll>,
2432 window: &mut Window,
2433 cx: &mut Context<Self>,
2434 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2435 ) -> R {
2436 self.change_selections_inner(autoscroll, true, window, cx, change)
2437 }
2438
2439 fn change_selections_inner<R>(
2440 &mut self,
2441 autoscroll: Option<Autoscroll>,
2442 request_completions: bool,
2443 window: &mut Window,
2444 cx: &mut Context<Self>,
2445 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2446 ) -> R {
2447 let old_cursor_position = self.selections.newest_anchor().head();
2448 self.push_to_selection_history();
2449
2450 let (changed, result) = self.selections.change_with(cx, change);
2451
2452 if changed {
2453 if let Some(autoscroll) = autoscroll {
2454 self.request_autoscroll(autoscroll, cx);
2455 }
2456 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2457
2458 if self.should_open_signature_help_automatically(
2459 &old_cursor_position,
2460 self.signature_help_state.backspace_pressed(),
2461 cx,
2462 ) {
2463 self.show_signature_help(&ShowSignatureHelp, window, cx);
2464 }
2465 self.signature_help_state.set_backspace_pressed(false);
2466 }
2467
2468 result
2469 }
2470
2471 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2472 where
2473 I: IntoIterator<Item = (Range<S>, T)>,
2474 S: ToOffset,
2475 T: Into<Arc<str>>,
2476 {
2477 if self.read_only(cx) {
2478 return;
2479 }
2480
2481 self.buffer
2482 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2483 }
2484
2485 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2486 where
2487 I: IntoIterator<Item = (Range<S>, T)>,
2488 S: ToOffset,
2489 T: Into<Arc<str>>,
2490 {
2491 if self.read_only(cx) {
2492 return;
2493 }
2494
2495 self.buffer.update(cx, |buffer, cx| {
2496 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2497 });
2498 }
2499
2500 pub fn edit_with_block_indent<I, S, T>(
2501 &mut self,
2502 edits: I,
2503 original_indent_columns: Vec<Option<u32>>,
2504 cx: &mut Context<Self>,
2505 ) where
2506 I: IntoIterator<Item = (Range<S>, T)>,
2507 S: ToOffset,
2508 T: Into<Arc<str>>,
2509 {
2510 if self.read_only(cx) {
2511 return;
2512 }
2513
2514 self.buffer.update(cx, |buffer, cx| {
2515 buffer.edit(
2516 edits,
2517 Some(AutoindentMode::Block {
2518 original_indent_columns,
2519 }),
2520 cx,
2521 )
2522 });
2523 }
2524
2525 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2526 self.hide_context_menu(window, cx);
2527
2528 match phase {
2529 SelectPhase::Begin {
2530 position,
2531 add,
2532 click_count,
2533 } => self.begin_selection(position, add, click_count, window, cx),
2534 SelectPhase::BeginColumnar {
2535 position,
2536 goal_column,
2537 reset,
2538 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2539 SelectPhase::Extend {
2540 position,
2541 click_count,
2542 } => self.extend_selection(position, click_count, window, cx),
2543 SelectPhase::Update {
2544 position,
2545 goal_column,
2546 scroll_delta,
2547 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2548 SelectPhase::End => self.end_selection(window, cx),
2549 }
2550 }
2551
2552 fn extend_selection(
2553 &mut self,
2554 position: DisplayPoint,
2555 click_count: usize,
2556 window: &mut Window,
2557 cx: &mut Context<Self>,
2558 ) {
2559 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2560 let tail = self.selections.newest::<usize>(cx).tail();
2561 self.begin_selection(position, false, click_count, window, cx);
2562
2563 let position = position.to_offset(&display_map, Bias::Left);
2564 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2565
2566 let mut pending_selection = self
2567 .selections
2568 .pending_anchor()
2569 .expect("extend_selection not called with pending selection");
2570 if position >= tail {
2571 pending_selection.start = tail_anchor;
2572 } else {
2573 pending_selection.end = tail_anchor;
2574 pending_selection.reversed = true;
2575 }
2576
2577 let mut pending_mode = self.selections.pending_mode().unwrap();
2578 match &mut pending_mode {
2579 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2580 _ => {}
2581 }
2582
2583 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2584 s.set_pending(pending_selection, pending_mode)
2585 });
2586 }
2587
2588 fn begin_selection(
2589 &mut self,
2590 position: DisplayPoint,
2591 add: bool,
2592 click_count: usize,
2593 window: &mut Window,
2594 cx: &mut Context<Self>,
2595 ) {
2596 if !self.focus_handle.is_focused(window) {
2597 self.last_focused_descendant = None;
2598 window.focus(&self.focus_handle);
2599 }
2600
2601 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2602 let buffer = &display_map.buffer_snapshot;
2603 let newest_selection = self.selections.newest_anchor().clone();
2604 let position = display_map.clip_point(position, Bias::Left);
2605
2606 let start;
2607 let end;
2608 let mode;
2609 let mut auto_scroll;
2610 match click_count {
2611 1 => {
2612 start = buffer.anchor_before(position.to_point(&display_map));
2613 end = start;
2614 mode = SelectMode::Character;
2615 auto_scroll = true;
2616 }
2617 2 => {
2618 let range = movement::surrounding_word(&display_map, position);
2619 start = buffer.anchor_before(range.start.to_point(&display_map));
2620 end = buffer.anchor_before(range.end.to_point(&display_map));
2621 mode = SelectMode::Word(start..end);
2622 auto_scroll = true;
2623 }
2624 3 => {
2625 let position = display_map
2626 .clip_point(position, Bias::Left)
2627 .to_point(&display_map);
2628 let line_start = display_map.prev_line_boundary(position).0;
2629 let next_line_start = buffer.clip_point(
2630 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2631 Bias::Left,
2632 );
2633 start = buffer.anchor_before(line_start);
2634 end = buffer.anchor_before(next_line_start);
2635 mode = SelectMode::Line(start..end);
2636 auto_scroll = true;
2637 }
2638 _ => {
2639 start = buffer.anchor_before(0);
2640 end = buffer.anchor_before(buffer.len());
2641 mode = SelectMode::All;
2642 auto_scroll = false;
2643 }
2644 }
2645 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2646
2647 let point_to_delete: Option<usize> = {
2648 let selected_points: Vec<Selection<Point>> =
2649 self.selections.disjoint_in_range(start..end, cx);
2650
2651 if !add || click_count > 1 {
2652 None
2653 } else if !selected_points.is_empty() {
2654 Some(selected_points[0].id)
2655 } else {
2656 let clicked_point_already_selected =
2657 self.selections.disjoint.iter().find(|selection| {
2658 selection.start.to_point(buffer) == start.to_point(buffer)
2659 || selection.end.to_point(buffer) == end.to_point(buffer)
2660 });
2661
2662 clicked_point_already_selected.map(|selection| selection.id)
2663 }
2664 };
2665
2666 let selections_count = self.selections.count();
2667
2668 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2669 if let Some(point_to_delete) = point_to_delete {
2670 s.delete(point_to_delete);
2671
2672 if selections_count == 1 {
2673 s.set_pending_anchor_range(start..end, mode);
2674 }
2675 } else {
2676 if !add {
2677 s.clear_disjoint();
2678 } else if click_count > 1 {
2679 s.delete(newest_selection.id)
2680 }
2681
2682 s.set_pending_anchor_range(start..end, mode);
2683 }
2684 });
2685 }
2686
2687 fn begin_columnar_selection(
2688 &mut self,
2689 position: DisplayPoint,
2690 goal_column: u32,
2691 reset: bool,
2692 window: &mut Window,
2693 cx: &mut Context<Self>,
2694 ) {
2695 if !self.focus_handle.is_focused(window) {
2696 self.last_focused_descendant = None;
2697 window.focus(&self.focus_handle);
2698 }
2699
2700 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2701
2702 if reset {
2703 let pointer_position = display_map
2704 .buffer_snapshot
2705 .anchor_before(position.to_point(&display_map));
2706
2707 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2708 s.clear_disjoint();
2709 s.set_pending_anchor_range(
2710 pointer_position..pointer_position,
2711 SelectMode::Character,
2712 );
2713 });
2714 }
2715
2716 let tail = self.selections.newest::<Point>(cx).tail();
2717 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2718
2719 if !reset {
2720 self.select_columns(
2721 tail.to_display_point(&display_map),
2722 position,
2723 goal_column,
2724 &display_map,
2725 window,
2726 cx,
2727 );
2728 }
2729 }
2730
2731 fn update_selection(
2732 &mut self,
2733 position: DisplayPoint,
2734 goal_column: u32,
2735 scroll_delta: gpui::Point<f32>,
2736 window: &mut Window,
2737 cx: &mut Context<Self>,
2738 ) {
2739 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2740
2741 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2742 let tail = tail.to_display_point(&display_map);
2743 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2744 } else if let Some(mut pending) = self.selections.pending_anchor() {
2745 let buffer = self.buffer.read(cx).snapshot(cx);
2746 let head;
2747 let tail;
2748 let mode = self.selections.pending_mode().unwrap();
2749 match &mode {
2750 SelectMode::Character => {
2751 head = position.to_point(&display_map);
2752 tail = pending.tail().to_point(&buffer);
2753 }
2754 SelectMode::Word(original_range) => {
2755 let original_display_range = original_range.start.to_display_point(&display_map)
2756 ..original_range.end.to_display_point(&display_map);
2757 let original_buffer_range = original_display_range.start.to_point(&display_map)
2758 ..original_display_range.end.to_point(&display_map);
2759 if movement::is_inside_word(&display_map, position)
2760 || original_display_range.contains(&position)
2761 {
2762 let word_range = movement::surrounding_word(&display_map, position);
2763 if word_range.start < original_display_range.start {
2764 head = word_range.start.to_point(&display_map);
2765 } else {
2766 head = word_range.end.to_point(&display_map);
2767 }
2768 } else {
2769 head = position.to_point(&display_map);
2770 }
2771
2772 if head <= original_buffer_range.start {
2773 tail = original_buffer_range.end;
2774 } else {
2775 tail = original_buffer_range.start;
2776 }
2777 }
2778 SelectMode::Line(original_range) => {
2779 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2780
2781 let position = display_map
2782 .clip_point(position, Bias::Left)
2783 .to_point(&display_map);
2784 let line_start = display_map.prev_line_boundary(position).0;
2785 let next_line_start = buffer.clip_point(
2786 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2787 Bias::Left,
2788 );
2789
2790 if line_start < original_range.start {
2791 head = line_start
2792 } else {
2793 head = next_line_start
2794 }
2795
2796 if head <= original_range.start {
2797 tail = original_range.end;
2798 } else {
2799 tail = original_range.start;
2800 }
2801 }
2802 SelectMode::All => {
2803 return;
2804 }
2805 };
2806
2807 if head < tail {
2808 pending.start = buffer.anchor_before(head);
2809 pending.end = buffer.anchor_before(tail);
2810 pending.reversed = true;
2811 } else {
2812 pending.start = buffer.anchor_before(tail);
2813 pending.end = buffer.anchor_before(head);
2814 pending.reversed = false;
2815 }
2816
2817 self.change_selections(None, window, cx, |s| {
2818 s.set_pending(pending, mode);
2819 });
2820 } else {
2821 log::error!("update_selection dispatched with no pending selection");
2822 return;
2823 }
2824
2825 self.apply_scroll_delta(scroll_delta, window, cx);
2826 cx.notify();
2827 }
2828
2829 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2830 self.columnar_selection_tail.take();
2831 if self.selections.pending_anchor().is_some() {
2832 let selections = self.selections.all::<usize>(cx);
2833 self.change_selections(None, window, cx, |s| {
2834 s.select(selections);
2835 s.clear_pending();
2836 });
2837 }
2838 }
2839
2840 fn select_columns(
2841 &mut self,
2842 tail: DisplayPoint,
2843 head: DisplayPoint,
2844 goal_column: u32,
2845 display_map: &DisplaySnapshot,
2846 window: &mut Window,
2847 cx: &mut Context<Self>,
2848 ) {
2849 let start_row = cmp::min(tail.row(), head.row());
2850 let end_row = cmp::max(tail.row(), head.row());
2851 let start_column = cmp::min(tail.column(), goal_column);
2852 let end_column = cmp::max(tail.column(), goal_column);
2853 let reversed = start_column < tail.column();
2854
2855 let selection_ranges = (start_row.0..=end_row.0)
2856 .map(DisplayRow)
2857 .filter_map(|row| {
2858 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2859 let start = display_map
2860 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2861 .to_point(display_map);
2862 let end = display_map
2863 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2864 .to_point(display_map);
2865 if reversed {
2866 Some(end..start)
2867 } else {
2868 Some(start..end)
2869 }
2870 } else {
2871 None
2872 }
2873 })
2874 .collect::<Vec<_>>();
2875
2876 self.change_selections(None, window, cx, |s| {
2877 s.select_ranges(selection_ranges);
2878 });
2879 cx.notify();
2880 }
2881
2882 pub fn has_pending_nonempty_selection(&self) -> bool {
2883 let pending_nonempty_selection = match self.selections.pending_anchor() {
2884 Some(Selection { start, end, .. }) => start != end,
2885 None => false,
2886 };
2887
2888 pending_nonempty_selection
2889 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2890 }
2891
2892 pub fn has_pending_selection(&self) -> bool {
2893 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2894 }
2895
2896 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2897 self.selection_mark_mode = false;
2898
2899 if self.clear_expanded_diff_hunks(cx) {
2900 cx.notify();
2901 return;
2902 }
2903 if self.dismiss_menus_and_popups(true, window, cx) {
2904 return;
2905 }
2906
2907 if self.mode == EditorMode::Full
2908 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2909 {
2910 return;
2911 }
2912
2913 cx.propagate();
2914 }
2915
2916 pub fn dismiss_menus_and_popups(
2917 &mut self,
2918 is_user_requested: bool,
2919 window: &mut Window,
2920 cx: &mut Context<Self>,
2921 ) -> bool {
2922 if self.take_rename(false, window, cx).is_some() {
2923 return true;
2924 }
2925
2926 if hide_hover(self, cx) {
2927 return true;
2928 }
2929
2930 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2931 return true;
2932 }
2933
2934 if self.hide_context_menu(window, cx).is_some() {
2935 return true;
2936 }
2937
2938 if self.mouse_context_menu.take().is_some() {
2939 return true;
2940 }
2941
2942 if is_user_requested && self.discard_inline_completion(true, cx) {
2943 return true;
2944 }
2945
2946 if self.snippet_stack.pop().is_some() {
2947 return true;
2948 }
2949
2950 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2951 self.dismiss_diagnostics(cx);
2952 return true;
2953 }
2954
2955 false
2956 }
2957
2958 fn linked_editing_ranges_for(
2959 &self,
2960 selection: Range<text::Anchor>,
2961 cx: &App,
2962 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2963 if self.linked_edit_ranges.is_empty() {
2964 return None;
2965 }
2966 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2967 selection.end.buffer_id.and_then(|end_buffer_id| {
2968 if selection.start.buffer_id != Some(end_buffer_id) {
2969 return None;
2970 }
2971 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2972 let snapshot = buffer.read(cx).snapshot();
2973 self.linked_edit_ranges
2974 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2975 .map(|ranges| (ranges, snapshot, buffer))
2976 })?;
2977 use text::ToOffset as TO;
2978 // find offset from the start of current range to current cursor position
2979 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2980
2981 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2982 let start_difference = start_offset - start_byte_offset;
2983 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2984 let end_difference = end_offset - start_byte_offset;
2985 // Current range has associated linked ranges.
2986 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2987 for range in linked_ranges.iter() {
2988 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2989 let end_offset = start_offset + end_difference;
2990 let start_offset = start_offset + start_difference;
2991 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2992 continue;
2993 }
2994 if self.selections.disjoint_anchor_ranges().any(|s| {
2995 if s.start.buffer_id != selection.start.buffer_id
2996 || s.end.buffer_id != selection.end.buffer_id
2997 {
2998 return false;
2999 }
3000 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3001 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3002 }) {
3003 continue;
3004 }
3005 let start = buffer_snapshot.anchor_after(start_offset);
3006 let end = buffer_snapshot.anchor_after(end_offset);
3007 linked_edits
3008 .entry(buffer.clone())
3009 .or_default()
3010 .push(start..end);
3011 }
3012 Some(linked_edits)
3013 }
3014
3015 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3016 let text: Arc<str> = text.into();
3017
3018 if self.read_only(cx) {
3019 return;
3020 }
3021
3022 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3023
3024 let selections = self.selections.all_adjusted(cx);
3025 let mut bracket_inserted = false;
3026 let mut edits = Vec::new();
3027 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3028 let mut new_selections = Vec::with_capacity(selections.len());
3029 let mut new_autoclose_regions = Vec::new();
3030 let snapshot = self.buffer.read(cx).read(cx);
3031
3032 for (selection, autoclose_region) in
3033 self.selections_with_autoclose_regions(selections, &snapshot)
3034 {
3035 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3036 // Determine if the inserted text matches the opening or closing
3037 // bracket of any of this language's bracket pairs.
3038 let mut bracket_pair = None;
3039 let mut is_bracket_pair_start = false;
3040 let mut is_bracket_pair_end = false;
3041 if !text.is_empty() {
3042 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3043 // and they are removing the character that triggered IME popup.
3044 for (pair, enabled) in scope.brackets() {
3045 if !pair.close && !pair.surround {
3046 continue;
3047 }
3048
3049 if enabled && pair.start.ends_with(text.as_ref()) {
3050 let prefix_len = pair.start.len() - text.len();
3051 let preceding_text_matches_prefix = prefix_len == 0
3052 || (selection.start.column >= (prefix_len as u32)
3053 && snapshot.contains_str_at(
3054 Point::new(
3055 selection.start.row,
3056 selection.start.column - (prefix_len as u32),
3057 ),
3058 &pair.start[..prefix_len],
3059 ));
3060 if preceding_text_matches_prefix {
3061 bracket_pair = Some(pair.clone());
3062 is_bracket_pair_start = true;
3063 break;
3064 }
3065 }
3066 if pair.end.as_str() == text.as_ref() {
3067 bracket_pair = Some(pair.clone());
3068 is_bracket_pair_end = true;
3069 break;
3070 }
3071 }
3072 }
3073
3074 if let Some(bracket_pair) = bracket_pair {
3075 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3076 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3077 let auto_surround =
3078 self.use_auto_surround && snapshot_settings.use_auto_surround;
3079 if selection.is_empty() {
3080 if is_bracket_pair_start {
3081 // If the inserted text is a suffix of an opening bracket and the
3082 // selection is preceded by the rest of the opening bracket, then
3083 // insert the closing bracket.
3084 let following_text_allows_autoclose = snapshot
3085 .chars_at(selection.start)
3086 .next()
3087 .map_or(true, |c| scope.should_autoclose_before(c));
3088
3089 let preceding_text_allows_autoclose = selection.start.column == 0
3090 || snapshot.reversed_chars_at(selection.start).next().map_or(
3091 true,
3092 |c| {
3093 bracket_pair.start != bracket_pair.end
3094 || !snapshot
3095 .char_classifier_at(selection.start)
3096 .is_word(c)
3097 },
3098 );
3099
3100 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3101 && bracket_pair.start.len() == 1
3102 {
3103 let target = bracket_pair.start.chars().next().unwrap();
3104 let current_line_count = snapshot
3105 .reversed_chars_at(selection.start)
3106 .take_while(|&c| c != '\n')
3107 .filter(|&c| c == target)
3108 .count();
3109 current_line_count % 2 == 1
3110 } else {
3111 false
3112 };
3113
3114 if autoclose
3115 && bracket_pair.close
3116 && following_text_allows_autoclose
3117 && preceding_text_allows_autoclose
3118 && !is_closing_quote
3119 {
3120 let anchor = snapshot.anchor_before(selection.end);
3121 new_selections.push((selection.map(|_| anchor), text.len()));
3122 new_autoclose_regions.push((
3123 anchor,
3124 text.len(),
3125 selection.id,
3126 bracket_pair.clone(),
3127 ));
3128 edits.push((
3129 selection.range(),
3130 format!("{}{}", text, bracket_pair.end).into(),
3131 ));
3132 bracket_inserted = true;
3133 continue;
3134 }
3135 }
3136
3137 if let Some(region) = autoclose_region {
3138 // If the selection is followed by an auto-inserted closing bracket,
3139 // then don't insert that closing bracket again; just move the selection
3140 // past the closing bracket.
3141 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3142 && text.as_ref() == region.pair.end.as_str();
3143 if should_skip {
3144 let anchor = snapshot.anchor_after(selection.end);
3145 new_selections
3146 .push((selection.map(|_| anchor), region.pair.end.len()));
3147 continue;
3148 }
3149 }
3150
3151 let always_treat_brackets_as_autoclosed = snapshot
3152 .language_settings_at(selection.start, cx)
3153 .always_treat_brackets_as_autoclosed;
3154 if always_treat_brackets_as_autoclosed
3155 && is_bracket_pair_end
3156 && snapshot.contains_str_at(selection.end, text.as_ref())
3157 {
3158 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3159 // and the inserted text is a closing bracket and the selection is followed
3160 // by the closing bracket then move the selection past the closing bracket.
3161 let anchor = snapshot.anchor_after(selection.end);
3162 new_selections.push((selection.map(|_| anchor), text.len()));
3163 continue;
3164 }
3165 }
3166 // If an opening bracket is 1 character long and is typed while
3167 // text is selected, then surround that text with the bracket pair.
3168 else if auto_surround
3169 && bracket_pair.surround
3170 && is_bracket_pair_start
3171 && bracket_pair.start.chars().count() == 1
3172 {
3173 edits.push((selection.start..selection.start, text.clone()));
3174 edits.push((
3175 selection.end..selection.end,
3176 bracket_pair.end.as_str().into(),
3177 ));
3178 bracket_inserted = true;
3179 new_selections.push((
3180 Selection {
3181 id: selection.id,
3182 start: snapshot.anchor_after(selection.start),
3183 end: snapshot.anchor_before(selection.end),
3184 reversed: selection.reversed,
3185 goal: selection.goal,
3186 },
3187 0,
3188 ));
3189 continue;
3190 }
3191 }
3192 }
3193
3194 if self.auto_replace_emoji_shortcode
3195 && selection.is_empty()
3196 && text.as_ref().ends_with(':')
3197 {
3198 if let Some(possible_emoji_short_code) =
3199 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3200 {
3201 if !possible_emoji_short_code.is_empty() {
3202 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3203 let emoji_shortcode_start = Point::new(
3204 selection.start.row,
3205 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3206 );
3207
3208 // Remove shortcode from buffer
3209 edits.push((
3210 emoji_shortcode_start..selection.start,
3211 "".to_string().into(),
3212 ));
3213 new_selections.push((
3214 Selection {
3215 id: selection.id,
3216 start: snapshot.anchor_after(emoji_shortcode_start),
3217 end: snapshot.anchor_before(selection.start),
3218 reversed: selection.reversed,
3219 goal: selection.goal,
3220 },
3221 0,
3222 ));
3223
3224 // Insert emoji
3225 let selection_start_anchor = snapshot.anchor_after(selection.start);
3226 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3227 edits.push((selection.start..selection.end, emoji.to_string().into()));
3228
3229 continue;
3230 }
3231 }
3232 }
3233 }
3234
3235 // If not handling any auto-close operation, then just replace the selected
3236 // text with the given input and move the selection to the end of the
3237 // newly inserted text.
3238 let anchor = snapshot.anchor_after(selection.end);
3239 if !self.linked_edit_ranges.is_empty() {
3240 let start_anchor = snapshot.anchor_before(selection.start);
3241
3242 let is_word_char = text.chars().next().map_or(true, |char| {
3243 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3244 classifier.is_word(char)
3245 });
3246
3247 if is_word_char {
3248 if let Some(ranges) = self
3249 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3250 {
3251 for (buffer, edits) in ranges {
3252 linked_edits
3253 .entry(buffer.clone())
3254 .or_default()
3255 .extend(edits.into_iter().map(|range| (range, text.clone())));
3256 }
3257 }
3258 }
3259 }
3260
3261 new_selections.push((selection.map(|_| anchor), 0));
3262 edits.push((selection.start..selection.end, text.clone()));
3263 }
3264
3265 drop(snapshot);
3266
3267 self.transact(window, cx, |this, window, cx| {
3268 let initial_buffer_versions =
3269 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3270
3271 this.buffer.update(cx, |buffer, cx| {
3272 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3273 });
3274 for (buffer, edits) in linked_edits {
3275 buffer.update(cx, |buffer, cx| {
3276 let snapshot = buffer.snapshot();
3277 let edits = edits
3278 .into_iter()
3279 .map(|(range, text)| {
3280 use text::ToPoint as TP;
3281 let end_point = TP::to_point(&range.end, &snapshot);
3282 let start_point = TP::to_point(&range.start, &snapshot);
3283 (start_point..end_point, text)
3284 })
3285 .sorted_by_key(|(range, _)| range.start);
3286 buffer.edit(edits, None, cx);
3287 })
3288 }
3289 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3290 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3291 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3292 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3293 .zip(new_selection_deltas)
3294 .map(|(selection, delta)| Selection {
3295 id: selection.id,
3296 start: selection.start + delta,
3297 end: selection.end + delta,
3298 reversed: selection.reversed,
3299 goal: SelectionGoal::None,
3300 })
3301 .collect::<Vec<_>>();
3302
3303 let mut i = 0;
3304 for (position, delta, selection_id, pair) in new_autoclose_regions {
3305 let position = position.to_offset(&map.buffer_snapshot) + delta;
3306 let start = map.buffer_snapshot.anchor_before(position);
3307 let end = map.buffer_snapshot.anchor_after(position);
3308 while let Some(existing_state) = this.autoclose_regions.get(i) {
3309 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3310 Ordering::Less => i += 1,
3311 Ordering::Greater => break,
3312 Ordering::Equal => {
3313 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3314 Ordering::Less => i += 1,
3315 Ordering::Equal => break,
3316 Ordering::Greater => break,
3317 }
3318 }
3319 }
3320 }
3321 this.autoclose_regions.insert(
3322 i,
3323 AutocloseRegion {
3324 selection_id,
3325 range: start..end,
3326 pair,
3327 },
3328 );
3329 }
3330
3331 let had_active_inline_completion = this.has_active_inline_completion();
3332 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3333 s.select(new_selections)
3334 });
3335
3336 if !bracket_inserted {
3337 if let Some(on_type_format_task) =
3338 this.trigger_on_type_formatting(text.to_string(), window, cx)
3339 {
3340 on_type_format_task.detach_and_log_err(cx);
3341 }
3342 }
3343
3344 let editor_settings = EditorSettings::get_global(cx);
3345 if bracket_inserted
3346 && (editor_settings.auto_signature_help
3347 || editor_settings.show_signature_help_after_edits)
3348 {
3349 this.show_signature_help(&ShowSignatureHelp, window, cx);
3350 }
3351
3352 let trigger_in_words =
3353 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3354 if this.hard_wrap.is_some() {
3355 let latest: Range<Point> = this.selections.newest(cx).range();
3356 if latest.is_empty()
3357 && this
3358 .buffer()
3359 .read(cx)
3360 .snapshot(cx)
3361 .line_len(MultiBufferRow(latest.start.row))
3362 == latest.start.column
3363 {
3364 this.rewrap_impl(
3365 RewrapOptions {
3366 override_language_settings: true,
3367 preserve_existing_whitespace: true,
3368 },
3369 cx,
3370 )
3371 }
3372 }
3373 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3374 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3375 this.refresh_inline_completion(true, false, window, cx);
3376 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3377 });
3378 }
3379
3380 fn find_possible_emoji_shortcode_at_position(
3381 snapshot: &MultiBufferSnapshot,
3382 position: Point,
3383 ) -> Option<String> {
3384 let mut chars = Vec::new();
3385 let mut found_colon = false;
3386 for char in snapshot.reversed_chars_at(position).take(100) {
3387 // Found a possible emoji shortcode in the middle of the buffer
3388 if found_colon {
3389 if char.is_whitespace() {
3390 chars.reverse();
3391 return Some(chars.iter().collect());
3392 }
3393 // If the previous character is not a whitespace, we are in the middle of a word
3394 // and we only want to complete the shortcode if the word is made up of other emojis
3395 let mut containing_word = String::new();
3396 for ch in snapshot
3397 .reversed_chars_at(position)
3398 .skip(chars.len() + 1)
3399 .take(100)
3400 {
3401 if ch.is_whitespace() {
3402 break;
3403 }
3404 containing_word.push(ch);
3405 }
3406 let containing_word = containing_word.chars().rev().collect::<String>();
3407 if util::word_consists_of_emojis(containing_word.as_str()) {
3408 chars.reverse();
3409 return Some(chars.iter().collect());
3410 }
3411 }
3412
3413 if char.is_whitespace() || !char.is_ascii() {
3414 return None;
3415 }
3416 if char == ':' {
3417 found_colon = true;
3418 } else {
3419 chars.push(char);
3420 }
3421 }
3422 // Found a possible emoji shortcode at the beginning of the buffer
3423 chars.reverse();
3424 Some(chars.iter().collect())
3425 }
3426
3427 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3428 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3429 self.transact(window, cx, |this, window, cx| {
3430 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3431 let selections = this.selections.all::<usize>(cx);
3432 let multi_buffer = this.buffer.read(cx);
3433 let buffer = multi_buffer.snapshot(cx);
3434 selections
3435 .iter()
3436 .map(|selection| {
3437 let start_point = selection.start.to_point(&buffer);
3438 let mut indent =
3439 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3440 indent.len = cmp::min(indent.len, start_point.column);
3441 let start = selection.start;
3442 let end = selection.end;
3443 let selection_is_empty = start == end;
3444 let language_scope = buffer.language_scope_at(start);
3445 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3446 &language_scope
3447 {
3448 let insert_extra_newline =
3449 insert_extra_newline_brackets(&buffer, start..end, language)
3450 || insert_extra_newline_tree_sitter(&buffer, start..end);
3451
3452 // Comment extension on newline is allowed only for cursor selections
3453 let comment_delimiter = maybe!({
3454 if !selection_is_empty {
3455 return None;
3456 }
3457
3458 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3459 return None;
3460 }
3461
3462 let delimiters = language.line_comment_prefixes();
3463 let max_len_of_delimiter =
3464 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3465 let (snapshot, range) =
3466 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3467
3468 let mut index_of_first_non_whitespace = 0;
3469 let comment_candidate = snapshot
3470 .chars_for_range(range)
3471 .skip_while(|c| {
3472 let should_skip = c.is_whitespace();
3473 if should_skip {
3474 index_of_first_non_whitespace += 1;
3475 }
3476 should_skip
3477 })
3478 .take(max_len_of_delimiter)
3479 .collect::<String>();
3480 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3481 comment_candidate.starts_with(comment_prefix.as_ref())
3482 })?;
3483 let cursor_is_placed_after_comment_marker =
3484 index_of_first_non_whitespace + comment_prefix.len()
3485 <= start_point.column as usize;
3486 if cursor_is_placed_after_comment_marker {
3487 Some(comment_prefix.clone())
3488 } else {
3489 None
3490 }
3491 });
3492 (comment_delimiter, insert_extra_newline)
3493 } else {
3494 (None, false)
3495 };
3496
3497 let capacity_for_delimiter = comment_delimiter
3498 .as_deref()
3499 .map(str::len)
3500 .unwrap_or_default();
3501 let mut new_text =
3502 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3503 new_text.push('\n');
3504 new_text.extend(indent.chars());
3505 if let Some(delimiter) = &comment_delimiter {
3506 new_text.push_str(delimiter);
3507 }
3508 if insert_extra_newline {
3509 new_text = new_text.repeat(2);
3510 }
3511
3512 let anchor = buffer.anchor_after(end);
3513 let new_selection = selection.map(|_| anchor);
3514 (
3515 (start..end, new_text),
3516 (insert_extra_newline, new_selection),
3517 )
3518 })
3519 .unzip()
3520 };
3521
3522 this.edit_with_autoindent(edits, cx);
3523 let buffer = this.buffer.read(cx).snapshot(cx);
3524 let new_selections = selection_fixup_info
3525 .into_iter()
3526 .map(|(extra_newline_inserted, new_selection)| {
3527 let mut cursor = new_selection.end.to_point(&buffer);
3528 if extra_newline_inserted {
3529 cursor.row -= 1;
3530 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3531 }
3532 new_selection.map(|_| cursor)
3533 })
3534 .collect();
3535
3536 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3537 s.select(new_selections)
3538 });
3539 this.refresh_inline_completion(true, false, window, cx);
3540 });
3541 }
3542
3543 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3544 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3545
3546 let buffer = self.buffer.read(cx);
3547 let snapshot = buffer.snapshot(cx);
3548
3549 let mut edits = Vec::new();
3550 let mut rows = Vec::new();
3551
3552 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3553 let cursor = selection.head();
3554 let row = cursor.row;
3555
3556 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3557
3558 let newline = "\n".to_string();
3559 edits.push((start_of_line..start_of_line, newline));
3560
3561 rows.push(row + rows_inserted as u32);
3562 }
3563
3564 self.transact(window, cx, |editor, window, cx| {
3565 editor.edit(edits, cx);
3566
3567 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3568 let mut index = 0;
3569 s.move_cursors_with(|map, _, _| {
3570 let row = rows[index];
3571 index += 1;
3572
3573 let point = Point::new(row, 0);
3574 let boundary = map.next_line_boundary(point).1;
3575 let clipped = map.clip_point(boundary, Bias::Left);
3576
3577 (clipped, SelectionGoal::None)
3578 });
3579 });
3580
3581 let mut indent_edits = Vec::new();
3582 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3583 for row in rows {
3584 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3585 for (row, indent) in indents {
3586 if indent.len == 0 {
3587 continue;
3588 }
3589
3590 let text = match indent.kind {
3591 IndentKind::Space => " ".repeat(indent.len as usize),
3592 IndentKind::Tab => "\t".repeat(indent.len as usize),
3593 };
3594 let point = Point::new(row.0, 0);
3595 indent_edits.push((point..point, text));
3596 }
3597 }
3598 editor.edit(indent_edits, cx);
3599 });
3600 }
3601
3602 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3603 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3604
3605 let buffer = self.buffer.read(cx);
3606 let snapshot = buffer.snapshot(cx);
3607
3608 let mut edits = Vec::new();
3609 let mut rows = Vec::new();
3610 let mut rows_inserted = 0;
3611
3612 for selection in self.selections.all_adjusted(cx) {
3613 let cursor = selection.head();
3614 let row = cursor.row;
3615
3616 let point = Point::new(row + 1, 0);
3617 let start_of_line = snapshot.clip_point(point, Bias::Left);
3618
3619 let newline = "\n".to_string();
3620 edits.push((start_of_line..start_of_line, newline));
3621
3622 rows_inserted += 1;
3623 rows.push(row + rows_inserted);
3624 }
3625
3626 self.transact(window, cx, |editor, window, cx| {
3627 editor.edit(edits, cx);
3628
3629 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3630 let mut index = 0;
3631 s.move_cursors_with(|map, _, _| {
3632 let row = rows[index];
3633 index += 1;
3634
3635 let point = Point::new(row, 0);
3636 let boundary = map.next_line_boundary(point).1;
3637 let clipped = map.clip_point(boundary, Bias::Left);
3638
3639 (clipped, SelectionGoal::None)
3640 });
3641 });
3642
3643 let mut indent_edits = Vec::new();
3644 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3645 for row in rows {
3646 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3647 for (row, indent) in indents {
3648 if indent.len == 0 {
3649 continue;
3650 }
3651
3652 let text = match indent.kind {
3653 IndentKind::Space => " ".repeat(indent.len as usize),
3654 IndentKind::Tab => "\t".repeat(indent.len as usize),
3655 };
3656 let point = Point::new(row.0, 0);
3657 indent_edits.push((point..point, text));
3658 }
3659 }
3660 editor.edit(indent_edits, cx);
3661 });
3662 }
3663
3664 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3665 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3666 original_indent_columns: Vec::new(),
3667 });
3668 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3669 }
3670
3671 fn insert_with_autoindent_mode(
3672 &mut self,
3673 text: &str,
3674 autoindent_mode: Option<AutoindentMode>,
3675 window: &mut Window,
3676 cx: &mut Context<Self>,
3677 ) {
3678 if self.read_only(cx) {
3679 return;
3680 }
3681
3682 let text: Arc<str> = text.into();
3683 self.transact(window, cx, |this, window, cx| {
3684 let old_selections = this.selections.all_adjusted(cx);
3685 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3686 let anchors = {
3687 let snapshot = buffer.read(cx);
3688 old_selections
3689 .iter()
3690 .map(|s| {
3691 let anchor = snapshot.anchor_after(s.head());
3692 s.map(|_| anchor)
3693 })
3694 .collect::<Vec<_>>()
3695 };
3696 buffer.edit(
3697 old_selections
3698 .iter()
3699 .map(|s| (s.start..s.end, text.clone())),
3700 autoindent_mode,
3701 cx,
3702 );
3703 anchors
3704 });
3705
3706 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3707 s.select_anchors(selection_anchors);
3708 });
3709
3710 cx.notify();
3711 });
3712 }
3713
3714 fn trigger_completion_on_input(
3715 &mut self,
3716 text: &str,
3717 trigger_in_words: bool,
3718 window: &mut Window,
3719 cx: &mut Context<Self>,
3720 ) {
3721 let ignore_completion_provider = self
3722 .context_menu
3723 .borrow()
3724 .as_ref()
3725 .map(|menu| match menu {
3726 CodeContextMenu::Completions(completions_menu) => {
3727 completions_menu.ignore_completion_provider
3728 }
3729 CodeContextMenu::CodeActions(_) => false,
3730 })
3731 .unwrap_or(false);
3732
3733 if ignore_completion_provider {
3734 self.show_word_completions(&ShowWordCompletions, window, cx);
3735 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3736 self.show_completions(
3737 &ShowCompletions {
3738 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3739 },
3740 window,
3741 cx,
3742 );
3743 } else {
3744 self.hide_context_menu(window, cx);
3745 }
3746 }
3747
3748 fn is_completion_trigger(
3749 &self,
3750 text: &str,
3751 trigger_in_words: bool,
3752 cx: &mut Context<Self>,
3753 ) -> bool {
3754 let position = self.selections.newest_anchor().head();
3755 let multibuffer = self.buffer.read(cx);
3756 let Some(buffer) = position
3757 .buffer_id
3758 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3759 else {
3760 return false;
3761 };
3762
3763 if let Some(completion_provider) = &self.completion_provider {
3764 completion_provider.is_completion_trigger(
3765 &buffer,
3766 position.text_anchor,
3767 text,
3768 trigger_in_words,
3769 cx,
3770 )
3771 } else {
3772 false
3773 }
3774 }
3775
3776 /// If any empty selections is touching the start of its innermost containing autoclose
3777 /// region, expand it to select the brackets.
3778 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3779 let selections = self.selections.all::<usize>(cx);
3780 let buffer = self.buffer.read(cx).read(cx);
3781 let new_selections = self
3782 .selections_with_autoclose_regions(selections, &buffer)
3783 .map(|(mut selection, region)| {
3784 if !selection.is_empty() {
3785 return selection;
3786 }
3787
3788 if let Some(region) = region {
3789 let mut range = region.range.to_offset(&buffer);
3790 if selection.start == range.start && range.start >= region.pair.start.len() {
3791 range.start -= region.pair.start.len();
3792 if buffer.contains_str_at(range.start, ®ion.pair.start)
3793 && buffer.contains_str_at(range.end, ®ion.pair.end)
3794 {
3795 range.end += region.pair.end.len();
3796 selection.start = range.start;
3797 selection.end = range.end;
3798
3799 return selection;
3800 }
3801 }
3802 }
3803
3804 let always_treat_brackets_as_autoclosed = buffer
3805 .language_settings_at(selection.start, cx)
3806 .always_treat_brackets_as_autoclosed;
3807
3808 if !always_treat_brackets_as_autoclosed {
3809 return selection;
3810 }
3811
3812 if let Some(scope) = buffer.language_scope_at(selection.start) {
3813 for (pair, enabled) in scope.brackets() {
3814 if !enabled || !pair.close {
3815 continue;
3816 }
3817
3818 if buffer.contains_str_at(selection.start, &pair.end) {
3819 let pair_start_len = pair.start.len();
3820 if buffer.contains_str_at(
3821 selection.start.saturating_sub(pair_start_len),
3822 &pair.start,
3823 ) {
3824 selection.start -= pair_start_len;
3825 selection.end += pair.end.len();
3826
3827 return selection;
3828 }
3829 }
3830 }
3831 }
3832
3833 selection
3834 })
3835 .collect();
3836
3837 drop(buffer);
3838 self.change_selections(None, window, cx, |selections| {
3839 selections.select(new_selections)
3840 });
3841 }
3842
3843 /// Iterate the given selections, and for each one, find the smallest surrounding
3844 /// autoclose region. This uses the ordering of the selections and the autoclose
3845 /// regions to avoid repeated comparisons.
3846 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3847 &'a self,
3848 selections: impl IntoIterator<Item = Selection<D>>,
3849 buffer: &'a MultiBufferSnapshot,
3850 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3851 let mut i = 0;
3852 let mut regions = self.autoclose_regions.as_slice();
3853 selections.into_iter().map(move |selection| {
3854 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3855
3856 let mut enclosing = None;
3857 while let Some(pair_state) = regions.get(i) {
3858 if pair_state.range.end.to_offset(buffer) < range.start {
3859 regions = ®ions[i + 1..];
3860 i = 0;
3861 } else if pair_state.range.start.to_offset(buffer) > range.end {
3862 break;
3863 } else {
3864 if pair_state.selection_id == selection.id {
3865 enclosing = Some(pair_state);
3866 }
3867 i += 1;
3868 }
3869 }
3870
3871 (selection, enclosing)
3872 })
3873 }
3874
3875 /// Remove any autoclose regions that no longer contain their selection.
3876 fn invalidate_autoclose_regions(
3877 &mut self,
3878 mut selections: &[Selection<Anchor>],
3879 buffer: &MultiBufferSnapshot,
3880 ) {
3881 self.autoclose_regions.retain(|state| {
3882 let mut i = 0;
3883 while let Some(selection) = selections.get(i) {
3884 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3885 selections = &selections[1..];
3886 continue;
3887 }
3888 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3889 break;
3890 }
3891 if selection.id == state.selection_id {
3892 return true;
3893 } else {
3894 i += 1;
3895 }
3896 }
3897 false
3898 });
3899 }
3900
3901 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3902 let offset = position.to_offset(buffer);
3903 let (word_range, kind) = buffer.surrounding_word(offset, true);
3904 if offset > word_range.start && kind == Some(CharKind::Word) {
3905 Some(
3906 buffer
3907 .text_for_range(word_range.start..offset)
3908 .collect::<String>(),
3909 )
3910 } else {
3911 None
3912 }
3913 }
3914
3915 pub fn toggle_inlay_hints(
3916 &mut self,
3917 _: &ToggleInlayHints,
3918 _: &mut Window,
3919 cx: &mut Context<Self>,
3920 ) {
3921 self.refresh_inlay_hints(
3922 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3923 cx,
3924 );
3925 }
3926
3927 pub fn inlay_hints_enabled(&self) -> bool {
3928 self.inlay_hint_cache.enabled
3929 }
3930
3931 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3932 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3933 return;
3934 }
3935
3936 let reason_description = reason.description();
3937 let ignore_debounce = matches!(
3938 reason,
3939 InlayHintRefreshReason::SettingsChange(_)
3940 | InlayHintRefreshReason::Toggle(_)
3941 | InlayHintRefreshReason::ExcerptsRemoved(_)
3942 | InlayHintRefreshReason::ModifiersChanged(_)
3943 );
3944 let (invalidate_cache, required_languages) = match reason {
3945 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3946 match self.inlay_hint_cache.modifiers_override(enabled) {
3947 Some(enabled) => {
3948 if enabled {
3949 (InvalidationStrategy::RefreshRequested, None)
3950 } else {
3951 self.splice_inlays(
3952 &self
3953 .visible_inlay_hints(cx)
3954 .iter()
3955 .map(|inlay| inlay.id)
3956 .collect::<Vec<InlayId>>(),
3957 Vec::new(),
3958 cx,
3959 );
3960 return;
3961 }
3962 }
3963 None => return,
3964 }
3965 }
3966 InlayHintRefreshReason::Toggle(enabled) => {
3967 if self.inlay_hint_cache.toggle(enabled) {
3968 if enabled {
3969 (InvalidationStrategy::RefreshRequested, None)
3970 } else {
3971 self.splice_inlays(
3972 &self
3973 .visible_inlay_hints(cx)
3974 .iter()
3975 .map(|inlay| inlay.id)
3976 .collect::<Vec<InlayId>>(),
3977 Vec::new(),
3978 cx,
3979 );
3980 return;
3981 }
3982 } else {
3983 return;
3984 }
3985 }
3986 InlayHintRefreshReason::SettingsChange(new_settings) => {
3987 match self.inlay_hint_cache.update_settings(
3988 &self.buffer,
3989 new_settings,
3990 self.visible_inlay_hints(cx),
3991 cx,
3992 ) {
3993 ControlFlow::Break(Some(InlaySplice {
3994 to_remove,
3995 to_insert,
3996 })) => {
3997 self.splice_inlays(&to_remove, to_insert, cx);
3998 return;
3999 }
4000 ControlFlow::Break(None) => return,
4001 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4002 }
4003 }
4004 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4005 if let Some(InlaySplice {
4006 to_remove,
4007 to_insert,
4008 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4009 {
4010 self.splice_inlays(&to_remove, to_insert, cx);
4011 }
4012 return;
4013 }
4014 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4015 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4016 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4017 }
4018 InlayHintRefreshReason::RefreshRequested => {
4019 (InvalidationStrategy::RefreshRequested, None)
4020 }
4021 };
4022
4023 if let Some(InlaySplice {
4024 to_remove,
4025 to_insert,
4026 }) = self.inlay_hint_cache.spawn_hint_refresh(
4027 reason_description,
4028 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4029 invalidate_cache,
4030 ignore_debounce,
4031 cx,
4032 ) {
4033 self.splice_inlays(&to_remove, to_insert, cx);
4034 }
4035 }
4036
4037 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4038 self.display_map
4039 .read(cx)
4040 .current_inlays()
4041 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4042 .cloned()
4043 .collect()
4044 }
4045
4046 pub fn excerpts_for_inlay_hints_query(
4047 &self,
4048 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4049 cx: &mut Context<Editor>,
4050 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4051 let Some(project) = self.project.as_ref() else {
4052 return HashMap::default();
4053 };
4054 let project = project.read(cx);
4055 let multi_buffer = self.buffer().read(cx);
4056 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4057 let multi_buffer_visible_start = self
4058 .scroll_manager
4059 .anchor()
4060 .anchor
4061 .to_point(&multi_buffer_snapshot);
4062 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4063 multi_buffer_visible_start
4064 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4065 Bias::Left,
4066 );
4067 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4068 multi_buffer_snapshot
4069 .range_to_buffer_ranges(multi_buffer_visible_range)
4070 .into_iter()
4071 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4072 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4073 let buffer_file = project::File::from_dyn(buffer.file())?;
4074 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4075 let worktree_entry = buffer_worktree
4076 .read(cx)
4077 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4078 if worktree_entry.is_ignored {
4079 return None;
4080 }
4081
4082 let language = buffer.language()?;
4083 if let Some(restrict_to_languages) = restrict_to_languages {
4084 if !restrict_to_languages.contains(language) {
4085 return None;
4086 }
4087 }
4088 Some((
4089 excerpt_id,
4090 (
4091 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4092 buffer.version().clone(),
4093 excerpt_visible_range,
4094 ),
4095 ))
4096 })
4097 .collect()
4098 }
4099
4100 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4101 TextLayoutDetails {
4102 text_system: window.text_system().clone(),
4103 editor_style: self.style.clone().unwrap(),
4104 rem_size: window.rem_size(),
4105 scroll_anchor: self.scroll_manager.anchor(),
4106 visible_rows: self.visible_line_count(),
4107 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4108 }
4109 }
4110
4111 pub fn splice_inlays(
4112 &self,
4113 to_remove: &[InlayId],
4114 to_insert: Vec<Inlay>,
4115 cx: &mut Context<Self>,
4116 ) {
4117 self.display_map.update(cx, |display_map, cx| {
4118 display_map.splice_inlays(to_remove, to_insert, cx)
4119 });
4120 cx.notify();
4121 }
4122
4123 fn trigger_on_type_formatting(
4124 &self,
4125 input: String,
4126 window: &mut Window,
4127 cx: &mut Context<Self>,
4128 ) -> Option<Task<Result<()>>> {
4129 if input.len() != 1 {
4130 return None;
4131 }
4132
4133 let project = self.project.as_ref()?;
4134 let position = self.selections.newest_anchor().head();
4135 let (buffer, buffer_position) = self
4136 .buffer
4137 .read(cx)
4138 .text_anchor_for_position(position, cx)?;
4139
4140 let settings = language_settings::language_settings(
4141 buffer
4142 .read(cx)
4143 .language_at(buffer_position)
4144 .map(|l| l.name()),
4145 buffer.read(cx).file(),
4146 cx,
4147 );
4148 if !settings.use_on_type_format {
4149 return None;
4150 }
4151
4152 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4153 // hence we do LSP request & edit on host side only — add formats to host's history.
4154 let push_to_lsp_host_history = true;
4155 // If this is not the host, append its history with new edits.
4156 let push_to_client_history = project.read(cx).is_via_collab();
4157
4158 let on_type_formatting = project.update(cx, |project, cx| {
4159 project.on_type_format(
4160 buffer.clone(),
4161 buffer_position,
4162 input,
4163 push_to_lsp_host_history,
4164 cx,
4165 )
4166 });
4167 Some(cx.spawn_in(window, async move |editor, cx| {
4168 if let Some(transaction) = on_type_formatting.await? {
4169 if push_to_client_history {
4170 buffer
4171 .update(cx, |buffer, _| {
4172 buffer.push_transaction(transaction, Instant::now());
4173 })
4174 .ok();
4175 }
4176 editor.update(cx, |editor, cx| {
4177 editor.refresh_document_highlights(cx);
4178 })?;
4179 }
4180 Ok(())
4181 }))
4182 }
4183
4184 pub fn show_word_completions(
4185 &mut self,
4186 _: &ShowWordCompletions,
4187 window: &mut Window,
4188 cx: &mut Context<Self>,
4189 ) {
4190 self.open_completions_menu(true, None, window, cx);
4191 }
4192
4193 pub fn show_completions(
4194 &mut self,
4195 options: &ShowCompletions,
4196 window: &mut Window,
4197 cx: &mut Context<Self>,
4198 ) {
4199 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4200 }
4201
4202 fn open_completions_menu(
4203 &mut self,
4204 ignore_completion_provider: bool,
4205 trigger: Option<&str>,
4206 window: &mut Window,
4207 cx: &mut Context<Self>,
4208 ) {
4209 if self.pending_rename.is_some() {
4210 return;
4211 }
4212 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4213 return;
4214 }
4215
4216 let position = self.selections.newest_anchor().head();
4217 if position.diff_base_anchor.is_some() {
4218 return;
4219 }
4220 let (buffer, buffer_position) =
4221 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4222 output
4223 } else {
4224 return;
4225 };
4226 let buffer_snapshot = buffer.read(cx).snapshot();
4227 let show_completion_documentation = buffer_snapshot
4228 .settings_at(buffer_position, cx)
4229 .show_completion_documentation;
4230
4231 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4232
4233 let trigger_kind = match trigger {
4234 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4235 CompletionTriggerKind::TRIGGER_CHARACTER
4236 }
4237 _ => CompletionTriggerKind::INVOKED,
4238 };
4239 let completion_context = CompletionContext {
4240 trigger_character: trigger.and_then(|trigger| {
4241 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4242 Some(String::from(trigger))
4243 } else {
4244 None
4245 }
4246 }),
4247 trigger_kind,
4248 };
4249
4250 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4251 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4252 let word_to_exclude = buffer_snapshot
4253 .text_for_range(old_range.clone())
4254 .collect::<String>();
4255 (
4256 buffer_snapshot.anchor_before(old_range.start)
4257 ..buffer_snapshot.anchor_after(old_range.end),
4258 Some(word_to_exclude),
4259 )
4260 } else {
4261 (buffer_position..buffer_position, None)
4262 };
4263
4264 let completion_settings = language_settings(
4265 buffer_snapshot
4266 .language_at(buffer_position)
4267 .map(|language| language.name()),
4268 buffer_snapshot.file(),
4269 cx,
4270 )
4271 .completions;
4272
4273 // The document can be large, so stay in reasonable bounds when searching for words,
4274 // otherwise completion pop-up might be slow to appear.
4275 const WORD_LOOKUP_ROWS: u32 = 5_000;
4276 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4277 let min_word_search = buffer_snapshot.clip_point(
4278 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4279 Bias::Left,
4280 );
4281 let max_word_search = buffer_snapshot.clip_point(
4282 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4283 Bias::Right,
4284 );
4285 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4286 ..buffer_snapshot.point_to_offset(max_word_search);
4287
4288 let provider = self
4289 .completion_provider
4290 .as_ref()
4291 .filter(|_| !ignore_completion_provider);
4292 let skip_digits = query
4293 .as_ref()
4294 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4295
4296 let (mut words, provided_completions) = match provider {
4297 Some(provider) => {
4298 let completions = provider.completions(
4299 position.excerpt_id,
4300 &buffer,
4301 buffer_position,
4302 completion_context,
4303 window,
4304 cx,
4305 );
4306
4307 let words = match completion_settings.words {
4308 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4309 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4310 .background_spawn(async move {
4311 buffer_snapshot.words_in_range(WordsQuery {
4312 fuzzy_contents: None,
4313 range: word_search_range,
4314 skip_digits,
4315 })
4316 }),
4317 };
4318
4319 (words, completions)
4320 }
4321 None => (
4322 cx.background_spawn(async move {
4323 buffer_snapshot.words_in_range(WordsQuery {
4324 fuzzy_contents: None,
4325 range: word_search_range,
4326 skip_digits,
4327 })
4328 }),
4329 Task::ready(Ok(None)),
4330 ),
4331 };
4332
4333 let sort_completions = provider
4334 .as_ref()
4335 .map_or(true, |provider| provider.sort_completions());
4336
4337 let filter_completions = provider
4338 .as_ref()
4339 .map_or(true, |provider| provider.filter_completions());
4340
4341 let id = post_inc(&mut self.next_completion_id);
4342 let task = cx.spawn_in(window, async move |editor, cx| {
4343 async move {
4344 editor.update(cx, |this, _| {
4345 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4346 })?;
4347
4348 let mut completions = Vec::new();
4349 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4350 completions.extend(provided_completions);
4351 if completion_settings.words == WordsCompletionMode::Fallback {
4352 words = Task::ready(HashMap::default());
4353 }
4354 }
4355
4356 let mut words = words.await;
4357 if let Some(word_to_exclude) = &word_to_exclude {
4358 words.remove(word_to_exclude);
4359 }
4360 for lsp_completion in &completions {
4361 words.remove(&lsp_completion.new_text);
4362 }
4363 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4364 old_range: old_range.clone(),
4365 new_text: word.clone(),
4366 label: CodeLabel::plain(word, None),
4367 icon_path: None,
4368 documentation: None,
4369 source: CompletionSource::BufferWord {
4370 word_range,
4371 resolved: false,
4372 },
4373 confirm: None,
4374 }));
4375
4376 let menu = if completions.is_empty() {
4377 None
4378 } else {
4379 let mut menu = CompletionsMenu::new(
4380 id,
4381 sort_completions,
4382 show_completion_documentation,
4383 ignore_completion_provider,
4384 position,
4385 buffer.clone(),
4386 completions.into(),
4387 );
4388
4389 menu.filter(
4390 if filter_completions {
4391 query.as_deref()
4392 } else {
4393 None
4394 },
4395 cx.background_executor().clone(),
4396 )
4397 .await;
4398
4399 menu.visible().then_some(menu)
4400 };
4401
4402 editor.update_in(cx, |editor, window, cx| {
4403 match editor.context_menu.borrow().as_ref() {
4404 None => {}
4405 Some(CodeContextMenu::Completions(prev_menu)) => {
4406 if prev_menu.id > id {
4407 return;
4408 }
4409 }
4410 _ => return,
4411 }
4412
4413 if editor.focus_handle.is_focused(window) && menu.is_some() {
4414 let mut menu = menu.unwrap();
4415 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4416
4417 *editor.context_menu.borrow_mut() =
4418 Some(CodeContextMenu::Completions(menu));
4419
4420 if editor.show_edit_predictions_in_menu() {
4421 editor.update_visible_inline_completion(window, cx);
4422 } else {
4423 editor.discard_inline_completion(false, cx);
4424 }
4425
4426 cx.notify();
4427 } else if editor.completion_tasks.len() <= 1 {
4428 // If there are no more completion tasks and the last menu was
4429 // empty, we should hide it.
4430 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4431 // If it was already hidden and we don't show inline
4432 // completions in the menu, we should also show the
4433 // inline-completion when available.
4434 if was_hidden && editor.show_edit_predictions_in_menu() {
4435 editor.update_visible_inline_completion(window, cx);
4436 }
4437 }
4438 })?;
4439
4440 anyhow::Ok(())
4441 }
4442 .log_err()
4443 .await
4444 });
4445
4446 self.completion_tasks.push((id, task));
4447 }
4448
4449 #[cfg(feature = "test-support")]
4450 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4451 let menu = self.context_menu.borrow();
4452 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4453 let completions = menu.completions.borrow();
4454 Some(completions.to_vec())
4455 } else {
4456 None
4457 }
4458 }
4459
4460 pub fn confirm_completion(
4461 &mut self,
4462 action: &ConfirmCompletion,
4463 window: &mut Window,
4464 cx: &mut Context<Self>,
4465 ) -> Option<Task<Result<()>>> {
4466 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4467 }
4468
4469 pub fn compose_completion(
4470 &mut self,
4471 action: &ComposeCompletion,
4472 window: &mut Window,
4473 cx: &mut Context<Self>,
4474 ) -> Option<Task<Result<()>>> {
4475 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4476 }
4477
4478 fn do_completion(
4479 &mut self,
4480 item_ix: Option<usize>,
4481 intent: CompletionIntent,
4482 window: &mut Window,
4483 cx: &mut Context<Editor>,
4484 ) -> Option<Task<Result<()>>> {
4485 use language::ToOffset as _;
4486
4487 let completions_menu =
4488 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4489 menu
4490 } else {
4491 return None;
4492 };
4493
4494 let candidate_id = {
4495 let entries = completions_menu.entries.borrow();
4496 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4497 if self.show_edit_predictions_in_menu() {
4498 self.discard_inline_completion(true, cx);
4499 }
4500 mat.candidate_id
4501 };
4502
4503 let buffer_handle = completions_menu.buffer;
4504 let completion = completions_menu
4505 .completions
4506 .borrow()
4507 .get(candidate_id)?
4508 .clone();
4509 cx.stop_propagation();
4510
4511 let snippet;
4512 let new_text;
4513 if completion.is_snippet() {
4514 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4515 new_text = snippet.as_ref().unwrap().text.clone();
4516 } else {
4517 snippet = None;
4518 new_text = completion.new_text.clone();
4519 };
4520 let selections = self.selections.all::<usize>(cx);
4521 let buffer = buffer_handle.read(cx);
4522 let old_range = completion.old_range.to_offset(buffer);
4523 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4524
4525 let newest_selection = self.selections.newest_anchor();
4526 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4527 return None;
4528 }
4529
4530 let lookbehind = newest_selection
4531 .start
4532 .text_anchor
4533 .to_offset(buffer)
4534 .saturating_sub(old_range.start);
4535 let lookahead = old_range
4536 .end
4537 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4538 let mut common_prefix_len = old_text
4539 .bytes()
4540 .zip(new_text.bytes())
4541 .take_while(|(a, b)| a == b)
4542 .count();
4543
4544 let snapshot = self.buffer.read(cx).snapshot(cx);
4545 let mut range_to_replace: Option<Range<isize>> = None;
4546 let mut ranges = Vec::new();
4547 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4548 for selection in &selections {
4549 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4550 let start = selection.start.saturating_sub(lookbehind);
4551 let end = selection.end + lookahead;
4552 if selection.id == newest_selection.id {
4553 range_to_replace = Some(
4554 ((start + common_prefix_len) as isize - selection.start as isize)
4555 ..(end as isize - selection.start as isize),
4556 );
4557 }
4558 ranges.push(start + common_prefix_len..end);
4559 } else {
4560 common_prefix_len = 0;
4561 ranges.clear();
4562 ranges.extend(selections.iter().map(|s| {
4563 if s.id == newest_selection.id {
4564 range_to_replace = Some(
4565 old_range.start.to_offset_utf16(&snapshot).0 as isize
4566 - selection.start as isize
4567 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4568 - selection.start as isize,
4569 );
4570 old_range.clone()
4571 } else {
4572 s.start..s.end
4573 }
4574 }));
4575 break;
4576 }
4577 if !self.linked_edit_ranges.is_empty() {
4578 let start_anchor = snapshot.anchor_before(selection.head());
4579 let end_anchor = snapshot.anchor_after(selection.tail());
4580 if let Some(ranges) = self
4581 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4582 {
4583 for (buffer, edits) in ranges {
4584 linked_edits.entry(buffer.clone()).or_default().extend(
4585 edits
4586 .into_iter()
4587 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4588 );
4589 }
4590 }
4591 }
4592 }
4593 let text = &new_text[common_prefix_len..];
4594
4595 cx.emit(EditorEvent::InputHandled {
4596 utf16_range_to_replace: range_to_replace,
4597 text: text.into(),
4598 });
4599
4600 self.transact(window, cx, |this, window, cx| {
4601 if let Some(mut snippet) = snippet {
4602 snippet.text = text.to_string();
4603 for tabstop in snippet
4604 .tabstops
4605 .iter_mut()
4606 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4607 {
4608 tabstop.start -= common_prefix_len as isize;
4609 tabstop.end -= common_prefix_len as isize;
4610 }
4611
4612 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4613 } else {
4614 this.buffer.update(cx, |buffer, cx| {
4615 let edits = ranges.iter().map(|range| (range.clone(), text));
4616 buffer.edit(edits, this.autoindent_mode.clone(), cx);
4617 });
4618 }
4619 for (buffer, edits) in linked_edits {
4620 buffer.update(cx, |buffer, cx| {
4621 let snapshot = buffer.snapshot();
4622 let edits = edits
4623 .into_iter()
4624 .map(|(range, text)| {
4625 use text::ToPoint as TP;
4626 let end_point = TP::to_point(&range.end, &snapshot);
4627 let start_point = TP::to_point(&range.start, &snapshot);
4628 (start_point..end_point, text)
4629 })
4630 .sorted_by_key(|(range, _)| range.start);
4631 buffer.edit(edits, None, cx);
4632 })
4633 }
4634
4635 this.refresh_inline_completion(true, false, window, cx);
4636 });
4637
4638 let show_new_completions_on_confirm = completion
4639 .confirm
4640 .as_ref()
4641 .map_or(false, |confirm| confirm(intent, window, cx));
4642 if show_new_completions_on_confirm {
4643 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4644 }
4645
4646 let provider = self.completion_provider.as_ref()?;
4647 drop(completion);
4648 let apply_edits = provider.apply_additional_edits_for_completion(
4649 buffer_handle,
4650 completions_menu.completions.clone(),
4651 candidate_id,
4652 true,
4653 cx,
4654 );
4655
4656 let editor_settings = EditorSettings::get_global(cx);
4657 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4658 // After the code completion is finished, users often want to know what signatures are needed.
4659 // so we should automatically call signature_help
4660 self.show_signature_help(&ShowSignatureHelp, window, cx);
4661 }
4662
4663 Some(cx.foreground_executor().spawn(async move {
4664 apply_edits.await?;
4665 Ok(())
4666 }))
4667 }
4668
4669 pub fn toggle_code_actions(
4670 &mut self,
4671 action: &ToggleCodeActions,
4672 window: &mut Window,
4673 cx: &mut Context<Self>,
4674 ) {
4675 let mut context_menu = self.context_menu.borrow_mut();
4676 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4677 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4678 // Toggle if we're selecting the same one
4679 *context_menu = None;
4680 cx.notify();
4681 return;
4682 } else {
4683 // Otherwise, clear it and start a new one
4684 *context_menu = None;
4685 cx.notify();
4686 }
4687 }
4688 drop(context_menu);
4689 let snapshot = self.snapshot(window, cx);
4690 let deployed_from_indicator = action.deployed_from_indicator;
4691 let mut task = self.code_actions_task.take();
4692 let action = action.clone();
4693 cx.spawn_in(window, async move |editor, cx| {
4694 while let Some(prev_task) = task {
4695 prev_task.await.log_err();
4696 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4697 }
4698
4699 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4700 if editor.focus_handle.is_focused(window) {
4701 let multibuffer_point = action
4702 .deployed_from_indicator
4703 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4704 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4705 let (buffer, buffer_row) = snapshot
4706 .buffer_snapshot
4707 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4708 .and_then(|(buffer_snapshot, range)| {
4709 editor
4710 .buffer
4711 .read(cx)
4712 .buffer(buffer_snapshot.remote_id())
4713 .map(|buffer| (buffer, range.start.row))
4714 })?;
4715 let (_, code_actions) = editor
4716 .available_code_actions
4717 .clone()
4718 .and_then(|(location, code_actions)| {
4719 let snapshot = location.buffer.read(cx).snapshot();
4720 let point_range = location.range.to_point(&snapshot);
4721 let point_range = point_range.start.row..=point_range.end.row;
4722 if point_range.contains(&buffer_row) {
4723 Some((location, code_actions))
4724 } else {
4725 None
4726 }
4727 })
4728 .unzip();
4729 let buffer_id = buffer.read(cx).remote_id();
4730 let tasks = editor
4731 .tasks
4732 .get(&(buffer_id, buffer_row))
4733 .map(|t| Arc::new(t.to_owned()));
4734 if tasks.is_none() && code_actions.is_none() {
4735 return None;
4736 }
4737
4738 editor.completion_tasks.clear();
4739 editor.discard_inline_completion(false, cx);
4740 let task_context =
4741 tasks
4742 .as_ref()
4743 .zip(editor.project.clone())
4744 .map(|(tasks, project)| {
4745 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4746 });
4747
4748 Some(cx.spawn_in(window, async move |editor, cx| {
4749 let task_context = match task_context {
4750 Some(task_context) => task_context.await,
4751 None => None,
4752 };
4753 let resolved_tasks =
4754 tasks.zip(task_context).map(|(tasks, task_context)| {
4755 Rc::new(ResolvedTasks {
4756 templates: tasks.resolve(&task_context).collect(),
4757 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4758 multibuffer_point.row,
4759 tasks.column,
4760 )),
4761 })
4762 });
4763 let spawn_straight_away = resolved_tasks
4764 .as_ref()
4765 .map_or(false, |tasks| tasks.templates.len() == 1)
4766 && code_actions
4767 .as_ref()
4768 .map_or(true, |actions| actions.is_empty());
4769 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4770 *editor.context_menu.borrow_mut() =
4771 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4772 buffer,
4773 actions: CodeActionContents {
4774 tasks: resolved_tasks,
4775 actions: code_actions,
4776 },
4777 selected_item: Default::default(),
4778 scroll_handle: UniformListScrollHandle::default(),
4779 deployed_from_indicator,
4780 }));
4781 if spawn_straight_away {
4782 if let Some(task) = editor.confirm_code_action(
4783 &ConfirmCodeAction { item_ix: Some(0) },
4784 window,
4785 cx,
4786 ) {
4787 cx.notify();
4788 return task;
4789 }
4790 }
4791 cx.notify();
4792 Task::ready(Ok(()))
4793 }) {
4794 task.await
4795 } else {
4796 Ok(())
4797 }
4798 }))
4799 } else {
4800 Some(Task::ready(Ok(())))
4801 }
4802 })?;
4803 if let Some(task) = spawned_test_task {
4804 task.await?;
4805 }
4806
4807 Ok::<_, anyhow::Error>(())
4808 })
4809 .detach_and_log_err(cx);
4810 }
4811
4812 pub fn confirm_code_action(
4813 &mut self,
4814 action: &ConfirmCodeAction,
4815 window: &mut Window,
4816 cx: &mut Context<Self>,
4817 ) -> Option<Task<Result<()>>> {
4818 let actions_menu =
4819 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4820 menu
4821 } else {
4822 return None;
4823 };
4824 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4825 let action = actions_menu.actions.get(action_ix)?;
4826 let title = action.label();
4827 let buffer = actions_menu.buffer;
4828 let workspace = self.workspace()?;
4829
4830 match action {
4831 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4832 workspace.update(cx, |workspace, cx| {
4833 workspace::tasks::schedule_resolved_task(
4834 workspace,
4835 task_source_kind,
4836 resolved_task,
4837 false,
4838 cx,
4839 );
4840
4841 Some(Task::ready(Ok(())))
4842 })
4843 }
4844 CodeActionsItem::CodeAction {
4845 excerpt_id,
4846 action,
4847 provider,
4848 } => {
4849 let apply_code_action =
4850 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4851 let workspace = workspace.downgrade();
4852 Some(cx.spawn_in(window, async move |editor, cx| {
4853 let project_transaction = apply_code_action.await?;
4854 Self::open_project_transaction(
4855 &editor,
4856 workspace,
4857 project_transaction,
4858 title,
4859 cx,
4860 )
4861 .await
4862 }))
4863 }
4864 }
4865 }
4866
4867 pub async fn open_project_transaction(
4868 this: &WeakEntity<Editor>,
4869 workspace: WeakEntity<Workspace>,
4870 transaction: ProjectTransaction,
4871 title: String,
4872 cx: &mut AsyncWindowContext,
4873 ) -> Result<()> {
4874 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4875 cx.update(|_, cx| {
4876 entries.sort_unstable_by_key(|(buffer, _)| {
4877 buffer.read(cx).file().map(|f| f.path().clone())
4878 });
4879 })?;
4880
4881 // If the project transaction's edits are all contained within this editor, then
4882 // avoid opening a new editor to display them.
4883
4884 if let Some((buffer, transaction)) = entries.first() {
4885 if entries.len() == 1 {
4886 let excerpt = this.update(cx, |editor, cx| {
4887 editor
4888 .buffer()
4889 .read(cx)
4890 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4891 })?;
4892 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4893 if excerpted_buffer == *buffer {
4894 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
4895 let excerpt_range = excerpt_range.to_offset(buffer);
4896 buffer
4897 .edited_ranges_for_transaction::<usize>(transaction)
4898 .all(|range| {
4899 excerpt_range.start <= range.start
4900 && excerpt_range.end >= range.end
4901 })
4902 })?;
4903
4904 if all_edits_within_excerpt {
4905 return Ok(());
4906 }
4907 }
4908 }
4909 }
4910 } else {
4911 return Ok(());
4912 }
4913
4914 let mut ranges_to_highlight = Vec::new();
4915 let excerpt_buffer = cx.new(|cx| {
4916 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4917 for (buffer_handle, transaction) in &entries {
4918 let buffer = buffer_handle.read(cx);
4919 ranges_to_highlight.extend(
4920 multibuffer.push_excerpts_with_context_lines(
4921 buffer_handle.clone(),
4922 buffer
4923 .edited_ranges_for_transaction::<usize>(transaction)
4924 .collect(),
4925 DEFAULT_MULTIBUFFER_CONTEXT,
4926 cx,
4927 ),
4928 );
4929 }
4930 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4931 multibuffer
4932 })?;
4933
4934 workspace.update_in(cx, |workspace, window, cx| {
4935 let project = workspace.project().clone();
4936 let editor =
4937 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
4938 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4939 editor.update(cx, |editor, cx| {
4940 editor.highlight_background::<Self>(
4941 &ranges_to_highlight,
4942 |theme| theme.editor_highlighted_line_background,
4943 cx,
4944 );
4945 });
4946 })?;
4947
4948 Ok(())
4949 }
4950
4951 pub fn clear_code_action_providers(&mut self) {
4952 self.code_action_providers.clear();
4953 self.available_code_actions.take();
4954 }
4955
4956 pub fn add_code_action_provider(
4957 &mut self,
4958 provider: Rc<dyn CodeActionProvider>,
4959 window: &mut Window,
4960 cx: &mut Context<Self>,
4961 ) {
4962 if self
4963 .code_action_providers
4964 .iter()
4965 .any(|existing_provider| existing_provider.id() == provider.id())
4966 {
4967 return;
4968 }
4969
4970 self.code_action_providers.push(provider);
4971 self.refresh_code_actions(window, cx);
4972 }
4973
4974 pub fn remove_code_action_provider(
4975 &mut self,
4976 id: Arc<str>,
4977 window: &mut Window,
4978 cx: &mut Context<Self>,
4979 ) {
4980 self.code_action_providers
4981 .retain(|provider| provider.id() != id);
4982 self.refresh_code_actions(window, cx);
4983 }
4984
4985 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4986 let buffer = self.buffer.read(cx);
4987 let newest_selection = self.selections.newest_anchor().clone();
4988 if newest_selection.head().diff_base_anchor.is_some() {
4989 return None;
4990 }
4991 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4992 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4993 if start_buffer != end_buffer {
4994 return None;
4995 }
4996
4997 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
4998 cx.background_executor()
4999 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5000 .await;
5001
5002 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5003 let providers = this.code_action_providers.clone();
5004 let tasks = this
5005 .code_action_providers
5006 .iter()
5007 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5008 .collect::<Vec<_>>();
5009 (providers, tasks)
5010 })?;
5011
5012 let mut actions = Vec::new();
5013 for (provider, provider_actions) in
5014 providers.into_iter().zip(future::join_all(tasks).await)
5015 {
5016 if let Some(provider_actions) = provider_actions.log_err() {
5017 actions.extend(provider_actions.into_iter().map(|action| {
5018 AvailableCodeAction {
5019 excerpt_id: newest_selection.start.excerpt_id,
5020 action,
5021 provider: provider.clone(),
5022 }
5023 }));
5024 }
5025 }
5026
5027 this.update(cx, |this, cx| {
5028 this.available_code_actions = if actions.is_empty() {
5029 None
5030 } else {
5031 Some((
5032 Location {
5033 buffer: start_buffer,
5034 range: start..end,
5035 },
5036 actions.into(),
5037 ))
5038 };
5039 cx.notify();
5040 })
5041 }));
5042 None
5043 }
5044
5045 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5046 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5047 self.show_git_blame_inline = false;
5048
5049 self.show_git_blame_inline_delay_task =
5050 Some(cx.spawn_in(window, async move |this, cx| {
5051 cx.background_executor().timer(delay).await;
5052
5053 this.update(cx, |this, cx| {
5054 this.show_git_blame_inline = true;
5055 cx.notify();
5056 })
5057 .log_err();
5058 }));
5059 }
5060 }
5061
5062 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5063 if self.pending_rename.is_some() {
5064 return None;
5065 }
5066
5067 let provider = self.semantics_provider.clone()?;
5068 let buffer = self.buffer.read(cx);
5069 let newest_selection = self.selections.newest_anchor().clone();
5070 let cursor_position = newest_selection.head();
5071 let (cursor_buffer, cursor_buffer_position) =
5072 buffer.text_anchor_for_position(cursor_position, cx)?;
5073 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5074 if cursor_buffer != tail_buffer {
5075 return None;
5076 }
5077 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5078 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5079 cx.background_executor()
5080 .timer(Duration::from_millis(debounce))
5081 .await;
5082
5083 let highlights = if let Some(highlights) = cx
5084 .update(|cx| {
5085 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5086 })
5087 .ok()
5088 .flatten()
5089 {
5090 highlights.await.log_err()
5091 } else {
5092 None
5093 };
5094
5095 if let Some(highlights) = highlights {
5096 this.update(cx, |this, cx| {
5097 if this.pending_rename.is_some() {
5098 return;
5099 }
5100
5101 let buffer_id = cursor_position.buffer_id;
5102 let buffer = this.buffer.read(cx);
5103 if !buffer
5104 .text_anchor_for_position(cursor_position, cx)
5105 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5106 {
5107 return;
5108 }
5109
5110 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5111 let mut write_ranges = Vec::new();
5112 let mut read_ranges = Vec::new();
5113 for highlight in highlights {
5114 for (excerpt_id, excerpt_range) in
5115 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5116 {
5117 let start = highlight
5118 .range
5119 .start
5120 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5121 let end = highlight
5122 .range
5123 .end
5124 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5125 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5126 continue;
5127 }
5128
5129 let range = Anchor {
5130 buffer_id,
5131 excerpt_id,
5132 text_anchor: start,
5133 diff_base_anchor: None,
5134 }..Anchor {
5135 buffer_id,
5136 excerpt_id,
5137 text_anchor: end,
5138 diff_base_anchor: None,
5139 };
5140 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5141 write_ranges.push(range);
5142 } else {
5143 read_ranges.push(range);
5144 }
5145 }
5146 }
5147
5148 this.highlight_background::<DocumentHighlightRead>(
5149 &read_ranges,
5150 |theme| theme.editor_document_highlight_read_background,
5151 cx,
5152 );
5153 this.highlight_background::<DocumentHighlightWrite>(
5154 &write_ranges,
5155 |theme| theme.editor_document_highlight_write_background,
5156 cx,
5157 );
5158 cx.notify();
5159 })
5160 .log_err();
5161 }
5162 }));
5163 None
5164 }
5165
5166 pub fn refresh_selected_text_highlights(
5167 &mut self,
5168 window: &mut Window,
5169 cx: &mut Context<Editor>,
5170 ) {
5171 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5172 return;
5173 }
5174 self.selection_highlight_task.take();
5175 if !EditorSettings::get_global(cx).selection_highlight {
5176 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5177 return;
5178 }
5179 if self.selections.count() != 1 || self.selections.line_mode {
5180 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5181 return;
5182 }
5183 let selection = self.selections.newest::<Point>(cx);
5184 if selection.is_empty() || selection.start.row != selection.end.row {
5185 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5186 return;
5187 }
5188 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5189 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5190 cx.background_executor()
5191 .timer(Duration::from_millis(debounce))
5192 .await;
5193 let Some(Some(matches_task)) = editor
5194 .update_in(cx, |editor, _, cx| {
5195 if editor.selections.count() != 1 || editor.selections.line_mode {
5196 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5197 return None;
5198 }
5199 let selection = editor.selections.newest::<Point>(cx);
5200 if selection.is_empty() || selection.start.row != selection.end.row {
5201 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5202 return None;
5203 }
5204 let buffer = editor.buffer().read(cx).snapshot(cx);
5205 let query = buffer.text_for_range(selection.range()).collect::<String>();
5206 if query.trim().is_empty() {
5207 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5208 return None;
5209 }
5210 Some(cx.background_spawn(async move {
5211 let mut ranges = Vec::new();
5212 let selection_anchors = selection.range().to_anchors(&buffer);
5213 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5214 for (search_buffer, search_range, excerpt_id) in
5215 buffer.range_to_buffer_ranges(range)
5216 {
5217 ranges.extend(
5218 project::search::SearchQuery::text(
5219 query.clone(),
5220 false,
5221 false,
5222 false,
5223 Default::default(),
5224 Default::default(),
5225 None,
5226 )
5227 .unwrap()
5228 .search(search_buffer, Some(search_range.clone()))
5229 .await
5230 .into_iter()
5231 .filter_map(
5232 |match_range| {
5233 let start = search_buffer.anchor_after(
5234 search_range.start + match_range.start,
5235 );
5236 let end = search_buffer.anchor_before(
5237 search_range.start + match_range.end,
5238 );
5239 let range = Anchor::range_in_buffer(
5240 excerpt_id,
5241 search_buffer.remote_id(),
5242 start..end,
5243 );
5244 (range != selection_anchors).then_some(range)
5245 },
5246 ),
5247 );
5248 }
5249 }
5250 ranges
5251 }))
5252 })
5253 .log_err()
5254 else {
5255 return;
5256 };
5257 let matches = matches_task.await;
5258 editor
5259 .update_in(cx, |editor, _, cx| {
5260 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5261 if !matches.is_empty() {
5262 editor.highlight_background::<SelectedTextHighlight>(
5263 &matches,
5264 |theme| theme.editor_document_highlight_bracket_background,
5265 cx,
5266 )
5267 }
5268 })
5269 .log_err();
5270 }));
5271 }
5272
5273 pub fn refresh_inline_completion(
5274 &mut self,
5275 debounce: bool,
5276 user_requested: bool,
5277 window: &mut Window,
5278 cx: &mut Context<Self>,
5279 ) -> Option<()> {
5280 let provider = self.edit_prediction_provider()?;
5281 let cursor = self.selections.newest_anchor().head();
5282 let (buffer, cursor_buffer_position) =
5283 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5284
5285 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5286 self.discard_inline_completion(false, cx);
5287 return None;
5288 }
5289
5290 if !user_requested
5291 && (!self.should_show_edit_predictions()
5292 || !self.is_focused(window)
5293 || buffer.read(cx).is_empty())
5294 {
5295 self.discard_inline_completion(false, cx);
5296 return None;
5297 }
5298
5299 self.update_visible_inline_completion(window, cx);
5300 provider.refresh(
5301 self.project.clone(),
5302 buffer,
5303 cursor_buffer_position,
5304 debounce,
5305 cx,
5306 );
5307 Some(())
5308 }
5309
5310 fn show_edit_predictions_in_menu(&self) -> bool {
5311 match self.edit_prediction_settings {
5312 EditPredictionSettings::Disabled => false,
5313 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5314 }
5315 }
5316
5317 pub fn edit_predictions_enabled(&self) -> bool {
5318 match self.edit_prediction_settings {
5319 EditPredictionSettings::Disabled => false,
5320 EditPredictionSettings::Enabled { .. } => true,
5321 }
5322 }
5323
5324 fn edit_prediction_requires_modifier(&self) -> bool {
5325 match self.edit_prediction_settings {
5326 EditPredictionSettings::Disabled => false,
5327 EditPredictionSettings::Enabled {
5328 preview_requires_modifier,
5329 ..
5330 } => preview_requires_modifier,
5331 }
5332 }
5333
5334 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5335 if self.edit_prediction_provider.is_none() {
5336 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5337 } else {
5338 let selection = self.selections.newest_anchor();
5339 let cursor = selection.head();
5340
5341 if let Some((buffer, cursor_buffer_position)) =
5342 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5343 {
5344 self.edit_prediction_settings =
5345 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5346 }
5347 }
5348 }
5349
5350 fn edit_prediction_settings_at_position(
5351 &self,
5352 buffer: &Entity<Buffer>,
5353 buffer_position: language::Anchor,
5354 cx: &App,
5355 ) -> EditPredictionSettings {
5356 if self.mode != EditorMode::Full
5357 || !self.show_inline_completions_override.unwrap_or(true)
5358 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5359 {
5360 return EditPredictionSettings::Disabled;
5361 }
5362
5363 let buffer = buffer.read(cx);
5364
5365 let file = buffer.file();
5366
5367 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5368 return EditPredictionSettings::Disabled;
5369 };
5370
5371 let by_provider = matches!(
5372 self.menu_inline_completions_policy,
5373 MenuInlineCompletionsPolicy::ByProvider
5374 );
5375
5376 let show_in_menu = by_provider
5377 && self
5378 .edit_prediction_provider
5379 .as_ref()
5380 .map_or(false, |provider| {
5381 provider.provider.show_completions_in_menu()
5382 });
5383
5384 let preview_requires_modifier =
5385 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5386
5387 EditPredictionSettings::Enabled {
5388 show_in_menu,
5389 preview_requires_modifier,
5390 }
5391 }
5392
5393 fn should_show_edit_predictions(&self) -> bool {
5394 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5395 }
5396
5397 pub fn edit_prediction_preview_is_active(&self) -> bool {
5398 matches!(
5399 self.edit_prediction_preview,
5400 EditPredictionPreview::Active { .. }
5401 )
5402 }
5403
5404 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5405 let cursor = self.selections.newest_anchor().head();
5406 if let Some((buffer, cursor_position)) =
5407 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5408 {
5409 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5410 } else {
5411 false
5412 }
5413 }
5414
5415 fn edit_predictions_enabled_in_buffer(
5416 &self,
5417 buffer: &Entity<Buffer>,
5418 buffer_position: language::Anchor,
5419 cx: &App,
5420 ) -> bool {
5421 maybe!({
5422 if self.read_only(cx) {
5423 return Some(false);
5424 }
5425 let provider = self.edit_prediction_provider()?;
5426 if !provider.is_enabled(&buffer, buffer_position, cx) {
5427 return Some(false);
5428 }
5429 let buffer = buffer.read(cx);
5430 let Some(file) = buffer.file() else {
5431 return Some(true);
5432 };
5433 let settings = all_language_settings(Some(file), cx);
5434 Some(settings.edit_predictions_enabled_for_file(file, cx))
5435 })
5436 .unwrap_or(false)
5437 }
5438
5439 fn cycle_inline_completion(
5440 &mut self,
5441 direction: Direction,
5442 window: &mut Window,
5443 cx: &mut Context<Self>,
5444 ) -> Option<()> {
5445 let provider = self.edit_prediction_provider()?;
5446 let cursor = self.selections.newest_anchor().head();
5447 let (buffer, cursor_buffer_position) =
5448 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5449 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5450 return None;
5451 }
5452
5453 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5454 self.update_visible_inline_completion(window, cx);
5455
5456 Some(())
5457 }
5458
5459 pub fn show_inline_completion(
5460 &mut self,
5461 _: &ShowEditPrediction,
5462 window: &mut Window,
5463 cx: &mut Context<Self>,
5464 ) {
5465 if !self.has_active_inline_completion() {
5466 self.refresh_inline_completion(false, true, window, cx);
5467 return;
5468 }
5469
5470 self.update_visible_inline_completion(window, cx);
5471 }
5472
5473 pub fn display_cursor_names(
5474 &mut self,
5475 _: &DisplayCursorNames,
5476 window: &mut Window,
5477 cx: &mut Context<Self>,
5478 ) {
5479 self.show_cursor_names(window, cx);
5480 }
5481
5482 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5483 self.show_cursor_names = true;
5484 cx.notify();
5485 cx.spawn_in(window, async move |this, cx| {
5486 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5487 this.update(cx, |this, cx| {
5488 this.show_cursor_names = false;
5489 cx.notify()
5490 })
5491 .ok()
5492 })
5493 .detach();
5494 }
5495
5496 pub fn next_edit_prediction(
5497 &mut self,
5498 _: &NextEditPrediction,
5499 window: &mut Window,
5500 cx: &mut Context<Self>,
5501 ) {
5502 if self.has_active_inline_completion() {
5503 self.cycle_inline_completion(Direction::Next, window, cx);
5504 } else {
5505 let is_copilot_disabled = self
5506 .refresh_inline_completion(false, true, window, cx)
5507 .is_none();
5508 if is_copilot_disabled {
5509 cx.propagate();
5510 }
5511 }
5512 }
5513
5514 pub fn previous_edit_prediction(
5515 &mut self,
5516 _: &PreviousEditPrediction,
5517 window: &mut Window,
5518 cx: &mut Context<Self>,
5519 ) {
5520 if self.has_active_inline_completion() {
5521 self.cycle_inline_completion(Direction::Prev, window, cx);
5522 } else {
5523 let is_copilot_disabled = self
5524 .refresh_inline_completion(false, true, window, cx)
5525 .is_none();
5526 if is_copilot_disabled {
5527 cx.propagate();
5528 }
5529 }
5530 }
5531
5532 pub fn accept_edit_prediction(
5533 &mut self,
5534 _: &AcceptEditPrediction,
5535 window: &mut Window,
5536 cx: &mut Context<Self>,
5537 ) {
5538 if self.show_edit_predictions_in_menu() {
5539 self.hide_context_menu(window, cx);
5540 }
5541
5542 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5543 return;
5544 };
5545
5546 self.report_inline_completion_event(
5547 active_inline_completion.completion_id.clone(),
5548 true,
5549 cx,
5550 );
5551
5552 match &active_inline_completion.completion {
5553 InlineCompletion::Move { target, .. } => {
5554 let target = *target;
5555
5556 if let Some(position_map) = &self.last_position_map {
5557 if position_map
5558 .visible_row_range
5559 .contains(&target.to_display_point(&position_map.snapshot).row())
5560 || !self.edit_prediction_requires_modifier()
5561 {
5562 self.unfold_ranges(&[target..target], true, false, cx);
5563 // Note that this is also done in vim's handler of the Tab action.
5564 self.change_selections(
5565 Some(Autoscroll::newest()),
5566 window,
5567 cx,
5568 |selections| {
5569 selections.select_anchor_ranges([target..target]);
5570 },
5571 );
5572 self.clear_row_highlights::<EditPredictionPreview>();
5573
5574 self.edit_prediction_preview
5575 .set_previous_scroll_position(None);
5576 } else {
5577 self.edit_prediction_preview
5578 .set_previous_scroll_position(Some(
5579 position_map.snapshot.scroll_anchor,
5580 ));
5581
5582 self.highlight_rows::<EditPredictionPreview>(
5583 target..target,
5584 cx.theme().colors().editor_highlighted_line_background,
5585 true,
5586 cx,
5587 );
5588 self.request_autoscroll(Autoscroll::fit(), cx);
5589 }
5590 }
5591 }
5592 InlineCompletion::Edit { edits, .. } => {
5593 if let Some(provider) = self.edit_prediction_provider() {
5594 provider.accept(cx);
5595 }
5596
5597 let snapshot = self.buffer.read(cx).snapshot(cx);
5598 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5599
5600 self.buffer.update(cx, |buffer, cx| {
5601 buffer.edit(edits.iter().cloned(), None, cx)
5602 });
5603
5604 self.change_selections(None, window, cx, |s| {
5605 s.select_anchor_ranges([last_edit_end..last_edit_end])
5606 });
5607
5608 self.update_visible_inline_completion(window, cx);
5609 if self.active_inline_completion.is_none() {
5610 self.refresh_inline_completion(true, true, window, cx);
5611 }
5612
5613 cx.notify();
5614 }
5615 }
5616
5617 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5618 }
5619
5620 pub fn accept_partial_inline_completion(
5621 &mut self,
5622 _: &AcceptPartialEditPrediction,
5623 window: &mut Window,
5624 cx: &mut Context<Self>,
5625 ) {
5626 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5627 return;
5628 };
5629 if self.selections.count() != 1 {
5630 return;
5631 }
5632
5633 self.report_inline_completion_event(
5634 active_inline_completion.completion_id.clone(),
5635 true,
5636 cx,
5637 );
5638
5639 match &active_inline_completion.completion {
5640 InlineCompletion::Move { target, .. } => {
5641 let target = *target;
5642 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5643 selections.select_anchor_ranges([target..target]);
5644 });
5645 }
5646 InlineCompletion::Edit { edits, .. } => {
5647 // Find an insertion that starts at the cursor position.
5648 let snapshot = self.buffer.read(cx).snapshot(cx);
5649 let cursor_offset = self.selections.newest::<usize>(cx).head();
5650 let insertion = edits.iter().find_map(|(range, text)| {
5651 let range = range.to_offset(&snapshot);
5652 if range.is_empty() && range.start == cursor_offset {
5653 Some(text)
5654 } else {
5655 None
5656 }
5657 });
5658
5659 if let Some(text) = insertion {
5660 let mut partial_completion = text
5661 .chars()
5662 .by_ref()
5663 .take_while(|c| c.is_alphabetic())
5664 .collect::<String>();
5665 if partial_completion.is_empty() {
5666 partial_completion = text
5667 .chars()
5668 .by_ref()
5669 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5670 .collect::<String>();
5671 }
5672
5673 cx.emit(EditorEvent::InputHandled {
5674 utf16_range_to_replace: None,
5675 text: partial_completion.clone().into(),
5676 });
5677
5678 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5679
5680 self.refresh_inline_completion(true, true, window, cx);
5681 cx.notify();
5682 } else {
5683 self.accept_edit_prediction(&Default::default(), window, cx);
5684 }
5685 }
5686 }
5687 }
5688
5689 fn discard_inline_completion(
5690 &mut self,
5691 should_report_inline_completion_event: bool,
5692 cx: &mut Context<Self>,
5693 ) -> bool {
5694 if should_report_inline_completion_event {
5695 let completion_id = self
5696 .active_inline_completion
5697 .as_ref()
5698 .and_then(|active_completion| active_completion.completion_id.clone());
5699
5700 self.report_inline_completion_event(completion_id, false, cx);
5701 }
5702
5703 if let Some(provider) = self.edit_prediction_provider() {
5704 provider.discard(cx);
5705 }
5706
5707 self.take_active_inline_completion(cx)
5708 }
5709
5710 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5711 let Some(provider) = self.edit_prediction_provider() else {
5712 return;
5713 };
5714
5715 let Some((_, buffer, _)) = self
5716 .buffer
5717 .read(cx)
5718 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5719 else {
5720 return;
5721 };
5722
5723 let extension = buffer
5724 .read(cx)
5725 .file()
5726 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5727
5728 let event_type = match accepted {
5729 true => "Edit Prediction Accepted",
5730 false => "Edit Prediction Discarded",
5731 };
5732 telemetry::event!(
5733 event_type,
5734 provider = provider.name(),
5735 prediction_id = id,
5736 suggestion_accepted = accepted,
5737 file_extension = extension,
5738 );
5739 }
5740
5741 pub fn has_active_inline_completion(&self) -> bool {
5742 self.active_inline_completion.is_some()
5743 }
5744
5745 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5746 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5747 return false;
5748 };
5749
5750 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5751 self.clear_highlights::<InlineCompletionHighlight>(cx);
5752 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5753 true
5754 }
5755
5756 /// Returns true when we're displaying the edit prediction popover below the cursor
5757 /// like we are not previewing and the LSP autocomplete menu is visible
5758 /// or we are in `when_holding_modifier` mode.
5759 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5760 if self.edit_prediction_preview_is_active()
5761 || !self.show_edit_predictions_in_menu()
5762 || !self.edit_predictions_enabled()
5763 {
5764 return false;
5765 }
5766
5767 if self.has_visible_completions_menu() {
5768 return true;
5769 }
5770
5771 has_completion && self.edit_prediction_requires_modifier()
5772 }
5773
5774 fn handle_modifiers_changed(
5775 &mut self,
5776 modifiers: Modifiers,
5777 position_map: &PositionMap,
5778 window: &mut Window,
5779 cx: &mut Context<Self>,
5780 ) {
5781 if self.show_edit_predictions_in_menu() {
5782 self.update_edit_prediction_preview(&modifiers, window, cx);
5783 }
5784
5785 self.update_selection_mode(&modifiers, position_map, window, cx);
5786
5787 let mouse_position = window.mouse_position();
5788 if !position_map.text_hitbox.is_hovered(window) {
5789 return;
5790 }
5791
5792 self.update_hovered_link(
5793 position_map.point_for_position(mouse_position),
5794 &position_map.snapshot,
5795 modifiers,
5796 window,
5797 cx,
5798 )
5799 }
5800
5801 fn update_selection_mode(
5802 &mut self,
5803 modifiers: &Modifiers,
5804 position_map: &PositionMap,
5805 window: &mut Window,
5806 cx: &mut Context<Self>,
5807 ) {
5808 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5809 return;
5810 }
5811
5812 let mouse_position = window.mouse_position();
5813 let point_for_position = position_map.point_for_position(mouse_position);
5814 let position = point_for_position.previous_valid;
5815
5816 self.select(
5817 SelectPhase::BeginColumnar {
5818 position,
5819 reset: false,
5820 goal_column: point_for_position.exact_unclipped.column(),
5821 },
5822 window,
5823 cx,
5824 );
5825 }
5826
5827 fn update_edit_prediction_preview(
5828 &mut self,
5829 modifiers: &Modifiers,
5830 window: &mut Window,
5831 cx: &mut Context<Self>,
5832 ) {
5833 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5834 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5835 return;
5836 };
5837
5838 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5839 if matches!(
5840 self.edit_prediction_preview,
5841 EditPredictionPreview::Inactive { .. }
5842 ) {
5843 self.edit_prediction_preview = EditPredictionPreview::Active {
5844 previous_scroll_position: None,
5845 since: Instant::now(),
5846 };
5847
5848 self.update_visible_inline_completion(window, cx);
5849 cx.notify();
5850 }
5851 } else if let EditPredictionPreview::Active {
5852 previous_scroll_position,
5853 since,
5854 } = self.edit_prediction_preview
5855 {
5856 if let (Some(previous_scroll_position), Some(position_map)) =
5857 (previous_scroll_position, self.last_position_map.as_ref())
5858 {
5859 self.set_scroll_position(
5860 previous_scroll_position
5861 .scroll_position(&position_map.snapshot.display_snapshot),
5862 window,
5863 cx,
5864 );
5865 }
5866
5867 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5868 released_too_fast: since.elapsed() < Duration::from_millis(200),
5869 };
5870 self.clear_row_highlights::<EditPredictionPreview>();
5871 self.update_visible_inline_completion(window, cx);
5872 cx.notify();
5873 }
5874 }
5875
5876 fn update_visible_inline_completion(
5877 &mut self,
5878 _window: &mut Window,
5879 cx: &mut Context<Self>,
5880 ) -> Option<()> {
5881 let selection = self.selections.newest_anchor();
5882 let cursor = selection.head();
5883 let multibuffer = self.buffer.read(cx).snapshot(cx);
5884 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5885 let excerpt_id = cursor.excerpt_id;
5886
5887 let show_in_menu = self.show_edit_predictions_in_menu();
5888 let completions_menu_has_precedence = !show_in_menu
5889 && (self.context_menu.borrow().is_some()
5890 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5891
5892 if completions_menu_has_precedence
5893 || !offset_selection.is_empty()
5894 || self
5895 .active_inline_completion
5896 .as_ref()
5897 .map_or(false, |completion| {
5898 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5899 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5900 !invalidation_range.contains(&offset_selection.head())
5901 })
5902 {
5903 self.discard_inline_completion(false, cx);
5904 return None;
5905 }
5906
5907 self.take_active_inline_completion(cx);
5908 let Some(provider) = self.edit_prediction_provider() else {
5909 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5910 return None;
5911 };
5912
5913 let (buffer, cursor_buffer_position) =
5914 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5915
5916 self.edit_prediction_settings =
5917 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5918
5919 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5920
5921 if self.edit_prediction_indent_conflict {
5922 let cursor_point = cursor.to_point(&multibuffer);
5923
5924 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5925
5926 if let Some((_, indent)) = indents.iter().next() {
5927 if indent.len == cursor_point.column {
5928 self.edit_prediction_indent_conflict = false;
5929 }
5930 }
5931 }
5932
5933 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5934 let edits = inline_completion
5935 .edits
5936 .into_iter()
5937 .flat_map(|(range, new_text)| {
5938 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5939 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5940 Some((start..end, new_text))
5941 })
5942 .collect::<Vec<_>>();
5943 if edits.is_empty() {
5944 return None;
5945 }
5946
5947 let first_edit_start = edits.first().unwrap().0.start;
5948 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5949 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5950
5951 let last_edit_end = edits.last().unwrap().0.end;
5952 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5953 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5954
5955 let cursor_row = cursor.to_point(&multibuffer).row;
5956
5957 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5958
5959 let mut inlay_ids = Vec::new();
5960 let invalidation_row_range;
5961 let move_invalidation_row_range = if cursor_row < edit_start_row {
5962 Some(cursor_row..edit_end_row)
5963 } else if cursor_row > edit_end_row {
5964 Some(edit_start_row..cursor_row)
5965 } else {
5966 None
5967 };
5968 let is_move =
5969 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5970 let completion = if is_move {
5971 invalidation_row_range =
5972 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5973 let target = first_edit_start;
5974 InlineCompletion::Move { target, snapshot }
5975 } else {
5976 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5977 && !self.inline_completions_hidden_for_vim_mode;
5978
5979 if show_completions_in_buffer {
5980 if edits
5981 .iter()
5982 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5983 {
5984 let mut inlays = Vec::new();
5985 for (range, new_text) in &edits {
5986 let inlay = Inlay::inline_completion(
5987 post_inc(&mut self.next_inlay_id),
5988 range.start,
5989 new_text.as_str(),
5990 );
5991 inlay_ids.push(inlay.id);
5992 inlays.push(inlay);
5993 }
5994
5995 self.splice_inlays(&[], inlays, cx);
5996 } else {
5997 let background_color = cx.theme().status().deleted_background;
5998 self.highlight_text::<InlineCompletionHighlight>(
5999 edits.iter().map(|(range, _)| range.clone()).collect(),
6000 HighlightStyle {
6001 background_color: Some(background_color),
6002 ..Default::default()
6003 },
6004 cx,
6005 );
6006 }
6007 }
6008
6009 invalidation_row_range = edit_start_row..edit_end_row;
6010
6011 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6012 if provider.show_tab_accept_marker() {
6013 EditDisplayMode::TabAccept
6014 } else {
6015 EditDisplayMode::Inline
6016 }
6017 } else {
6018 EditDisplayMode::DiffPopover
6019 };
6020
6021 InlineCompletion::Edit {
6022 edits,
6023 edit_preview: inline_completion.edit_preview,
6024 display_mode,
6025 snapshot,
6026 }
6027 };
6028
6029 let invalidation_range = multibuffer
6030 .anchor_before(Point::new(invalidation_row_range.start, 0))
6031 ..multibuffer.anchor_after(Point::new(
6032 invalidation_row_range.end,
6033 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6034 ));
6035
6036 self.stale_inline_completion_in_menu = None;
6037 self.active_inline_completion = Some(InlineCompletionState {
6038 inlay_ids,
6039 completion,
6040 completion_id: inline_completion.id,
6041 invalidation_range,
6042 });
6043
6044 cx.notify();
6045
6046 Some(())
6047 }
6048
6049 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6050 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6051 }
6052
6053 fn render_code_actions_indicator(
6054 &self,
6055 _style: &EditorStyle,
6056 row: DisplayRow,
6057 is_active: bool,
6058 breakpoint: Option<&(Anchor, Breakpoint)>,
6059 cx: &mut Context<Self>,
6060 ) -> Option<IconButton> {
6061 let color = Color::Muted;
6062 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6063
6064 if self.available_code_actions.is_some() {
6065 Some(
6066 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6067 .shape(ui::IconButtonShape::Square)
6068 .icon_size(IconSize::XSmall)
6069 .icon_color(color)
6070 .toggle_state(is_active)
6071 .tooltip({
6072 let focus_handle = self.focus_handle.clone();
6073 move |window, cx| {
6074 Tooltip::for_action_in(
6075 "Toggle Code Actions",
6076 &ToggleCodeActions {
6077 deployed_from_indicator: None,
6078 },
6079 &focus_handle,
6080 window,
6081 cx,
6082 )
6083 }
6084 })
6085 .on_click(cx.listener(move |editor, _e, window, cx| {
6086 window.focus(&editor.focus_handle(cx));
6087 editor.toggle_code_actions(
6088 &ToggleCodeActions {
6089 deployed_from_indicator: Some(row),
6090 },
6091 window,
6092 cx,
6093 );
6094 }))
6095 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6096 editor.set_breakpoint_context_menu(
6097 row,
6098 position,
6099 event.down.position,
6100 window,
6101 cx,
6102 );
6103 })),
6104 )
6105 } else {
6106 None
6107 }
6108 }
6109
6110 fn clear_tasks(&mut self) {
6111 self.tasks.clear()
6112 }
6113
6114 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6115 if self.tasks.insert(key, value).is_some() {
6116 // This case should hopefully be rare, but just in case...
6117 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
6118 }
6119 }
6120
6121 /// Get all display points of breakpoints that will be rendered within editor
6122 ///
6123 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6124 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6125 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6126 fn active_breakpoints(
6127 &mut self,
6128 range: Range<DisplayRow>,
6129 window: &mut Window,
6130 cx: &mut Context<Self>,
6131 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6132 let mut breakpoint_display_points = HashMap::default();
6133
6134 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6135 return breakpoint_display_points;
6136 };
6137
6138 let snapshot = self.snapshot(window, cx);
6139
6140 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6141 let Some(project) = self.project.as_ref() else {
6142 return breakpoint_display_points;
6143 };
6144
6145 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6146 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6147
6148 for (buffer_snapshot, range, excerpt_id) in
6149 multi_buffer_snapshot.range_to_buffer_ranges(range)
6150 {
6151 let Some(buffer) = project.read_with(cx, |this, cx| {
6152 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6153 }) else {
6154 continue;
6155 };
6156 let breakpoints = breakpoint_store.read(cx).breakpoints(
6157 &buffer,
6158 Some(
6159 buffer_snapshot.anchor_before(range.start)
6160 ..buffer_snapshot.anchor_after(range.end),
6161 ),
6162 buffer_snapshot,
6163 cx,
6164 );
6165 for (anchor, breakpoint) in breakpoints {
6166 let multi_buffer_anchor =
6167 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6168 let position = multi_buffer_anchor
6169 .to_point(&multi_buffer_snapshot)
6170 .to_display_point(&snapshot);
6171
6172 breakpoint_display_points
6173 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6174 }
6175 }
6176
6177 breakpoint_display_points
6178 }
6179
6180 fn breakpoint_context_menu(
6181 &self,
6182 anchor: Anchor,
6183 window: &mut Window,
6184 cx: &mut Context<Self>,
6185 ) -> Entity<ui::ContextMenu> {
6186 let weak_editor = cx.weak_entity();
6187 let focus_handle = self.focus_handle(cx);
6188
6189 let row = self
6190 .buffer
6191 .read(cx)
6192 .snapshot(cx)
6193 .summary_for_anchor::<Point>(&anchor)
6194 .row;
6195
6196 let breakpoint = self
6197 .breakpoint_at_row(row, window, cx)
6198 .map(|(_, bp)| Arc::from(bp));
6199
6200 let log_breakpoint_msg = if breakpoint
6201 .as_ref()
6202 .is_some_and(|bp| bp.kind.log_message().is_some())
6203 {
6204 "Edit Log Breakpoint"
6205 } else {
6206 "Set Log Breakpoint"
6207 };
6208
6209 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6210 "Unset Breakpoint"
6211 } else {
6212 "Set Breakpoint"
6213 };
6214
6215 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.state {
6216 BreakpointState::Enabled => Some("Disable"),
6217 BreakpointState::Disabled => Some("Enable"),
6218 });
6219
6220 let breakpoint = breakpoint.unwrap_or_else(|| {
6221 Arc::new(Breakpoint {
6222 state: BreakpointState::Enabled,
6223 kind: BreakpointKind::Standard,
6224 })
6225 });
6226
6227 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6228 menu.on_blur_subscription(Subscription::new(|| {}))
6229 .context(focus_handle)
6230 .when_some(toggle_state_msg, |this, msg| {
6231 this.entry(msg, None, {
6232 let weak_editor = weak_editor.clone();
6233 let breakpoint = breakpoint.clone();
6234 move |_window, cx| {
6235 weak_editor
6236 .update(cx, |this, cx| {
6237 this.edit_breakpoint_at_anchor(
6238 anchor,
6239 breakpoint.as_ref().clone(),
6240 BreakpointEditAction::InvertState,
6241 cx,
6242 );
6243 })
6244 .log_err();
6245 }
6246 })
6247 })
6248 .entry(set_breakpoint_msg, None, {
6249 let weak_editor = weak_editor.clone();
6250 let breakpoint = breakpoint.clone();
6251 move |_window, cx| {
6252 weak_editor
6253 .update(cx, |this, cx| {
6254 this.edit_breakpoint_at_anchor(
6255 anchor,
6256 breakpoint.as_ref().clone(),
6257 BreakpointEditAction::Toggle,
6258 cx,
6259 );
6260 })
6261 .log_err();
6262 }
6263 })
6264 .entry(log_breakpoint_msg, None, move |window, cx| {
6265 weak_editor
6266 .update(cx, |this, cx| {
6267 this.add_edit_breakpoint_block(anchor, breakpoint.as_ref(), window, cx);
6268 })
6269 .log_err();
6270 })
6271 })
6272 }
6273
6274 fn render_breakpoint(
6275 &self,
6276 position: Anchor,
6277 row: DisplayRow,
6278 breakpoint: &Breakpoint,
6279 cx: &mut Context<Self>,
6280 ) -> IconButton {
6281 let (color, icon) = {
6282 let icon = match (&breakpoint.kind, breakpoint.is_disabled()) {
6283 (BreakpointKind::Standard, false) => ui::IconName::DebugBreakpoint,
6284 (BreakpointKind::Log(_), false) => ui::IconName::DebugLogBreakpoint,
6285 (BreakpointKind::Standard, true) => ui::IconName::DebugDisabledBreakpoint,
6286 (BreakpointKind::Log(_), true) => ui::IconName::DebugDisabledLogBreakpoint,
6287 };
6288
6289 let color = if self
6290 .gutter_breakpoint_indicator
6291 .is_some_and(|point| point.row() == row)
6292 {
6293 Color::Hint
6294 } else {
6295 Color::Debugger
6296 };
6297
6298 (color, icon)
6299 };
6300
6301 let breakpoint = Arc::from(breakpoint.clone());
6302
6303 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6304 .icon_size(IconSize::XSmall)
6305 .size(ui::ButtonSize::None)
6306 .icon_color(color)
6307 .style(ButtonStyle::Transparent)
6308 .on_click(cx.listener({
6309 let breakpoint = breakpoint.clone();
6310
6311 move |editor, event: &ClickEvent, window, cx| {
6312 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6313 BreakpointEditAction::InvertState
6314 } else {
6315 BreakpointEditAction::Toggle
6316 };
6317
6318 window.focus(&editor.focus_handle(cx));
6319 editor.edit_breakpoint_at_anchor(
6320 position,
6321 breakpoint.as_ref().clone(),
6322 edit_action,
6323 cx,
6324 );
6325 }
6326 }))
6327 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6328 editor.set_breakpoint_context_menu(
6329 row,
6330 Some(position),
6331 event.down.position,
6332 window,
6333 cx,
6334 );
6335 }))
6336 }
6337
6338 fn build_tasks_context(
6339 project: &Entity<Project>,
6340 buffer: &Entity<Buffer>,
6341 buffer_row: u32,
6342 tasks: &Arc<RunnableTasks>,
6343 cx: &mut Context<Self>,
6344 ) -> Task<Option<task::TaskContext>> {
6345 let position = Point::new(buffer_row, tasks.column);
6346 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6347 let location = Location {
6348 buffer: buffer.clone(),
6349 range: range_start..range_start,
6350 };
6351 // Fill in the environmental variables from the tree-sitter captures
6352 let mut captured_task_variables = TaskVariables::default();
6353 for (capture_name, value) in tasks.extra_variables.clone() {
6354 captured_task_variables.insert(
6355 task::VariableName::Custom(capture_name.into()),
6356 value.clone(),
6357 );
6358 }
6359 project.update(cx, |project, cx| {
6360 project.task_store().update(cx, |task_store, cx| {
6361 task_store.task_context_for_location(captured_task_variables, location, cx)
6362 })
6363 })
6364 }
6365
6366 pub fn spawn_nearest_task(
6367 &mut self,
6368 action: &SpawnNearestTask,
6369 window: &mut Window,
6370 cx: &mut Context<Self>,
6371 ) {
6372 let Some((workspace, _)) = self.workspace.clone() else {
6373 return;
6374 };
6375 let Some(project) = self.project.clone() else {
6376 return;
6377 };
6378
6379 // Try to find a closest, enclosing node using tree-sitter that has a
6380 // task
6381 let Some((buffer, buffer_row, tasks)) = self
6382 .find_enclosing_node_task(cx)
6383 // Or find the task that's closest in row-distance.
6384 .or_else(|| self.find_closest_task(cx))
6385 else {
6386 return;
6387 };
6388
6389 let reveal_strategy = action.reveal;
6390 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6391 cx.spawn_in(window, async move |_, cx| {
6392 let context = task_context.await?;
6393 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6394
6395 let resolved = resolved_task.resolved.as_mut()?;
6396 resolved.reveal = reveal_strategy;
6397
6398 workspace
6399 .update(cx, |workspace, cx| {
6400 workspace::tasks::schedule_resolved_task(
6401 workspace,
6402 task_source_kind,
6403 resolved_task,
6404 false,
6405 cx,
6406 );
6407 })
6408 .ok()
6409 })
6410 .detach();
6411 }
6412
6413 fn find_closest_task(
6414 &mut self,
6415 cx: &mut Context<Self>,
6416 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6417 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6418
6419 let ((buffer_id, row), tasks) = self
6420 .tasks
6421 .iter()
6422 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6423
6424 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6425 let tasks = Arc::new(tasks.to_owned());
6426 Some((buffer, *row, tasks))
6427 }
6428
6429 fn find_enclosing_node_task(
6430 &mut self,
6431 cx: &mut Context<Self>,
6432 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6433 let snapshot = self.buffer.read(cx).snapshot(cx);
6434 let offset = self.selections.newest::<usize>(cx).head();
6435 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6436 let buffer_id = excerpt.buffer().remote_id();
6437
6438 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6439 let mut cursor = layer.node().walk();
6440
6441 while cursor.goto_first_child_for_byte(offset).is_some() {
6442 if cursor.node().end_byte() == offset {
6443 cursor.goto_next_sibling();
6444 }
6445 }
6446
6447 // Ascend to the smallest ancestor that contains the range and has a task.
6448 loop {
6449 let node = cursor.node();
6450 let node_range = node.byte_range();
6451 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6452
6453 // Check if this node contains our offset
6454 if node_range.start <= offset && node_range.end >= offset {
6455 // If it contains offset, check for task
6456 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6457 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6458 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6459 }
6460 }
6461
6462 if !cursor.goto_parent() {
6463 break;
6464 }
6465 }
6466 None
6467 }
6468
6469 fn render_run_indicator(
6470 &self,
6471 _style: &EditorStyle,
6472 is_active: bool,
6473 row: DisplayRow,
6474 breakpoint: Option<(Anchor, Breakpoint)>,
6475 cx: &mut Context<Self>,
6476 ) -> IconButton {
6477 let color = Color::Muted;
6478 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6479
6480 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6481 .shape(ui::IconButtonShape::Square)
6482 .icon_size(IconSize::XSmall)
6483 .icon_color(color)
6484 .toggle_state(is_active)
6485 .on_click(cx.listener(move |editor, _e, window, cx| {
6486 window.focus(&editor.focus_handle(cx));
6487 editor.toggle_code_actions(
6488 &ToggleCodeActions {
6489 deployed_from_indicator: Some(row),
6490 },
6491 window,
6492 cx,
6493 );
6494 }))
6495 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6496 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6497 }))
6498 }
6499
6500 pub fn context_menu_visible(&self) -> bool {
6501 !self.edit_prediction_preview_is_active()
6502 && self
6503 .context_menu
6504 .borrow()
6505 .as_ref()
6506 .map_or(false, |menu| menu.visible())
6507 }
6508
6509 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6510 self.context_menu
6511 .borrow()
6512 .as_ref()
6513 .map(|menu| menu.origin())
6514 }
6515
6516 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6517 self.context_menu_options = Some(options);
6518 }
6519
6520 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6521 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6522
6523 fn render_edit_prediction_popover(
6524 &mut self,
6525 text_bounds: &Bounds<Pixels>,
6526 content_origin: gpui::Point<Pixels>,
6527 editor_snapshot: &EditorSnapshot,
6528 visible_row_range: Range<DisplayRow>,
6529 scroll_top: f32,
6530 scroll_bottom: f32,
6531 line_layouts: &[LineWithInvisibles],
6532 line_height: Pixels,
6533 scroll_pixel_position: gpui::Point<Pixels>,
6534 newest_selection_head: Option<DisplayPoint>,
6535 editor_width: Pixels,
6536 style: &EditorStyle,
6537 window: &mut Window,
6538 cx: &mut App,
6539 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6540 let active_inline_completion = self.active_inline_completion.as_ref()?;
6541
6542 if self.edit_prediction_visible_in_cursor_popover(true) {
6543 return None;
6544 }
6545
6546 match &active_inline_completion.completion {
6547 InlineCompletion::Move { target, .. } => {
6548 let target_display_point = target.to_display_point(editor_snapshot);
6549
6550 if self.edit_prediction_requires_modifier() {
6551 if !self.edit_prediction_preview_is_active() {
6552 return None;
6553 }
6554
6555 self.render_edit_prediction_modifier_jump_popover(
6556 text_bounds,
6557 content_origin,
6558 visible_row_range,
6559 line_layouts,
6560 line_height,
6561 scroll_pixel_position,
6562 newest_selection_head,
6563 target_display_point,
6564 window,
6565 cx,
6566 )
6567 } else {
6568 self.render_edit_prediction_eager_jump_popover(
6569 text_bounds,
6570 content_origin,
6571 editor_snapshot,
6572 visible_row_range,
6573 scroll_top,
6574 scroll_bottom,
6575 line_height,
6576 scroll_pixel_position,
6577 target_display_point,
6578 editor_width,
6579 window,
6580 cx,
6581 )
6582 }
6583 }
6584 InlineCompletion::Edit {
6585 display_mode: EditDisplayMode::Inline,
6586 ..
6587 } => None,
6588 InlineCompletion::Edit {
6589 display_mode: EditDisplayMode::TabAccept,
6590 edits,
6591 ..
6592 } => {
6593 let range = &edits.first()?.0;
6594 let target_display_point = range.end.to_display_point(editor_snapshot);
6595
6596 self.render_edit_prediction_end_of_line_popover(
6597 "Accept",
6598 editor_snapshot,
6599 visible_row_range,
6600 target_display_point,
6601 line_height,
6602 scroll_pixel_position,
6603 content_origin,
6604 editor_width,
6605 window,
6606 cx,
6607 )
6608 }
6609 InlineCompletion::Edit {
6610 edits,
6611 edit_preview,
6612 display_mode: EditDisplayMode::DiffPopover,
6613 snapshot,
6614 } => self.render_edit_prediction_diff_popover(
6615 text_bounds,
6616 content_origin,
6617 editor_snapshot,
6618 visible_row_range,
6619 line_layouts,
6620 line_height,
6621 scroll_pixel_position,
6622 newest_selection_head,
6623 editor_width,
6624 style,
6625 edits,
6626 edit_preview,
6627 snapshot,
6628 window,
6629 cx,
6630 ),
6631 }
6632 }
6633
6634 fn render_edit_prediction_modifier_jump_popover(
6635 &mut self,
6636 text_bounds: &Bounds<Pixels>,
6637 content_origin: gpui::Point<Pixels>,
6638 visible_row_range: Range<DisplayRow>,
6639 line_layouts: &[LineWithInvisibles],
6640 line_height: Pixels,
6641 scroll_pixel_position: gpui::Point<Pixels>,
6642 newest_selection_head: Option<DisplayPoint>,
6643 target_display_point: DisplayPoint,
6644 window: &mut Window,
6645 cx: &mut App,
6646 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6647 let scrolled_content_origin =
6648 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6649
6650 const SCROLL_PADDING_Y: Pixels = px(12.);
6651
6652 if target_display_point.row() < visible_row_range.start {
6653 return self.render_edit_prediction_scroll_popover(
6654 |_| SCROLL_PADDING_Y,
6655 IconName::ArrowUp,
6656 visible_row_range,
6657 line_layouts,
6658 newest_selection_head,
6659 scrolled_content_origin,
6660 window,
6661 cx,
6662 );
6663 } else if target_display_point.row() >= visible_row_range.end {
6664 return self.render_edit_prediction_scroll_popover(
6665 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6666 IconName::ArrowDown,
6667 visible_row_range,
6668 line_layouts,
6669 newest_selection_head,
6670 scrolled_content_origin,
6671 window,
6672 cx,
6673 );
6674 }
6675
6676 const POLE_WIDTH: Pixels = px(2.);
6677
6678 let line_layout =
6679 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6680 let target_column = target_display_point.column() as usize;
6681
6682 let target_x = line_layout.x_for_index(target_column);
6683 let target_y =
6684 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6685
6686 let flag_on_right = target_x < text_bounds.size.width / 2.;
6687
6688 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6689 border_color.l += 0.001;
6690
6691 let mut element = v_flex()
6692 .items_end()
6693 .when(flag_on_right, |el| el.items_start())
6694 .child(if flag_on_right {
6695 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6696 .rounded_bl(px(0.))
6697 .rounded_tl(px(0.))
6698 .border_l_2()
6699 .border_color(border_color)
6700 } else {
6701 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6702 .rounded_br(px(0.))
6703 .rounded_tr(px(0.))
6704 .border_r_2()
6705 .border_color(border_color)
6706 })
6707 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6708 .into_any();
6709
6710 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6711
6712 let mut origin = scrolled_content_origin + point(target_x, target_y)
6713 - point(
6714 if flag_on_right {
6715 POLE_WIDTH
6716 } else {
6717 size.width - POLE_WIDTH
6718 },
6719 size.height - line_height,
6720 );
6721
6722 origin.x = origin.x.max(content_origin.x);
6723
6724 element.prepaint_at(origin, window, cx);
6725
6726 Some((element, origin))
6727 }
6728
6729 fn render_edit_prediction_scroll_popover(
6730 &mut self,
6731 to_y: impl Fn(Size<Pixels>) -> Pixels,
6732 scroll_icon: IconName,
6733 visible_row_range: Range<DisplayRow>,
6734 line_layouts: &[LineWithInvisibles],
6735 newest_selection_head: Option<DisplayPoint>,
6736 scrolled_content_origin: gpui::Point<Pixels>,
6737 window: &mut Window,
6738 cx: &mut App,
6739 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6740 let mut element = self
6741 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6742 .into_any();
6743
6744 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6745
6746 let cursor = newest_selection_head?;
6747 let cursor_row_layout =
6748 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6749 let cursor_column = cursor.column() as usize;
6750
6751 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6752
6753 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6754
6755 element.prepaint_at(origin, window, cx);
6756 Some((element, origin))
6757 }
6758
6759 fn render_edit_prediction_eager_jump_popover(
6760 &mut self,
6761 text_bounds: &Bounds<Pixels>,
6762 content_origin: gpui::Point<Pixels>,
6763 editor_snapshot: &EditorSnapshot,
6764 visible_row_range: Range<DisplayRow>,
6765 scroll_top: f32,
6766 scroll_bottom: f32,
6767 line_height: Pixels,
6768 scroll_pixel_position: gpui::Point<Pixels>,
6769 target_display_point: DisplayPoint,
6770 editor_width: Pixels,
6771 window: &mut Window,
6772 cx: &mut App,
6773 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6774 if target_display_point.row().as_f32() < scroll_top {
6775 let mut element = self
6776 .render_edit_prediction_line_popover(
6777 "Jump to Edit",
6778 Some(IconName::ArrowUp),
6779 window,
6780 cx,
6781 )?
6782 .into_any();
6783
6784 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6785 let offset = point(
6786 (text_bounds.size.width - size.width) / 2.,
6787 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6788 );
6789
6790 let origin = text_bounds.origin + offset;
6791 element.prepaint_at(origin, window, cx);
6792 Some((element, origin))
6793 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6794 let mut element = self
6795 .render_edit_prediction_line_popover(
6796 "Jump to Edit",
6797 Some(IconName::ArrowDown),
6798 window,
6799 cx,
6800 )?
6801 .into_any();
6802
6803 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6804 let offset = point(
6805 (text_bounds.size.width - size.width) / 2.,
6806 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6807 );
6808
6809 let origin = text_bounds.origin + offset;
6810 element.prepaint_at(origin, window, cx);
6811 Some((element, origin))
6812 } else {
6813 self.render_edit_prediction_end_of_line_popover(
6814 "Jump to Edit",
6815 editor_snapshot,
6816 visible_row_range,
6817 target_display_point,
6818 line_height,
6819 scroll_pixel_position,
6820 content_origin,
6821 editor_width,
6822 window,
6823 cx,
6824 )
6825 }
6826 }
6827
6828 fn render_edit_prediction_end_of_line_popover(
6829 self: &mut Editor,
6830 label: &'static str,
6831 editor_snapshot: &EditorSnapshot,
6832 visible_row_range: Range<DisplayRow>,
6833 target_display_point: DisplayPoint,
6834 line_height: Pixels,
6835 scroll_pixel_position: gpui::Point<Pixels>,
6836 content_origin: gpui::Point<Pixels>,
6837 editor_width: Pixels,
6838 window: &mut Window,
6839 cx: &mut App,
6840 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6841 let target_line_end = DisplayPoint::new(
6842 target_display_point.row(),
6843 editor_snapshot.line_len(target_display_point.row()),
6844 );
6845
6846 let mut element = self
6847 .render_edit_prediction_line_popover(label, None, window, cx)?
6848 .into_any();
6849
6850 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6851
6852 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6853
6854 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6855 let mut origin = start_point
6856 + line_origin
6857 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6858 origin.x = origin.x.max(content_origin.x);
6859
6860 let max_x = content_origin.x + editor_width - size.width;
6861
6862 if origin.x > max_x {
6863 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6864
6865 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6866 origin.y += offset;
6867 IconName::ArrowUp
6868 } else {
6869 origin.y -= offset;
6870 IconName::ArrowDown
6871 };
6872
6873 element = self
6874 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6875 .into_any();
6876
6877 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6878
6879 origin.x = content_origin.x + editor_width - size.width - px(2.);
6880 }
6881
6882 element.prepaint_at(origin, window, cx);
6883 Some((element, origin))
6884 }
6885
6886 fn render_edit_prediction_diff_popover(
6887 self: &Editor,
6888 text_bounds: &Bounds<Pixels>,
6889 content_origin: gpui::Point<Pixels>,
6890 editor_snapshot: &EditorSnapshot,
6891 visible_row_range: Range<DisplayRow>,
6892 line_layouts: &[LineWithInvisibles],
6893 line_height: Pixels,
6894 scroll_pixel_position: gpui::Point<Pixels>,
6895 newest_selection_head: Option<DisplayPoint>,
6896 editor_width: Pixels,
6897 style: &EditorStyle,
6898 edits: &Vec<(Range<Anchor>, String)>,
6899 edit_preview: &Option<language::EditPreview>,
6900 snapshot: &language::BufferSnapshot,
6901 window: &mut Window,
6902 cx: &mut App,
6903 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6904 let edit_start = edits
6905 .first()
6906 .unwrap()
6907 .0
6908 .start
6909 .to_display_point(editor_snapshot);
6910 let edit_end = edits
6911 .last()
6912 .unwrap()
6913 .0
6914 .end
6915 .to_display_point(editor_snapshot);
6916
6917 let is_visible = visible_row_range.contains(&edit_start.row())
6918 || visible_row_range.contains(&edit_end.row());
6919 if !is_visible {
6920 return None;
6921 }
6922
6923 let highlighted_edits =
6924 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6925
6926 let styled_text = highlighted_edits.to_styled_text(&style.text);
6927 let line_count = highlighted_edits.text.lines().count();
6928
6929 const BORDER_WIDTH: Pixels = px(1.);
6930
6931 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6932 let has_keybind = keybind.is_some();
6933
6934 let mut element = h_flex()
6935 .items_start()
6936 .child(
6937 h_flex()
6938 .bg(cx.theme().colors().editor_background)
6939 .border(BORDER_WIDTH)
6940 .shadow_sm()
6941 .border_color(cx.theme().colors().border)
6942 .rounded_l_lg()
6943 .when(line_count > 1, |el| el.rounded_br_lg())
6944 .pr_1()
6945 .child(styled_text),
6946 )
6947 .child(
6948 h_flex()
6949 .h(line_height + BORDER_WIDTH * 2.)
6950 .px_1p5()
6951 .gap_1()
6952 // Workaround: For some reason, there's a gap if we don't do this
6953 .ml(-BORDER_WIDTH)
6954 .shadow(smallvec![gpui::BoxShadow {
6955 color: gpui::black().opacity(0.05),
6956 offset: point(px(1.), px(1.)),
6957 blur_radius: px(2.),
6958 spread_radius: px(0.),
6959 }])
6960 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6961 .border(BORDER_WIDTH)
6962 .border_color(cx.theme().colors().border)
6963 .rounded_r_lg()
6964 .id("edit_prediction_diff_popover_keybind")
6965 .when(!has_keybind, |el| {
6966 let status_colors = cx.theme().status();
6967
6968 el.bg(status_colors.error_background)
6969 .border_color(status_colors.error.opacity(0.6))
6970 .child(Icon::new(IconName::Info).color(Color::Error))
6971 .cursor_default()
6972 .hoverable_tooltip(move |_window, cx| {
6973 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6974 })
6975 })
6976 .children(keybind),
6977 )
6978 .into_any();
6979
6980 let longest_row =
6981 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6982 let longest_line_width = if visible_row_range.contains(&longest_row) {
6983 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6984 } else {
6985 layout_line(
6986 longest_row,
6987 editor_snapshot,
6988 style,
6989 editor_width,
6990 |_| false,
6991 window,
6992 cx,
6993 )
6994 .width
6995 };
6996
6997 let viewport_bounds =
6998 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6999 right: -EditorElement::SCROLLBAR_WIDTH,
7000 ..Default::default()
7001 });
7002
7003 let x_after_longest =
7004 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7005 - scroll_pixel_position.x;
7006
7007 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7008
7009 // Fully visible if it can be displayed within the window (allow overlapping other
7010 // panes). However, this is only allowed if the popover starts within text_bounds.
7011 let can_position_to_the_right = x_after_longest < text_bounds.right()
7012 && x_after_longest + element_bounds.width < viewport_bounds.right();
7013
7014 let mut origin = if can_position_to_the_right {
7015 point(
7016 x_after_longest,
7017 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7018 - scroll_pixel_position.y,
7019 )
7020 } else {
7021 let cursor_row = newest_selection_head.map(|head| head.row());
7022 let above_edit = edit_start
7023 .row()
7024 .0
7025 .checked_sub(line_count as u32)
7026 .map(DisplayRow);
7027 let below_edit = Some(edit_end.row() + 1);
7028 let above_cursor =
7029 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7030 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7031
7032 // Place the edit popover adjacent to the edit if there is a location
7033 // available that is onscreen and does not obscure the cursor. Otherwise,
7034 // place it adjacent to the cursor.
7035 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7036 .into_iter()
7037 .flatten()
7038 .find(|&start_row| {
7039 let end_row = start_row + line_count as u32;
7040 visible_row_range.contains(&start_row)
7041 && visible_row_range.contains(&end_row)
7042 && cursor_row.map_or(true, |cursor_row| {
7043 !((start_row..end_row).contains(&cursor_row))
7044 })
7045 })?;
7046
7047 content_origin
7048 + point(
7049 -scroll_pixel_position.x,
7050 row_target.as_f32() * line_height - scroll_pixel_position.y,
7051 )
7052 };
7053
7054 origin.x -= BORDER_WIDTH;
7055
7056 window.defer_draw(element, origin, 1);
7057
7058 // Do not return an element, since it will already be drawn due to defer_draw.
7059 None
7060 }
7061
7062 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7063 px(30.)
7064 }
7065
7066 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7067 if self.read_only(cx) {
7068 cx.theme().players().read_only()
7069 } else {
7070 self.style.as_ref().unwrap().local_player
7071 }
7072 }
7073
7074 fn render_edit_prediction_accept_keybind(
7075 &self,
7076 window: &mut Window,
7077 cx: &App,
7078 ) -> Option<AnyElement> {
7079 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7080 let accept_keystroke = accept_binding.keystroke()?;
7081
7082 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7083
7084 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7085 Color::Accent
7086 } else {
7087 Color::Muted
7088 };
7089
7090 h_flex()
7091 .px_0p5()
7092 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7093 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7094 .text_size(TextSize::XSmall.rems(cx))
7095 .child(h_flex().children(ui::render_modifiers(
7096 &accept_keystroke.modifiers,
7097 PlatformStyle::platform(),
7098 Some(modifiers_color),
7099 Some(IconSize::XSmall.rems().into()),
7100 true,
7101 )))
7102 .when(is_platform_style_mac, |parent| {
7103 parent.child(accept_keystroke.key.clone())
7104 })
7105 .when(!is_platform_style_mac, |parent| {
7106 parent.child(
7107 Key::new(
7108 util::capitalize(&accept_keystroke.key),
7109 Some(Color::Default),
7110 )
7111 .size(Some(IconSize::XSmall.rems().into())),
7112 )
7113 })
7114 .into_any()
7115 .into()
7116 }
7117
7118 fn render_edit_prediction_line_popover(
7119 &self,
7120 label: impl Into<SharedString>,
7121 icon: Option<IconName>,
7122 window: &mut Window,
7123 cx: &App,
7124 ) -> Option<Stateful<Div>> {
7125 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7126
7127 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7128 let has_keybind = keybind.is_some();
7129
7130 let result = h_flex()
7131 .id("ep-line-popover")
7132 .py_0p5()
7133 .pl_1()
7134 .pr(padding_right)
7135 .gap_1()
7136 .rounded_md()
7137 .border_1()
7138 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7139 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7140 .shadow_sm()
7141 .when(!has_keybind, |el| {
7142 let status_colors = cx.theme().status();
7143
7144 el.bg(status_colors.error_background)
7145 .border_color(status_colors.error.opacity(0.6))
7146 .pl_2()
7147 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7148 .cursor_default()
7149 .hoverable_tooltip(move |_window, cx| {
7150 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7151 })
7152 })
7153 .children(keybind)
7154 .child(
7155 Label::new(label)
7156 .size(LabelSize::Small)
7157 .when(!has_keybind, |el| {
7158 el.color(cx.theme().status().error.into()).strikethrough()
7159 }),
7160 )
7161 .when(!has_keybind, |el| {
7162 el.child(
7163 h_flex().ml_1().child(
7164 Icon::new(IconName::Info)
7165 .size(IconSize::Small)
7166 .color(cx.theme().status().error.into()),
7167 ),
7168 )
7169 })
7170 .when_some(icon, |element, icon| {
7171 element.child(
7172 div()
7173 .mt(px(1.5))
7174 .child(Icon::new(icon).size(IconSize::Small)),
7175 )
7176 });
7177
7178 Some(result)
7179 }
7180
7181 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7182 let accent_color = cx.theme().colors().text_accent;
7183 let editor_bg_color = cx.theme().colors().editor_background;
7184 editor_bg_color.blend(accent_color.opacity(0.1))
7185 }
7186
7187 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7188 let accent_color = cx.theme().colors().text_accent;
7189 let editor_bg_color = cx.theme().colors().editor_background;
7190 editor_bg_color.blend(accent_color.opacity(0.6))
7191 }
7192
7193 fn render_edit_prediction_cursor_popover(
7194 &self,
7195 min_width: Pixels,
7196 max_width: Pixels,
7197 cursor_point: Point,
7198 style: &EditorStyle,
7199 accept_keystroke: Option<&gpui::Keystroke>,
7200 _window: &Window,
7201 cx: &mut Context<Editor>,
7202 ) -> Option<AnyElement> {
7203 let provider = self.edit_prediction_provider.as_ref()?;
7204
7205 if provider.provider.needs_terms_acceptance(cx) {
7206 return Some(
7207 h_flex()
7208 .min_w(min_width)
7209 .flex_1()
7210 .px_2()
7211 .py_1()
7212 .gap_3()
7213 .elevation_2(cx)
7214 .hover(|style| style.bg(cx.theme().colors().element_hover))
7215 .id("accept-terms")
7216 .cursor_pointer()
7217 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7218 .on_click(cx.listener(|this, _event, window, cx| {
7219 cx.stop_propagation();
7220 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7221 window.dispatch_action(
7222 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7223 cx,
7224 );
7225 }))
7226 .child(
7227 h_flex()
7228 .flex_1()
7229 .gap_2()
7230 .child(Icon::new(IconName::ZedPredict))
7231 .child(Label::new("Accept Terms of Service"))
7232 .child(div().w_full())
7233 .child(
7234 Icon::new(IconName::ArrowUpRight)
7235 .color(Color::Muted)
7236 .size(IconSize::Small),
7237 )
7238 .into_any_element(),
7239 )
7240 .into_any(),
7241 );
7242 }
7243
7244 let is_refreshing = provider.provider.is_refreshing(cx);
7245
7246 fn pending_completion_container() -> Div {
7247 h_flex()
7248 .h_full()
7249 .flex_1()
7250 .gap_2()
7251 .child(Icon::new(IconName::ZedPredict))
7252 }
7253
7254 let completion = match &self.active_inline_completion {
7255 Some(prediction) => {
7256 if !self.has_visible_completions_menu() {
7257 const RADIUS: Pixels = px(6.);
7258 const BORDER_WIDTH: Pixels = px(1.);
7259
7260 return Some(
7261 h_flex()
7262 .elevation_2(cx)
7263 .border(BORDER_WIDTH)
7264 .border_color(cx.theme().colors().border)
7265 .when(accept_keystroke.is_none(), |el| {
7266 el.border_color(cx.theme().status().error)
7267 })
7268 .rounded(RADIUS)
7269 .rounded_tl(px(0.))
7270 .overflow_hidden()
7271 .child(div().px_1p5().child(match &prediction.completion {
7272 InlineCompletion::Move { target, snapshot } => {
7273 use text::ToPoint as _;
7274 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7275 {
7276 Icon::new(IconName::ZedPredictDown)
7277 } else {
7278 Icon::new(IconName::ZedPredictUp)
7279 }
7280 }
7281 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7282 }))
7283 .child(
7284 h_flex()
7285 .gap_1()
7286 .py_1()
7287 .px_2()
7288 .rounded_r(RADIUS - BORDER_WIDTH)
7289 .border_l_1()
7290 .border_color(cx.theme().colors().border)
7291 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7292 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7293 el.child(
7294 Label::new("Hold")
7295 .size(LabelSize::Small)
7296 .when(accept_keystroke.is_none(), |el| {
7297 el.strikethrough()
7298 })
7299 .line_height_style(LineHeightStyle::UiLabel),
7300 )
7301 })
7302 .id("edit_prediction_cursor_popover_keybind")
7303 .when(accept_keystroke.is_none(), |el| {
7304 let status_colors = cx.theme().status();
7305
7306 el.bg(status_colors.error_background)
7307 .border_color(status_colors.error.opacity(0.6))
7308 .child(Icon::new(IconName::Info).color(Color::Error))
7309 .cursor_default()
7310 .hoverable_tooltip(move |_window, cx| {
7311 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7312 .into()
7313 })
7314 })
7315 .when_some(
7316 accept_keystroke.as_ref(),
7317 |el, accept_keystroke| {
7318 el.child(h_flex().children(ui::render_modifiers(
7319 &accept_keystroke.modifiers,
7320 PlatformStyle::platform(),
7321 Some(Color::Default),
7322 Some(IconSize::XSmall.rems().into()),
7323 false,
7324 )))
7325 },
7326 ),
7327 )
7328 .into_any(),
7329 );
7330 }
7331
7332 self.render_edit_prediction_cursor_popover_preview(
7333 prediction,
7334 cursor_point,
7335 style,
7336 cx,
7337 )?
7338 }
7339
7340 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7341 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7342 stale_completion,
7343 cursor_point,
7344 style,
7345 cx,
7346 )?,
7347
7348 None => {
7349 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7350 }
7351 },
7352
7353 None => pending_completion_container().child(Label::new("No Prediction")),
7354 };
7355
7356 let completion = if is_refreshing {
7357 completion
7358 .with_animation(
7359 "loading-completion",
7360 Animation::new(Duration::from_secs(2))
7361 .repeat()
7362 .with_easing(pulsating_between(0.4, 0.8)),
7363 |label, delta| label.opacity(delta),
7364 )
7365 .into_any_element()
7366 } else {
7367 completion.into_any_element()
7368 };
7369
7370 let has_completion = self.active_inline_completion.is_some();
7371
7372 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7373 Some(
7374 h_flex()
7375 .min_w(min_width)
7376 .max_w(max_width)
7377 .flex_1()
7378 .elevation_2(cx)
7379 .border_color(cx.theme().colors().border)
7380 .child(
7381 div()
7382 .flex_1()
7383 .py_1()
7384 .px_2()
7385 .overflow_hidden()
7386 .child(completion),
7387 )
7388 .when_some(accept_keystroke, |el, accept_keystroke| {
7389 if !accept_keystroke.modifiers.modified() {
7390 return el;
7391 }
7392
7393 el.child(
7394 h_flex()
7395 .h_full()
7396 .border_l_1()
7397 .rounded_r_lg()
7398 .border_color(cx.theme().colors().border)
7399 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7400 .gap_1()
7401 .py_1()
7402 .px_2()
7403 .child(
7404 h_flex()
7405 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7406 .when(is_platform_style_mac, |parent| parent.gap_1())
7407 .child(h_flex().children(ui::render_modifiers(
7408 &accept_keystroke.modifiers,
7409 PlatformStyle::platform(),
7410 Some(if !has_completion {
7411 Color::Muted
7412 } else {
7413 Color::Default
7414 }),
7415 None,
7416 false,
7417 ))),
7418 )
7419 .child(Label::new("Preview").into_any_element())
7420 .opacity(if has_completion { 1.0 } else { 0.4 }),
7421 )
7422 })
7423 .into_any(),
7424 )
7425 }
7426
7427 fn render_edit_prediction_cursor_popover_preview(
7428 &self,
7429 completion: &InlineCompletionState,
7430 cursor_point: Point,
7431 style: &EditorStyle,
7432 cx: &mut Context<Editor>,
7433 ) -> Option<Div> {
7434 use text::ToPoint as _;
7435
7436 fn render_relative_row_jump(
7437 prefix: impl Into<String>,
7438 current_row: u32,
7439 target_row: u32,
7440 ) -> Div {
7441 let (row_diff, arrow) = if target_row < current_row {
7442 (current_row - target_row, IconName::ArrowUp)
7443 } else {
7444 (target_row - current_row, IconName::ArrowDown)
7445 };
7446
7447 h_flex()
7448 .child(
7449 Label::new(format!("{}{}", prefix.into(), row_diff))
7450 .color(Color::Muted)
7451 .size(LabelSize::Small),
7452 )
7453 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7454 }
7455
7456 match &completion.completion {
7457 InlineCompletion::Move {
7458 target, snapshot, ..
7459 } => Some(
7460 h_flex()
7461 .px_2()
7462 .gap_2()
7463 .flex_1()
7464 .child(
7465 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7466 Icon::new(IconName::ZedPredictDown)
7467 } else {
7468 Icon::new(IconName::ZedPredictUp)
7469 },
7470 )
7471 .child(Label::new("Jump to Edit")),
7472 ),
7473
7474 InlineCompletion::Edit {
7475 edits,
7476 edit_preview,
7477 snapshot,
7478 display_mode: _,
7479 } => {
7480 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7481
7482 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7483 &snapshot,
7484 &edits,
7485 edit_preview.as_ref()?,
7486 true,
7487 cx,
7488 )
7489 .first_line_preview();
7490
7491 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7492 .with_default_highlights(&style.text, highlighted_edits.highlights);
7493
7494 let preview = h_flex()
7495 .gap_1()
7496 .min_w_16()
7497 .child(styled_text)
7498 .when(has_more_lines, |parent| parent.child("…"));
7499
7500 let left = if first_edit_row != cursor_point.row {
7501 render_relative_row_jump("", cursor_point.row, first_edit_row)
7502 .into_any_element()
7503 } else {
7504 Icon::new(IconName::ZedPredict).into_any_element()
7505 };
7506
7507 Some(
7508 h_flex()
7509 .h_full()
7510 .flex_1()
7511 .gap_2()
7512 .pr_1()
7513 .overflow_x_hidden()
7514 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7515 .child(left)
7516 .child(preview),
7517 )
7518 }
7519 }
7520 }
7521
7522 fn render_context_menu(
7523 &self,
7524 style: &EditorStyle,
7525 max_height_in_lines: u32,
7526 y_flipped: bool,
7527 window: &mut Window,
7528 cx: &mut Context<Editor>,
7529 ) -> Option<AnyElement> {
7530 let menu = self.context_menu.borrow();
7531 let menu = menu.as_ref()?;
7532 if !menu.visible() {
7533 return None;
7534 };
7535 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7536 }
7537
7538 fn render_context_menu_aside(
7539 &mut self,
7540 max_size: Size<Pixels>,
7541 window: &mut Window,
7542 cx: &mut Context<Editor>,
7543 ) -> Option<AnyElement> {
7544 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7545 if menu.visible() {
7546 menu.render_aside(self, max_size, window, cx)
7547 } else {
7548 None
7549 }
7550 })
7551 }
7552
7553 fn hide_context_menu(
7554 &mut self,
7555 window: &mut Window,
7556 cx: &mut Context<Self>,
7557 ) -> Option<CodeContextMenu> {
7558 cx.notify();
7559 self.completion_tasks.clear();
7560 let context_menu = self.context_menu.borrow_mut().take();
7561 self.stale_inline_completion_in_menu.take();
7562 self.update_visible_inline_completion(window, cx);
7563 context_menu
7564 }
7565
7566 fn show_snippet_choices(
7567 &mut self,
7568 choices: &Vec<String>,
7569 selection: Range<Anchor>,
7570 cx: &mut Context<Self>,
7571 ) {
7572 if selection.start.buffer_id.is_none() {
7573 return;
7574 }
7575 let buffer_id = selection.start.buffer_id.unwrap();
7576 let buffer = self.buffer().read(cx).buffer(buffer_id);
7577 let id = post_inc(&mut self.next_completion_id);
7578
7579 if let Some(buffer) = buffer {
7580 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7581 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7582 ));
7583 }
7584 }
7585
7586 pub fn insert_snippet(
7587 &mut self,
7588 insertion_ranges: &[Range<usize>],
7589 snippet: Snippet,
7590 window: &mut Window,
7591 cx: &mut Context<Self>,
7592 ) -> Result<()> {
7593 struct Tabstop<T> {
7594 is_end_tabstop: bool,
7595 ranges: Vec<Range<T>>,
7596 choices: Option<Vec<String>>,
7597 }
7598
7599 let tabstops = self.buffer.update(cx, |buffer, cx| {
7600 let snippet_text: Arc<str> = snippet.text.clone().into();
7601 let edits = insertion_ranges
7602 .iter()
7603 .cloned()
7604 .map(|range| (range, snippet_text.clone()));
7605 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7606
7607 let snapshot = &*buffer.read(cx);
7608 let snippet = &snippet;
7609 snippet
7610 .tabstops
7611 .iter()
7612 .map(|tabstop| {
7613 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7614 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7615 });
7616 let mut tabstop_ranges = tabstop
7617 .ranges
7618 .iter()
7619 .flat_map(|tabstop_range| {
7620 let mut delta = 0_isize;
7621 insertion_ranges.iter().map(move |insertion_range| {
7622 let insertion_start = insertion_range.start as isize + delta;
7623 delta +=
7624 snippet.text.len() as isize - insertion_range.len() as isize;
7625
7626 let start = ((insertion_start + tabstop_range.start) as usize)
7627 .min(snapshot.len());
7628 let end = ((insertion_start + tabstop_range.end) as usize)
7629 .min(snapshot.len());
7630 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7631 })
7632 })
7633 .collect::<Vec<_>>();
7634 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7635
7636 Tabstop {
7637 is_end_tabstop,
7638 ranges: tabstop_ranges,
7639 choices: tabstop.choices.clone(),
7640 }
7641 })
7642 .collect::<Vec<_>>()
7643 });
7644 if let Some(tabstop) = tabstops.first() {
7645 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7646 s.select_ranges(tabstop.ranges.iter().cloned());
7647 });
7648
7649 if let Some(choices) = &tabstop.choices {
7650 if let Some(selection) = tabstop.ranges.first() {
7651 self.show_snippet_choices(choices, selection.clone(), cx)
7652 }
7653 }
7654
7655 // If we're already at the last tabstop and it's at the end of the snippet,
7656 // we're done, we don't need to keep the state around.
7657 if !tabstop.is_end_tabstop {
7658 let choices = tabstops
7659 .iter()
7660 .map(|tabstop| tabstop.choices.clone())
7661 .collect();
7662
7663 let ranges = tabstops
7664 .into_iter()
7665 .map(|tabstop| tabstop.ranges)
7666 .collect::<Vec<_>>();
7667
7668 self.snippet_stack.push(SnippetState {
7669 active_index: 0,
7670 ranges,
7671 choices,
7672 });
7673 }
7674
7675 // Check whether the just-entered snippet ends with an auto-closable bracket.
7676 if self.autoclose_regions.is_empty() {
7677 let snapshot = self.buffer.read(cx).snapshot(cx);
7678 for selection in &mut self.selections.all::<Point>(cx) {
7679 let selection_head = selection.head();
7680 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7681 continue;
7682 };
7683
7684 let mut bracket_pair = None;
7685 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7686 let prev_chars = snapshot
7687 .reversed_chars_at(selection_head)
7688 .collect::<String>();
7689 for (pair, enabled) in scope.brackets() {
7690 if enabled
7691 && pair.close
7692 && prev_chars.starts_with(pair.start.as_str())
7693 && next_chars.starts_with(pair.end.as_str())
7694 {
7695 bracket_pair = Some(pair.clone());
7696 break;
7697 }
7698 }
7699 if let Some(pair) = bracket_pair {
7700 let start = snapshot.anchor_after(selection_head);
7701 let end = snapshot.anchor_after(selection_head);
7702 self.autoclose_regions.push(AutocloseRegion {
7703 selection_id: selection.id,
7704 range: start..end,
7705 pair,
7706 });
7707 }
7708 }
7709 }
7710 }
7711 Ok(())
7712 }
7713
7714 pub fn move_to_next_snippet_tabstop(
7715 &mut self,
7716 window: &mut Window,
7717 cx: &mut Context<Self>,
7718 ) -> bool {
7719 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7720 }
7721
7722 pub fn move_to_prev_snippet_tabstop(
7723 &mut self,
7724 window: &mut Window,
7725 cx: &mut Context<Self>,
7726 ) -> bool {
7727 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7728 }
7729
7730 pub fn move_to_snippet_tabstop(
7731 &mut self,
7732 bias: Bias,
7733 window: &mut Window,
7734 cx: &mut Context<Self>,
7735 ) -> bool {
7736 if let Some(mut snippet) = self.snippet_stack.pop() {
7737 match bias {
7738 Bias::Left => {
7739 if snippet.active_index > 0 {
7740 snippet.active_index -= 1;
7741 } else {
7742 self.snippet_stack.push(snippet);
7743 return false;
7744 }
7745 }
7746 Bias::Right => {
7747 if snippet.active_index + 1 < snippet.ranges.len() {
7748 snippet.active_index += 1;
7749 } else {
7750 self.snippet_stack.push(snippet);
7751 return false;
7752 }
7753 }
7754 }
7755 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7756 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7757 s.select_anchor_ranges(current_ranges.iter().cloned())
7758 });
7759
7760 if let Some(choices) = &snippet.choices[snippet.active_index] {
7761 if let Some(selection) = current_ranges.first() {
7762 self.show_snippet_choices(&choices, selection.clone(), cx);
7763 }
7764 }
7765
7766 // If snippet state is not at the last tabstop, push it back on the stack
7767 if snippet.active_index + 1 < snippet.ranges.len() {
7768 self.snippet_stack.push(snippet);
7769 }
7770 return true;
7771 }
7772 }
7773
7774 false
7775 }
7776
7777 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7778 self.transact(window, cx, |this, window, cx| {
7779 this.select_all(&SelectAll, window, cx);
7780 this.insert("", window, cx);
7781 });
7782 }
7783
7784 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7785 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7786 self.transact(window, cx, |this, window, cx| {
7787 this.select_autoclose_pair(window, cx);
7788 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7789 if !this.linked_edit_ranges.is_empty() {
7790 let selections = this.selections.all::<MultiBufferPoint>(cx);
7791 let snapshot = this.buffer.read(cx).snapshot(cx);
7792
7793 for selection in selections.iter() {
7794 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7795 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7796 if selection_start.buffer_id != selection_end.buffer_id {
7797 continue;
7798 }
7799 if let Some(ranges) =
7800 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7801 {
7802 for (buffer, entries) in ranges {
7803 linked_ranges.entry(buffer).or_default().extend(entries);
7804 }
7805 }
7806 }
7807 }
7808
7809 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7810 if !this.selections.line_mode {
7811 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7812 for selection in &mut selections {
7813 if selection.is_empty() {
7814 let old_head = selection.head();
7815 let mut new_head =
7816 movement::left(&display_map, old_head.to_display_point(&display_map))
7817 .to_point(&display_map);
7818 if let Some((buffer, line_buffer_range)) = display_map
7819 .buffer_snapshot
7820 .buffer_line_for_row(MultiBufferRow(old_head.row))
7821 {
7822 let indent_size =
7823 buffer.indent_size_for_line(line_buffer_range.start.row);
7824 let indent_len = match indent_size.kind {
7825 IndentKind::Space => {
7826 buffer.settings_at(line_buffer_range.start, cx).tab_size
7827 }
7828 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7829 };
7830 if old_head.column <= indent_size.len && old_head.column > 0 {
7831 let indent_len = indent_len.get();
7832 new_head = cmp::min(
7833 new_head,
7834 MultiBufferPoint::new(
7835 old_head.row,
7836 ((old_head.column - 1) / indent_len) * indent_len,
7837 ),
7838 );
7839 }
7840 }
7841
7842 selection.set_head(new_head, SelectionGoal::None);
7843 }
7844 }
7845 }
7846
7847 this.signature_help_state.set_backspace_pressed(true);
7848 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7849 s.select(selections)
7850 });
7851 this.insert("", window, cx);
7852 let empty_str: Arc<str> = Arc::from("");
7853 for (buffer, edits) in linked_ranges {
7854 let snapshot = buffer.read(cx).snapshot();
7855 use text::ToPoint as TP;
7856
7857 let edits = edits
7858 .into_iter()
7859 .map(|range| {
7860 let end_point = TP::to_point(&range.end, &snapshot);
7861 let mut start_point = TP::to_point(&range.start, &snapshot);
7862
7863 if end_point == start_point {
7864 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7865 .saturating_sub(1);
7866 start_point =
7867 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7868 };
7869
7870 (start_point..end_point, empty_str.clone())
7871 })
7872 .sorted_by_key(|(range, _)| range.start)
7873 .collect::<Vec<_>>();
7874 buffer.update(cx, |this, cx| {
7875 this.edit(edits, None, cx);
7876 })
7877 }
7878 this.refresh_inline_completion(true, false, window, cx);
7879 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7880 });
7881 }
7882
7883 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7884 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7885 self.transact(window, cx, |this, window, cx| {
7886 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7887 let line_mode = s.line_mode;
7888 s.move_with(|map, selection| {
7889 if selection.is_empty() && !line_mode {
7890 let cursor = movement::right(map, selection.head());
7891 selection.end = cursor;
7892 selection.reversed = true;
7893 selection.goal = SelectionGoal::None;
7894 }
7895 })
7896 });
7897 this.insert("", window, cx);
7898 this.refresh_inline_completion(true, false, window, cx);
7899 });
7900 }
7901
7902 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7903 if self.move_to_prev_snippet_tabstop(window, cx) {
7904 return;
7905 }
7906 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7907 self.outdent(&Outdent, window, cx);
7908 }
7909
7910 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7911 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7912 return;
7913 }
7914 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7915 let mut selections = self.selections.all_adjusted(cx);
7916 let buffer = self.buffer.read(cx);
7917 let snapshot = buffer.snapshot(cx);
7918 let rows_iter = selections.iter().map(|s| s.head().row);
7919 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7920
7921 let mut edits = Vec::new();
7922 let mut prev_edited_row = 0;
7923 let mut row_delta = 0;
7924 for selection in &mut selections {
7925 if selection.start.row != prev_edited_row {
7926 row_delta = 0;
7927 }
7928 prev_edited_row = selection.end.row;
7929
7930 // If the selection is non-empty, then increase the indentation of the selected lines.
7931 if !selection.is_empty() {
7932 row_delta =
7933 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7934 continue;
7935 }
7936
7937 // If the selection is empty and the cursor is in the leading whitespace before the
7938 // suggested indentation, then auto-indent the line.
7939 let cursor = selection.head();
7940 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7941 if let Some(suggested_indent) =
7942 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7943 {
7944 if cursor.column < suggested_indent.len
7945 && cursor.column <= current_indent.len
7946 && current_indent.len <= suggested_indent.len
7947 {
7948 selection.start = Point::new(cursor.row, suggested_indent.len);
7949 selection.end = selection.start;
7950 if row_delta == 0 {
7951 edits.extend(Buffer::edit_for_indent_size_adjustment(
7952 cursor.row,
7953 current_indent,
7954 suggested_indent,
7955 ));
7956 row_delta = suggested_indent.len - current_indent.len;
7957 }
7958 continue;
7959 }
7960 }
7961
7962 // Otherwise, insert a hard or soft tab.
7963 let settings = buffer.language_settings_at(cursor, cx);
7964 let tab_size = if settings.hard_tabs {
7965 IndentSize::tab()
7966 } else {
7967 let tab_size = settings.tab_size.get();
7968 let char_column = snapshot
7969 .text_for_range(Point::new(cursor.row, 0)..cursor)
7970 .flat_map(str::chars)
7971 .count()
7972 + row_delta as usize;
7973 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7974 IndentSize::spaces(chars_to_next_tab_stop)
7975 };
7976 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7977 selection.end = selection.start;
7978 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7979 row_delta += tab_size.len;
7980 }
7981
7982 self.transact(window, cx, |this, window, cx| {
7983 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7984 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7985 s.select(selections)
7986 });
7987 this.refresh_inline_completion(true, false, window, cx);
7988 });
7989 }
7990
7991 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7992 if self.read_only(cx) {
7993 return;
7994 }
7995 let mut selections = self.selections.all::<Point>(cx);
7996 let mut prev_edited_row = 0;
7997 let mut row_delta = 0;
7998 let mut edits = Vec::new();
7999 let buffer = self.buffer.read(cx);
8000 let snapshot = buffer.snapshot(cx);
8001 for selection in &mut selections {
8002 if selection.start.row != prev_edited_row {
8003 row_delta = 0;
8004 }
8005 prev_edited_row = selection.end.row;
8006
8007 row_delta =
8008 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8009 }
8010
8011 self.transact(window, cx, |this, window, cx| {
8012 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8013 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8014 s.select(selections)
8015 });
8016 });
8017 }
8018
8019 fn indent_selection(
8020 buffer: &MultiBuffer,
8021 snapshot: &MultiBufferSnapshot,
8022 selection: &mut Selection<Point>,
8023 edits: &mut Vec<(Range<Point>, String)>,
8024 delta_for_start_row: u32,
8025 cx: &App,
8026 ) -> u32 {
8027 let settings = buffer.language_settings_at(selection.start, cx);
8028 let tab_size = settings.tab_size.get();
8029 let indent_kind = if settings.hard_tabs {
8030 IndentKind::Tab
8031 } else {
8032 IndentKind::Space
8033 };
8034 let mut start_row = selection.start.row;
8035 let mut end_row = selection.end.row + 1;
8036
8037 // If a selection ends at the beginning of a line, don't indent
8038 // that last line.
8039 if selection.end.column == 0 && selection.end.row > selection.start.row {
8040 end_row -= 1;
8041 }
8042
8043 // Avoid re-indenting a row that has already been indented by a
8044 // previous selection, but still update this selection's column
8045 // to reflect that indentation.
8046 if delta_for_start_row > 0 {
8047 start_row += 1;
8048 selection.start.column += delta_for_start_row;
8049 if selection.end.row == selection.start.row {
8050 selection.end.column += delta_for_start_row;
8051 }
8052 }
8053
8054 let mut delta_for_end_row = 0;
8055 let has_multiple_rows = start_row + 1 != end_row;
8056 for row in start_row..end_row {
8057 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8058 let indent_delta = match (current_indent.kind, indent_kind) {
8059 (IndentKind::Space, IndentKind::Space) => {
8060 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8061 IndentSize::spaces(columns_to_next_tab_stop)
8062 }
8063 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8064 (_, IndentKind::Tab) => IndentSize::tab(),
8065 };
8066
8067 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8068 0
8069 } else {
8070 selection.start.column
8071 };
8072 let row_start = Point::new(row, start);
8073 edits.push((
8074 row_start..row_start,
8075 indent_delta.chars().collect::<String>(),
8076 ));
8077
8078 // Update this selection's endpoints to reflect the indentation.
8079 if row == selection.start.row {
8080 selection.start.column += indent_delta.len;
8081 }
8082 if row == selection.end.row {
8083 selection.end.column += indent_delta.len;
8084 delta_for_end_row = indent_delta.len;
8085 }
8086 }
8087
8088 if selection.start.row == selection.end.row {
8089 delta_for_start_row + delta_for_end_row
8090 } else {
8091 delta_for_end_row
8092 }
8093 }
8094
8095 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8096 if self.read_only(cx) {
8097 return;
8098 }
8099 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8100 let selections = self.selections.all::<Point>(cx);
8101 let mut deletion_ranges = Vec::new();
8102 let mut last_outdent = None;
8103 {
8104 let buffer = self.buffer.read(cx);
8105 let snapshot = buffer.snapshot(cx);
8106 for selection in &selections {
8107 let settings = buffer.language_settings_at(selection.start, cx);
8108 let tab_size = settings.tab_size.get();
8109 let mut rows = selection.spanned_rows(false, &display_map);
8110
8111 // Avoid re-outdenting a row that has already been outdented by a
8112 // previous selection.
8113 if let Some(last_row) = last_outdent {
8114 if last_row == rows.start {
8115 rows.start = rows.start.next_row();
8116 }
8117 }
8118 let has_multiple_rows = rows.len() > 1;
8119 for row in rows.iter_rows() {
8120 let indent_size = snapshot.indent_size_for_line(row);
8121 if indent_size.len > 0 {
8122 let deletion_len = match indent_size.kind {
8123 IndentKind::Space => {
8124 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8125 if columns_to_prev_tab_stop == 0 {
8126 tab_size
8127 } else {
8128 columns_to_prev_tab_stop
8129 }
8130 }
8131 IndentKind::Tab => 1,
8132 };
8133 let start = if has_multiple_rows
8134 || deletion_len > selection.start.column
8135 || indent_size.len < selection.start.column
8136 {
8137 0
8138 } else {
8139 selection.start.column - deletion_len
8140 };
8141 deletion_ranges.push(
8142 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8143 );
8144 last_outdent = Some(row);
8145 }
8146 }
8147 }
8148 }
8149
8150 self.transact(window, cx, |this, window, cx| {
8151 this.buffer.update(cx, |buffer, cx| {
8152 let empty_str: Arc<str> = Arc::default();
8153 buffer.edit(
8154 deletion_ranges
8155 .into_iter()
8156 .map(|range| (range, empty_str.clone())),
8157 None,
8158 cx,
8159 );
8160 });
8161 let selections = this.selections.all::<usize>(cx);
8162 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8163 s.select(selections)
8164 });
8165 });
8166 }
8167
8168 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8169 if self.read_only(cx) {
8170 return;
8171 }
8172 let selections = self
8173 .selections
8174 .all::<usize>(cx)
8175 .into_iter()
8176 .map(|s| s.range());
8177
8178 self.transact(window, cx, |this, window, cx| {
8179 this.buffer.update(cx, |buffer, cx| {
8180 buffer.autoindent_ranges(selections, cx);
8181 });
8182 let selections = this.selections.all::<usize>(cx);
8183 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8184 s.select(selections)
8185 });
8186 });
8187 }
8188
8189 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8190 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8191 let selections = self.selections.all::<Point>(cx);
8192
8193 let mut new_cursors = Vec::new();
8194 let mut edit_ranges = Vec::new();
8195 let mut selections = selections.iter().peekable();
8196 while let Some(selection) = selections.next() {
8197 let mut rows = selection.spanned_rows(false, &display_map);
8198 let goal_display_column = selection.head().to_display_point(&display_map).column();
8199
8200 // Accumulate contiguous regions of rows that we want to delete.
8201 while let Some(next_selection) = selections.peek() {
8202 let next_rows = next_selection.spanned_rows(false, &display_map);
8203 if next_rows.start <= rows.end {
8204 rows.end = next_rows.end;
8205 selections.next().unwrap();
8206 } else {
8207 break;
8208 }
8209 }
8210
8211 let buffer = &display_map.buffer_snapshot;
8212 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8213 let edit_end;
8214 let cursor_buffer_row;
8215 if buffer.max_point().row >= rows.end.0 {
8216 // If there's a line after the range, delete the \n from the end of the row range
8217 // and position the cursor on the next line.
8218 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8219 cursor_buffer_row = rows.end;
8220 } else {
8221 // If there isn't a line after the range, delete the \n from the line before the
8222 // start of the row range and position the cursor there.
8223 edit_start = edit_start.saturating_sub(1);
8224 edit_end = buffer.len();
8225 cursor_buffer_row = rows.start.previous_row();
8226 }
8227
8228 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8229 *cursor.column_mut() =
8230 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8231
8232 new_cursors.push((
8233 selection.id,
8234 buffer.anchor_after(cursor.to_point(&display_map)),
8235 ));
8236 edit_ranges.push(edit_start..edit_end);
8237 }
8238
8239 self.transact(window, cx, |this, window, cx| {
8240 let buffer = this.buffer.update(cx, |buffer, cx| {
8241 let empty_str: Arc<str> = Arc::default();
8242 buffer.edit(
8243 edit_ranges
8244 .into_iter()
8245 .map(|range| (range, empty_str.clone())),
8246 None,
8247 cx,
8248 );
8249 buffer.snapshot(cx)
8250 });
8251 let new_selections = new_cursors
8252 .into_iter()
8253 .map(|(id, cursor)| {
8254 let cursor = cursor.to_point(&buffer);
8255 Selection {
8256 id,
8257 start: cursor,
8258 end: cursor,
8259 reversed: false,
8260 goal: SelectionGoal::None,
8261 }
8262 })
8263 .collect();
8264
8265 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8266 s.select(new_selections);
8267 });
8268 });
8269 }
8270
8271 pub fn join_lines_impl(
8272 &mut self,
8273 insert_whitespace: bool,
8274 window: &mut Window,
8275 cx: &mut Context<Self>,
8276 ) {
8277 if self.read_only(cx) {
8278 return;
8279 }
8280 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8281 for selection in self.selections.all::<Point>(cx) {
8282 let start = MultiBufferRow(selection.start.row);
8283 // Treat single line selections as if they include the next line. Otherwise this action
8284 // would do nothing for single line selections individual cursors.
8285 let end = if selection.start.row == selection.end.row {
8286 MultiBufferRow(selection.start.row + 1)
8287 } else {
8288 MultiBufferRow(selection.end.row)
8289 };
8290
8291 if let Some(last_row_range) = row_ranges.last_mut() {
8292 if start <= last_row_range.end {
8293 last_row_range.end = end;
8294 continue;
8295 }
8296 }
8297 row_ranges.push(start..end);
8298 }
8299
8300 let snapshot = self.buffer.read(cx).snapshot(cx);
8301 let mut cursor_positions = Vec::new();
8302 for row_range in &row_ranges {
8303 let anchor = snapshot.anchor_before(Point::new(
8304 row_range.end.previous_row().0,
8305 snapshot.line_len(row_range.end.previous_row()),
8306 ));
8307 cursor_positions.push(anchor..anchor);
8308 }
8309
8310 self.transact(window, cx, |this, window, cx| {
8311 for row_range in row_ranges.into_iter().rev() {
8312 for row in row_range.iter_rows().rev() {
8313 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8314 let next_line_row = row.next_row();
8315 let indent = snapshot.indent_size_for_line(next_line_row);
8316 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8317
8318 let replace =
8319 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8320 " "
8321 } else {
8322 ""
8323 };
8324
8325 this.buffer.update(cx, |buffer, cx| {
8326 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8327 });
8328 }
8329 }
8330
8331 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8332 s.select_anchor_ranges(cursor_positions)
8333 });
8334 });
8335 }
8336
8337 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8338 self.join_lines_impl(true, window, cx);
8339 }
8340
8341 pub fn sort_lines_case_sensitive(
8342 &mut self,
8343 _: &SortLinesCaseSensitive,
8344 window: &mut Window,
8345 cx: &mut Context<Self>,
8346 ) {
8347 self.manipulate_lines(window, cx, |lines| lines.sort())
8348 }
8349
8350 pub fn sort_lines_case_insensitive(
8351 &mut self,
8352 _: &SortLinesCaseInsensitive,
8353 window: &mut Window,
8354 cx: &mut Context<Self>,
8355 ) {
8356 self.manipulate_lines(window, cx, |lines| {
8357 lines.sort_by_key(|line| line.to_lowercase())
8358 })
8359 }
8360
8361 pub fn unique_lines_case_insensitive(
8362 &mut self,
8363 _: &UniqueLinesCaseInsensitive,
8364 window: &mut Window,
8365 cx: &mut Context<Self>,
8366 ) {
8367 self.manipulate_lines(window, cx, |lines| {
8368 let mut seen = HashSet::default();
8369 lines.retain(|line| seen.insert(line.to_lowercase()));
8370 })
8371 }
8372
8373 pub fn unique_lines_case_sensitive(
8374 &mut self,
8375 _: &UniqueLinesCaseSensitive,
8376 window: &mut Window,
8377 cx: &mut Context<Self>,
8378 ) {
8379 self.manipulate_lines(window, cx, |lines| {
8380 let mut seen = HashSet::default();
8381 lines.retain(|line| seen.insert(*line));
8382 })
8383 }
8384
8385 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8386 let Some(project) = self.project.clone() else {
8387 return;
8388 };
8389 self.reload(project, window, cx)
8390 .detach_and_notify_err(window, cx);
8391 }
8392
8393 pub fn restore_file(
8394 &mut self,
8395 _: &::git::RestoreFile,
8396 window: &mut Window,
8397 cx: &mut Context<Self>,
8398 ) {
8399 let mut buffer_ids = HashSet::default();
8400 let snapshot = self.buffer().read(cx).snapshot(cx);
8401 for selection in self.selections.all::<usize>(cx) {
8402 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8403 }
8404
8405 let buffer = self.buffer().read(cx);
8406 let ranges = buffer_ids
8407 .into_iter()
8408 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8409 .collect::<Vec<_>>();
8410
8411 self.restore_hunks_in_ranges(ranges, window, cx);
8412 }
8413
8414 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8415 let selections = self
8416 .selections
8417 .all(cx)
8418 .into_iter()
8419 .map(|s| s.range())
8420 .collect();
8421 self.restore_hunks_in_ranges(selections, window, cx);
8422 }
8423
8424 pub fn restore_hunks_in_ranges(
8425 &mut self,
8426 ranges: Vec<Range<Point>>,
8427 window: &mut Window,
8428 cx: &mut Context<Editor>,
8429 ) {
8430 let mut revert_changes = HashMap::default();
8431 let chunk_by = self
8432 .snapshot(window, cx)
8433 .hunks_for_ranges(ranges)
8434 .into_iter()
8435 .chunk_by(|hunk| hunk.buffer_id);
8436 for (buffer_id, hunks) in &chunk_by {
8437 let hunks = hunks.collect::<Vec<_>>();
8438 for hunk in &hunks {
8439 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8440 }
8441 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8442 }
8443 drop(chunk_by);
8444 if !revert_changes.is_empty() {
8445 self.transact(window, cx, |editor, window, cx| {
8446 editor.restore(revert_changes, window, cx);
8447 });
8448 }
8449 }
8450
8451 pub fn open_active_item_in_terminal(
8452 &mut self,
8453 _: &OpenInTerminal,
8454 window: &mut Window,
8455 cx: &mut Context<Self>,
8456 ) {
8457 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8458 let project_path = buffer.read(cx).project_path(cx)?;
8459 let project = self.project.as_ref()?.read(cx);
8460 let entry = project.entry_for_path(&project_path, cx)?;
8461 let parent = match &entry.canonical_path {
8462 Some(canonical_path) => canonical_path.to_path_buf(),
8463 None => project.absolute_path(&project_path, cx)?,
8464 }
8465 .parent()?
8466 .to_path_buf();
8467 Some(parent)
8468 }) {
8469 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8470 }
8471 }
8472
8473 fn set_breakpoint_context_menu(
8474 &mut self,
8475 display_row: DisplayRow,
8476 position: Option<Anchor>,
8477 clicked_point: gpui::Point<Pixels>,
8478 window: &mut Window,
8479 cx: &mut Context<Self>,
8480 ) {
8481 if !cx.has_flag::<Debugger>() {
8482 return;
8483 }
8484 let source = self
8485 .buffer
8486 .read(cx)
8487 .snapshot(cx)
8488 .anchor_before(Point::new(display_row.0, 0u32));
8489
8490 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8491
8492 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8493 self,
8494 source,
8495 clicked_point,
8496 context_menu,
8497 window,
8498 cx,
8499 );
8500 }
8501
8502 fn add_edit_breakpoint_block(
8503 &mut self,
8504 anchor: Anchor,
8505 breakpoint: &Breakpoint,
8506 window: &mut Window,
8507 cx: &mut Context<Self>,
8508 ) {
8509 let weak_editor = cx.weak_entity();
8510 let bp_prompt = cx.new(|cx| {
8511 BreakpointPromptEditor::new(weak_editor, anchor, breakpoint.clone(), window, cx)
8512 });
8513
8514 let height = bp_prompt.update(cx, |this, cx| {
8515 this.prompt
8516 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8517 });
8518 let cloned_prompt = bp_prompt.clone();
8519 let blocks = vec![BlockProperties {
8520 style: BlockStyle::Sticky,
8521 placement: BlockPlacement::Above(anchor),
8522 height,
8523 render: Arc::new(move |cx| {
8524 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8525 cloned_prompt.clone().into_any_element()
8526 }),
8527 priority: 0,
8528 }];
8529
8530 let focus_handle = bp_prompt.focus_handle(cx);
8531 window.focus(&focus_handle);
8532
8533 let block_ids = self.insert_blocks(blocks, None, cx);
8534 bp_prompt.update(cx, |prompt, _| {
8535 prompt.add_block_ids(block_ids);
8536 });
8537 }
8538
8539 fn breakpoint_at_cursor_head(
8540 &self,
8541 window: &mut Window,
8542 cx: &mut Context<Self>,
8543 ) -> Option<(Anchor, Breakpoint)> {
8544 let cursor_position: Point = self.selections.newest(cx).head();
8545 self.breakpoint_at_row(cursor_position.row, window, cx)
8546 }
8547
8548 pub(crate) fn breakpoint_at_row(
8549 &self,
8550 row: u32,
8551 window: &mut Window,
8552 cx: &mut Context<Self>,
8553 ) -> Option<(Anchor, Breakpoint)> {
8554 let snapshot = self.snapshot(window, cx);
8555 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8556
8557 let project = self.project.clone()?;
8558
8559 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8560 snapshot
8561 .buffer_snapshot
8562 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8563 })?;
8564
8565 let enclosing_excerpt = breakpoint_position.excerpt_id;
8566 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8567 let buffer_snapshot = buffer.read(cx).snapshot();
8568
8569 let row = buffer_snapshot
8570 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8571 .row;
8572
8573 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8574 let anchor_end = snapshot
8575 .buffer_snapshot
8576 .anchor_before(Point::new(row, line_len));
8577
8578 let bp = self
8579 .breakpoint_store
8580 .as_ref()?
8581 .read_with(cx, |breakpoint_store, cx| {
8582 breakpoint_store
8583 .breakpoints(
8584 &buffer,
8585 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8586 &buffer_snapshot,
8587 cx,
8588 )
8589 .next()
8590 .and_then(|(anchor, bp)| {
8591 let breakpoint_row = buffer_snapshot
8592 .summary_for_anchor::<text::PointUtf16>(anchor)
8593 .row;
8594
8595 if breakpoint_row == row {
8596 snapshot
8597 .buffer_snapshot
8598 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8599 .map(|anchor| (anchor, bp.clone()))
8600 } else {
8601 None
8602 }
8603 })
8604 });
8605 bp
8606 }
8607
8608 pub fn edit_log_breakpoint(
8609 &mut self,
8610 _: &EditLogBreakpoint,
8611 window: &mut Window,
8612 cx: &mut Context<Self>,
8613 ) {
8614 let (anchor, bp) = self
8615 .breakpoint_at_cursor_head(window, cx)
8616 .unwrap_or_else(|| {
8617 let cursor_position: Point = self.selections.newest(cx).head();
8618
8619 let breakpoint_position = self
8620 .snapshot(window, cx)
8621 .display_snapshot
8622 .buffer_snapshot
8623 .anchor_after(Point::new(cursor_position.row, 0));
8624
8625 (
8626 breakpoint_position,
8627 Breakpoint {
8628 kind: BreakpointKind::Standard,
8629 state: BreakpointState::Enabled,
8630 },
8631 )
8632 });
8633
8634 self.add_edit_breakpoint_block(anchor, &bp, window, cx);
8635 }
8636
8637 pub fn enable_breakpoint(
8638 &mut self,
8639 _: &crate::actions::EnableBreakpoint,
8640 window: &mut Window,
8641 cx: &mut Context<Self>,
8642 ) {
8643 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8644 if breakpoint.is_disabled() {
8645 self.edit_breakpoint_at_anchor(
8646 anchor,
8647 breakpoint,
8648 BreakpointEditAction::InvertState,
8649 cx,
8650 );
8651 }
8652 }
8653 }
8654
8655 pub fn disable_breakpoint(
8656 &mut self,
8657 _: &crate::actions::DisableBreakpoint,
8658 window: &mut Window,
8659 cx: &mut Context<Self>,
8660 ) {
8661 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8662 if breakpoint.is_enabled() {
8663 self.edit_breakpoint_at_anchor(
8664 anchor,
8665 breakpoint,
8666 BreakpointEditAction::InvertState,
8667 cx,
8668 );
8669 }
8670 }
8671 }
8672
8673 pub fn toggle_breakpoint(
8674 &mut self,
8675 _: &crate::actions::ToggleBreakpoint,
8676 window: &mut Window,
8677 cx: &mut Context<Self>,
8678 ) {
8679 let edit_action = BreakpointEditAction::Toggle;
8680
8681 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8682 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8683 } else {
8684 let cursor_position: Point = self.selections.newest(cx).head();
8685
8686 let breakpoint_position = self
8687 .snapshot(window, cx)
8688 .display_snapshot
8689 .buffer_snapshot
8690 .anchor_after(Point::new(cursor_position.row, 0));
8691
8692 self.edit_breakpoint_at_anchor(
8693 breakpoint_position,
8694 Breakpoint::new_standard(),
8695 edit_action,
8696 cx,
8697 );
8698 }
8699 }
8700
8701 pub fn edit_breakpoint_at_anchor(
8702 &mut self,
8703 breakpoint_position: Anchor,
8704 breakpoint: Breakpoint,
8705 edit_action: BreakpointEditAction,
8706 cx: &mut Context<Self>,
8707 ) {
8708 let Some(breakpoint_store) = &self.breakpoint_store else {
8709 return;
8710 };
8711
8712 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8713 if breakpoint_position == Anchor::min() {
8714 self.buffer()
8715 .read(cx)
8716 .excerpt_buffer_ids()
8717 .into_iter()
8718 .next()
8719 } else {
8720 None
8721 }
8722 }) else {
8723 return;
8724 };
8725
8726 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8727 return;
8728 };
8729
8730 breakpoint_store.update(cx, |breakpoint_store, cx| {
8731 breakpoint_store.toggle_breakpoint(
8732 buffer,
8733 (breakpoint_position.text_anchor, breakpoint),
8734 edit_action,
8735 cx,
8736 );
8737 });
8738
8739 cx.notify();
8740 }
8741
8742 #[cfg(any(test, feature = "test-support"))]
8743 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8744 self.breakpoint_store.clone()
8745 }
8746
8747 pub fn prepare_restore_change(
8748 &self,
8749 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8750 hunk: &MultiBufferDiffHunk,
8751 cx: &mut App,
8752 ) -> Option<()> {
8753 if hunk.is_created_file() {
8754 return None;
8755 }
8756 let buffer = self.buffer.read(cx);
8757 let diff = buffer.diff_for(hunk.buffer_id)?;
8758 let buffer = buffer.buffer(hunk.buffer_id)?;
8759 let buffer = buffer.read(cx);
8760 let original_text = diff
8761 .read(cx)
8762 .base_text()
8763 .as_rope()
8764 .slice(hunk.diff_base_byte_range.clone());
8765 let buffer_snapshot = buffer.snapshot();
8766 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8767 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8768 probe
8769 .0
8770 .start
8771 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8772 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8773 }) {
8774 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8775 Some(())
8776 } else {
8777 None
8778 }
8779 }
8780
8781 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8782 self.manipulate_lines(window, cx, |lines| lines.reverse())
8783 }
8784
8785 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8786 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8787 }
8788
8789 fn manipulate_lines<Fn>(
8790 &mut self,
8791 window: &mut Window,
8792 cx: &mut Context<Self>,
8793 mut callback: Fn,
8794 ) where
8795 Fn: FnMut(&mut Vec<&str>),
8796 {
8797 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8798 let buffer = self.buffer.read(cx).snapshot(cx);
8799
8800 let mut edits = Vec::new();
8801
8802 let selections = self.selections.all::<Point>(cx);
8803 let mut selections = selections.iter().peekable();
8804 let mut contiguous_row_selections = Vec::new();
8805 let mut new_selections = Vec::new();
8806 let mut added_lines = 0;
8807 let mut removed_lines = 0;
8808
8809 while let Some(selection) = selections.next() {
8810 let (start_row, end_row) = consume_contiguous_rows(
8811 &mut contiguous_row_selections,
8812 selection,
8813 &display_map,
8814 &mut selections,
8815 );
8816
8817 let start_point = Point::new(start_row.0, 0);
8818 let end_point = Point::new(
8819 end_row.previous_row().0,
8820 buffer.line_len(end_row.previous_row()),
8821 );
8822 let text = buffer
8823 .text_for_range(start_point..end_point)
8824 .collect::<String>();
8825
8826 let mut lines = text.split('\n').collect_vec();
8827
8828 let lines_before = lines.len();
8829 callback(&mut lines);
8830 let lines_after = lines.len();
8831
8832 edits.push((start_point..end_point, lines.join("\n")));
8833
8834 // Selections must change based on added and removed line count
8835 let start_row =
8836 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8837 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8838 new_selections.push(Selection {
8839 id: selection.id,
8840 start: start_row,
8841 end: end_row,
8842 goal: SelectionGoal::None,
8843 reversed: selection.reversed,
8844 });
8845
8846 if lines_after > lines_before {
8847 added_lines += lines_after - lines_before;
8848 } else if lines_before > lines_after {
8849 removed_lines += lines_before - lines_after;
8850 }
8851 }
8852
8853 self.transact(window, cx, |this, window, cx| {
8854 let buffer = this.buffer.update(cx, |buffer, cx| {
8855 buffer.edit(edits, None, cx);
8856 buffer.snapshot(cx)
8857 });
8858
8859 // Recalculate offsets on newly edited buffer
8860 let new_selections = new_selections
8861 .iter()
8862 .map(|s| {
8863 let start_point = Point::new(s.start.0, 0);
8864 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8865 Selection {
8866 id: s.id,
8867 start: buffer.point_to_offset(start_point),
8868 end: buffer.point_to_offset(end_point),
8869 goal: s.goal,
8870 reversed: s.reversed,
8871 }
8872 })
8873 .collect();
8874
8875 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8876 s.select(new_selections);
8877 });
8878
8879 this.request_autoscroll(Autoscroll::fit(), cx);
8880 });
8881 }
8882
8883 pub fn convert_to_upper_case(
8884 &mut self,
8885 _: &ConvertToUpperCase,
8886 window: &mut Window,
8887 cx: &mut Context<Self>,
8888 ) {
8889 self.manipulate_text(window, cx, |text| text.to_uppercase())
8890 }
8891
8892 pub fn convert_to_lower_case(
8893 &mut self,
8894 _: &ConvertToLowerCase,
8895 window: &mut Window,
8896 cx: &mut Context<Self>,
8897 ) {
8898 self.manipulate_text(window, cx, |text| text.to_lowercase())
8899 }
8900
8901 pub fn convert_to_title_case(
8902 &mut self,
8903 _: &ConvertToTitleCase,
8904 window: &mut Window,
8905 cx: &mut Context<Self>,
8906 ) {
8907 self.manipulate_text(window, cx, |text| {
8908 text.split('\n')
8909 .map(|line| line.to_case(Case::Title))
8910 .join("\n")
8911 })
8912 }
8913
8914 pub fn convert_to_snake_case(
8915 &mut self,
8916 _: &ConvertToSnakeCase,
8917 window: &mut Window,
8918 cx: &mut Context<Self>,
8919 ) {
8920 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8921 }
8922
8923 pub fn convert_to_kebab_case(
8924 &mut self,
8925 _: &ConvertToKebabCase,
8926 window: &mut Window,
8927 cx: &mut Context<Self>,
8928 ) {
8929 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8930 }
8931
8932 pub fn convert_to_upper_camel_case(
8933 &mut self,
8934 _: &ConvertToUpperCamelCase,
8935 window: &mut Window,
8936 cx: &mut Context<Self>,
8937 ) {
8938 self.manipulate_text(window, cx, |text| {
8939 text.split('\n')
8940 .map(|line| line.to_case(Case::UpperCamel))
8941 .join("\n")
8942 })
8943 }
8944
8945 pub fn convert_to_lower_camel_case(
8946 &mut self,
8947 _: &ConvertToLowerCamelCase,
8948 window: &mut Window,
8949 cx: &mut Context<Self>,
8950 ) {
8951 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8952 }
8953
8954 pub fn convert_to_opposite_case(
8955 &mut self,
8956 _: &ConvertToOppositeCase,
8957 window: &mut Window,
8958 cx: &mut Context<Self>,
8959 ) {
8960 self.manipulate_text(window, cx, |text| {
8961 text.chars()
8962 .fold(String::with_capacity(text.len()), |mut t, c| {
8963 if c.is_uppercase() {
8964 t.extend(c.to_lowercase());
8965 } else {
8966 t.extend(c.to_uppercase());
8967 }
8968 t
8969 })
8970 })
8971 }
8972
8973 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8974 where
8975 Fn: FnMut(&str) -> String,
8976 {
8977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8978 let buffer = self.buffer.read(cx).snapshot(cx);
8979
8980 let mut new_selections = Vec::new();
8981 let mut edits = Vec::new();
8982 let mut selection_adjustment = 0i32;
8983
8984 for selection in self.selections.all::<usize>(cx) {
8985 let selection_is_empty = selection.is_empty();
8986
8987 let (start, end) = if selection_is_empty {
8988 let word_range = movement::surrounding_word(
8989 &display_map,
8990 selection.start.to_display_point(&display_map),
8991 );
8992 let start = word_range.start.to_offset(&display_map, Bias::Left);
8993 let end = word_range.end.to_offset(&display_map, Bias::Left);
8994 (start, end)
8995 } else {
8996 (selection.start, selection.end)
8997 };
8998
8999 let text = buffer.text_for_range(start..end).collect::<String>();
9000 let old_length = text.len() as i32;
9001 let text = callback(&text);
9002
9003 new_selections.push(Selection {
9004 start: (start as i32 - selection_adjustment) as usize,
9005 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9006 goal: SelectionGoal::None,
9007 ..selection
9008 });
9009
9010 selection_adjustment += old_length - text.len() as i32;
9011
9012 edits.push((start..end, text));
9013 }
9014
9015 self.transact(window, cx, |this, window, cx| {
9016 this.buffer.update(cx, |buffer, cx| {
9017 buffer.edit(edits, None, cx);
9018 });
9019
9020 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9021 s.select(new_selections);
9022 });
9023
9024 this.request_autoscroll(Autoscroll::fit(), cx);
9025 });
9026 }
9027
9028 pub fn duplicate(
9029 &mut self,
9030 upwards: bool,
9031 whole_lines: bool,
9032 window: &mut Window,
9033 cx: &mut Context<Self>,
9034 ) {
9035 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9036 let buffer = &display_map.buffer_snapshot;
9037 let selections = self.selections.all::<Point>(cx);
9038
9039 let mut edits = Vec::new();
9040 let mut selections_iter = selections.iter().peekable();
9041 while let Some(selection) = selections_iter.next() {
9042 let mut rows = selection.spanned_rows(false, &display_map);
9043 // duplicate line-wise
9044 if whole_lines || selection.start == selection.end {
9045 // Avoid duplicating the same lines twice.
9046 while let Some(next_selection) = selections_iter.peek() {
9047 let next_rows = next_selection.spanned_rows(false, &display_map);
9048 if next_rows.start < rows.end {
9049 rows.end = next_rows.end;
9050 selections_iter.next().unwrap();
9051 } else {
9052 break;
9053 }
9054 }
9055
9056 // Copy the text from the selected row region and splice it either at the start
9057 // or end of the region.
9058 let start = Point::new(rows.start.0, 0);
9059 let end = Point::new(
9060 rows.end.previous_row().0,
9061 buffer.line_len(rows.end.previous_row()),
9062 );
9063 let text = buffer
9064 .text_for_range(start..end)
9065 .chain(Some("\n"))
9066 .collect::<String>();
9067 let insert_location = if upwards {
9068 Point::new(rows.end.0, 0)
9069 } else {
9070 start
9071 };
9072 edits.push((insert_location..insert_location, text));
9073 } else {
9074 // duplicate character-wise
9075 let start = selection.start;
9076 let end = selection.end;
9077 let text = buffer.text_for_range(start..end).collect::<String>();
9078 edits.push((selection.end..selection.end, text));
9079 }
9080 }
9081
9082 self.transact(window, cx, |this, _, cx| {
9083 this.buffer.update(cx, |buffer, cx| {
9084 buffer.edit(edits, None, cx);
9085 });
9086
9087 this.request_autoscroll(Autoscroll::fit(), cx);
9088 });
9089 }
9090
9091 pub fn duplicate_line_up(
9092 &mut self,
9093 _: &DuplicateLineUp,
9094 window: &mut Window,
9095 cx: &mut Context<Self>,
9096 ) {
9097 self.duplicate(true, true, window, cx);
9098 }
9099
9100 pub fn duplicate_line_down(
9101 &mut self,
9102 _: &DuplicateLineDown,
9103 window: &mut Window,
9104 cx: &mut Context<Self>,
9105 ) {
9106 self.duplicate(false, true, window, cx);
9107 }
9108
9109 pub fn duplicate_selection(
9110 &mut self,
9111 _: &DuplicateSelection,
9112 window: &mut Window,
9113 cx: &mut Context<Self>,
9114 ) {
9115 self.duplicate(false, false, window, cx);
9116 }
9117
9118 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9119 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9120 let buffer = self.buffer.read(cx).snapshot(cx);
9121
9122 let mut edits = Vec::new();
9123 let mut unfold_ranges = Vec::new();
9124 let mut refold_creases = Vec::new();
9125
9126 let selections = self.selections.all::<Point>(cx);
9127 let mut selections = selections.iter().peekable();
9128 let mut contiguous_row_selections = Vec::new();
9129 let mut new_selections = Vec::new();
9130
9131 while let Some(selection) = selections.next() {
9132 // Find all the selections that span a contiguous row range
9133 let (start_row, end_row) = consume_contiguous_rows(
9134 &mut contiguous_row_selections,
9135 selection,
9136 &display_map,
9137 &mut selections,
9138 );
9139
9140 // Move the text spanned by the row range to be before the line preceding the row range
9141 if start_row.0 > 0 {
9142 let range_to_move = Point::new(
9143 start_row.previous_row().0,
9144 buffer.line_len(start_row.previous_row()),
9145 )
9146 ..Point::new(
9147 end_row.previous_row().0,
9148 buffer.line_len(end_row.previous_row()),
9149 );
9150 let insertion_point = display_map
9151 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9152 .0;
9153
9154 // Don't move lines across excerpts
9155 if buffer
9156 .excerpt_containing(insertion_point..range_to_move.end)
9157 .is_some()
9158 {
9159 let text = buffer
9160 .text_for_range(range_to_move.clone())
9161 .flat_map(|s| s.chars())
9162 .skip(1)
9163 .chain(['\n'])
9164 .collect::<String>();
9165
9166 edits.push((
9167 buffer.anchor_after(range_to_move.start)
9168 ..buffer.anchor_before(range_to_move.end),
9169 String::new(),
9170 ));
9171 let insertion_anchor = buffer.anchor_after(insertion_point);
9172 edits.push((insertion_anchor..insertion_anchor, text));
9173
9174 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9175
9176 // Move selections up
9177 new_selections.extend(contiguous_row_selections.drain(..).map(
9178 |mut selection| {
9179 selection.start.row -= row_delta;
9180 selection.end.row -= row_delta;
9181 selection
9182 },
9183 ));
9184
9185 // Move folds up
9186 unfold_ranges.push(range_to_move.clone());
9187 for fold in display_map.folds_in_range(
9188 buffer.anchor_before(range_to_move.start)
9189 ..buffer.anchor_after(range_to_move.end),
9190 ) {
9191 let mut start = fold.range.start.to_point(&buffer);
9192 let mut end = fold.range.end.to_point(&buffer);
9193 start.row -= row_delta;
9194 end.row -= row_delta;
9195 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9196 }
9197 }
9198 }
9199
9200 // If we didn't move line(s), preserve the existing selections
9201 new_selections.append(&mut contiguous_row_selections);
9202 }
9203
9204 self.transact(window, cx, |this, window, cx| {
9205 this.unfold_ranges(&unfold_ranges, true, true, cx);
9206 this.buffer.update(cx, |buffer, cx| {
9207 for (range, text) in edits {
9208 buffer.edit([(range, text)], None, cx);
9209 }
9210 });
9211 this.fold_creases(refold_creases, true, window, cx);
9212 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9213 s.select(new_selections);
9214 })
9215 });
9216 }
9217
9218 pub fn move_line_down(
9219 &mut self,
9220 _: &MoveLineDown,
9221 window: &mut Window,
9222 cx: &mut Context<Self>,
9223 ) {
9224 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9225 let buffer = self.buffer.read(cx).snapshot(cx);
9226
9227 let mut edits = Vec::new();
9228 let mut unfold_ranges = Vec::new();
9229 let mut refold_creases = Vec::new();
9230
9231 let selections = self.selections.all::<Point>(cx);
9232 let mut selections = selections.iter().peekable();
9233 let mut contiguous_row_selections = Vec::new();
9234 let mut new_selections = Vec::new();
9235
9236 while let Some(selection) = selections.next() {
9237 // Find all the selections that span a contiguous row range
9238 let (start_row, end_row) = consume_contiguous_rows(
9239 &mut contiguous_row_selections,
9240 selection,
9241 &display_map,
9242 &mut selections,
9243 );
9244
9245 // Move the text spanned by the row range to be after the last line of the row range
9246 if end_row.0 <= buffer.max_point().row {
9247 let range_to_move =
9248 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9249 let insertion_point = display_map
9250 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9251 .0;
9252
9253 // Don't move lines across excerpt boundaries
9254 if buffer
9255 .excerpt_containing(range_to_move.start..insertion_point)
9256 .is_some()
9257 {
9258 let mut text = String::from("\n");
9259 text.extend(buffer.text_for_range(range_to_move.clone()));
9260 text.pop(); // Drop trailing newline
9261 edits.push((
9262 buffer.anchor_after(range_to_move.start)
9263 ..buffer.anchor_before(range_to_move.end),
9264 String::new(),
9265 ));
9266 let insertion_anchor = buffer.anchor_after(insertion_point);
9267 edits.push((insertion_anchor..insertion_anchor, text));
9268
9269 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9270
9271 // Move selections down
9272 new_selections.extend(contiguous_row_selections.drain(..).map(
9273 |mut selection| {
9274 selection.start.row += row_delta;
9275 selection.end.row += row_delta;
9276 selection
9277 },
9278 ));
9279
9280 // Move folds down
9281 unfold_ranges.push(range_to_move.clone());
9282 for fold in display_map.folds_in_range(
9283 buffer.anchor_before(range_to_move.start)
9284 ..buffer.anchor_after(range_to_move.end),
9285 ) {
9286 let mut start = fold.range.start.to_point(&buffer);
9287 let mut end = fold.range.end.to_point(&buffer);
9288 start.row += row_delta;
9289 end.row += row_delta;
9290 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9291 }
9292 }
9293 }
9294
9295 // If we didn't move line(s), preserve the existing selections
9296 new_selections.append(&mut contiguous_row_selections);
9297 }
9298
9299 self.transact(window, cx, |this, window, cx| {
9300 this.unfold_ranges(&unfold_ranges, true, true, cx);
9301 this.buffer.update(cx, |buffer, cx| {
9302 for (range, text) in edits {
9303 buffer.edit([(range, text)], None, cx);
9304 }
9305 });
9306 this.fold_creases(refold_creases, true, window, cx);
9307 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9308 s.select(new_selections)
9309 });
9310 });
9311 }
9312
9313 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9314 let text_layout_details = &self.text_layout_details(window);
9315 self.transact(window, cx, |this, window, cx| {
9316 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9317 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9318 let line_mode = s.line_mode;
9319 s.move_with(|display_map, selection| {
9320 if !selection.is_empty() || line_mode {
9321 return;
9322 }
9323
9324 let mut head = selection.head();
9325 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9326 if head.column() == display_map.line_len(head.row()) {
9327 transpose_offset = display_map
9328 .buffer_snapshot
9329 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9330 }
9331
9332 if transpose_offset == 0 {
9333 return;
9334 }
9335
9336 *head.column_mut() += 1;
9337 head = display_map.clip_point(head, Bias::Right);
9338 let goal = SelectionGoal::HorizontalPosition(
9339 display_map
9340 .x_for_display_point(head, text_layout_details)
9341 .into(),
9342 );
9343 selection.collapse_to(head, goal);
9344
9345 let transpose_start = display_map
9346 .buffer_snapshot
9347 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9348 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9349 let transpose_end = display_map
9350 .buffer_snapshot
9351 .clip_offset(transpose_offset + 1, Bias::Right);
9352 if let Some(ch) =
9353 display_map.buffer_snapshot.chars_at(transpose_start).next()
9354 {
9355 edits.push((transpose_start..transpose_offset, String::new()));
9356 edits.push((transpose_end..transpose_end, ch.to_string()));
9357 }
9358 }
9359 });
9360 edits
9361 });
9362 this.buffer
9363 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9364 let selections = this.selections.all::<usize>(cx);
9365 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9366 s.select(selections);
9367 });
9368 });
9369 }
9370
9371 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9372 self.rewrap_impl(RewrapOptions::default(), cx)
9373 }
9374
9375 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9376 let buffer = self.buffer.read(cx).snapshot(cx);
9377 let selections = self.selections.all::<Point>(cx);
9378 let mut selections = selections.iter().peekable();
9379
9380 let mut edits = Vec::new();
9381 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9382
9383 while let Some(selection) = selections.next() {
9384 let mut start_row = selection.start.row;
9385 let mut end_row = selection.end.row;
9386
9387 // Skip selections that overlap with a range that has already been rewrapped.
9388 let selection_range = start_row..end_row;
9389 if rewrapped_row_ranges
9390 .iter()
9391 .any(|range| range.overlaps(&selection_range))
9392 {
9393 continue;
9394 }
9395
9396 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9397
9398 // Since not all lines in the selection may be at the same indent
9399 // level, choose the indent size that is the most common between all
9400 // of the lines.
9401 //
9402 // If there is a tie, we use the deepest indent.
9403 let (indent_size, indent_end) = {
9404 let mut indent_size_occurrences = HashMap::default();
9405 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9406
9407 for row in start_row..=end_row {
9408 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9409 rows_by_indent_size.entry(indent).or_default().push(row);
9410 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9411 }
9412
9413 let indent_size = indent_size_occurrences
9414 .into_iter()
9415 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9416 .map(|(indent, _)| indent)
9417 .unwrap_or_default();
9418 let row = rows_by_indent_size[&indent_size][0];
9419 let indent_end = Point::new(row, indent_size.len);
9420
9421 (indent_size, indent_end)
9422 };
9423
9424 let mut line_prefix = indent_size.chars().collect::<String>();
9425
9426 let mut inside_comment = false;
9427 if let Some(comment_prefix) =
9428 buffer
9429 .language_scope_at(selection.head())
9430 .and_then(|language| {
9431 language
9432 .line_comment_prefixes()
9433 .iter()
9434 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9435 .cloned()
9436 })
9437 {
9438 line_prefix.push_str(&comment_prefix);
9439 inside_comment = true;
9440 }
9441
9442 let language_settings = buffer.language_settings_at(selection.head(), cx);
9443 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9444 RewrapBehavior::InComments => inside_comment,
9445 RewrapBehavior::InSelections => !selection.is_empty(),
9446 RewrapBehavior::Anywhere => true,
9447 };
9448
9449 let should_rewrap = options.override_language_settings
9450 || allow_rewrap_based_on_language
9451 || self.hard_wrap.is_some();
9452 if !should_rewrap {
9453 continue;
9454 }
9455
9456 if selection.is_empty() {
9457 'expand_upwards: while start_row > 0 {
9458 let prev_row = start_row - 1;
9459 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9460 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9461 {
9462 start_row = prev_row;
9463 } else {
9464 break 'expand_upwards;
9465 }
9466 }
9467
9468 'expand_downwards: while end_row < buffer.max_point().row {
9469 let next_row = end_row + 1;
9470 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9471 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9472 {
9473 end_row = next_row;
9474 } else {
9475 break 'expand_downwards;
9476 }
9477 }
9478 }
9479
9480 let start = Point::new(start_row, 0);
9481 let start_offset = start.to_offset(&buffer);
9482 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9483 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9484 let Some(lines_without_prefixes) = selection_text
9485 .lines()
9486 .map(|line| {
9487 line.strip_prefix(&line_prefix)
9488 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9489 .ok_or_else(|| {
9490 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9491 })
9492 })
9493 .collect::<Result<Vec<_>, _>>()
9494 .log_err()
9495 else {
9496 continue;
9497 };
9498
9499 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9500 buffer
9501 .language_settings_at(Point::new(start_row, 0), cx)
9502 .preferred_line_length as usize
9503 });
9504 let wrapped_text = wrap_with_prefix(
9505 line_prefix,
9506 lines_without_prefixes.join("\n"),
9507 wrap_column,
9508 tab_size,
9509 options.preserve_existing_whitespace,
9510 );
9511
9512 // TODO: should always use char-based diff while still supporting cursor behavior that
9513 // matches vim.
9514 let mut diff_options = DiffOptions::default();
9515 if options.override_language_settings {
9516 diff_options.max_word_diff_len = 0;
9517 diff_options.max_word_diff_line_count = 0;
9518 } else {
9519 diff_options.max_word_diff_len = usize::MAX;
9520 diff_options.max_word_diff_line_count = usize::MAX;
9521 }
9522
9523 for (old_range, new_text) in
9524 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9525 {
9526 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9527 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9528 edits.push((edit_start..edit_end, new_text));
9529 }
9530
9531 rewrapped_row_ranges.push(start_row..=end_row);
9532 }
9533
9534 self.buffer
9535 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9536 }
9537
9538 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9539 let mut text = String::new();
9540 let buffer = self.buffer.read(cx).snapshot(cx);
9541 let mut selections = self.selections.all::<Point>(cx);
9542 let mut clipboard_selections = Vec::with_capacity(selections.len());
9543 {
9544 let max_point = buffer.max_point();
9545 let mut is_first = true;
9546 for selection in &mut selections {
9547 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9548 if is_entire_line {
9549 selection.start = Point::new(selection.start.row, 0);
9550 if !selection.is_empty() && selection.end.column == 0 {
9551 selection.end = cmp::min(max_point, selection.end);
9552 } else {
9553 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9554 }
9555 selection.goal = SelectionGoal::None;
9556 }
9557 if is_first {
9558 is_first = false;
9559 } else {
9560 text += "\n";
9561 }
9562 let mut len = 0;
9563 for chunk in buffer.text_for_range(selection.start..selection.end) {
9564 text.push_str(chunk);
9565 len += chunk.len();
9566 }
9567 clipboard_selections.push(ClipboardSelection {
9568 len,
9569 is_entire_line,
9570 first_line_indent: buffer
9571 .indent_size_for_line(MultiBufferRow(selection.start.row))
9572 .len,
9573 });
9574 }
9575 }
9576
9577 self.transact(window, cx, |this, window, cx| {
9578 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9579 s.select(selections);
9580 });
9581 this.insert("", window, cx);
9582 });
9583 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9584 }
9585
9586 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9587 let item = self.cut_common(window, cx);
9588 cx.write_to_clipboard(item);
9589 }
9590
9591 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9592 self.change_selections(None, window, cx, |s| {
9593 s.move_with(|snapshot, sel| {
9594 if sel.is_empty() {
9595 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9596 }
9597 });
9598 });
9599 let item = self.cut_common(window, cx);
9600 cx.set_global(KillRing(item))
9601 }
9602
9603 pub fn kill_ring_yank(
9604 &mut self,
9605 _: &KillRingYank,
9606 window: &mut Window,
9607 cx: &mut Context<Self>,
9608 ) {
9609 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9610 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9611 (kill_ring.text().to_string(), kill_ring.metadata_json())
9612 } else {
9613 return;
9614 }
9615 } else {
9616 return;
9617 };
9618 self.do_paste(&text, metadata, false, window, cx);
9619 }
9620
9621 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9622 self.do_copy(true, cx);
9623 }
9624
9625 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9626 self.do_copy(false, cx);
9627 }
9628
9629 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9630 let selections = self.selections.all::<Point>(cx);
9631 let buffer = self.buffer.read(cx).read(cx);
9632 let mut text = String::new();
9633
9634 let mut clipboard_selections = Vec::with_capacity(selections.len());
9635 {
9636 let max_point = buffer.max_point();
9637 let mut is_first = true;
9638 for selection in &selections {
9639 let mut start = selection.start;
9640 let mut end = selection.end;
9641 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9642 if is_entire_line {
9643 start = Point::new(start.row, 0);
9644 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9645 }
9646
9647 let mut trimmed_selections = Vec::new();
9648 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9649 let row = MultiBufferRow(start.row);
9650 let first_indent = buffer.indent_size_for_line(row);
9651 if first_indent.len == 0 || start.column > first_indent.len {
9652 trimmed_selections.push(start..end);
9653 } else {
9654 trimmed_selections.push(
9655 Point::new(row.0, first_indent.len)
9656 ..Point::new(row.0, buffer.line_len(row)),
9657 );
9658 for row in start.row + 1..=end.row {
9659 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9660 if row_indent_size.len >= first_indent.len {
9661 trimmed_selections.push(
9662 Point::new(row, first_indent.len)
9663 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9664 );
9665 } else {
9666 trimmed_selections.clear();
9667 trimmed_selections.push(start..end);
9668 break;
9669 }
9670 }
9671 }
9672 } else {
9673 trimmed_selections.push(start..end);
9674 }
9675
9676 for trimmed_range in trimmed_selections {
9677 if is_first {
9678 is_first = false;
9679 } else {
9680 text += "\n";
9681 }
9682 let mut len = 0;
9683 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9684 text.push_str(chunk);
9685 len += chunk.len();
9686 }
9687 clipboard_selections.push(ClipboardSelection {
9688 len,
9689 is_entire_line,
9690 first_line_indent: buffer
9691 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9692 .len,
9693 });
9694 }
9695 }
9696 }
9697
9698 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9699 text,
9700 clipboard_selections,
9701 ));
9702 }
9703
9704 pub fn do_paste(
9705 &mut self,
9706 text: &String,
9707 clipboard_selections: Option<Vec<ClipboardSelection>>,
9708 handle_entire_lines: bool,
9709 window: &mut Window,
9710 cx: &mut Context<Self>,
9711 ) {
9712 if self.read_only(cx) {
9713 return;
9714 }
9715
9716 let clipboard_text = Cow::Borrowed(text);
9717
9718 self.transact(window, cx, |this, window, cx| {
9719 if let Some(mut clipboard_selections) = clipboard_selections {
9720 let old_selections = this.selections.all::<usize>(cx);
9721 let all_selections_were_entire_line =
9722 clipboard_selections.iter().all(|s| s.is_entire_line);
9723 let first_selection_indent_column =
9724 clipboard_selections.first().map(|s| s.first_line_indent);
9725 if clipboard_selections.len() != old_selections.len() {
9726 clipboard_selections.drain(..);
9727 }
9728 let cursor_offset = this.selections.last::<usize>(cx).head();
9729 let mut auto_indent_on_paste = true;
9730
9731 this.buffer.update(cx, |buffer, cx| {
9732 let snapshot = buffer.read(cx);
9733 auto_indent_on_paste = snapshot
9734 .language_settings_at(cursor_offset, cx)
9735 .auto_indent_on_paste;
9736
9737 let mut start_offset = 0;
9738 let mut edits = Vec::new();
9739 let mut original_indent_columns = Vec::new();
9740 for (ix, selection) in old_selections.iter().enumerate() {
9741 let to_insert;
9742 let entire_line;
9743 let original_indent_column;
9744 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
9745 let end_offset = start_offset + clipboard_selection.len;
9746 to_insert = &clipboard_text[start_offset..end_offset];
9747 entire_line = clipboard_selection.is_entire_line;
9748 start_offset = end_offset + 1;
9749 original_indent_column = Some(clipboard_selection.first_line_indent);
9750 } else {
9751 to_insert = clipboard_text.as_str();
9752 entire_line = all_selections_were_entire_line;
9753 original_indent_column = first_selection_indent_column
9754 }
9755
9756 // If the corresponding selection was empty when this slice of the
9757 // clipboard text was written, then the entire line containing the
9758 // selection was copied. If this selection is also currently empty,
9759 // then paste the line before the current line of the buffer.
9760 let range = if selection.is_empty() && handle_entire_lines && entire_line {
9761 let column = selection.start.to_point(&snapshot).column as usize;
9762 let line_start = selection.start - column;
9763 line_start..line_start
9764 } else {
9765 selection.range()
9766 };
9767
9768 edits.push((range, to_insert));
9769 original_indent_columns.push(original_indent_column);
9770 }
9771 drop(snapshot);
9772
9773 buffer.edit(
9774 edits,
9775 if auto_indent_on_paste {
9776 Some(AutoindentMode::Block {
9777 original_indent_columns,
9778 })
9779 } else {
9780 None
9781 },
9782 cx,
9783 );
9784 });
9785
9786 let selections = this.selections.all::<usize>(cx);
9787 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9788 s.select(selections)
9789 });
9790 } else {
9791 this.insert(&clipboard_text, window, cx);
9792 }
9793 });
9794 }
9795
9796 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
9797 if let Some(item) = cx.read_from_clipboard() {
9798 let entries = item.entries();
9799
9800 match entries.first() {
9801 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
9802 // of all the pasted entries.
9803 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9804 .do_paste(
9805 clipboard_string.text(),
9806 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9807 true,
9808 window,
9809 cx,
9810 ),
9811 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9812 }
9813 }
9814 }
9815
9816 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9817 if self.read_only(cx) {
9818 return;
9819 }
9820
9821 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9822 if let Some((selections, _)) =
9823 self.selection_history.transaction(transaction_id).cloned()
9824 {
9825 self.change_selections(None, window, cx, |s| {
9826 s.select_anchors(selections.to_vec());
9827 });
9828 } else {
9829 log::error!(
9830 "No entry in selection_history found for undo. \
9831 This may correspond to a bug where undo does not update the selection. \
9832 If this is occurring, please add details to \
9833 https://github.com/zed-industries/zed/issues/22692"
9834 );
9835 }
9836 self.request_autoscroll(Autoscroll::fit(), cx);
9837 self.unmark_text(window, cx);
9838 self.refresh_inline_completion(true, false, window, cx);
9839 cx.emit(EditorEvent::Edited { transaction_id });
9840 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9841 }
9842 }
9843
9844 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9845 if self.read_only(cx) {
9846 return;
9847 }
9848
9849 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9850 if let Some((_, Some(selections))) =
9851 self.selection_history.transaction(transaction_id).cloned()
9852 {
9853 self.change_selections(None, window, cx, |s| {
9854 s.select_anchors(selections.to_vec());
9855 });
9856 } else {
9857 log::error!(
9858 "No entry in selection_history found for redo. \
9859 This may correspond to a bug where undo does not update the selection. \
9860 If this is occurring, please add details to \
9861 https://github.com/zed-industries/zed/issues/22692"
9862 );
9863 }
9864 self.request_autoscroll(Autoscroll::fit(), cx);
9865 self.unmark_text(window, cx);
9866 self.refresh_inline_completion(true, false, window, cx);
9867 cx.emit(EditorEvent::Edited { transaction_id });
9868 }
9869 }
9870
9871 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9872 self.buffer
9873 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9874 }
9875
9876 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9877 self.buffer
9878 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9879 }
9880
9881 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9882 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9883 let line_mode = s.line_mode;
9884 s.move_with(|map, selection| {
9885 let cursor = if selection.is_empty() && !line_mode {
9886 movement::left(map, selection.start)
9887 } else {
9888 selection.start
9889 };
9890 selection.collapse_to(cursor, SelectionGoal::None);
9891 });
9892 })
9893 }
9894
9895 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9896 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9897 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9898 })
9899 }
9900
9901 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9902 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9903 let line_mode = s.line_mode;
9904 s.move_with(|map, selection| {
9905 let cursor = if selection.is_empty() && !line_mode {
9906 movement::right(map, selection.end)
9907 } else {
9908 selection.end
9909 };
9910 selection.collapse_to(cursor, SelectionGoal::None)
9911 });
9912 })
9913 }
9914
9915 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9916 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9917 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9918 })
9919 }
9920
9921 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9922 if self.take_rename(true, window, cx).is_some() {
9923 return;
9924 }
9925
9926 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9927 cx.propagate();
9928 return;
9929 }
9930
9931 let text_layout_details = &self.text_layout_details(window);
9932 let selection_count = self.selections.count();
9933 let first_selection = self.selections.first_anchor();
9934
9935 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9936 let line_mode = s.line_mode;
9937 s.move_with(|map, selection| {
9938 if !selection.is_empty() && !line_mode {
9939 selection.goal = SelectionGoal::None;
9940 }
9941 let (cursor, goal) = movement::up(
9942 map,
9943 selection.start,
9944 selection.goal,
9945 false,
9946 text_layout_details,
9947 );
9948 selection.collapse_to(cursor, goal);
9949 });
9950 });
9951
9952 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9953 {
9954 cx.propagate();
9955 }
9956 }
9957
9958 pub fn move_up_by_lines(
9959 &mut self,
9960 action: &MoveUpByLines,
9961 window: &mut Window,
9962 cx: &mut Context<Self>,
9963 ) {
9964 if self.take_rename(true, window, cx).is_some() {
9965 return;
9966 }
9967
9968 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9969 cx.propagate();
9970 return;
9971 }
9972
9973 let text_layout_details = &self.text_layout_details(window);
9974
9975 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9976 let line_mode = s.line_mode;
9977 s.move_with(|map, selection| {
9978 if !selection.is_empty() && !line_mode {
9979 selection.goal = SelectionGoal::None;
9980 }
9981 let (cursor, goal) = movement::up_by_rows(
9982 map,
9983 selection.start,
9984 action.lines,
9985 selection.goal,
9986 false,
9987 text_layout_details,
9988 );
9989 selection.collapse_to(cursor, goal);
9990 });
9991 })
9992 }
9993
9994 pub fn move_down_by_lines(
9995 &mut self,
9996 action: &MoveDownByLines,
9997 window: &mut Window,
9998 cx: &mut Context<Self>,
9999 ) {
10000 if self.take_rename(true, window, cx).is_some() {
10001 return;
10002 }
10003
10004 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10005 cx.propagate();
10006 return;
10007 }
10008
10009 let text_layout_details = &self.text_layout_details(window);
10010
10011 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10012 let line_mode = s.line_mode;
10013 s.move_with(|map, selection| {
10014 if !selection.is_empty() && !line_mode {
10015 selection.goal = SelectionGoal::None;
10016 }
10017 let (cursor, goal) = movement::down_by_rows(
10018 map,
10019 selection.start,
10020 action.lines,
10021 selection.goal,
10022 false,
10023 text_layout_details,
10024 );
10025 selection.collapse_to(cursor, goal);
10026 });
10027 })
10028 }
10029
10030 pub fn select_down_by_lines(
10031 &mut self,
10032 action: &SelectDownByLines,
10033 window: &mut Window,
10034 cx: &mut Context<Self>,
10035 ) {
10036 let text_layout_details = &self.text_layout_details(window);
10037 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10038 s.move_heads_with(|map, head, goal| {
10039 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10040 })
10041 })
10042 }
10043
10044 pub fn select_up_by_lines(
10045 &mut self,
10046 action: &SelectUpByLines,
10047 window: &mut Window,
10048 cx: &mut Context<Self>,
10049 ) {
10050 let text_layout_details = &self.text_layout_details(window);
10051 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10052 s.move_heads_with(|map, head, goal| {
10053 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10054 })
10055 })
10056 }
10057
10058 pub fn select_page_up(
10059 &mut self,
10060 _: &SelectPageUp,
10061 window: &mut Window,
10062 cx: &mut Context<Self>,
10063 ) {
10064 let Some(row_count) = self.visible_row_count() else {
10065 return;
10066 };
10067
10068 let text_layout_details = &self.text_layout_details(window);
10069
10070 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10071 s.move_heads_with(|map, head, goal| {
10072 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10073 })
10074 })
10075 }
10076
10077 pub fn move_page_up(
10078 &mut self,
10079 action: &MovePageUp,
10080 window: &mut Window,
10081 cx: &mut Context<Self>,
10082 ) {
10083 if self.take_rename(true, window, cx).is_some() {
10084 return;
10085 }
10086
10087 if self
10088 .context_menu
10089 .borrow_mut()
10090 .as_mut()
10091 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10092 .unwrap_or(false)
10093 {
10094 return;
10095 }
10096
10097 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10098 cx.propagate();
10099 return;
10100 }
10101
10102 let Some(row_count) = self.visible_row_count() else {
10103 return;
10104 };
10105
10106 let autoscroll = if action.center_cursor {
10107 Autoscroll::center()
10108 } else {
10109 Autoscroll::fit()
10110 };
10111
10112 let text_layout_details = &self.text_layout_details(window);
10113
10114 self.change_selections(Some(autoscroll), window, cx, |s| {
10115 let line_mode = s.line_mode;
10116 s.move_with(|map, selection| {
10117 if !selection.is_empty() && !line_mode {
10118 selection.goal = SelectionGoal::None;
10119 }
10120 let (cursor, goal) = movement::up_by_rows(
10121 map,
10122 selection.end,
10123 row_count,
10124 selection.goal,
10125 false,
10126 text_layout_details,
10127 );
10128 selection.collapse_to(cursor, goal);
10129 });
10130 });
10131 }
10132
10133 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10134 let text_layout_details = &self.text_layout_details(window);
10135 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10136 s.move_heads_with(|map, head, goal| {
10137 movement::up(map, head, goal, false, text_layout_details)
10138 })
10139 })
10140 }
10141
10142 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10143 self.take_rename(true, window, cx);
10144
10145 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10146 cx.propagate();
10147 return;
10148 }
10149
10150 let text_layout_details = &self.text_layout_details(window);
10151 let selection_count = self.selections.count();
10152 let first_selection = self.selections.first_anchor();
10153
10154 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10155 let line_mode = s.line_mode;
10156 s.move_with(|map, selection| {
10157 if !selection.is_empty() && !line_mode {
10158 selection.goal = SelectionGoal::None;
10159 }
10160 let (cursor, goal) = movement::down(
10161 map,
10162 selection.end,
10163 selection.goal,
10164 false,
10165 text_layout_details,
10166 );
10167 selection.collapse_to(cursor, goal);
10168 });
10169 });
10170
10171 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10172 {
10173 cx.propagate();
10174 }
10175 }
10176
10177 pub fn select_page_down(
10178 &mut self,
10179 _: &SelectPageDown,
10180 window: &mut Window,
10181 cx: &mut Context<Self>,
10182 ) {
10183 let Some(row_count) = self.visible_row_count() else {
10184 return;
10185 };
10186
10187 let text_layout_details = &self.text_layout_details(window);
10188
10189 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10190 s.move_heads_with(|map, head, goal| {
10191 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10192 })
10193 })
10194 }
10195
10196 pub fn move_page_down(
10197 &mut self,
10198 action: &MovePageDown,
10199 window: &mut Window,
10200 cx: &mut Context<Self>,
10201 ) {
10202 if self.take_rename(true, window, cx).is_some() {
10203 return;
10204 }
10205
10206 if self
10207 .context_menu
10208 .borrow_mut()
10209 .as_mut()
10210 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10211 .unwrap_or(false)
10212 {
10213 return;
10214 }
10215
10216 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10217 cx.propagate();
10218 return;
10219 }
10220
10221 let Some(row_count) = self.visible_row_count() else {
10222 return;
10223 };
10224
10225 let autoscroll = if action.center_cursor {
10226 Autoscroll::center()
10227 } else {
10228 Autoscroll::fit()
10229 };
10230
10231 let text_layout_details = &self.text_layout_details(window);
10232 self.change_selections(Some(autoscroll), window, cx, |s| {
10233 let line_mode = s.line_mode;
10234 s.move_with(|map, selection| {
10235 if !selection.is_empty() && !line_mode {
10236 selection.goal = SelectionGoal::None;
10237 }
10238 let (cursor, goal) = movement::down_by_rows(
10239 map,
10240 selection.end,
10241 row_count,
10242 selection.goal,
10243 false,
10244 text_layout_details,
10245 );
10246 selection.collapse_to(cursor, goal);
10247 });
10248 });
10249 }
10250
10251 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10252 let text_layout_details = &self.text_layout_details(window);
10253 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10254 s.move_heads_with(|map, head, goal| {
10255 movement::down(map, head, goal, false, text_layout_details)
10256 })
10257 });
10258 }
10259
10260 pub fn context_menu_first(
10261 &mut self,
10262 _: &ContextMenuFirst,
10263 _window: &mut Window,
10264 cx: &mut Context<Self>,
10265 ) {
10266 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10267 context_menu.select_first(self.completion_provider.as_deref(), cx);
10268 }
10269 }
10270
10271 pub fn context_menu_prev(
10272 &mut self,
10273 _: &ContextMenuPrevious,
10274 _window: &mut Window,
10275 cx: &mut Context<Self>,
10276 ) {
10277 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10278 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10279 }
10280 }
10281
10282 pub fn context_menu_next(
10283 &mut self,
10284 _: &ContextMenuNext,
10285 _window: &mut Window,
10286 cx: &mut Context<Self>,
10287 ) {
10288 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10289 context_menu.select_next(self.completion_provider.as_deref(), cx);
10290 }
10291 }
10292
10293 pub fn context_menu_last(
10294 &mut self,
10295 _: &ContextMenuLast,
10296 _window: &mut Window,
10297 cx: &mut Context<Self>,
10298 ) {
10299 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10300 context_menu.select_last(self.completion_provider.as_deref(), cx);
10301 }
10302 }
10303
10304 pub fn move_to_previous_word_start(
10305 &mut self,
10306 _: &MoveToPreviousWordStart,
10307 window: &mut Window,
10308 cx: &mut Context<Self>,
10309 ) {
10310 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10311 s.move_cursors_with(|map, head, _| {
10312 (
10313 movement::previous_word_start(map, head),
10314 SelectionGoal::None,
10315 )
10316 });
10317 })
10318 }
10319
10320 pub fn move_to_previous_subword_start(
10321 &mut self,
10322 _: &MoveToPreviousSubwordStart,
10323 window: &mut Window,
10324 cx: &mut Context<Self>,
10325 ) {
10326 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10327 s.move_cursors_with(|map, head, _| {
10328 (
10329 movement::previous_subword_start(map, head),
10330 SelectionGoal::None,
10331 )
10332 });
10333 })
10334 }
10335
10336 pub fn select_to_previous_word_start(
10337 &mut self,
10338 _: &SelectToPreviousWordStart,
10339 window: &mut Window,
10340 cx: &mut Context<Self>,
10341 ) {
10342 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10343 s.move_heads_with(|map, head, _| {
10344 (
10345 movement::previous_word_start(map, head),
10346 SelectionGoal::None,
10347 )
10348 });
10349 })
10350 }
10351
10352 pub fn select_to_previous_subword_start(
10353 &mut self,
10354 _: &SelectToPreviousSubwordStart,
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 (
10361 movement::previous_subword_start(map, head),
10362 SelectionGoal::None,
10363 )
10364 });
10365 })
10366 }
10367
10368 pub fn delete_to_previous_word_start(
10369 &mut self,
10370 action: &DeleteToPreviousWordStart,
10371 window: &mut Window,
10372 cx: &mut Context<Self>,
10373 ) {
10374 self.transact(window, cx, |this, window, cx| {
10375 this.select_autoclose_pair(window, cx);
10376 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10377 let line_mode = s.line_mode;
10378 s.move_with(|map, selection| {
10379 if selection.is_empty() && !line_mode {
10380 let cursor = if action.ignore_newlines {
10381 movement::previous_word_start(map, selection.head())
10382 } else {
10383 movement::previous_word_start_or_newline(map, selection.head())
10384 };
10385 selection.set_head(cursor, SelectionGoal::None);
10386 }
10387 });
10388 });
10389 this.insert("", window, cx);
10390 });
10391 }
10392
10393 pub fn delete_to_previous_subword_start(
10394 &mut self,
10395 _: &DeleteToPreviousSubwordStart,
10396 window: &mut Window,
10397 cx: &mut Context<Self>,
10398 ) {
10399 self.transact(window, cx, |this, window, cx| {
10400 this.select_autoclose_pair(window, cx);
10401 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10402 let line_mode = s.line_mode;
10403 s.move_with(|map, selection| {
10404 if selection.is_empty() && !line_mode {
10405 let cursor = movement::previous_subword_start(map, selection.head());
10406 selection.set_head(cursor, SelectionGoal::None);
10407 }
10408 });
10409 });
10410 this.insert("", window, cx);
10411 });
10412 }
10413
10414 pub fn move_to_next_word_end(
10415 &mut self,
10416 _: &MoveToNextWordEnd,
10417 window: &mut Window,
10418 cx: &mut Context<Self>,
10419 ) {
10420 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10421 s.move_cursors_with(|map, head, _| {
10422 (movement::next_word_end(map, head), SelectionGoal::None)
10423 });
10424 })
10425 }
10426
10427 pub fn move_to_next_subword_end(
10428 &mut self,
10429 _: &MoveToNextSubwordEnd,
10430 window: &mut Window,
10431 cx: &mut Context<Self>,
10432 ) {
10433 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10434 s.move_cursors_with(|map, head, _| {
10435 (movement::next_subword_end(map, head), SelectionGoal::None)
10436 });
10437 })
10438 }
10439
10440 pub fn select_to_next_word_end(
10441 &mut self,
10442 _: &SelectToNextWordEnd,
10443 window: &mut Window,
10444 cx: &mut Context<Self>,
10445 ) {
10446 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10447 s.move_heads_with(|map, head, _| {
10448 (movement::next_word_end(map, head), SelectionGoal::None)
10449 });
10450 })
10451 }
10452
10453 pub fn select_to_next_subword_end(
10454 &mut self,
10455 _: &SelectToNextSubwordEnd,
10456 window: &mut Window,
10457 cx: &mut Context<Self>,
10458 ) {
10459 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10460 s.move_heads_with(|map, head, _| {
10461 (movement::next_subword_end(map, head), SelectionGoal::None)
10462 });
10463 })
10464 }
10465
10466 pub fn delete_to_next_word_end(
10467 &mut self,
10468 action: &DeleteToNextWordEnd,
10469 window: &mut Window,
10470 cx: &mut Context<Self>,
10471 ) {
10472 self.transact(window, cx, |this, window, cx| {
10473 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10474 let line_mode = s.line_mode;
10475 s.move_with(|map, selection| {
10476 if selection.is_empty() && !line_mode {
10477 let cursor = if action.ignore_newlines {
10478 movement::next_word_end(map, selection.head())
10479 } else {
10480 movement::next_word_end_or_newline(map, selection.head())
10481 };
10482 selection.set_head(cursor, SelectionGoal::None);
10483 }
10484 });
10485 });
10486 this.insert("", window, cx);
10487 });
10488 }
10489
10490 pub fn delete_to_next_subword_end(
10491 &mut self,
10492 _: &DeleteToNextSubwordEnd,
10493 window: &mut Window,
10494 cx: &mut Context<Self>,
10495 ) {
10496 self.transact(window, cx, |this, window, cx| {
10497 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10498 s.move_with(|map, selection| {
10499 if selection.is_empty() {
10500 let cursor = movement::next_subword_end(map, selection.head());
10501 selection.set_head(cursor, SelectionGoal::None);
10502 }
10503 });
10504 });
10505 this.insert("", window, cx);
10506 });
10507 }
10508
10509 pub fn move_to_beginning_of_line(
10510 &mut self,
10511 action: &MoveToBeginningOfLine,
10512 window: &mut Window,
10513 cx: &mut Context<Self>,
10514 ) {
10515 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10516 s.move_cursors_with(|map, head, _| {
10517 (
10518 movement::indented_line_beginning(
10519 map,
10520 head,
10521 action.stop_at_soft_wraps,
10522 action.stop_at_indent,
10523 ),
10524 SelectionGoal::None,
10525 )
10526 });
10527 })
10528 }
10529
10530 pub fn select_to_beginning_of_line(
10531 &mut self,
10532 action: &SelectToBeginningOfLine,
10533 window: &mut Window,
10534 cx: &mut Context<Self>,
10535 ) {
10536 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10537 s.move_heads_with(|map, head, _| {
10538 (
10539 movement::indented_line_beginning(
10540 map,
10541 head,
10542 action.stop_at_soft_wraps,
10543 action.stop_at_indent,
10544 ),
10545 SelectionGoal::None,
10546 )
10547 });
10548 });
10549 }
10550
10551 pub fn delete_to_beginning_of_line(
10552 &mut self,
10553 action: &DeleteToBeginningOfLine,
10554 window: &mut Window,
10555 cx: &mut Context<Self>,
10556 ) {
10557 self.transact(window, cx, |this, window, cx| {
10558 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10559 s.move_with(|_, selection| {
10560 selection.reversed = true;
10561 });
10562 });
10563
10564 this.select_to_beginning_of_line(
10565 &SelectToBeginningOfLine {
10566 stop_at_soft_wraps: false,
10567 stop_at_indent: action.stop_at_indent,
10568 },
10569 window,
10570 cx,
10571 );
10572 this.backspace(&Backspace, window, cx);
10573 });
10574 }
10575
10576 pub fn move_to_end_of_line(
10577 &mut self,
10578 action: &MoveToEndOfLine,
10579 window: &mut Window,
10580 cx: &mut Context<Self>,
10581 ) {
10582 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10583 s.move_cursors_with(|map, head, _| {
10584 (
10585 movement::line_end(map, head, action.stop_at_soft_wraps),
10586 SelectionGoal::None,
10587 )
10588 });
10589 })
10590 }
10591
10592 pub fn select_to_end_of_line(
10593 &mut self,
10594 action: &SelectToEndOfLine,
10595 window: &mut Window,
10596 cx: &mut Context<Self>,
10597 ) {
10598 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10599 s.move_heads_with(|map, head, _| {
10600 (
10601 movement::line_end(map, head, action.stop_at_soft_wraps),
10602 SelectionGoal::None,
10603 )
10604 });
10605 })
10606 }
10607
10608 pub fn delete_to_end_of_line(
10609 &mut self,
10610 _: &DeleteToEndOfLine,
10611 window: &mut Window,
10612 cx: &mut Context<Self>,
10613 ) {
10614 self.transact(window, cx, |this, window, cx| {
10615 this.select_to_end_of_line(
10616 &SelectToEndOfLine {
10617 stop_at_soft_wraps: false,
10618 },
10619 window,
10620 cx,
10621 );
10622 this.delete(&Delete, window, cx);
10623 });
10624 }
10625
10626 pub fn cut_to_end_of_line(
10627 &mut self,
10628 _: &CutToEndOfLine,
10629 window: &mut Window,
10630 cx: &mut Context<Self>,
10631 ) {
10632 self.transact(window, cx, |this, window, cx| {
10633 this.select_to_end_of_line(
10634 &SelectToEndOfLine {
10635 stop_at_soft_wraps: false,
10636 },
10637 window,
10638 cx,
10639 );
10640 this.cut(&Cut, window, cx);
10641 });
10642 }
10643
10644 pub fn move_to_start_of_paragraph(
10645 &mut self,
10646 _: &MoveToStartOfParagraph,
10647 window: &mut Window,
10648 cx: &mut Context<Self>,
10649 ) {
10650 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10651 cx.propagate();
10652 return;
10653 }
10654
10655 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10656 s.move_with(|map, selection| {
10657 selection.collapse_to(
10658 movement::start_of_paragraph(map, selection.head(), 1),
10659 SelectionGoal::None,
10660 )
10661 });
10662 })
10663 }
10664
10665 pub fn move_to_end_of_paragraph(
10666 &mut self,
10667 _: &MoveToEndOfParagraph,
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::end_of_paragraph(map, selection.head(), 1),
10680 SelectionGoal::None,
10681 )
10682 });
10683 })
10684 }
10685
10686 pub fn select_to_start_of_paragraph(
10687 &mut self,
10688 _: &SelectToStartOfParagraph,
10689 window: &mut Window,
10690 cx: &mut Context<Self>,
10691 ) {
10692 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10693 cx.propagate();
10694 return;
10695 }
10696
10697 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10698 s.move_heads_with(|map, head, _| {
10699 (
10700 movement::start_of_paragraph(map, head, 1),
10701 SelectionGoal::None,
10702 )
10703 });
10704 })
10705 }
10706
10707 pub fn select_to_end_of_paragraph(
10708 &mut self,
10709 _: &SelectToEndOfParagraph,
10710 window: &mut Window,
10711 cx: &mut Context<Self>,
10712 ) {
10713 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10714 cx.propagate();
10715 return;
10716 }
10717
10718 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10719 s.move_heads_with(|map, head, _| {
10720 (
10721 movement::end_of_paragraph(map, head, 1),
10722 SelectionGoal::None,
10723 )
10724 });
10725 })
10726 }
10727
10728 pub fn move_to_start_of_excerpt(
10729 &mut self,
10730 _: &MoveToStartOfExcerpt,
10731 window: &mut Window,
10732 cx: &mut Context<Self>,
10733 ) {
10734 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10735 cx.propagate();
10736 return;
10737 }
10738
10739 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10740 s.move_with(|map, selection| {
10741 selection.collapse_to(
10742 movement::start_of_excerpt(
10743 map,
10744 selection.head(),
10745 workspace::searchable::Direction::Prev,
10746 ),
10747 SelectionGoal::None,
10748 )
10749 });
10750 })
10751 }
10752
10753 pub fn move_to_start_of_next_excerpt(
10754 &mut self,
10755 _: &MoveToStartOfNextExcerpt,
10756 window: &mut Window,
10757 cx: &mut Context<Self>,
10758 ) {
10759 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10760 cx.propagate();
10761 return;
10762 }
10763
10764 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10765 s.move_with(|map, selection| {
10766 selection.collapse_to(
10767 movement::start_of_excerpt(
10768 map,
10769 selection.head(),
10770 workspace::searchable::Direction::Next,
10771 ),
10772 SelectionGoal::None,
10773 )
10774 });
10775 })
10776 }
10777
10778 pub fn move_to_end_of_excerpt(
10779 &mut self,
10780 _: &MoveToEndOfExcerpt,
10781 window: &mut Window,
10782 cx: &mut Context<Self>,
10783 ) {
10784 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10785 cx.propagate();
10786 return;
10787 }
10788
10789 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10790 s.move_with(|map, selection| {
10791 selection.collapse_to(
10792 movement::end_of_excerpt(
10793 map,
10794 selection.head(),
10795 workspace::searchable::Direction::Next,
10796 ),
10797 SelectionGoal::None,
10798 )
10799 });
10800 })
10801 }
10802
10803 pub fn move_to_end_of_previous_excerpt(
10804 &mut self,
10805 _: &MoveToEndOfPreviousExcerpt,
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_with(|map, selection| {
10816 selection.collapse_to(
10817 movement::end_of_excerpt(
10818 map,
10819 selection.head(),
10820 workspace::searchable::Direction::Prev,
10821 ),
10822 SelectionGoal::None,
10823 )
10824 });
10825 })
10826 }
10827
10828 pub fn select_to_start_of_excerpt(
10829 &mut self,
10830 _: &SelectToStartOfExcerpt,
10831 window: &mut Window,
10832 cx: &mut Context<Self>,
10833 ) {
10834 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10835 cx.propagate();
10836 return;
10837 }
10838
10839 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10840 s.move_heads_with(|map, head, _| {
10841 (
10842 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10843 SelectionGoal::None,
10844 )
10845 });
10846 })
10847 }
10848
10849 pub fn select_to_start_of_next_excerpt(
10850 &mut self,
10851 _: &SelectToStartOfNextExcerpt,
10852 window: &mut Window,
10853 cx: &mut Context<Self>,
10854 ) {
10855 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10856 cx.propagate();
10857 return;
10858 }
10859
10860 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10861 s.move_heads_with(|map, head, _| {
10862 (
10863 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10864 SelectionGoal::None,
10865 )
10866 });
10867 })
10868 }
10869
10870 pub fn select_to_end_of_excerpt(
10871 &mut self,
10872 _: &SelectToEndOfExcerpt,
10873 window: &mut Window,
10874 cx: &mut Context<Self>,
10875 ) {
10876 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10877 cx.propagate();
10878 return;
10879 }
10880
10881 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10882 s.move_heads_with(|map, head, _| {
10883 (
10884 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10885 SelectionGoal::None,
10886 )
10887 });
10888 })
10889 }
10890
10891 pub fn select_to_end_of_previous_excerpt(
10892 &mut self,
10893 _: &SelectToEndOfPreviousExcerpt,
10894 window: &mut Window,
10895 cx: &mut Context<Self>,
10896 ) {
10897 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10898 cx.propagate();
10899 return;
10900 }
10901
10902 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10903 s.move_heads_with(|map, head, _| {
10904 (
10905 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10906 SelectionGoal::None,
10907 )
10908 });
10909 })
10910 }
10911
10912 pub fn move_to_beginning(
10913 &mut self,
10914 _: &MoveToBeginning,
10915 window: &mut Window,
10916 cx: &mut Context<Self>,
10917 ) {
10918 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10919 cx.propagate();
10920 return;
10921 }
10922
10923 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10924 s.select_ranges(vec![0..0]);
10925 });
10926 }
10927
10928 pub fn select_to_beginning(
10929 &mut self,
10930 _: &SelectToBeginning,
10931 window: &mut Window,
10932 cx: &mut Context<Self>,
10933 ) {
10934 let mut selection = self.selections.last::<Point>(cx);
10935 selection.set_head(Point::zero(), SelectionGoal::None);
10936
10937 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10938 s.select(vec![selection]);
10939 });
10940 }
10941
10942 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10943 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10944 cx.propagate();
10945 return;
10946 }
10947
10948 let cursor = self.buffer.read(cx).read(cx).len();
10949 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10950 s.select_ranges(vec![cursor..cursor])
10951 });
10952 }
10953
10954 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10955 self.nav_history = nav_history;
10956 }
10957
10958 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10959 self.nav_history.as_ref()
10960 }
10961
10962 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
10963 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
10964 }
10965
10966 fn push_to_nav_history(
10967 &mut self,
10968 cursor_anchor: Anchor,
10969 new_position: Option<Point>,
10970 is_deactivate: bool,
10971 cx: &mut Context<Self>,
10972 ) {
10973 if let Some(nav_history) = self.nav_history.as_mut() {
10974 let buffer = self.buffer.read(cx).read(cx);
10975 let cursor_position = cursor_anchor.to_point(&buffer);
10976 let scroll_state = self.scroll_manager.anchor();
10977 let scroll_top_row = scroll_state.top_row(&buffer);
10978 drop(buffer);
10979
10980 if let Some(new_position) = new_position {
10981 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10982 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10983 return;
10984 }
10985 }
10986
10987 nav_history.push(
10988 Some(NavigationData {
10989 cursor_anchor,
10990 cursor_position,
10991 scroll_anchor: scroll_state,
10992 scroll_top_row,
10993 }),
10994 cx,
10995 );
10996 cx.emit(EditorEvent::PushedToNavHistory {
10997 anchor: cursor_anchor,
10998 is_deactivate,
10999 })
11000 }
11001 }
11002
11003 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11004 let buffer = self.buffer.read(cx).snapshot(cx);
11005 let mut selection = self.selections.first::<usize>(cx);
11006 selection.set_head(buffer.len(), SelectionGoal::None);
11007 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11008 s.select(vec![selection]);
11009 });
11010 }
11011
11012 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11013 let end = self.buffer.read(cx).read(cx).len();
11014 self.change_selections(None, window, cx, |s| {
11015 s.select_ranges(vec![0..end]);
11016 });
11017 }
11018
11019 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11020 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11021 let mut selections = self.selections.all::<Point>(cx);
11022 let max_point = display_map.buffer_snapshot.max_point();
11023 for selection in &mut selections {
11024 let rows = selection.spanned_rows(true, &display_map);
11025 selection.start = Point::new(rows.start.0, 0);
11026 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11027 selection.reversed = false;
11028 }
11029 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11030 s.select(selections);
11031 });
11032 }
11033
11034 pub fn split_selection_into_lines(
11035 &mut self,
11036 _: &SplitSelectionIntoLines,
11037 window: &mut Window,
11038 cx: &mut Context<Self>,
11039 ) {
11040 let selections = self
11041 .selections
11042 .all::<Point>(cx)
11043 .into_iter()
11044 .map(|selection| selection.start..selection.end)
11045 .collect::<Vec<_>>();
11046 self.unfold_ranges(&selections, true, true, cx);
11047
11048 let mut new_selection_ranges = Vec::new();
11049 {
11050 let buffer = self.buffer.read(cx).read(cx);
11051 for selection in selections {
11052 for row in selection.start.row..selection.end.row {
11053 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11054 new_selection_ranges.push(cursor..cursor);
11055 }
11056
11057 let is_multiline_selection = selection.start.row != selection.end.row;
11058 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11059 // so this action feels more ergonomic when paired with other selection operations
11060 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11061 if !should_skip_last {
11062 new_selection_ranges.push(selection.end..selection.end);
11063 }
11064 }
11065 }
11066 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11067 s.select_ranges(new_selection_ranges);
11068 });
11069 }
11070
11071 pub fn add_selection_above(
11072 &mut self,
11073 _: &AddSelectionAbove,
11074 window: &mut Window,
11075 cx: &mut Context<Self>,
11076 ) {
11077 self.add_selection(true, window, cx);
11078 }
11079
11080 pub fn add_selection_below(
11081 &mut self,
11082 _: &AddSelectionBelow,
11083 window: &mut Window,
11084 cx: &mut Context<Self>,
11085 ) {
11086 self.add_selection(false, window, cx);
11087 }
11088
11089 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11090 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11091 let mut selections = self.selections.all::<Point>(cx);
11092 let text_layout_details = self.text_layout_details(window);
11093 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11094 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11095 let range = oldest_selection.display_range(&display_map).sorted();
11096
11097 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11098 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11099 let positions = start_x.min(end_x)..start_x.max(end_x);
11100
11101 selections.clear();
11102 let mut stack = Vec::new();
11103 for row in range.start.row().0..=range.end.row().0 {
11104 if let Some(selection) = self.selections.build_columnar_selection(
11105 &display_map,
11106 DisplayRow(row),
11107 &positions,
11108 oldest_selection.reversed,
11109 &text_layout_details,
11110 ) {
11111 stack.push(selection.id);
11112 selections.push(selection);
11113 }
11114 }
11115
11116 if above {
11117 stack.reverse();
11118 }
11119
11120 AddSelectionsState { above, stack }
11121 });
11122
11123 let last_added_selection = *state.stack.last().unwrap();
11124 let mut new_selections = Vec::new();
11125 if above == state.above {
11126 let end_row = if above {
11127 DisplayRow(0)
11128 } else {
11129 display_map.max_point().row()
11130 };
11131
11132 'outer: for selection in selections {
11133 if selection.id == last_added_selection {
11134 let range = selection.display_range(&display_map).sorted();
11135 debug_assert_eq!(range.start.row(), range.end.row());
11136 let mut row = range.start.row();
11137 let positions =
11138 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11139 px(start)..px(end)
11140 } else {
11141 let start_x =
11142 display_map.x_for_display_point(range.start, &text_layout_details);
11143 let end_x =
11144 display_map.x_for_display_point(range.end, &text_layout_details);
11145 start_x.min(end_x)..start_x.max(end_x)
11146 };
11147
11148 while row != end_row {
11149 if above {
11150 row.0 -= 1;
11151 } else {
11152 row.0 += 1;
11153 }
11154
11155 if let Some(new_selection) = self.selections.build_columnar_selection(
11156 &display_map,
11157 row,
11158 &positions,
11159 selection.reversed,
11160 &text_layout_details,
11161 ) {
11162 state.stack.push(new_selection.id);
11163 if above {
11164 new_selections.push(new_selection);
11165 new_selections.push(selection);
11166 } else {
11167 new_selections.push(selection);
11168 new_selections.push(new_selection);
11169 }
11170
11171 continue 'outer;
11172 }
11173 }
11174 }
11175
11176 new_selections.push(selection);
11177 }
11178 } else {
11179 new_selections = selections;
11180 new_selections.retain(|s| s.id != last_added_selection);
11181 state.stack.pop();
11182 }
11183
11184 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11185 s.select(new_selections);
11186 });
11187 if state.stack.len() > 1 {
11188 self.add_selections_state = Some(state);
11189 }
11190 }
11191
11192 pub fn select_next_match_internal(
11193 &mut self,
11194 display_map: &DisplaySnapshot,
11195 replace_newest: bool,
11196 autoscroll: Option<Autoscroll>,
11197 window: &mut Window,
11198 cx: &mut Context<Self>,
11199 ) -> Result<()> {
11200 fn select_next_match_ranges(
11201 this: &mut Editor,
11202 range: Range<usize>,
11203 replace_newest: bool,
11204 auto_scroll: Option<Autoscroll>,
11205 window: &mut Window,
11206 cx: &mut Context<Editor>,
11207 ) {
11208 this.unfold_ranges(&[range.clone()], false, true, cx);
11209 this.change_selections(auto_scroll, window, cx, |s| {
11210 if replace_newest {
11211 s.delete(s.newest_anchor().id);
11212 }
11213 s.insert_range(range.clone());
11214 });
11215 }
11216
11217 let buffer = &display_map.buffer_snapshot;
11218 let mut selections = self.selections.all::<usize>(cx);
11219 if let Some(mut select_next_state) = self.select_next_state.take() {
11220 let query = &select_next_state.query;
11221 if !select_next_state.done {
11222 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11223 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11224 let mut next_selected_range = None;
11225
11226 let bytes_after_last_selection =
11227 buffer.bytes_in_range(last_selection.end..buffer.len());
11228 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11229 let query_matches = query
11230 .stream_find_iter(bytes_after_last_selection)
11231 .map(|result| (last_selection.end, result))
11232 .chain(
11233 query
11234 .stream_find_iter(bytes_before_first_selection)
11235 .map(|result| (0, result)),
11236 );
11237
11238 for (start_offset, query_match) in query_matches {
11239 let query_match = query_match.unwrap(); // can only fail due to I/O
11240 let offset_range =
11241 start_offset + query_match.start()..start_offset + query_match.end();
11242 let display_range = offset_range.start.to_display_point(display_map)
11243 ..offset_range.end.to_display_point(display_map);
11244
11245 if !select_next_state.wordwise
11246 || (!movement::is_inside_word(display_map, display_range.start)
11247 && !movement::is_inside_word(display_map, display_range.end))
11248 {
11249 // TODO: This is n^2, because we might check all the selections
11250 if !selections
11251 .iter()
11252 .any(|selection| selection.range().overlaps(&offset_range))
11253 {
11254 next_selected_range = Some(offset_range);
11255 break;
11256 }
11257 }
11258 }
11259
11260 if let Some(next_selected_range) = next_selected_range {
11261 select_next_match_ranges(
11262 self,
11263 next_selected_range,
11264 replace_newest,
11265 autoscroll,
11266 window,
11267 cx,
11268 );
11269 } else {
11270 select_next_state.done = true;
11271 }
11272 }
11273
11274 self.select_next_state = Some(select_next_state);
11275 } else {
11276 let mut only_carets = true;
11277 let mut same_text_selected = true;
11278 let mut selected_text = None;
11279
11280 let mut selections_iter = selections.iter().peekable();
11281 while let Some(selection) = selections_iter.next() {
11282 if selection.start != selection.end {
11283 only_carets = false;
11284 }
11285
11286 if same_text_selected {
11287 if selected_text.is_none() {
11288 selected_text =
11289 Some(buffer.text_for_range(selection.range()).collect::<String>());
11290 }
11291
11292 if let Some(next_selection) = selections_iter.peek() {
11293 if next_selection.range().len() == selection.range().len() {
11294 let next_selected_text = buffer
11295 .text_for_range(next_selection.range())
11296 .collect::<String>();
11297 if Some(next_selected_text) != selected_text {
11298 same_text_selected = false;
11299 selected_text = None;
11300 }
11301 } else {
11302 same_text_selected = false;
11303 selected_text = None;
11304 }
11305 }
11306 }
11307 }
11308
11309 if only_carets {
11310 for selection in &mut selections {
11311 let word_range = movement::surrounding_word(
11312 display_map,
11313 selection.start.to_display_point(display_map),
11314 );
11315 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11316 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11317 selection.goal = SelectionGoal::None;
11318 selection.reversed = false;
11319 select_next_match_ranges(
11320 self,
11321 selection.start..selection.end,
11322 replace_newest,
11323 autoscroll,
11324 window,
11325 cx,
11326 );
11327 }
11328
11329 if selections.len() == 1 {
11330 let selection = selections
11331 .last()
11332 .expect("ensured that there's only one selection");
11333 let query = buffer
11334 .text_for_range(selection.start..selection.end)
11335 .collect::<String>();
11336 let is_empty = query.is_empty();
11337 let select_state = SelectNextState {
11338 query: AhoCorasick::new(&[query])?,
11339 wordwise: true,
11340 done: is_empty,
11341 };
11342 self.select_next_state = Some(select_state);
11343 } else {
11344 self.select_next_state = None;
11345 }
11346 } else if let Some(selected_text) = selected_text {
11347 self.select_next_state = Some(SelectNextState {
11348 query: AhoCorasick::new(&[selected_text])?,
11349 wordwise: false,
11350 done: false,
11351 });
11352 self.select_next_match_internal(
11353 display_map,
11354 replace_newest,
11355 autoscroll,
11356 window,
11357 cx,
11358 )?;
11359 }
11360 }
11361 Ok(())
11362 }
11363
11364 pub fn select_all_matches(
11365 &mut self,
11366 _action: &SelectAllMatches,
11367 window: &mut Window,
11368 cx: &mut Context<Self>,
11369 ) -> Result<()> {
11370 self.push_to_selection_history();
11371 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11372
11373 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11374 let Some(select_next_state) = self.select_next_state.as_mut() else {
11375 return Ok(());
11376 };
11377 if select_next_state.done {
11378 return Ok(());
11379 }
11380
11381 let mut new_selections = self.selections.all::<usize>(cx);
11382
11383 let buffer = &display_map.buffer_snapshot;
11384 let query_matches = select_next_state
11385 .query
11386 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11387
11388 for query_match in query_matches {
11389 let query_match = query_match.unwrap(); // can only fail due to I/O
11390 let offset_range = query_match.start()..query_match.end();
11391 let display_range = offset_range.start.to_display_point(&display_map)
11392 ..offset_range.end.to_display_point(&display_map);
11393
11394 if !select_next_state.wordwise
11395 || (!movement::is_inside_word(&display_map, display_range.start)
11396 && !movement::is_inside_word(&display_map, display_range.end))
11397 {
11398 self.selections.change_with(cx, |selections| {
11399 new_selections.push(Selection {
11400 id: selections.new_selection_id(),
11401 start: offset_range.start,
11402 end: offset_range.end,
11403 reversed: false,
11404 goal: SelectionGoal::None,
11405 });
11406 });
11407 }
11408 }
11409
11410 new_selections.sort_by_key(|selection| selection.start);
11411 let mut ix = 0;
11412 while ix + 1 < new_selections.len() {
11413 let current_selection = &new_selections[ix];
11414 let next_selection = &new_selections[ix + 1];
11415 if current_selection.range().overlaps(&next_selection.range()) {
11416 if current_selection.id < next_selection.id {
11417 new_selections.remove(ix + 1);
11418 } else {
11419 new_selections.remove(ix);
11420 }
11421 } else {
11422 ix += 1;
11423 }
11424 }
11425
11426 let reversed = self.selections.oldest::<usize>(cx).reversed;
11427
11428 for selection in new_selections.iter_mut() {
11429 selection.reversed = reversed;
11430 }
11431
11432 select_next_state.done = true;
11433 self.unfold_ranges(
11434 &new_selections
11435 .iter()
11436 .map(|selection| selection.range())
11437 .collect::<Vec<_>>(),
11438 false,
11439 false,
11440 cx,
11441 );
11442 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11443 selections.select(new_selections)
11444 });
11445
11446 Ok(())
11447 }
11448
11449 pub fn select_next(
11450 &mut self,
11451 action: &SelectNext,
11452 window: &mut Window,
11453 cx: &mut Context<Self>,
11454 ) -> Result<()> {
11455 self.push_to_selection_history();
11456 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11457 self.select_next_match_internal(
11458 &display_map,
11459 action.replace_newest,
11460 Some(Autoscroll::newest()),
11461 window,
11462 cx,
11463 )?;
11464 Ok(())
11465 }
11466
11467 pub fn select_previous(
11468 &mut self,
11469 action: &SelectPrevious,
11470 window: &mut Window,
11471 cx: &mut Context<Self>,
11472 ) -> Result<()> {
11473 self.push_to_selection_history();
11474 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11475 let buffer = &display_map.buffer_snapshot;
11476 let mut selections = self.selections.all::<usize>(cx);
11477 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11478 let query = &select_prev_state.query;
11479 if !select_prev_state.done {
11480 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11481 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11482 let mut next_selected_range = None;
11483 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11484 let bytes_before_last_selection =
11485 buffer.reversed_bytes_in_range(0..last_selection.start);
11486 let bytes_after_first_selection =
11487 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11488 let query_matches = query
11489 .stream_find_iter(bytes_before_last_selection)
11490 .map(|result| (last_selection.start, result))
11491 .chain(
11492 query
11493 .stream_find_iter(bytes_after_first_selection)
11494 .map(|result| (buffer.len(), result)),
11495 );
11496 for (end_offset, query_match) in query_matches {
11497 let query_match = query_match.unwrap(); // can only fail due to I/O
11498 let offset_range =
11499 end_offset - query_match.end()..end_offset - query_match.start();
11500 let display_range = offset_range.start.to_display_point(&display_map)
11501 ..offset_range.end.to_display_point(&display_map);
11502
11503 if !select_prev_state.wordwise
11504 || (!movement::is_inside_word(&display_map, display_range.start)
11505 && !movement::is_inside_word(&display_map, display_range.end))
11506 {
11507 next_selected_range = Some(offset_range);
11508 break;
11509 }
11510 }
11511
11512 if let Some(next_selected_range) = next_selected_range {
11513 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11514 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11515 if action.replace_newest {
11516 s.delete(s.newest_anchor().id);
11517 }
11518 s.insert_range(next_selected_range);
11519 });
11520 } else {
11521 select_prev_state.done = true;
11522 }
11523 }
11524
11525 self.select_prev_state = Some(select_prev_state);
11526 } else {
11527 let mut only_carets = true;
11528 let mut same_text_selected = true;
11529 let mut selected_text = None;
11530
11531 let mut selections_iter = selections.iter().peekable();
11532 while let Some(selection) = selections_iter.next() {
11533 if selection.start != selection.end {
11534 only_carets = false;
11535 }
11536
11537 if same_text_selected {
11538 if selected_text.is_none() {
11539 selected_text =
11540 Some(buffer.text_for_range(selection.range()).collect::<String>());
11541 }
11542
11543 if let Some(next_selection) = selections_iter.peek() {
11544 if next_selection.range().len() == selection.range().len() {
11545 let next_selected_text = buffer
11546 .text_for_range(next_selection.range())
11547 .collect::<String>();
11548 if Some(next_selected_text) != selected_text {
11549 same_text_selected = false;
11550 selected_text = None;
11551 }
11552 } else {
11553 same_text_selected = false;
11554 selected_text = None;
11555 }
11556 }
11557 }
11558 }
11559
11560 if only_carets {
11561 for selection in &mut selections {
11562 let word_range = movement::surrounding_word(
11563 &display_map,
11564 selection.start.to_display_point(&display_map),
11565 );
11566 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11567 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11568 selection.goal = SelectionGoal::None;
11569 selection.reversed = false;
11570 }
11571 if selections.len() == 1 {
11572 let selection = selections
11573 .last()
11574 .expect("ensured that there's only one selection");
11575 let query = buffer
11576 .text_for_range(selection.start..selection.end)
11577 .collect::<String>();
11578 let is_empty = query.is_empty();
11579 let select_state = SelectNextState {
11580 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11581 wordwise: true,
11582 done: is_empty,
11583 };
11584 self.select_prev_state = Some(select_state);
11585 } else {
11586 self.select_prev_state = None;
11587 }
11588
11589 self.unfold_ranges(
11590 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11591 false,
11592 true,
11593 cx,
11594 );
11595 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11596 s.select(selections);
11597 });
11598 } else if let Some(selected_text) = selected_text {
11599 self.select_prev_state = Some(SelectNextState {
11600 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11601 wordwise: false,
11602 done: false,
11603 });
11604 self.select_previous(action, window, cx)?;
11605 }
11606 }
11607 Ok(())
11608 }
11609
11610 pub fn toggle_comments(
11611 &mut self,
11612 action: &ToggleComments,
11613 window: &mut Window,
11614 cx: &mut Context<Self>,
11615 ) {
11616 if self.read_only(cx) {
11617 return;
11618 }
11619 let text_layout_details = &self.text_layout_details(window);
11620 self.transact(window, cx, |this, window, cx| {
11621 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11622 let mut edits = Vec::new();
11623 let mut selection_edit_ranges = Vec::new();
11624 let mut last_toggled_row = None;
11625 let snapshot = this.buffer.read(cx).read(cx);
11626 let empty_str: Arc<str> = Arc::default();
11627 let mut suffixes_inserted = Vec::new();
11628 let ignore_indent = action.ignore_indent;
11629
11630 fn comment_prefix_range(
11631 snapshot: &MultiBufferSnapshot,
11632 row: MultiBufferRow,
11633 comment_prefix: &str,
11634 comment_prefix_whitespace: &str,
11635 ignore_indent: bool,
11636 ) -> Range<Point> {
11637 let indent_size = if ignore_indent {
11638 0
11639 } else {
11640 snapshot.indent_size_for_line(row).len
11641 };
11642
11643 let start = Point::new(row.0, indent_size);
11644
11645 let mut line_bytes = snapshot
11646 .bytes_in_range(start..snapshot.max_point())
11647 .flatten()
11648 .copied();
11649
11650 // If this line currently begins with the line comment prefix, then record
11651 // the range containing the prefix.
11652 if line_bytes
11653 .by_ref()
11654 .take(comment_prefix.len())
11655 .eq(comment_prefix.bytes())
11656 {
11657 // Include any whitespace that matches the comment prefix.
11658 let matching_whitespace_len = line_bytes
11659 .zip(comment_prefix_whitespace.bytes())
11660 .take_while(|(a, b)| a == b)
11661 .count() as u32;
11662 let end = Point::new(
11663 start.row,
11664 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11665 );
11666 start..end
11667 } else {
11668 start..start
11669 }
11670 }
11671
11672 fn comment_suffix_range(
11673 snapshot: &MultiBufferSnapshot,
11674 row: MultiBufferRow,
11675 comment_suffix: &str,
11676 comment_suffix_has_leading_space: bool,
11677 ) -> Range<Point> {
11678 let end = Point::new(row.0, snapshot.line_len(row));
11679 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11680
11681 let mut line_end_bytes = snapshot
11682 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11683 .flatten()
11684 .copied();
11685
11686 let leading_space_len = if suffix_start_column > 0
11687 && line_end_bytes.next() == Some(b' ')
11688 && comment_suffix_has_leading_space
11689 {
11690 1
11691 } else {
11692 0
11693 };
11694
11695 // If this line currently begins with the line comment prefix, then record
11696 // the range containing the prefix.
11697 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11698 let start = Point::new(end.row, suffix_start_column - leading_space_len);
11699 start..end
11700 } else {
11701 end..end
11702 }
11703 }
11704
11705 // TODO: Handle selections that cross excerpts
11706 for selection in &mut selections {
11707 let start_column = snapshot
11708 .indent_size_for_line(MultiBufferRow(selection.start.row))
11709 .len;
11710 let language = if let Some(language) =
11711 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11712 {
11713 language
11714 } else {
11715 continue;
11716 };
11717
11718 selection_edit_ranges.clear();
11719
11720 // If multiple selections contain a given row, avoid processing that
11721 // row more than once.
11722 let mut start_row = MultiBufferRow(selection.start.row);
11723 if last_toggled_row == Some(start_row) {
11724 start_row = start_row.next_row();
11725 }
11726 let end_row =
11727 if selection.end.row > selection.start.row && selection.end.column == 0 {
11728 MultiBufferRow(selection.end.row - 1)
11729 } else {
11730 MultiBufferRow(selection.end.row)
11731 };
11732 last_toggled_row = Some(end_row);
11733
11734 if start_row > end_row {
11735 continue;
11736 }
11737
11738 // If the language has line comments, toggle those.
11739 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11740
11741 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11742 if ignore_indent {
11743 full_comment_prefixes = full_comment_prefixes
11744 .into_iter()
11745 .map(|s| Arc::from(s.trim_end()))
11746 .collect();
11747 }
11748
11749 if !full_comment_prefixes.is_empty() {
11750 let first_prefix = full_comment_prefixes
11751 .first()
11752 .expect("prefixes is non-empty");
11753 let prefix_trimmed_lengths = full_comment_prefixes
11754 .iter()
11755 .map(|p| p.trim_end_matches(' ').len())
11756 .collect::<SmallVec<[usize; 4]>>();
11757
11758 let mut all_selection_lines_are_comments = true;
11759
11760 for row in start_row.0..=end_row.0 {
11761 let row = MultiBufferRow(row);
11762 if start_row < end_row && snapshot.is_line_blank(row) {
11763 continue;
11764 }
11765
11766 let prefix_range = full_comment_prefixes
11767 .iter()
11768 .zip(prefix_trimmed_lengths.iter().copied())
11769 .map(|(prefix, trimmed_prefix_len)| {
11770 comment_prefix_range(
11771 snapshot.deref(),
11772 row,
11773 &prefix[..trimmed_prefix_len],
11774 &prefix[trimmed_prefix_len..],
11775 ignore_indent,
11776 )
11777 })
11778 .max_by_key(|range| range.end.column - range.start.column)
11779 .expect("prefixes is non-empty");
11780
11781 if prefix_range.is_empty() {
11782 all_selection_lines_are_comments = false;
11783 }
11784
11785 selection_edit_ranges.push(prefix_range);
11786 }
11787
11788 if all_selection_lines_are_comments {
11789 edits.extend(
11790 selection_edit_ranges
11791 .iter()
11792 .cloned()
11793 .map(|range| (range, empty_str.clone())),
11794 );
11795 } else {
11796 let min_column = selection_edit_ranges
11797 .iter()
11798 .map(|range| range.start.column)
11799 .min()
11800 .unwrap_or(0);
11801 edits.extend(selection_edit_ranges.iter().map(|range| {
11802 let position = Point::new(range.start.row, min_column);
11803 (position..position, first_prefix.clone())
11804 }));
11805 }
11806 } else if let Some((full_comment_prefix, comment_suffix)) =
11807 language.block_comment_delimiters()
11808 {
11809 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11810 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11811 let prefix_range = comment_prefix_range(
11812 snapshot.deref(),
11813 start_row,
11814 comment_prefix,
11815 comment_prefix_whitespace,
11816 ignore_indent,
11817 );
11818 let suffix_range = comment_suffix_range(
11819 snapshot.deref(),
11820 end_row,
11821 comment_suffix.trim_start_matches(' '),
11822 comment_suffix.starts_with(' '),
11823 );
11824
11825 if prefix_range.is_empty() || suffix_range.is_empty() {
11826 edits.push((
11827 prefix_range.start..prefix_range.start,
11828 full_comment_prefix.clone(),
11829 ));
11830 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11831 suffixes_inserted.push((end_row, comment_suffix.len()));
11832 } else {
11833 edits.push((prefix_range, empty_str.clone()));
11834 edits.push((suffix_range, empty_str.clone()));
11835 }
11836 } else {
11837 continue;
11838 }
11839 }
11840
11841 drop(snapshot);
11842 this.buffer.update(cx, |buffer, cx| {
11843 buffer.edit(edits, None, cx);
11844 });
11845
11846 // Adjust selections so that they end before any comment suffixes that
11847 // were inserted.
11848 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11849 let mut selections = this.selections.all::<Point>(cx);
11850 let snapshot = this.buffer.read(cx).read(cx);
11851 for selection in &mut selections {
11852 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11853 match row.cmp(&MultiBufferRow(selection.end.row)) {
11854 Ordering::Less => {
11855 suffixes_inserted.next();
11856 continue;
11857 }
11858 Ordering::Greater => break,
11859 Ordering::Equal => {
11860 if selection.end.column == snapshot.line_len(row) {
11861 if selection.is_empty() {
11862 selection.start.column -= suffix_len as u32;
11863 }
11864 selection.end.column -= suffix_len as u32;
11865 }
11866 break;
11867 }
11868 }
11869 }
11870 }
11871
11872 drop(snapshot);
11873 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11874 s.select(selections)
11875 });
11876
11877 let selections = this.selections.all::<Point>(cx);
11878 let selections_on_single_row = selections.windows(2).all(|selections| {
11879 selections[0].start.row == selections[1].start.row
11880 && selections[0].end.row == selections[1].end.row
11881 && selections[0].start.row == selections[0].end.row
11882 });
11883 let selections_selecting = selections
11884 .iter()
11885 .any(|selection| selection.start != selection.end);
11886 let advance_downwards = action.advance_downwards
11887 && selections_on_single_row
11888 && !selections_selecting
11889 && !matches!(this.mode, EditorMode::SingleLine { .. });
11890
11891 if advance_downwards {
11892 let snapshot = this.buffer.read(cx).snapshot(cx);
11893
11894 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11895 s.move_cursors_with(|display_snapshot, display_point, _| {
11896 let mut point = display_point.to_point(display_snapshot);
11897 point.row += 1;
11898 point = snapshot.clip_point(point, Bias::Left);
11899 let display_point = point.to_display_point(display_snapshot);
11900 let goal = SelectionGoal::HorizontalPosition(
11901 display_snapshot
11902 .x_for_display_point(display_point, text_layout_details)
11903 .into(),
11904 );
11905 (display_point, goal)
11906 })
11907 });
11908 }
11909 });
11910 }
11911
11912 pub fn select_enclosing_symbol(
11913 &mut self,
11914 _: &SelectEnclosingSymbol,
11915 window: &mut Window,
11916 cx: &mut Context<Self>,
11917 ) {
11918 let buffer = self.buffer.read(cx).snapshot(cx);
11919 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11920
11921 fn update_selection(
11922 selection: &Selection<usize>,
11923 buffer_snap: &MultiBufferSnapshot,
11924 ) -> Option<Selection<usize>> {
11925 let cursor = selection.head();
11926 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11927 for symbol in symbols.iter().rev() {
11928 let start = symbol.range.start.to_offset(buffer_snap);
11929 let end = symbol.range.end.to_offset(buffer_snap);
11930 let new_range = start..end;
11931 if start < selection.start || end > selection.end {
11932 return Some(Selection {
11933 id: selection.id,
11934 start: new_range.start,
11935 end: new_range.end,
11936 goal: SelectionGoal::None,
11937 reversed: selection.reversed,
11938 });
11939 }
11940 }
11941 None
11942 }
11943
11944 let mut selected_larger_symbol = false;
11945 let new_selections = old_selections
11946 .iter()
11947 .map(|selection| match update_selection(selection, &buffer) {
11948 Some(new_selection) => {
11949 if new_selection.range() != selection.range() {
11950 selected_larger_symbol = true;
11951 }
11952 new_selection
11953 }
11954 None => selection.clone(),
11955 })
11956 .collect::<Vec<_>>();
11957
11958 if selected_larger_symbol {
11959 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11960 s.select(new_selections);
11961 });
11962 }
11963 }
11964
11965 pub fn select_larger_syntax_node(
11966 &mut self,
11967 _: &SelectLargerSyntaxNode,
11968 window: &mut Window,
11969 cx: &mut Context<Self>,
11970 ) {
11971 let Some(visible_row_count) = self.visible_row_count() else {
11972 return;
11973 };
11974 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
11975 if old_selections.is_empty() {
11976 return;
11977 }
11978
11979 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11980 let buffer = self.buffer.read(cx).snapshot(cx);
11981
11982 let mut selected_larger_node = false;
11983 let mut new_selections = old_selections
11984 .iter()
11985 .map(|selection| {
11986 let old_range = selection.start..selection.end;
11987 let mut new_range = old_range.clone();
11988 let mut new_node = None;
11989 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11990 {
11991 new_node = Some(node);
11992 new_range = match containing_range {
11993 MultiOrSingleBufferOffsetRange::Single(_) => break,
11994 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11995 };
11996 if !display_map.intersects_fold(new_range.start)
11997 && !display_map.intersects_fold(new_range.end)
11998 {
11999 break;
12000 }
12001 }
12002
12003 if let Some(node) = new_node {
12004 // Log the ancestor, to support using this action as a way to explore TreeSitter
12005 // nodes. Parent and grandparent are also logged because this operation will not
12006 // visit nodes that have the same range as their parent.
12007 log::info!("Node: {node:?}");
12008 let parent = node.parent();
12009 log::info!("Parent: {parent:?}");
12010 let grandparent = parent.and_then(|x| x.parent());
12011 log::info!("Grandparent: {grandparent:?}");
12012 }
12013
12014 selected_larger_node |= new_range != old_range;
12015 Selection {
12016 id: selection.id,
12017 start: new_range.start,
12018 end: new_range.end,
12019 goal: SelectionGoal::None,
12020 reversed: selection.reversed,
12021 }
12022 })
12023 .collect::<Vec<_>>();
12024
12025 if !selected_larger_node {
12026 return; // don't put this call in the history
12027 }
12028
12029 // scroll based on transformation done to the last selection created by the user
12030 let (last_old, last_new) = old_selections
12031 .last()
12032 .zip(new_selections.last().cloned())
12033 .expect("old_selections isn't empty");
12034
12035 // revert selection
12036 let is_selection_reversed = {
12037 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12038 new_selections.last_mut().expect("checked above").reversed =
12039 should_newest_selection_be_reversed;
12040 should_newest_selection_be_reversed
12041 };
12042
12043 if selected_larger_node {
12044 self.select_syntax_node_history.disable_clearing = true;
12045 self.change_selections(None, window, cx, |s| {
12046 s.select(new_selections.clone());
12047 });
12048 self.select_syntax_node_history.disable_clearing = false;
12049 }
12050
12051 let start_row = last_new.start.to_display_point(&display_map).row().0;
12052 let end_row = last_new.end.to_display_point(&display_map).row().0;
12053 let selection_height = end_row - start_row + 1;
12054 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12055
12056 // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
12057 let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
12058 let middle_row = (end_row + start_row) / 2;
12059 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12060 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12061 SelectSyntaxNodeScrollBehavior::CenterSelection
12062 } else if is_selection_reversed {
12063 self.scroll_cursor_top(&Default::default(), window, cx);
12064 SelectSyntaxNodeScrollBehavior::CursorTop
12065 } else {
12066 self.scroll_cursor_bottom(&Default::default(), window, cx);
12067 SelectSyntaxNodeScrollBehavior::CursorBottom
12068 };
12069
12070 self.select_syntax_node_history.push((
12071 old_selections,
12072 scroll_behavior,
12073 is_selection_reversed,
12074 ));
12075 }
12076
12077 pub fn select_smaller_syntax_node(
12078 &mut self,
12079 _: &SelectSmallerSyntaxNode,
12080 window: &mut Window,
12081 cx: &mut Context<Self>,
12082 ) {
12083 let Some(visible_row_count) = self.visible_row_count() else {
12084 return;
12085 };
12086
12087 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12088 self.select_syntax_node_history.pop()
12089 {
12090 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12091
12092 if let Some(selection) = selections.last_mut() {
12093 selection.reversed = is_selection_reversed;
12094 }
12095
12096 self.select_syntax_node_history.disable_clearing = true;
12097 self.change_selections(None, window, cx, |s| {
12098 s.select(selections.to_vec());
12099 });
12100 self.select_syntax_node_history.disable_clearing = false;
12101
12102 let newest = self.selections.newest::<usize>(cx);
12103 let start_row = newest.start.to_display_point(&display_map).row().0;
12104 let end_row = newest.end.to_display_point(&display_map).row().0;
12105
12106 match scroll_behavior {
12107 SelectSyntaxNodeScrollBehavior::CursorTop => {
12108 self.scroll_cursor_top(&Default::default(), window, cx);
12109 }
12110 SelectSyntaxNodeScrollBehavior::CenterSelection => {
12111 let middle_row = (end_row + start_row) / 2;
12112 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12113 // centralize the selection, not the cursor
12114 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12115 }
12116 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12117 self.scroll_cursor_bottom(&Default::default(), window, cx);
12118 }
12119 }
12120 }
12121 }
12122
12123 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12124 if !EditorSettings::get_global(cx).gutter.runnables {
12125 self.clear_tasks();
12126 return Task::ready(());
12127 }
12128 let project = self.project.as_ref().map(Entity::downgrade);
12129 cx.spawn_in(window, async move |this, cx| {
12130 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12131 let Some(project) = project.and_then(|p| p.upgrade()) else {
12132 return;
12133 };
12134 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12135 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12136 }) else {
12137 return;
12138 };
12139
12140 let hide_runnables = project
12141 .update(cx, |project, cx| {
12142 // Do not display any test indicators in non-dev server remote projects.
12143 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12144 })
12145 .unwrap_or(true);
12146 if hide_runnables {
12147 return;
12148 }
12149 let new_rows =
12150 cx.background_spawn({
12151 let snapshot = display_snapshot.clone();
12152 async move {
12153 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12154 }
12155 })
12156 .await;
12157
12158 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12159 this.update(cx, |this, _| {
12160 this.clear_tasks();
12161 for (key, value) in rows {
12162 this.insert_tasks(key, value);
12163 }
12164 })
12165 .ok();
12166 })
12167 }
12168 fn fetch_runnable_ranges(
12169 snapshot: &DisplaySnapshot,
12170 range: Range<Anchor>,
12171 ) -> Vec<language::RunnableRange> {
12172 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12173 }
12174
12175 fn runnable_rows(
12176 project: Entity<Project>,
12177 snapshot: DisplaySnapshot,
12178 runnable_ranges: Vec<RunnableRange>,
12179 mut cx: AsyncWindowContext,
12180 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12181 runnable_ranges
12182 .into_iter()
12183 .filter_map(|mut runnable| {
12184 let tasks = cx
12185 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12186 .ok()?;
12187 if tasks.is_empty() {
12188 return None;
12189 }
12190
12191 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12192
12193 let row = snapshot
12194 .buffer_snapshot
12195 .buffer_line_for_row(MultiBufferRow(point.row))?
12196 .1
12197 .start
12198 .row;
12199
12200 let context_range =
12201 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12202 Some((
12203 (runnable.buffer_id, row),
12204 RunnableTasks {
12205 templates: tasks,
12206 offset: snapshot
12207 .buffer_snapshot
12208 .anchor_before(runnable.run_range.start),
12209 context_range,
12210 column: point.column,
12211 extra_variables: runnable.extra_captures,
12212 },
12213 ))
12214 })
12215 .collect()
12216 }
12217
12218 fn templates_with_tags(
12219 project: &Entity<Project>,
12220 runnable: &mut Runnable,
12221 cx: &mut App,
12222 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12223 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12224 let (worktree_id, file) = project
12225 .buffer_for_id(runnable.buffer, cx)
12226 .and_then(|buffer| buffer.read(cx).file())
12227 .map(|file| (file.worktree_id(cx), file.clone()))
12228 .unzip();
12229
12230 (
12231 project.task_store().read(cx).task_inventory().cloned(),
12232 worktree_id,
12233 file,
12234 )
12235 });
12236
12237 let tags = mem::take(&mut runnable.tags);
12238 let mut tags: Vec<_> = tags
12239 .into_iter()
12240 .flat_map(|tag| {
12241 let tag = tag.0.clone();
12242 inventory
12243 .as_ref()
12244 .into_iter()
12245 .flat_map(|inventory| {
12246 inventory.read(cx).list_tasks(
12247 file.clone(),
12248 Some(runnable.language.clone()),
12249 worktree_id,
12250 cx,
12251 )
12252 })
12253 .filter(move |(_, template)| {
12254 template.tags.iter().any(|source_tag| source_tag == &tag)
12255 })
12256 })
12257 .sorted_by_key(|(kind, _)| kind.to_owned())
12258 .collect();
12259 if let Some((leading_tag_source, _)) = tags.first() {
12260 // Strongest source wins; if we have worktree tag binding, prefer that to
12261 // global and language bindings;
12262 // if we have a global binding, prefer that to language binding.
12263 let first_mismatch = tags
12264 .iter()
12265 .position(|(tag_source, _)| tag_source != leading_tag_source);
12266 if let Some(index) = first_mismatch {
12267 tags.truncate(index);
12268 }
12269 }
12270
12271 tags
12272 }
12273
12274 pub fn move_to_enclosing_bracket(
12275 &mut self,
12276 _: &MoveToEnclosingBracket,
12277 window: &mut Window,
12278 cx: &mut Context<Self>,
12279 ) {
12280 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12281 s.move_offsets_with(|snapshot, selection| {
12282 let Some(enclosing_bracket_ranges) =
12283 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12284 else {
12285 return;
12286 };
12287
12288 let mut best_length = usize::MAX;
12289 let mut best_inside = false;
12290 let mut best_in_bracket_range = false;
12291 let mut best_destination = None;
12292 for (open, close) in enclosing_bracket_ranges {
12293 let close = close.to_inclusive();
12294 let length = close.end() - open.start;
12295 let inside = selection.start >= open.end && selection.end <= *close.start();
12296 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12297 || close.contains(&selection.head());
12298
12299 // If best is next to a bracket and current isn't, skip
12300 if !in_bracket_range && best_in_bracket_range {
12301 continue;
12302 }
12303
12304 // Prefer smaller lengths unless best is inside and current isn't
12305 if length > best_length && (best_inside || !inside) {
12306 continue;
12307 }
12308
12309 best_length = length;
12310 best_inside = inside;
12311 best_in_bracket_range = in_bracket_range;
12312 best_destination = Some(
12313 if close.contains(&selection.start) && close.contains(&selection.end) {
12314 if inside {
12315 open.end
12316 } else {
12317 open.start
12318 }
12319 } else if inside {
12320 *close.start()
12321 } else {
12322 *close.end()
12323 },
12324 );
12325 }
12326
12327 if let Some(destination) = best_destination {
12328 selection.collapse_to(destination, SelectionGoal::None);
12329 }
12330 })
12331 });
12332 }
12333
12334 pub fn undo_selection(
12335 &mut self,
12336 _: &UndoSelection,
12337 window: &mut Window,
12338 cx: &mut Context<Self>,
12339 ) {
12340 self.end_selection(window, cx);
12341 self.selection_history.mode = SelectionHistoryMode::Undoing;
12342 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12343 self.change_selections(None, window, cx, |s| {
12344 s.select_anchors(entry.selections.to_vec())
12345 });
12346 self.select_next_state = entry.select_next_state;
12347 self.select_prev_state = entry.select_prev_state;
12348 self.add_selections_state = entry.add_selections_state;
12349 self.request_autoscroll(Autoscroll::newest(), cx);
12350 }
12351 self.selection_history.mode = SelectionHistoryMode::Normal;
12352 }
12353
12354 pub fn redo_selection(
12355 &mut self,
12356 _: &RedoSelection,
12357 window: &mut Window,
12358 cx: &mut Context<Self>,
12359 ) {
12360 self.end_selection(window, cx);
12361 self.selection_history.mode = SelectionHistoryMode::Redoing;
12362 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12363 self.change_selections(None, window, cx, |s| {
12364 s.select_anchors(entry.selections.to_vec())
12365 });
12366 self.select_next_state = entry.select_next_state;
12367 self.select_prev_state = entry.select_prev_state;
12368 self.add_selections_state = entry.add_selections_state;
12369 self.request_autoscroll(Autoscroll::newest(), cx);
12370 }
12371 self.selection_history.mode = SelectionHistoryMode::Normal;
12372 }
12373
12374 pub fn expand_excerpts(
12375 &mut self,
12376 action: &ExpandExcerpts,
12377 _: &mut Window,
12378 cx: &mut Context<Self>,
12379 ) {
12380 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12381 }
12382
12383 pub fn expand_excerpts_down(
12384 &mut self,
12385 action: &ExpandExcerptsDown,
12386 _: &mut Window,
12387 cx: &mut Context<Self>,
12388 ) {
12389 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12390 }
12391
12392 pub fn expand_excerpts_up(
12393 &mut self,
12394 action: &ExpandExcerptsUp,
12395 _: &mut Window,
12396 cx: &mut Context<Self>,
12397 ) {
12398 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12399 }
12400
12401 pub fn expand_excerpts_for_direction(
12402 &mut self,
12403 lines: u32,
12404 direction: ExpandExcerptDirection,
12405
12406 cx: &mut Context<Self>,
12407 ) {
12408 let selections = self.selections.disjoint_anchors();
12409
12410 let lines = if lines == 0 {
12411 EditorSettings::get_global(cx).expand_excerpt_lines
12412 } else {
12413 lines
12414 };
12415
12416 self.buffer.update(cx, |buffer, cx| {
12417 let snapshot = buffer.snapshot(cx);
12418 let mut excerpt_ids = selections
12419 .iter()
12420 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12421 .collect::<Vec<_>>();
12422 excerpt_ids.sort();
12423 excerpt_ids.dedup();
12424 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12425 })
12426 }
12427
12428 pub fn expand_excerpt(
12429 &mut self,
12430 excerpt: ExcerptId,
12431 direction: ExpandExcerptDirection,
12432 window: &mut Window,
12433 cx: &mut Context<Self>,
12434 ) {
12435 let current_scroll_position = self.scroll_position(cx);
12436 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12437 self.buffer.update(cx, |buffer, cx| {
12438 buffer.expand_excerpts([excerpt], lines, direction, cx)
12439 });
12440 if direction == ExpandExcerptDirection::Down {
12441 let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12442 self.set_scroll_position(new_scroll_position, window, cx);
12443 }
12444 }
12445
12446 pub fn go_to_singleton_buffer_point(
12447 &mut self,
12448 point: Point,
12449 window: &mut Window,
12450 cx: &mut Context<Self>,
12451 ) {
12452 self.go_to_singleton_buffer_range(point..point, window, cx);
12453 }
12454
12455 pub fn go_to_singleton_buffer_range(
12456 &mut self,
12457 range: Range<Point>,
12458 window: &mut Window,
12459 cx: &mut Context<Self>,
12460 ) {
12461 let multibuffer = self.buffer().read(cx);
12462 let Some(buffer) = multibuffer.as_singleton() else {
12463 return;
12464 };
12465 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12466 return;
12467 };
12468 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12469 return;
12470 };
12471 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12472 s.select_anchor_ranges([start..end])
12473 });
12474 }
12475
12476 fn go_to_diagnostic(
12477 &mut self,
12478 _: &GoToDiagnostic,
12479 window: &mut Window,
12480 cx: &mut Context<Self>,
12481 ) {
12482 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12483 }
12484
12485 fn go_to_prev_diagnostic(
12486 &mut self,
12487 _: &GoToPreviousDiagnostic,
12488 window: &mut Window,
12489 cx: &mut Context<Self>,
12490 ) {
12491 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12492 }
12493
12494 pub fn go_to_diagnostic_impl(
12495 &mut self,
12496 direction: Direction,
12497 window: &mut Window,
12498 cx: &mut Context<Self>,
12499 ) {
12500 let buffer = self.buffer.read(cx).snapshot(cx);
12501 let selection = self.selections.newest::<usize>(cx);
12502
12503 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12504 if direction == Direction::Next {
12505 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12506 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12507 return;
12508 };
12509 self.activate_diagnostics(
12510 buffer_id,
12511 popover.local_diagnostic.diagnostic.group_id,
12512 window,
12513 cx,
12514 );
12515 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12516 let primary_range_start = active_diagnostics.primary_range.start;
12517 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12518 let mut new_selection = s.newest_anchor().clone();
12519 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12520 s.select_anchors(vec![new_selection.clone()]);
12521 });
12522 self.refresh_inline_completion(false, true, window, cx);
12523 }
12524 return;
12525 }
12526 }
12527
12528 let active_group_id = self
12529 .active_diagnostics
12530 .as_ref()
12531 .map(|active_group| active_group.group_id);
12532 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12533 active_diagnostics
12534 .primary_range
12535 .to_offset(&buffer)
12536 .to_inclusive()
12537 });
12538 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12539 if active_primary_range.contains(&selection.head()) {
12540 *active_primary_range.start()
12541 } else {
12542 selection.head()
12543 }
12544 } else {
12545 selection.head()
12546 };
12547
12548 let snapshot = self.snapshot(window, cx);
12549 let primary_diagnostics_before = buffer
12550 .diagnostics_in_range::<usize>(0..search_start)
12551 .filter(|entry| entry.diagnostic.is_primary)
12552 .filter(|entry| entry.range.start != entry.range.end)
12553 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12554 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12555 .collect::<Vec<_>>();
12556 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12557 primary_diagnostics_before
12558 .iter()
12559 .position(|entry| entry.diagnostic.group_id == active_group_id)
12560 });
12561
12562 let primary_diagnostics_after = buffer
12563 .diagnostics_in_range::<usize>(search_start..buffer.len())
12564 .filter(|entry| entry.diagnostic.is_primary)
12565 .filter(|entry| entry.range.start != entry.range.end)
12566 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12567 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12568 .collect::<Vec<_>>();
12569 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12570 primary_diagnostics_after
12571 .iter()
12572 .enumerate()
12573 .rev()
12574 .find_map(|(i, entry)| {
12575 if entry.diagnostic.group_id == active_group_id {
12576 Some(i)
12577 } else {
12578 None
12579 }
12580 })
12581 });
12582
12583 let next_primary_diagnostic = match direction {
12584 Direction::Prev => primary_diagnostics_before
12585 .iter()
12586 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12587 .rev()
12588 .next(),
12589 Direction::Next => primary_diagnostics_after
12590 .iter()
12591 .skip(
12592 last_same_group_diagnostic_after
12593 .map(|index| index + 1)
12594 .unwrap_or(0),
12595 )
12596 .next(),
12597 };
12598
12599 // Cycle around to the start of the buffer, potentially moving back to the start of
12600 // the currently active diagnostic.
12601 let cycle_around = || match direction {
12602 Direction::Prev => primary_diagnostics_after
12603 .iter()
12604 .rev()
12605 .chain(primary_diagnostics_before.iter().rev())
12606 .next(),
12607 Direction::Next => primary_diagnostics_before
12608 .iter()
12609 .chain(primary_diagnostics_after.iter())
12610 .next(),
12611 };
12612
12613 if let Some((primary_range, group_id)) = next_primary_diagnostic
12614 .or_else(cycle_around)
12615 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12616 {
12617 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12618 return;
12619 };
12620 self.activate_diagnostics(buffer_id, group_id, window, cx);
12621 if self.active_diagnostics.is_some() {
12622 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12623 s.select(vec![Selection {
12624 id: selection.id,
12625 start: primary_range.start,
12626 end: primary_range.start,
12627 reversed: false,
12628 goal: SelectionGoal::None,
12629 }]);
12630 });
12631 self.refresh_inline_completion(false, true, window, cx);
12632 }
12633 }
12634 }
12635
12636 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12637 let snapshot = self.snapshot(window, cx);
12638 let selection = self.selections.newest::<Point>(cx);
12639 self.go_to_hunk_before_or_after_position(
12640 &snapshot,
12641 selection.head(),
12642 Direction::Next,
12643 window,
12644 cx,
12645 );
12646 }
12647
12648 pub fn go_to_hunk_before_or_after_position(
12649 &mut self,
12650 snapshot: &EditorSnapshot,
12651 position: Point,
12652 direction: Direction,
12653 window: &mut Window,
12654 cx: &mut Context<Editor>,
12655 ) {
12656 let row = if direction == Direction::Next {
12657 self.hunk_after_position(snapshot, position)
12658 .map(|hunk| hunk.row_range.start)
12659 } else {
12660 self.hunk_before_position(snapshot, position)
12661 };
12662
12663 if let Some(row) = row {
12664 let destination = Point::new(row.0, 0);
12665 let autoscroll = Autoscroll::center();
12666
12667 self.unfold_ranges(&[destination..destination], false, false, cx);
12668 self.change_selections(Some(autoscroll), window, cx, |s| {
12669 s.select_ranges([destination..destination]);
12670 });
12671 }
12672 }
12673
12674 fn hunk_after_position(
12675 &mut self,
12676 snapshot: &EditorSnapshot,
12677 position: Point,
12678 ) -> Option<MultiBufferDiffHunk> {
12679 snapshot
12680 .buffer_snapshot
12681 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12682 .find(|hunk| hunk.row_range.start.0 > position.row)
12683 .or_else(|| {
12684 snapshot
12685 .buffer_snapshot
12686 .diff_hunks_in_range(Point::zero()..position)
12687 .find(|hunk| hunk.row_range.end.0 < position.row)
12688 })
12689 }
12690
12691 fn go_to_prev_hunk(
12692 &mut self,
12693 _: &GoToPreviousHunk,
12694 window: &mut Window,
12695 cx: &mut Context<Self>,
12696 ) {
12697 let snapshot = self.snapshot(window, cx);
12698 let selection = self.selections.newest::<Point>(cx);
12699 self.go_to_hunk_before_or_after_position(
12700 &snapshot,
12701 selection.head(),
12702 Direction::Prev,
12703 window,
12704 cx,
12705 );
12706 }
12707
12708 fn hunk_before_position(
12709 &mut self,
12710 snapshot: &EditorSnapshot,
12711 position: Point,
12712 ) -> Option<MultiBufferRow> {
12713 snapshot
12714 .buffer_snapshot
12715 .diff_hunk_before(position)
12716 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12717 }
12718
12719 fn go_to_line<T: 'static>(
12720 &mut self,
12721 position: Anchor,
12722 highlight_color: Option<Hsla>,
12723 window: &mut Window,
12724 cx: &mut Context<Self>,
12725 ) {
12726 let snapshot = self.snapshot(window, cx).display_snapshot;
12727 let position = position.to_point(&snapshot.buffer_snapshot);
12728 let start = snapshot
12729 .buffer_snapshot
12730 .clip_point(Point::new(position.row, 0), Bias::Left);
12731 let end = start + Point::new(1, 0);
12732 let start = snapshot.buffer_snapshot.anchor_before(start);
12733 let end = snapshot.buffer_snapshot.anchor_before(end);
12734
12735 self.highlight_rows::<T>(
12736 start..end,
12737 highlight_color
12738 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12739 false,
12740 cx,
12741 );
12742 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
12743 }
12744
12745 pub fn go_to_definition(
12746 &mut self,
12747 _: &GoToDefinition,
12748 window: &mut Window,
12749 cx: &mut Context<Self>,
12750 ) -> Task<Result<Navigated>> {
12751 let definition =
12752 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12753 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
12754 cx.spawn_in(window, async move |editor, cx| {
12755 if definition.await? == Navigated::Yes {
12756 return Ok(Navigated::Yes);
12757 }
12758 match fallback_strategy {
12759 GoToDefinitionFallback::None => Ok(Navigated::No),
12760 GoToDefinitionFallback::FindAllReferences => {
12761 match editor.update_in(cx, |editor, window, cx| {
12762 editor.find_all_references(&FindAllReferences, window, cx)
12763 })? {
12764 Some(references) => references.await,
12765 None => Ok(Navigated::No),
12766 }
12767 }
12768 }
12769 })
12770 }
12771
12772 pub fn go_to_declaration(
12773 &mut self,
12774 _: &GoToDeclaration,
12775 window: &mut Window,
12776 cx: &mut Context<Self>,
12777 ) -> Task<Result<Navigated>> {
12778 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12779 }
12780
12781 pub fn go_to_declaration_split(
12782 &mut self,
12783 _: &GoToDeclaration,
12784 window: &mut Window,
12785 cx: &mut Context<Self>,
12786 ) -> Task<Result<Navigated>> {
12787 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12788 }
12789
12790 pub fn go_to_implementation(
12791 &mut self,
12792 _: &GoToImplementation,
12793 window: &mut Window,
12794 cx: &mut Context<Self>,
12795 ) -> Task<Result<Navigated>> {
12796 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12797 }
12798
12799 pub fn go_to_implementation_split(
12800 &mut self,
12801 _: &GoToImplementationSplit,
12802 window: &mut Window,
12803 cx: &mut Context<Self>,
12804 ) -> Task<Result<Navigated>> {
12805 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12806 }
12807
12808 pub fn go_to_type_definition(
12809 &mut self,
12810 _: &GoToTypeDefinition,
12811 window: &mut Window,
12812 cx: &mut Context<Self>,
12813 ) -> Task<Result<Navigated>> {
12814 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12815 }
12816
12817 pub fn go_to_definition_split(
12818 &mut self,
12819 _: &GoToDefinitionSplit,
12820 window: &mut Window,
12821 cx: &mut Context<Self>,
12822 ) -> Task<Result<Navigated>> {
12823 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12824 }
12825
12826 pub fn go_to_type_definition_split(
12827 &mut self,
12828 _: &GoToTypeDefinitionSplit,
12829 window: &mut Window,
12830 cx: &mut Context<Self>,
12831 ) -> Task<Result<Navigated>> {
12832 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12833 }
12834
12835 fn go_to_definition_of_kind(
12836 &mut self,
12837 kind: GotoDefinitionKind,
12838 split: bool,
12839 window: &mut Window,
12840 cx: &mut Context<Self>,
12841 ) -> Task<Result<Navigated>> {
12842 let Some(provider) = self.semantics_provider.clone() else {
12843 return Task::ready(Ok(Navigated::No));
12844 };
12845 let head = self.selections.newest::<usize>(cx).head();
12846 let buffer = self.buffer.read(cx);
12847 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12848 text_anchor
12849 } else {
12850 return Task::ready(Ok(Navigated::No));
12851 };
12852
12853 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12854 return Task::ready(Ok(Navigated::No));
12855 };
12856
12857 cx.spawn_in(window, async move |editor, cx| {
12858 let definitions = definitions.await?;
12859 let navigated = editor
12860 .update_in(cx, |editor, window, cx| {
12861 editor.navigate_to_hover_links(
12862 Some(kind),
12863 definitions
12864 .into_iter()
12865 .filter(|location| {
12866 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12867 })
12868 .map(HoverLink::Text)
12869 .collect::<Vec<_>>(),
12870 split,
12871 window,
12872 cx,
12873 )
12874 })?
12875 .await?;
12876 anyhow::Ok(navigated)
12877 })
12878 }
12879
12880 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12881 let selection = self.selections.newest_anchor();
12882 let head = selection.head();
12883 let tail = selection.tail();
12884
12885 let Some((buffer, start_position)) =
12886 self.buffer.read(cx).text_anchor_for_position(head, cx)
12887 else {
12888 return;
12889 };
12890
12891 let end_position = if head != tail {
12892 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12893 return;
12894 };
12895 Some(pos)
12896 } else {
12897 None
12898 };
12899
12900 let url_finder = cx.spawn_in(window, async move |editor, cx| {
12901 let url = if let Some(end_pos) = end_position {
12902 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12903 } else {
12904 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12905 };
12906
12907 if let Some(url) = url {
12908 editor.update(cx, |_, cx| {
12909 cx.open_url(&url);
12910 })
12911 } else {
12912 Ok(())
12913 }
12914 });
12915
12916 url_finder.detach();
12917 }
12918
12919 pub fn open_selected_filename(
12920 &mut self,
12921 _: &OpenSelectedFilename,
12922 window: &mut Window,
12923 cx: &mut Context<Self>,
12924 ) {
12925 let Some(workspace) = self.workspace() else {
12926 return;
12927 };
12928
12929 let position = self.selections.newest_anchor().head();
12930
12931 let Some((buffer, buffer_position)) =
12932 self.buffer.read(cx).text_anchor_for_position(position, cx)
12933 else {
12934 return;
12935 };
12936
12937 let project = self.project.clone();
12938
12939 cx.spawn_in(window, async move |_, cx| {
12940 let result = find_file(&buffer, project, buffer_position, cx).await;
12941
12942 if let Some((_, path)) = result {
12943 workspace
12944 .update_in(cx, |workspace, window, cx| {
12945 workspace.open_resolved_path(path, window, cx)
12946 })?
12947 .await?;
12948 }
12949 anyhow::Ok(())
12950 })
12951 .detach();
12952 }
12953
12954 pub(crate) fn navigate_to_hover_links(
12955 &mut self,
12956 kind: Option<GotoDefinitionKind>,
12957 mut definitions: Vec<HoverLink>,
12958 split: bool,
12959 window: &mut Window,
12960 cx: &mut Context<Editor>,
12961 ) -> Task<Result<Navigated>> {
12962 // If there is one definition, just open it directly
12963 if definitions.len() == 1 {
12964 let definition = definitions.pop().unwrap();
12965
12966 enum TargetTaskResult {
12967 Location(Option<Location>),
12968 AlreadyNavigated,
12969 }
12970
12971 let target_task = match definition {
12972 HoverLink::Text(link) => {
12973 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12974 }
12975 HoverLink::InlayHint(lsp_location, server_id) => {
12976 let computation =
12977 self.compute_target_location(lsp_location, server_id, window, cx);
12978 cx.background_spawn(async move {
12979 let location = computation.await?;
12980 Ok(TargetTaskResult::Location(location))
12981 })
12982 }
12983 HoverLink::Url(url) => {
12984 cx.open_url(&url);
12985 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12986 }
12987 HoverLink::File(path) => {
12988 if let Some(workspace) = self.workspace() {
12989 cx.spawn_in(window, async move |_, cx| {
12990 workspace
12991 .update_in(cx, |workspace, window, cx| {
12992 workspace.open_resolved_path(path, window, cx)
12993 })?
12994 .await
12995 .map(|_| TargetTaskResult::AlreadyNavigated)
12996 })
12997 } else {
12998 Task::ready(Ok(TargetTaskResult::Location(None)))
12999 }
13000 }
13001 };
13002 cx.spawn_in(window, async move |editor, cx| {
13003 let target = match target_task.await.context("target resolution task")? {
13004 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13005 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13006 TargetTaskResult::Location(Some(target)) => target,
13007 };
13008
13009 editor.update_in(cx, |editor, window, cx| {
13010 let Some(workspace) = editor.workspace() else {
13011 return Navigated::No;
13012 };
13013 let pane = workspace.read(cx).active_pane().clone();
13014
13015 let range = target.range.to_point(target.buffer.read(cx));
13016 let range = editor.range_for_match(&range);
13017 let range = collapse_multiline_range(range);
13018
13019 if !split
13020 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13021 {
13022 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13023 } else {
13024 window.defer(cx, move |window, cx| {
13025 let target_editor: Entity<Self> =
13026 workspace.update(cx, |workspace, cx| {
13027 let pane = if split {
13028 workspace.adjacent_pane(window, cx)
13029 } else {
13030 workspace.active_pane().clone()
13031 };
13032
13033 workspace.open_project_item(
13034 pane,
13035 target.buffer.clone(),
13036 true,
13037 true,
13038 window,
13039 cx,
13040 )
13041 });
13042 target_editor.update(cx, |target_editor, cx| {
13043 // When selecting a definition in a different buffer, disable the nav history
13044 // to avoid creating a history entry at the previous cursor location.
13045 pane.update(cx, |pane, _| pane.disable_history());
13046 target_editor.go_to_singleton_buffer_range(range, window, cx);
13047 pane.update(cx, |pane, _| pane.enable_history());
13048 });
13049 });
13050 }
13051 Navigated::Yes
13052 })
13053 })
13054 } else if !definitions.is_empty() {
13055 cx.spawn_in(window, async move |editor, cx| {
13056 let (title, location_tasks, workspace) = editor
13057 .update_in(cx, |editor, window, cx| {
13058 let tab_kind = match kind {
13059 Some(GotoDefinitionKind::Implementation) => "Implementations",
13060 _ => "Definitions",
13061 };
13062 let title = definitions
13063 .iter()
13064 .find_map(|definition| match definition {
13065 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13066 let buffer = origin.buffer.read(cx);
13067 format!(
13068 "{} for {}",
13069 tab_kind,
13070 buffer
13071 .text_for_range(origin.range.clone())
13072 .collect::<String>()
13073 )
13074 }),
13075 HoverLink::InlayHint(_, _) => None,
13076 HoverLink::Url(_) => None,
13077 HoverLink::File(_) => None,
13078 })
13079 .unwrap_or(tab_kind.to_string());
13080 let location_tasks = definitions
13081 .into_iter()
13082 .map(|definition| match definition {
13083 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13084 HoverLink::InlayHint(lsp_location, server_id) => editor
13085 .compute_target_location(lsp_location, server_id, window, cx),
13086 HoverLink::Url(_) => Task::ready(Ok(None)),
13087 HoverLink::File(_) => Task::ready(Ok(None)),
13088 })
13089 .collect::<Vec<_>>();
13090 (title, location_tasks, editor.workspace().clone())
13091 })
13092 .context("location tasks preparation")?;
13093
13094 let locations = future::join_all(location_tasks)
13095 .await
13096 .into_iter()
13097 .filter_map(|location| location.transpose())
13098 .collect::<Result<_>>()
13099 .context("location tasks")?;
13100
13101 let Some(workspace) = workspace else {
13102 return Ok(Navigated::No);
13103 };
13104 let opened = workspace
13105 .update_in(cx, |workspace, window, cx| {
13106 Self::open_locations_in_multibuffer(
13107 workspace,
13108 locations,
13109 title,
13110 split,
13111 MultibufferSelectionMode::First,
13112 window,
13113 cx,
13114 )
13115 })
13116 .ok();
13117
13118 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13119 })
13120 } else {
13121 Task::ready(Ok(Navigated::No))
13122 }
13123 }
13124
13125 fn compute_target_location(
13126 &self,
13127 lsp_location: lsp::Location,
13128 server_id: LanguageServerId,
13129 window: &mut Window,
13130 cx: &mut Context<Self>,
13131 ) -> Task<anyhow::Result<Option<Location>>> {
13132 let Some(project) = self.project.clone() else {
13133 return Task::ready(Ok(None));
13134 };
13135
13136 cx.spawn_in(window, async move |editor, cx| {
13137 let location_task = editor.update(cx, |_, cx| {
13138 project.update(cx, |project, cx| {
13139 let language_server_name = project
13140 .language_server_statuses(cx)
13141 .find(|(id, _)| server_id == *id)
13142 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13143 language_server_name.map(|language_server_name| {
13144 project.open_local_buffer_via_lsp(
13145 lsp_location.uri.clone(),
13146 server_id,
13147 language_server_name,
13148 cx,
13149 )
13150 })
13151 })
13152 })?;
13153 let location = match location_task {
13154 Some(task) => Some({
13155 let target_buffer_handle = task.await.context("open local buffer")?;
13156 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13157 let target_start = target_buffer
13158 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13159 let target_end = target_buffer
13160 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13161 target_buffer.anchor_after(target_start)
13162 ..target_buffer.anchor_before(target_end)
13163 })?;
13164 Location {
13165 buffer: target_buffer_handle,
13166 range,
13167 }
13168 }),
13169 None => None,
13170 };
13171 Ok(location)
13172 })
13173 }
13174
13175 pub fn find_all_references(
13176 &mut self,
13177 _: &FindAllReferences,
13178 window: &mut Window,
13179 cx: &mut Context<Self>,
13180 ) -> Option<Task<Result<Navigated>>> {
13181 let selection = self.selections.newest::<usize>(cx);
13182 let multi_buffer = self.buffer.read(cx);
13183 let head = selection.head();
13184
13185 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13186 let head_anchor = multi_buffer_snapshot.anchor_at(
13187 head,
13188 if head < selection.tail() {
13189 Bias::Right
13190 } else {
13191 Bias::Left
13192 },
13193 );
13194
13195 match self
13196 .find_all_references_task_sources
13197 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13198 {
13199 Ok(_) => {
13200 log::info!(
13201 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13202 );
13203 return None;
13204 }
13205 Err(i) => {
13206 self.find_all_references_task_sources.insert(i, head_anchor);
13207 }
13208 }
13209
13210 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13211 let workspace = self.workspace()?;
13212 let project = workspace.read(cx).project().clone();
13213 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13214 Some(cx.spawn_in(window, async move |editor, cx| {
13215 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13216 if let Ok(i) = editor
13217 .find_all_references_task_sources
13218 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13219 {
13220 editor.find_all_references_task_sources.remove(i);
13221 }
13222 });
13223
13224 let locations = references.await?;
13225 if locations.is_empty() {
13226 return anyhow::Ok(Navigated::No);
13227 }
13228
13229 workspace.update_in(cx, |workspace, window, cx| {
13230 let title = locations
13231 .first()
13232 .as_ref()
13233 .map(|location| {
13234 let buffer = location.buffer.read(cx);
13235 format!(
13236 "References to `{}`",
13237 buffer
13238 .text_for_range(location.range.clone())
13239 .collect::<String>()
13240 )
13241 })
13242 .unwrap();
13243 Self::open_locations_in_multibuffer(
13244 workspace,
13245 locations,
13246 title,
13247 false,
13248 MultibufferSelectionMode::First,
13249 window,
13250 cx,
13251 );
13252 Navigated::Yes
13253 })
13254 }))
13255 }
13256
13257 /// Opens a multibuffer with the given project locations in it
13258 pub fn open_locations_in_multibuffer(
13259 workspace: &mut Workspace,
13260 mut locations: Vec<Location>,
13261 title: String,
13262 split: bool,
13263 multibuffer_selection_mode: MultibufferSelectionMode,
13264 window: &mut Window,
13265 cx: &mut Context<Workspace>,
13266 ) {
13267 // If there are multiple definitions, open them in a multibuffer
13268 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13269 let mut locations = locations.into_iter().peekable();
13270 let mut ranges = Vec::new();
13271 let capability = workspace.project().read(cx).capability();
13272
13273 let excerpt_buffer = cx.new(|cx| {
13274 let mut multibuffer = MultiBuffer::new(capability);
13275 while let Some(location) = locations.next() {
13276 let buffer = location.buffer.read(cx);
13277 let mut ranges_for_buffer = Vec::new();
13278 let range = location.range.to_offset(buffer);
13279 ranges_for_buffer.push(range.clone());
13280
13281 while let Some(next_location) = locations.peek() {
13282 if next_location.buffer == location.buffer {
13283 ranges_for_buffer.push(next_location.range.to_offset(buffer));
13284 locations.next();
13285 } else {
13286 break;
13287 }
13288 }
13289
13290 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13291 ranges.extend(multibuffer.push_excerpts_with_context_lines(
13292 location.buffer.clone(),
13293 ranges_for_buffer,
13294 DEFAULT_MULTIBUFFER_CONTEXT,
13295 cx,
13296 ))
13297 }
13298
13299 multibuffer.with_title(title)
13300 });
13301
13302 let editor = cx.new(|cx| {
13303 Editor::for_multibuffer(
13304 excerpt_buffer,
13305 Some(workspace.project().clone()),
13306 window,
13307 cx,
13308 )
13309 });
13310 editor.update(cx, |editor, cx| {
13311 match multibuffer_selection_mode {
13312 MultibufferSelectionMode::First => {
13313 if let Some(first_range) = ranges.first() {
13314 editor.change_selections(None, window, cx, |selections| {
13315 selections.clear_disjoint();
13316 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13317 });
13318 }
13319 editor.highlight_background::<Self>(
13320 &ranges,
13321 |theme| theme.editor_highlighted_line_background,
13322 cx,
13323 );
13324 }
13325 MultibufferSelectionMode::All => {
13326 editor.change_selections(None, window, cx, |selections| {
13327 selections.clear_disjoint();
13328 selections.select_anchor_ranges(ranges);
13329 });
13330 }
13331 }
13332 editor.register_buffers_with_language_servers(cx);
13333 });
13334
13335 let item = Box::new(editor);
13336 let item_id = item.item_id();
13337
13338 if split {
13339 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13340 } else {
13341 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13342 let (preview_item_id, preview_item_idx) =
13343 workspace.active_pane().update(cx, |pane, _| {
13344 (pane.preview_item_id(), pane.preview_item_idx())
13345 });
13346
13347 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13348
13349 if let Some(preview_item_id) = preview_item_id {
13350 workspace.active_pane().update(cx, |pane, cx| {
13351 pane.remove_item(preview_item_id, false, false, window, cx);
13352 });
13353 }
13354 } else {
13355 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13356 }
13357 }
13358 workspace.active_pane().update(cx, |pane, cx| {
13359 pane.set_preview_item_id(Some(item_id), cx);
13360 });
13361 }
13362
13363 pub fn rename(
13364 &mut self,
13365 _: &Rename,
13366 window: &mut Window,
13367 cx: &mut Context<Self>,
13368 ) -> Option<Task<Result<()>>> {
13369 use language::ToOffset as _;
13370
13371 let provider = self.semantics_provider.clone()?;
13372 let selection = self.selections.newest_anchor().clone();
13373 let (cursor_buffer, cursor_buffer_position) = self
13374 .buffer
13375 .read(cx)
13376 .text_anchor_for_position(selection.head(), cx)?;
13377 let (tail_buffer, cursor_buffer_position_end) = self
13378 .buffer
13379 .read(cx)
13380 .text_anchor_for_position(selection.tail(), cx)?;
13381 if tail_buffer != cursor_buffer {
13382 return None;
13383 }
13384
13385 let snapshot = cursor_buffer.read(cx).snapshot();
13386 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13387 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13388 let prepare_rename = provider
13389 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13390 .unwrap_or_else(|| Task::ready(Ok(None)));
13391 drop(snapshot);
13392
13393 Some(cx.spawn_in(window, async move |this, cx| {
13394 let rename_range = if let Some(range) = prepare_rename.await? {
13395 Some(range)
13396 } else {
13397 this.update(cx, |this, cx| {
13398 let buffer = this.buffer.read(cx).snapshot(cx);
13399 let mut buffer_highlights = this
13400 .document_highlights_for_position(selection.head(), &buffer)
13401 .filter(|highlight| {
13402 highlight.start.excerpt_id == selection.head().excerpt_id
13403 && highlight.end.excerpt_id == selection.head().excerpt_id
13404 });
13405 buffer_highlights
13406 .next()
13407 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13408 })?
13409 };
13410 if let Some(rename_range) = rename_range {
13411 this.update_in(cx, |this, window, cx| {
13412 let snapshot = cursor_buffer.read(cx).snapshot();
13413 let rename_buffer_range = rename_range.to_offset(&snapshot);
13414 let cursor_offset_in_rename_range =
13415 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13416 let cursor_offset_in_rename_range_end =
13417 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13418
13419 this.take_rename(false, window, cx);
13420 let buffer = this.buffer.read(cx).read(cx);
13421 let cursor_offset = selection.head().to_offset(&buffer);
13422 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13423 let rename_end = rename_start + rename_buffer_range.len();
13424 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13425 let mut old_highlight_id = None;
13426 let old_name: Arc<str> = buffer
13427 .chunks(rename_start..rename_end, true)
13428 .map(|chunk| {
13429 if old_highlight_id.is_none() {
13430 old_highlight_id = chunk.syntax_highlight_id;
13431 }
13432 chunk.text
13433 })
13434 .collect::<String>()
13435 .into();
13436
13437 drop(buffer);
13438
13439 // Position the selection in the rename editor so that it matches the current selection.
13440 this.show_local_selections = false;
13441 let rename_editor = cx.new(|cx| {
13442 let mut editor = Editor::single_line(window, cx);
13443 editor.buffer.update(cx, |buffer, cx| {
13444 buffer.edit([(0..0, old_name.clone())], None, cx)
13445 });
13446 let rename_selection_range = match cursor_offset_in_rename_range
13447 .cmp(&cursor_offset_in_rename_range_end)
13448 {
13449 Ordering::Equal => {
13450 editor.select_all(&SelectAll, window, cx);
13451 return editor;
13452 }
13453 Ordering::Less => {
13454 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13455 }
13456 Ordering::Greater => {
13457 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13458 }
13459 };
13460 if rename_selection_range.end > old_name.len() {
13461 editor.select_all(&SelectAll, window, cx);
13462 } else {
13463 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13464 s.select_ranges([rename_selection_range]);
13465 });
13466 }
13467 editor
13468 });
13469 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13470 if e == &EditorEvent::Focused {
13471 cx.emit(EditorEvent::FocusedIn)
13472 }
13473 })
13474 .detach();
13475
13476 let write_highlights =
13477 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13478 let read_highlights =
13479 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13480 let ranges = write_highlights
13481 .iter()
13482 .flat_map(|(_, ranges)| ranges.iter())
13483 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13484 .cloned()
13485 .collect();
13486
13487 this.highlight_text::<Rename>(
13488 ranges,
13489 HighlightStyle {
13490 fade_out: Some(0.6),
13491 ..Default::default()
13492 },
13493 cx,
13494 );
13495 let rename_focus_handle = rename_editor.focus_handle(cx);
13496 window.focus(&rename_focus_handle);
13497 let block_id = this.insert_blocks(
13498 [BlockProperties {
13499 style: BlockStyle::Flex,
13500 placement: BlockPlacement::Below(range.start),
13501 height: 1,
13502 render: Arc::new({
13503 let rename_editor = rename_editor.clone();
13504 move |cx: &mut BlockContext| {
13505 let mut text_style = cx.editor_style.text.clone();
13506 if let Some(highlight_style) = old_highlight_id
13507 .and_then(|h| h.style(&cx.editor_style.syntax))
13508 {
13509 text_style = text_style.highlight(highlight_style);
13510 }
13511 div()
13512 .block_mouse_down()
13513 .pl(cx.anchor_x)
13514 .child(EditorElement::new(
13515 &rename_editor,
13516 EditorStyle {
13517 background: cx.theme().system().transparent,
13518 local_player: cx.editor_style.local_player,
13519 text: text_style,
13520 scrollbar_width: cx.editor_style.scrollbar_width,
13521 syntax: cx.editor_style.syntax.clone(),
13522 status: cx.editor_style.status.clone(),
13523 inlay_hints_style: HighlightStyle {
13524 font_weight: Some(FontWeight::BOLD),
13525 ..make_inlay_hints_style(cx.app)
13526 },
13527 inline_completion_styles: make_suggestion_styles(
13528 cx.app,
13529 ),
13530 ..EditorStyle::default()
13531 },
13532 ))
13533 .into_any_element()
13534 }
13535 }),
13536 priority: 0,
13537 }],
13538 Some(Autoscroll::fit()),
13539 cx,
13540 )[0];
13541 this.pending_rename = Some(RenameState {
13542 range,
13543 old_name,
13544 editor: rename_editor,
13545 block_id,
13546 });
13547 })?;
13548 }
13549
13550 Ok(())
13551 }))
13552 }
13553
13554 pub fn confirm_rename(
13555 &mut self,
13556 _: &ConfirmRename,
13557 window: &mut Window,
13558 cx: &mut Context<Self>,
13559 ) -> Option<Task<Result<()>>> {
13560 let rename = self.take_rename(false, window, cx)?;
13561 let workspace = self.workspace()?.downgrade();
13562 let (buffer, start) = self
13563 .buffer
13564 .read(cx)
13565 .text_anchor_for_position(rename.range.start, cx)?;
13566 let (end_buffer, _) = self
13567 .buffer
13568 .read(cx)
13569 .text_anchor_for_position(rename.range.end, cx)?;
13570 if buffer != end_buffer {
13571 return None;
13572 }
13573
13574 let old_name = rename.old_name;
13575 let new_name = rename.editor.read(cx).text(cx);
13576
13577 let rename = self.semantics_provider.as_ref()?.perform_rename(
13578 &buffer,
13579 start,
13580 new_name.clone(),
13581 cx,
13582 )?;
13583
13584 Some(cx.spawn_in(window, async move |editor, cx| {
13585 let project_transaction = rename.await?;
13586 Self::open_project_transaction(
13587 &editor,
13588 workspace,
13589 project_transaction,
13590 format!("Rename: {} → {}", old_name, new_name),
13591 cx,
13592 )
13593 .await?;
13594
13595 editor.update(cx, |editor, cx| {
13596 editor.refresh_document_highlights(cx);
13597 })?;
13598 Ok(())
13599 }))
13600 }
13601
13602 fn take_rename(
13603 &mut self,
13604 moving_cursor: bool,
13605 window: &mut Window,
13606 cx: &mut Context<Self>,
13607 ) -> Option<RenameState> {
13608 let rename = self.pending_rename.take()?;
13609 if rename.editor.focus_handle(cx).is_focused(window) {
13610 window.focus(&self.focus_handle);
13611 }
13612
13613 self.remove_blocks(
13614 [rename.block_id].into_iter().collect(),
13615 Some(Autoscroll::fit()),
13616 cx,
13617 );
13618 self.clear_highlights::<Rename>(cx);
13619 self.show_local_selections = true;
13620
13621 if moving_cursor {
13622 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13623 editor.selections.newest::<usize>(cx).head()
13624 });
13625
13626 // Update the selection to match the position of the selection inside
13627 // the rename editor.
13628 let snapshot = self.buffer.read(cx).read(cx);
13629 let rename_range = rename.range.to_offset(&snapshot);
13630 let cursor_in_editor = snapshot
13631 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13632 .min(rename_range.end);
13633 drop(snapshot);
13634
13635 self.change_selections(None, window, cx, |s| {
13636 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13637 });
13638 } else {
13639 self.refresh_document_highlights(cx);
13640 }
13641
13642 Some(rename)
13643 }
13644
13645 pub fn pending_rename(&self) -> Option<&RenameState> {
13646 self.pending_rename.as_ref()
13647 }
13648
13649 fn format(
13650 &mut self,
13651 _: &Format,
13652 window: &mut Window,
13653 cx: &mut Context<Self>,
13654 ) -> Option<Task<Result<()>>> {
13655 let project = match &self.project {
13656 Some(project) => project.clone(),
13657 None => return None,
13658 };
13659
13660 Some(self.perform_format(
13661 project,
13662 FormatTrigger::Manual,
13663 FormatTarget::Buffers,
13664 window,
13665 cx,
13666 ))
13667 }
13668
13669 fn format_selections(
13670 &mut self,
13671 _: &FormatSelections,
13672 window: &mut Window,
13673 cx: &mut Context<Self>,
13674 ) -> Option<Task<Result<()>>> {
13675 let project = match &self.project {
13676 Some(project) => project.clone(),
13677 None => return None,
13678 };
13679
13680 let ranges = self
13681 .selections
13682 .all_adjusted(cx)
13683 .into_iter()
13684 .map(|selection| selection.range())
13685 .collect_vec();
13686
13687 Some(self.perform_format(
13688 project,
13689 FormatTrigger::Manual,
13690 FormatTarget::Ranges(ranges),
13691 window,
13692 cx,
13693 ))
13694 }
13695
13696 fn perform_format(
13697 &mut self,
13698 project: Entity<Project>,
13699 trigger: FormatTrigger,
13700 target: FormatTarget,
13701 window: &mut Window,
13702 cx: &mut Context<Self>,
13703 ) -> Task<Result<()>> {
13704 let buffer = self.buffer.clone();
13705 let (buffers, target) = match target {
13706 FormatTarget::Buffers => {
13707 let mut buffers = buffer.read(cx).all_buffers();
13708 if trigger == FormatTrigger::Save {
13709 buffers.retain(|buffer| buffer.read(cx).is_dirty());
13710 }
13711 (buffers, LspFormatTarget::Buffers)
13712 }
13713 FormatTarget::Ranges(selection_ranges) => {
13714 let multi_buffer = buffer.read(cx);
13715 let snapshot = multi_buffer.read(cx);
13716 let mut buffers = HashSet::default();
13717 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13718 BTreeMap::new();
13719 for selection_range in selection_ranges {
13720 for (buffer, buffer_range, _) in
13721 snapshot.range_to_buffer_ranges(selection_range)
13722 {
13723 let buffer_id = buffer.remote_id();
13724 let start = buffer.anchor_before(buffer_range.start);
13725 let end = buffer.anchor_after(buffer_range.end);
13726 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13727 buffer_id_to_ranges
13728 .entry(buffer_id)
13729 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13730 .or_insert_with(|| vec![start..end]);
13731 }
13732 }
13733 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13734 }
13735 };
13736
13737 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13738 let format = project.update(cx, |project, cx| {
13739 project.format(buffers, target, true, trigger, cx)
13740 });
13741
13742 cx.spawn_in(window, async move |_, cx| {
13743 let transaction = futures::select_biased! {
13744 transaction = format.log_err().fuse() => transaction,
13745 () = timeout => {
13746 log::warn!("timed out waiting for formatting");
13747 None
13748 }
13749 };
13750
13751 buffer
13752 .update(cx, |buffer, cx| {
13753 if let Some(transaction) = transaction {
13754 if !buffer.is_singleton() {
13755 buffer.push_transaction(&transaction.0, cx);
13756 }
13757 }
13758 cx.notify();
13759 })
13760 .ok();
13761
13762 Ok(())
13763 })
13764 }
13765
13766 fn organize_imports(
13767 &mut self,
13768 _: &OrganizeImports,
13769 window: &mut Window,
13770 cx: &mut Context<Self>,
13771 ) -> Option<Task<Result<()>>> {
13772 let project = match &self.project {
13773 Some(project) => project.clone(),
13774 None => return None,
13775 };
13776 Some(self.perform_code_action_kind(
13777 project,
13778 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13779 window,
13780 cx,
13781 ))
13782 }
13783
13784 fn perform_code_action_kind(
13785 &mut self,
13786 project: Entity<Project>,
13787 kind: CodeActionKind,
13788 window: &mut Window,
13789 cx: &mut Context<Self>,
13790 ) -> Task<Result<()>> {
13791 let buffer = self.buffer.clone();
13792 let buffers = buffer.read(cx).all_buffers();
13793 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13794 let apply_action = project.update(cx, |project, cx| {
13795 project.apply_code_action_kind(buffers, kind, true, cx)
13796 });
13797 cx.spawn_in(window, async move |_, cx| {
13798 let transaction = futures::select_biased! {
13799 () = timeout => {
13800 log::warn!("timed out waiting for executing code action");
13801 None
13802 }
13803 transaction = apply_action.log_err().fuse() => transaction,
13804 };
13805 buffer
13806 .update(cx, |buffer, cx| {
13807 // check if we need this
13808 if let Some(transaction) = transaction {
13809 if !buffer.is_singleton() {
13810 buffer.push_transaction(&transaction.0, cx);
13811 }
13812 }
13813 cx.notify();
13814 })
13815 .ok();
13816 Ok(())
13817 })
13818 }
13819
13820 fn restart_language_server(
13821 &mut self,
13822 _: &RestartLanguageServer,
13823 _: &mut Window,
13824 cx: &mut Context<Self>,
13825 ) {
13826 if let Some(project) = self.project.clone() {
13827 self.buffer.update(cx, |multi_buffer, cx| {
13828 project.update(cx, |project, cx| {
13829 project.restart_language_servers_for_buffers(
13830 multi_buffer.all_buffers().into_iter().collect(),
13831 cx,
13832 );
13833 });
13834 })
13835 }
13836 }
13837
13838 fn cancel_language_server_work(
13839 workspace: &mut Workspace,
13840 _: &actions::CancelLanguageServerWork,
13841 _: &mut Window,
13842 cx: &mut Context<Workspace>,
13843 ) {
13844 let project = workspace.project();
13845 let buffers = workspace
13846 .active_item(cx)
13847 .and_then(|item| item.act_as::<Editor>(cx))
13848 .map_or(HashSet::default(), |editor| {
13849 editor.read(cx).buffer.read(cx).all_buffers()
13850 });
13851 project.update(cx, |project, cx| {
13852 project.cancel_language_server_work_for_buffers(buffers, cx);
13853 });
13854 }
13855
13856 fn show_character_palette(
13857 &mut self,
13858 _: &ShowCharacterPalette,
13859 window: &mut Window,
13860 _: &mut Context<Self>,
13861 ) {
13862 window.show_character_palette();
13863 }
13864
13865 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13866 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13867 let buffer = self.buffer.read(cx).snapshot(cx);
13868 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13869 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13870 let is_valid = buffer
13871 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13872 .any(|entry| {
13873 entry.diagnostic.is_primary
13874 && !entry.range.is_empty()
13875 && entry.range.start == primary_range_start
13876 && entry.diagnostic.message == active_diagnostics.primary_message
13877 });
13878
13879 if is_valid != active_diagnostics.is_valid {
13880 active_diagnostics.is_valid = is_valid;
13881 if is_valid {
13882 let mut new_styles = HashMap::default();
13883 for (block_id, diagnostic) in &active_diagnostics.blocks {
13884 new_styles.insert(
13885 *block_id,
13886 diagnostic_block_renderer(diagnostic.clone(), None, true),
13887 );
13888 }
13889 self.display_map.update(cx, |display_map, _cx| {
13890 display_map.replace_blocks(new_styles);
13891 });
13892 } else {
13893 self.dismiss_diagnostics(cx);
13894 }
13895 }
13896 }
13897 }
13898
13899 fn activate_diagnostics(
13900 &mut self,
13901 buffer_id: BufferId,
13902 group_id: usize,
13903 window: &mut Window,
13904 cx: &mut Context<Self>,
13905 ) {
13906 self.dismiss_diagnostics(cx);
13907 let snapshot = self.snapshot(window, cx);
13908 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13909 let buffer = self.buffer.read(cx).snapshot(cx);
13910
13911 let mut primary_range = None;
13912 let mut primary_message = None;
13913 let diagnostic_group = buffer
13914 .diagnostic_group(buffer_id, group_id)
13915 .filter_map(|entry| {
13916 let start = entry.range.start;
13917 let end = entry.range.end;
13918 if snapshot.is_line_folded(MultiBufferRow(start.row))
13919 && (start.row == end.row
13920 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13921 {
13922 return None;
13923 }
13924 if entry.diagnostic.is_primary {
13925 primary_range = Some(entry.range.clone());
13926 primary_message = Some(entry.diagnostic.message.clone());
13927 }
13928 Some(entry)
13929 })
13930 .collect::<Vec<_>>();
13931 let primary_range = primary_range?;
13932 let primary_message = primary_message?;
13933
13934 let blocks = display_map
13935 .insert_blocks(
13936 diagnostic_group.iter().map(|entry| {
13937 let diagnostic = entry.diagnostic.clone();
13938 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13939 BlockProperties {
13940 style: BlockStyle::Fixed,
13941 placement: BlockPlacement::Below(
13942 buffer.anchor_after(entry.range.start),
13943 ),
13944 height: message_height,
13945 render: diagnostic_block_renderer(diagnostic, None, true),
13946 priority: 0,
13947 }
13948 }),
13949 cx,
13950 )
13951 .into_iter()
13952 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13953 .collect();
13954
13955 Some(ActiveDiagnosticGroup {
13956 primary_range: buffer.anchor_before(primary_range.start)
13957 ..buffer.anchor_after(primary_range.end),
13958 primary_message,
13959 group_id,
13960 blocks,
13961 is_valid: true,
13962 })
13963 });
13964 }
13965
13966 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13967 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13968 self.display_map.update(cx, |display_map, cx| {
13969 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13970 });
13971 cx.notify();
13972 }
13973 }
13974
13975 /// Disable inline diagnostics rendering for this editor.
13976 pub fn disable_inline_diagnostics(&mut self) {
13977 self.inline_diagnostics_enabled = false;
13978 self.inline_diagnostics_update = Task::ready(());
13979 self.inline_diagnostics.clear();
13980 }
13981
13982 pub fn inline_diagnostics_enabled(&self) -> bool {
13983 self.inline_diagnostics_enabled
13984 }
13985
13986 pub fn show_inline_diagnostics(&self) -> bool {
13987 self.show_inline_diagnostics
13988 }
13989
13990 pub fn toggle_inline_diagnostics(
13991 &mut self,
13992 _: &ToggleInlineDiagnostics,
13993 window: &mut Window,
13994 cx: &mut Context<Editor>,
13995 ) {
13996 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13997 self.refresh_inline_diagnostics(false, window, cx);
13998 }
13999
14000 fn refresh_inline_diagnostics(
14001 &mut self,
14002 debounce: bool,
14003 window: &mut Window,
14004 cx: &mut Context<Self>,
14005 ) {
14006 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14007 self.inline_diagnostics_update = Task::ready(());
14008 self.inline_diagnostics.clear();
14009 return;
14010 }
14011
14012 let debounce_ms = ProjectSettings::get_global(cx)
14013 .diagnostics
14014 .inline
14015 .update_debounce_ms;
14016 let debounce = if debounce && debounce_ms > 0 {
14017 Some(Duration::from_millis(debounce_ms))
14018 } else {
14019 None
14020 };
14021 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14022 if let Some(debounce) = debounce {
14023 cx.background_executor().timer(debounce).await;
14024 }
14025 let Some(snapshot) = editor
14026 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14027 .ok()
14028 else {
14029 return;
14030 };
14031
14032 let new_inline_diagnostics = cx
14033 .background_spawn(async move {
14034 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14035 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14036 let message = diagnostic_entry
14037 .diagnostic
14038 .message
14039 .split_once('\n')
14040 .map(|(line, _)| line)
14041 .map(SharedString::new)
14042 .unwrap_or_else(|| {
14043 SharedString::from(diagnostic_entry.diagnostic.message)
14044 });
14045 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14046 let (Ok(i) | Err(i)) = inline_diagnostics
14047 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14048 inline_diagnostics.insert(
14049 i,
14050 (
14051 start_anchor,
14052 InlineDiagnostic {
14053 message,
14054 group_id: diagnostic_entry.diagnostic.group_id,
14055 start: diagnostic_entry.range.start.to_point(&snapshot),
14056 is_primary: diagnostic_entry.diagnostic.is_primary,
14057 severity: diagnostic_entry.diagnostic.severity,
14058 },
14059 ),
14060 );
14061 }
14062 inline_diagnostics
14063 })
14064 .await;
14065
14066 editor
14067 .update(cx, |editor, cx| {
14068 editor.inline_diagnostics = new_inline_diagnostics;
14069 cx.notify();
14070 })
14071 .ok();
14072 });
14073 }
14074
14075 pub fn set_selections_from_remote(
14076 &mut self,
14077 selections: Vec<Selection<Anchor>>,
14078 pending_selection: Option<Selection<Anchor>>,
14079 window: &mut Window,
14080 cx: &mut Context<Self>,
14081 ) {
14082 let old_cursor_position = self.selections.newest_anchor().head();
14083 self.selections.change_with(cx, |s| {
14084 s.select_anchors(selections);
14085 if let Some(pending_selection) = pending_selection {
14086 s.set_pending(pending_selection, SelectMode::Character);
14087 } else {
14088 s.clear_pending();
14089 }
14090 });
14091 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14092 }
14093
14094 fn push_to_selection_history(&mut self) {
14095 self.selection_history.push(SelectionHistoryEntry {
14096 selections: self.selections.disjoint_anchors(),
14097 select_next_state: self.select_next_state.clone(),
14098 select_prev_state: self.select_prev_state.clone(),
14099 add_selections_state: self.add_selections_state.clone(),
14100 });
14101 }
14102
14103 pub fn transact(
14104 &mut self,
14105 window: &mut Window,
14106 cx: &mut Context<Self>,
14107 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14108 ) -> Option<TransactionId> {
14109 self.start_transaction_at(Instant::now(), window, cx);
14110 update(self, window, cx);
14111 self.end_transaction_at(Instant::now(), cx)
14112 }
14113
14114 pub fn start_transaction_at(
14115 &mut self,
14116 now: Instant,
14117 window: &mut Window,
14118 cx: &mut Context<Self>,
14119 ) {
14120 self.end_selection(window, cx);
14121 if let Some(tx_id) = self
14122 .buffer
14123 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14124 {
14125 self.selection_history
14126 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14127 cx.emit(EditorEvent::TransactionBegun {
14128 transaction_id: tx_id,
14129 })
14130 }
14131 }
14132
14133 pub fn end_transaction_at(
14134 &mut self,
14135 now: Instant,
14136 cx: &mut Context<Self>,
14137 ) -> Option<TransactionId> {
14138 if let Some(transaction_id) = self
14139 .buffer
14140 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14141 {
14142 if let Some((_, end_selections)) =
14143 self.selection_history.transaction_mut(transaction_id)
14144 {
14145 *end_selections = Some(self.selections.disjoint_anchors());
14146 } else {
14147 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14148 }
14149
14150 cx.emit(EditorEvent::Edited { transaction_id });
14151 Some(transaction_id)
14152 } else {
14153 None
14154 }
14155 }
14156
14157 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14158 if self.selection_mark_mode {
14159 self.change_selections(None, window, cx, |s| {
14160 s.move_with(|_, sel| {
14161 sel.collapse_to(sel.head(), SelectionGoal::None);
14162 });
14163 })
14164 }
14165 self.selection_mark_mode = true;
14166 cx.notify();
14167 }
14168
14169 pub fn swap_selection_ends(
14170 &mut self,
14171 _: &actions::SwapSelectionEnds,
14172 window: &mut Window,
14173 cx: &mut Context<Self>,
14174 ) {
14175 self.change_selections(None, window, cx, |s| {
14176 s.move_with(|_, sel| {
14177 if sel.start != sel.end {
14178 sel.reversed = !sel.reversed
14179 }
14180 });
14181 });
14182 self.request_autoscroll(Autoscroll::newest(), cx);
14183 cx.notify();
14184 }
14185
14186 pub fn toggle_fold(
14187 &mut self,
14188 _: &actions::ToggleFold,
14189 window: &mut Window,
14190 cx: &mut Context<Self>,
14191 ) {
14192 if self.is_singleton(cx) {
14193 let selection = self.selections.newest::<Point>(cx);
14194
14195 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14196 let range = if selection.is_empty() {
14197 let point = selection.head().to_display_point(&display_map);
14198 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14199 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14200 .to_point(&display_map);
14201 start..end
14202 } else {
14203 selection.range()
14204 };
14205 if display_map.folds_in_range(range).next().is_some() {
14206 self.unfold_lines(&Default::default(), window, cx)
14207 } else {
14208 self.fold(&Default::default(), window, cx)
14209 }
14210 } else {
14211 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14212 let buffer_ids: HashSet<_> = self
14213 .selections
14214 .disjoint_anchor_ranges()
14215 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14216 .collect();
14217
14218 let should_unfold = buffer_ids
14219 .iter()
14220 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14221
14222 for buffer_id in buffer_ids {
14223 if should_unfold {
14224 self.unfold_buffer(buffer_id, cx);
14225 } else {
14226 self.fold_buffer(buffer_id, cx);
14227 }
14228 }
14229 }
14230 }
14231
14232 pub fn toggle_fold_recursive(
14233 &mut self,
14234 _: &actions::ToggleFoldRecursive,
14235 window: &mut Window,
14236 cx: &mut Context<Self>,
14237 ) {
14238 let selection = self.selections.newest::<Point>(cx);
14239
14240 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14241 let range = if selection.is_empty() {
14242 let point = selection.head().to_display_point(&display_map);
14243 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14244 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14245 .to_point(&display_map);
14246 start..end
14247 } else {
14248 selection.range()
14249 };
14250 if display_map.folds_in_range(range).next().is_some() {
14251 self.unfold_recursive(&Default::default(), window, cx)
14252 } else {
14253 self.fold_recursive(&Default::default(), window, cx)
14254 }
14255 }
14256
14257 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14258 if self.is_singleton(cx) {
14259 let mut to_fold = Vec::new();
14260 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14261 let selections = self.selections.all_adjusted(cx);
14262
14263 for selection in selections {
14264 let range = selection.range().sorted();
14265 let buffer_start_row = range.start.row;
14266
14267 if range.start.row != range.end.row {
14268 let mut found = false;
14269 let mut row = range.start.row;
14270 while row <= range.end.row {
14271 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14272 {
14273 found = true;
14274 row = crease.range().end.row + 1;
14275 to_fold.push(crease);
14276 } else {
14277 row += 1
14278 }
14279 }
14280 if found {
14281 continue;
14282 }
14283 }
14284
14285 for row in (0..=range.start.row).rev() {
14286 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14287 if crease.range().end.row >= buffer_start_row {
14288 to_fold.push(crease);
14289 if row <= range.start.row {
14290 break;
14291 }
14292 }
14293 }
14294 }
14295 }
14296
14297 self.fold_creases(to_fold, true, window, cx);
14298 } else {
14299 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14300 let buffer_ids = self
14301 .selections
14302 .disjoint_anchor_ranges()
14303 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14304 .collect::<HashSet<_>>();
14305 for buffer_id in buffer_ids {
14306 self.fold_buffer(buffer_id, cx);
14307 }
14308 }
14309 }
14310
14311 fn fold_at_level(
14312 &mut self,
14313 fold_at: &FoldAtLevel,
14314 window: &mut Window,
14315 cx: &mut Context<Self>,
14316 ) {
14317 if !self.buffer.read(cx).is_singleton() {
14318 return;
14319 }
14320
14321 let fold_at_level = fold_at.0;
14322 let snapshot = self.buffer.read(cx).snapshot(cx);
14323 let mut to_fold = Vec::new();
14324 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14325
14326 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14327 while start_row < end_row {
14328 match self
14329 .snapshot(window, cx)
14330 .crease_for_buffer_row(MultiBufferRow(start_row))
14331 {
14332 Some(crease) => {
14333 let nested_start_row = crease.range().start.row + 1;
14334 let nested_end_row = crease.range().end.row;
14335
14336 if current_level < fold_at_level {
14337 stack.push((nested_start_row, nested_end_row, current_level + 1));
14338 } else if current_level == fold_at_level {
14339 to_fold.push(crease);
14340 }
14341
14342 start_row = nested_end_row + 1;
14343 }
14344 None => start_row += 1,
14345 }
14346 }
14347 }
14348
14349 self.fold_creases(to_fold, true, window, cx);
14350 }
14351
14352 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14353 if self.buffer.read(cx).is_singleton() {
14354 let mut fold_ranges = Vec::new();
14355 let snapshot = self.buffer.read(cx).snapshot(cx);
14356
14357 for row in 0..snapshot.max_row().0 {
14358 if let Some(foldable_range) = self
14359 .snapshot(window, cx)
14360 .crease_for_buffer_row(MultiBufferRow(row))
14361 {
14362 fold_ranges.push(foldable_range);
14363 }
14364 }
14365
14366 self.fold_creases(fold_ranges, true, window, cx);
14367 } else {
14368 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14369 editor
14370 .update_in(cx, |editor, _, cx| {
14371 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14372 editor.fold_buffer(buffer_id, cx);
14373 }
14374 })
14375 .ok();
14376 });
14377 }
14378 }
14379
14380 pub fn fold_function_bodies(
14381 &mut self,
14382 _: &actions::FoldFunctionBodies,
14383 window: &mut Window,
14384 cx: &mut Context<Self>,
14385 ) {
14386 let snapshot = self.buffer.read(cx).snapshot(cx);
14387
14388 let ranges = snapshot
14389 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14390 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14391 .collect::<Vec<_>>();
14392
14393 let creases = ranges
14394 .into_iter()
14395 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14396 .collect();
14397
14398 self.fold_creases(creases, true, window, cx);
14399 }
14400
14401 pub fn fold_recursive(
14402 &mut self,
14403 _: &actions::FoldRecursive,
14404 window: &mut Window,
14405 cx: &mut Context<Self>,
14406 ) {
14407 let mut to_fold = Vec::new();
14408 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14409 let selections = self.selections.all_adjusted(cx);
14410
14411 for selection in selections {
14412 let range = selection.range().sorted();
14413 let buffer_start_row = range.start.row;
14414
14415 if range.start.row != range.end.row {
14416 let mut found = false;
14417 for row in range.start.row..=range.end.row {
14418 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14419 found = true;
14420 to_fold.push(crease);
14421 }
14422 }
14423 if found {
14424 continue;
14425 }
14426 }
14427
14428 for row in (0..=range.start.row).rev() {
14429 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14430 if crease.range().end.row >= buffer_start_row {
14431 to_fold.push(crease);
14432 } else {
14433 break;
14434 }
14435 }
14436 }
14437 }
14438
14439 self.fold_creases(to_fold, true, window, cx);
14440 }
14441
14442 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14443 let buffer_row = fold_at.buffer_row;
14444 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14445
14446 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14447 let autoscroll = self
14448 .selections
14449 .all::<Point>(cx)
14450 .iter()
14451 .any(|selection| crease.range().overlaps(&selection.range()));
14452
14453 self.fold_creases(vec![crease], autoscroll, window, cx);
14454 }
14455 }
14456
14457 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14458 if self.is_singleton(cx) {
14459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14460 let buffer = &display_map.buffer_snapshot;
14461 let selections = self.selections.all::<Point>(cx);
14462 let ranges = selections
14463 .iter()
14464 .map(|s| {
14465 let range = s.display_range(&display_map).sorted();
14466 let mut start = range.start.to_point(&display_map);
14467 let mut end = range.end.to_point(&display_map);
14468 start.column = 0;
14469 end.column = buffer.line_len(MultiBufferRow(end.row));
14470 start..end
14471 })
14472 .collect::<Vec<_>>();
14473
14474 self.unfold_ranges(&ranges, true, true, cx);
14475 } else {
14476 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14477 let buffer_ids = self
14478 .selections
14479 .disjoint_anchor_ranges()
14480 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14481 .collect::<HashSet<_>>();
14482 for buffer_id in buffer_ids {
14483 self.unfold_buffer(buffer_id, cx);
14484 }
14485 }
14486 }
14487
14488 pub fn unfold_recursive(
14489 &mut self,
14490 _: &UnfoldRecursive,
14491 _window: &mut Window,
14492 cx: &mut Context<Self>,
14493 ) {
14494 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14495 let selections = self.selections.all::<Point>(cx);
14496 let ranges = selections
14497 .iter()
14498 .map(|s| {
14499 let mut range = s.display_range(&display_map).sorted();
14500 *range.start.column_mut() = 0;
14501 *range.end.column_mut() = display_map.line_len(range.end.row());
14502 let start = range.start.to_point(&display_map);
14503 let end = range.end.to_point(&display_map);
14504 start..end
14505 })
14506 .collect::<Vec<_>>();
14507
14508 self.unfold_ranges(&ranges, true, true, cx);
14509 }
14510
14511 pub fn unfold_at(
14512 &mut self,
14513 unfold_at: &UnfoldAt,
14514 _window: &mut Window,
14515 cx: &mut Context<Self>,
14516 ) {
14517 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14518
14519 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14520 ..Point::new(
14521 unfold_at.buffer_row.0,
14522 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14523 );
14524
14525 let autoscroll = self
14526 .selections
14527 .all::<Point>(cx)
14528 .iter()
14529 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14530
14531 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14532 }
14533
14534 pub fn unfold_all(
14535 &mut self,
14536 _: &actions::UnfoldAll,
14537 _window: &mut Window,
14538 cx: &mut Context<Self>,
14539 ) {
14540 if self.buffer.read(cx).is_singleton() {
14541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14542 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14543 } else {
14544 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14545 editor
14546 .update(cx, |editor, cx| {
14547 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14548 editor.unfold_buffer(buffer_id, cx);
14549 }
14550 })
14551 .ok();
14552 });
14553 }
14554 }
14555
14556 pub fn fold_selected_ranges(
14557 &mut self,
14558 _: &FoldSelectedRanges,
14559 window: &mut Window,
14560 cx: &mut Context<Self>,
14561 ) {
14562 let selections = self.selections.all::<Point>(cx);
14563 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14564 let line_mode = self.selections.line_mode;
14565 let ranges = selections
14566 .into_iter()
14567 .map(|s| {
14568 if line_mode {
14569 let start = Point::new(s.start.row, 0);
14570 let end = Point::new(
14571 s.end.row,
14572 display_map
14573 .buffer_snapshot
14574 .line_len(MultiBufferRow(s.end.row)),
14575 );
14576 Crease::simple(start..end, display_map.fold_placeholder.clone())
14577 } else {
14578 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14579 }
14580 })
14581 .collect::<Vec<_>>();
14582 self.fold_creases(ranges, true, window, cx);
14583 }
14584
14585 pub fn fold_ranges<T: ToOffset + Clone>(
14586 &mut self,
14587 ranges: Vec<Range<T>>,
14588 auto_scroll: bool,
14589 window: &mut Window,
14590 cx: &mut Context<Self>,
14591 ) {
14592 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14593 let ranges = ranges
14594 .into_iter()
14595 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14596 .collect::<Vec<_>>();
14597 self.fold_creases(ranges, auto_scroll, window, cx);
14598 }
14599
14600 pub fn fold_creases<T: ToOffset + Clone>(
14601 &mut self,
14602 creases: Vec<Crease<T>>,
14603 auto_scroll: bool,
14604 window: &mut Window,
14605 cx: &mut Context<Self>,
14606 ) {
14607 if creases.is_empty() {
14608 return;
14609 }
14610
14611 let mut buffers_affected = HashSet::default();
14612 let multi_buffer = self.buffer().read(cx);
14613 for crease in &creases {
14614 if let Some((_, buffer, _)) =
14615 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14616 {
14617 buffers_affected.insert(buffer.read(cx).remote_id());
14618 };
14619 }
14620
14621 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14622
14623 if auto_scroll {
14624 self.request_autoscroll(Autoscroll::fit(), cx);
14625 }
14626
14627 cx.notify();
14628
14629 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14630 // Clear diagnostics block when folding a range that contains it.
14631 let snapshot = self.snapshot(window, cx);
14632 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14633 drop(snapshot);
14634 self.active_diagnostics = Some(active_diagnostics);
14635 self.dismiss_diagnostics(cx);
14636 } else {
14637 self.active_diagnostics = Some(active_diagnostics);
14638 }
14639 }
14640
14641 self.scrollbar_marker_state.dirty = true;
14642 self.folds_did_change(cx);
14643 }
14644
14645 /// Removes any folds whose ranges intersect any of the given ranges.
14646 pub fn unfold_ranges<T: ToOffset + Clone>(
14647 &mut self,
14648 ranges: &[Range<T>],
14649 inclusive: bool,
14650 auto_scroll: bool,
14651 cx: &mut Context<Self>,
14652 ) {
14653 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14654 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14655 });
14656 self.folds_did_change(cx);
14657 }
14658
14659 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14660 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14661 return;
14662 }
14663 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14664 self.display_map.update(cx, |display_map, cx| {
14665 display_map.fold_buffers([buffer_id], cx)
14666 });
14667 cx.emit(EditorEvent::BufferFoldToggled {
14668 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14669 folded: true,
14670 });
14671 cx.notify();
14672 }
14673
14674 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14675 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14676 return;
14677 }
14678 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14679 self.display_map.update(cx, |display_map, cx| {
14680 display_map.unfold_buffers([buffer_id], cx);
14681 });
14682 cx.emit(EditorEvent::BufferFoldToggled {
14683 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14684 folded: false,
14685 });
14686 cx.notify();
14687 }
14688
14689 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14690 self.display_map.read(cx).is_buffer_folded(buffer)
14691 }
14692
14693 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14694 self.display_map.read(cx).folded_buffers()
14695 }
14696
14697 /// Removes any folds with the given ranges.
14698 pub fn remove_folds_with_type<T: ToOffset + Clone>(
14699 &mut self,
14700 ranges: &[Range<T>],
14701 type_id: TypeId,
14702 auto_scroll: bool,
14703 cx: &mut Context<Self>,
14704 ) {
14705 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14706 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14707 });
14708 self.folds_did_change(cx);
14709 }
14710
14711 fn remove_folds_with<T: ToOffset + Clone>(
14712 &mut self,
14713 ranges: &[Range<T>],
14714 auto_scroll: bool,
14715 cx: &mut Context<Self>,
14716 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14717 ) {
14718 if ranges.is_empty() {
14719 return;
14720 }
14721
14722 let mut buffers_affected = HashSet::default();
14723 let multi_buffer = self.buffer().read(cx);
14724 for range in ranges {
14725 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14726 buffers_affected.insert(buffer.read(cx).remote_id());
14727 };
14728 }
14729
14730 self.display_map.update(cx, update);
14731
14732 if auto_scroll {
14733 self.request_autoscroll(Autoscroll::fit(), cx);
14734 }
14735
14736 cx.notify();
14737 self.scrollbar_marker_state.dirty = true;
14738 self.active_indent_guides_state.dirty = true;
14739 }
14740
14741 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14742 self.display_map.read(cx).fold_placeholder.clone()
14743 }
14744
14745 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14746 self.buffer.update(cx, |buffer, cx| {
14747 buffer.set_all_diff_hunks_expanded(cx);
14748 });
14749 }
14750
14751 pub fn expand_all_diff_hunks(
14752 &mut self,
14753 _: &ExpandAllDiffHunks,
14754 _window: &mut Window,
14755 cx: &mut Context<Self>,
14756 ) {
14757 self.buffer.update(cx, |buffer, cx| {
14758 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14759 });
14760 }
14761
14762 pub fn toggle_selected_diff_hunks(
14763 &mut self,
14764 _: &ToggleSelectedDiffHunks,
14765 _window: &mut Window,
14766 cx: &mut Context<Self>,
14767 ) {
14768 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14769 self.toggle_diff_hunks_in_ranges(ranges, cx);
14770 }
14771
14772 pub fn diff_hunks_in_ranges<'a>(
14773 &'a self,
14774 ranges: &'a [Range<Anchor>],
14775 buffer: &'a MultiBufferSnapshot,
14776 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14777 ranges.iter().flat_map(move |range| {
14778 let end_excerpt_id = range.end.excerpt_id;
14779 let range = range.to_point(buffer);
14780 let mut peek_end = range.end;
14781 if range.end.row < buffer.max_row().0 {
14782 peek_end = Point::new(range.end.row + 1, 0);
14783 }
14784 buffer
14785 .diff_hunks_in_range(range.start..peek_end)
14786 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14787 })
14788 }
14789
14790 pub fn has_stageable_diff_hunks_in_ranges(
14791 &self,
14792 ranges: &[Range<Anchor>],
14793 snapshot: &MultiBufferSnapshot,
14794 ) -> bool {
14795 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14796 hunks.any(|hunk| hunk.status().has_secondary_hunk())
14797 }
14798
14799 pub fn toggle_staged_selected_diff_hunks(
14800 &mut self,
14801 _: &::git::ToggleStaged,
14802 _: &mut Window,
14803 cx: &mut Context<Self>,
14804 ) {
14805 let snapshot = self.buffer.read(cx).snapshot(cx);
14806 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14807 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14808 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14809 }
14810
14811 pub fn set_render_diff_hunk_controls(
14812 &mut self,
14813 render_diff_hunk_controls: RenderDiffHunkControlsFn,
14814 cx: &mut Context<Self>,
14815 ) {
14816 self.render_diff_hunk_controls = render_diff_hunk_controls;
14817 cx.notify();
14818 }
14819
14820 pub fn stage_and_next(
14821 &mut self,
14822 _: &::git::StageAndNext,
14823 window: &mut Window,
14824 cx: &mut Context<Self>,
14825 ) {
14826 self.do_stage_or_unstage_and_next(true, window, cx);
14827 }
14828
14829 pub fn unstage_and_next(
14830 &mut self,
14831 _: &::git::UnstageAndNext,
14832 window: &mut Window,
14833 cx: &mut Context<Self>,
14834 ) {
14835 self.do_stage_or_unstage_and_next(false, window, cx);
14836 }
14837
14838 pub fn stage_or_unstage_diff_hunks(
14839 &mut self,
14840 stage: bool,
14841 ranges: Vec<Range<Anchor>>,
14842 cx: &mut Context<Self>,
14843 ) {
14844 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14845 cx.spawn(async move |this, cx| {
14846 task.await?;
14847 this.update(cx, |this, cx| {
14848 let snapshot = this.buffer.read(cx).snapshot(cx);
14849 let chunk_by = this
14850 .diff_hunks_in_ranges(&ranges, &snapshot)
14851 .chunk_by(|hunk| hunk.buffer_id);
14852 for (buffer_id, hunks) in &chunk_by {
14853 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14854 }
14855 })
14856 })
14857 .detach_and_log_err(cx);
14858 }
14859
14860 fn save_buffers_for_ranges_if_needed(
14861 &mut self,
14862 ranges: &[Range<Anchor>],
14863 cx: &mut Context<Editor>,
14864 ) -> Task<Result<()>> {
14865 let multibuffer = self.buffer.read(cx);
14866 let snapshot = multibuffer.read(cx);
14867 let buffer_ids: HashSet<_> = ranges
14868 .iter()
14869 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14870 .collect();
14871 drop(snapshot);
14872
14873 let mut buffers = HashSet::default();
14874 for buffer_id in buffer_ids {
14875 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14876 let buffer = buffer_entity.read(cx);
14877 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14878 {
14879 buffers.insert(buffer_entity);
14880 }
14881 }
14882 }
14883
14884 if let Some(project) = &self.project {
14885 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14886 } else {
14887 Task::ready(Ok(()))
14888 }
14889 }
14890
14891 fn do_stage_or_unstage_and_next(
14892 &mut self,
14893 stage: bool,
14894 window: &mut Window,
14895 cx: &mut Context<Self>,
14896 ) {
14897 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14898
14899 if ranges.iter().any(|range| range.start != range.end) {
14900 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14901 return;
14902 }
14903
14904 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14905 let snapshot = self.snapshot(window, cx);
14906 let position = self.selections.newest::<Point>(cx).head();
14907 let mut row = snapshot
14908 .buffer_snapshot
14909 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14910 .find(|hunk| hunk.row_range.start.0 > position.row)
14911 .map(|hunk| hunk.row_range.start);
14912
14913 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14914 // Outside of the project diff editor, wrap around to the beginning.
14915 if !all_diff_hunks_expanded {
14916 row = row.or_else(|| {
14917 snapshot
14918 .buffer_snapshot
14919 .diff_hunks_in_range(Point::zero()..position)
14920 .find(|hunk| hunk.row_range.end.0 < position.row)
14921 .map(|hunk| hunk.row_range.start)
14922 });
14923 }
14924
14925 if let Some(row) = row {
14926 let destination = Point::new(row.0, 0);
14927 let autoscroll = Autoscroll::center();
14928
14929 self.unfold_ranges(&[destination..destination], false, false, cx);
14930 self.change_selections(Some(autoscroll), window, cx, |s| {
14931 s.select_ranges([destination..destination]);
14932 });
14933 }
14934 }
14935
14936 fn do_stage_or_unstage(
14937 &self,
14938 stage: bool,
14939 buffer_id: BufferId,
14940 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14941 cx: &mut App,
14942 ) -> Option<()> {
14943 let project = self.project.as_ref()?;
14944 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14945 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14946 let buffer_snapshot = buffer.read(cx).snapshot();
14947 let file_exists = buffer_snapshot
14948 .file()
14949 .is_some_and(|file| file.disk_state().exists());
14950 diff.update(cx, |diff, cx| {
14951 diff.stage_or_unstage_hunks(
14952 stage,
14953 &hunks
14954 .map(|hunk| buffer_diff::DiffHunk {
14955 buffer_range: hunk.buffer_range,
14956 diff_base_byte_range: hunk.diff_base_byte_range,
14957 secondary_status: hunk.secondary_status,
14958 range: Point::zero()..Point::zero(), // unused
14959 })
14960 .collect::<Vec<_>>(),
14961 &buffer_snapshot,
14962 file_exists,
14963 cx,
14964 )
14965 });
14966 None
14967 }
14968
14969 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14970 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14971 self.buffer
14972 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14973 }
14974
14975 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14976 self.buffer.update(cx, |buffer, cx| {
14977 let ranges = vec![Anchor::min()..Anchor::max()];
14978 if !buffer.all_diff_hunks_expanded()
14979 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14980 {
14981 buffer.collapse_diff_hunks(ranges, cx);
14982 true
14983 } else {
14984 false
14985 }
14986 })
14987 }
14988
14989 fn toggle_diff_hunks_in_ranges(
14990 &mut self,
14991 ranges: Vec<Range<Anchor>>,
14992 cx: &mut Context<Editor>,
14993 ) {
14994 self.buffer.update(cx, |buffer, cx| {
14995 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14996 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14997 })
14998 }
14999
15000 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15001 self.buffer.update(cx, |buffer, cx| {
15002 let snapshot = buffer.snapshot(cx);
15003 let excerpt_id = range.end.excerpt_id;
15004 let point_range = range.to_point(&snapshot);
15005 let expand = !buffer.single_hunk_is_expanded(range, cx);
15006 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15007 })
15008 }
15009
15010 pub(crate) fn apply_all_diff_hunks(
15011 &mut self,
15012 _: &ApplyAllDiffHunks,
15013 window: &mut Window,
15014 cx: &mut Context<Self>,
15015 ) {
15016 let buffers = self.buffer.read(cx).all_buffers();
15017 for branch_buffer in buffers {
15018 branch_buffer.update(cx, |branch_buffer, cx| {
15019 branch_buffer.merge_into_base(Vec::new(), cx);
15020 });
15021 }
15022
15023 if let Some(project) = self.project.clone() {
15024 self.save(true, project, window, cx).detach_and_log_err(cx);
15025 }
15026 }
15027
15028 pub(crate) fn apply_selected_diff_hunks(
15029 &mut self,
15030 _: &ApplyDiffHunk,
15031 window: &mut Window,
15032 cx: &mut Context<Self>,
15033 ) {
15034 let snapshot = self.snapshot(window, cx);
15035 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15036 let mut ranges_by_buffer = HashMap::default();
15037 self.transact(window, cx, |editor, _window, cx| {
15038 for hunk in hunks {
15039 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15040 ranges_by_buffer
15041 .entry(buffer.clone())
15042 .or_insert_with(Vec::new)
15043 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15044 }
15045 }
15046
15047 for (buffer, ranges) in ranges_by_buffer {
15048 buffer.update(cx, |buffer, cx| {
15049 buffer.merge_into_base(ranges, cx);
15050 });
15051 }
15052 });
15053
15054 if let Some(project) = self.project.clone() {
15055 self.save(true, project, window, cx).detach_and_log_err(cx);
15056 }
15057 }
15058
15059 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15060 if hovered != self.gutter_hovered {
15061 self.gutter_hovered = hovered;
15062 cx.notify();
15063 }
15064 }
15065
15066 pub fn insert_blocks(
15067 &mut self,
15068 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15069 autoscroll: Option<Autoscroll>,
15070 cx: &mut Context<Self>,
15071 ) -> Vec<CustomBlockId> {
15072 let blocks = self
15073 .display_map
15074 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15075 if let Some(autoscroll) = autoscroll {
15076 self.request_autoscroll(autoscroll, cx);
15077 }
15078 cx.notify();
15079 blocks
15080 }
15081
15082 pub fn resize_blocks(
15083 &mut self,
15084 heights: HashMap<CustomBlockId, u32>,
15085 autoscroll: Option<Autoscroll>,
15086 cx: &mut Context<Self>,
15087 ) {
15088 self.display_map
15089 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15090 if let Some(autoscroll) = autoscroll {
15091 self.request_autoscroll(autoscroll, cx);
15092 }
15093 cx.notify();
15094 }
15095
15096 pub fn replace_blocks(
15097 &mut self,
15098 renderers: HashMap<CustomBlockId, RenderBlock>,
15099 autoscroll: Option<Autoscroll>,
15100 cx: &mut Context<Self>,
15101 ) {
15102 self.display_map
15103 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15104 if let Some(autoscroll) = autoscroll {
15105 self.request_autoscroll(autoscroll, cx);
15106 }
15107 cx.notify();
15108 }
15109
15110 pub fn remove_blocks(
15111 &mut self,
15112 block_ids: HashSet<CustomBlockId>,
15113 autoscroll: Option<Autoscroll>,
15114 cx: &mut Context<Self>,
15115 ) {
15116 self.display_map.update(cx, |display_map, cx| {
15117 display_map.remove_blocks(block_ids, cx)
15118 });
15119 if let Some(autoscroll) = autoscroll {
15120 self.request_autoscroll(autoscroll, cx);
15121 }
15122 cx.notify();
15123 }
15124
15125 pub fn row_for_block(
15126 &self,
15127 block_id: CustomBlockId,
15128 cx: &mut Context<Self>,
15129 ) -> Option<DisplayRow> {
15130 self.display_map
15131 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15132 }
15133
15134 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15135 self.focused_block = Some(focused_block);
15136 }
15137
15138 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15139 self.focused_block.take()
15140 }
15141
15142 pub fn insert_creases(
15143 &mut self,
15144 creases: impl IntoIterator<Item = Crease<Anchor>>,
15145 cx: &mut Context<Self>,
15146 ) -> Vec<CreaseId> {
15147 self.display_map
15148 .update(cx, |map, cx| map.insert_creases(creases, cx))
15149 }
15150
15151 pub fn remove_creases(
15152 &mut self,
15153 ids: impl IntoIterator<Item = CreaseId>,
15154 cx: &mut Context<Self>,
15155 ) {
15156 self.display_map
15157 .update(cx, |map, cx| map.remove_creases(ids, cx));
15158 }
15159
15160 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15161 self.display_map
15162 .update(cx, |map, cx| map.snapshot(cx))
15163 .longest_row()
15164 }
15165
15166 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15167 self.display_map
15168 .update(cx, |map, cx| map.snapshot(cx))
15169 .max_point()
15170 }
15171
15172 pub fn text(&self, cx: &App) -> String {
15173 self.buffer.read(cx).read(cx).text()
15174 }
15175
15176 pub fn is_empty(&self, cx: &App) -> bool {
15177 self.buffer.read(cx).read(cx).is_empty()
15178 }
15179
15180 pub fn text_option(&self, cx: &App) -> Option<String> {
15181 let text = self.text(cx);
15182 let text = text.trim();
15183
15184 if text.is_empty() {
15185 return None;
15186 }
15187
15188 Some(text.to_string())
15189 }
15190
15191 pub fn set_text(
15192 &mut self,
15193 text: impl Into<Arc<str>>,
15194 window: &mut Window,
15195 cx: &mut Context<Self>,
15196 ) {
15197 self.transact(window, cx, |this, _, cx| {
15198 this.buffer
15199 .read(cx)
15200 .as_singleton()
15201 .expect("you can only call set_text on editors for singleton buffers")
15202 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15203 });
15204 }
15205
15206 pub fn display_text(&self, cx: &mut App) -> String {
15207 self.display_map
15208 .update(cx, |map, cx| map.snapshot(cx))
15209 .text()
15210 }
15211
15212 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15213 let mut wrap_guides = smallvec::smallvec![];
15214
15215 if self.show_wrap_guides == Some(false) {
15216 return wrap_guides;
15217 }
15218
15219 let settings = self.buffer.read(cx).language_settings(cx);
15220 if settings.show_wrap_guides {
15221 match self.soft_wrap_mode(cx) {
15222 SoftWrap::Column(soft_wrap) => {
15223 wrap_guides.push((soft_wrap as usize, true));
15224 }
15225 SoftWrap::Bounded(soft_wrap) => {
15226 wrap_guides.push((soft_wrap as usize, true));
15227 }
15228 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15229 }
15230 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15231 }
15232
15233 wrap_guides
15234 }
15235
15236 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15237 let settings = self.buffer.read(cx).language_settings(cx);
15238 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15239 match mode {
15240 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15241 SoftWrap::None
15242 }
15243 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15244 language_settings::SoftWrap::PreferredLineLength => {
15245 SoftWrap::Column(settings.preferred_line_length)
15246 }
15247 language_settings::SoftWrap::Bounded => {
15248 SoftWrap::Bounded(settings.preferred_line_length)
15249 }
15250 }
15251 }
15252
15253 pub fn set_soft_wrap_mode(
15254 &mut self,
15255 mode: language_settings::SoftWrap,
15256
15257 cx: &mut Context<Self>,
15258 ) {
15259 self.soft_wrap_mode_override = Some(mode);
15260 cx.notify();
15261 }
15262
15263 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15264 self.hard_wrap = hard_wrap;
15265 cx.notify();
15266 }
15267
15268 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15269 self.text_style_refinement = Some(style);
15270 }
15271
15272 /// called by the Element so we know what style we were most recently rendered with.
15273 pub(crate) fn set_style(
15274 &mut self,
15275 style: EditorStyle,
15276 window: &mut Window,
15277 cx: &mut Context<Self>,
15278 ) {
15279 let rem_size = window.rem_size();
15280 self.display_map.update(cx, |map, cx| {
15281 map.set_font(
15282 style.text.font(),
15283 style.text.font_size.to_pixels(rem_size),
15284 cx,
15285 )
15286 });
15287 self.style = Some(style);
15288 }
15289
15290 pub fn style(&self) -> Option<&EditorStyle> {
15291 self.style.as_ref()
15292 }
15293
15294 // Called by the element. This method is not designed to be called outside of the editor
15295 // element's layout code because it does not notify when rewrapping is computed synchronously.
15296 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15297 self.display_map
15298 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15299 }
15300
15301 pub fn set_soft_wrap(&mut self) {
15302 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15303 }
15304
15305 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15306 if self.soft_wrap_mode_override.is_some() {
15307 self.soft_wrap_mode_override.take();
15308 } else {
15309 let soft_wrap = match self.soft_wrap_mode(cx) {
15310 SoftWrap::GitDiff => return,
15311 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15312 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15313 language_settings::SoftWrap::None
15314 }
15315 };
15316 self.soft_wrap_mode_override = Some(soft_wrap);
15317 }
15318 cx.notify();
15319 }
15320
15321 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15322 let Some(workspace) = self.workspace() else {
15323 return;
15324 };
15325 let fs = workspace.read(cx).app_state().fs.clone();
15326 let current_show = TabBarSettings::get_global(cx).show;
15327 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15328 setting.show = Some(!current_show);
15329 });
15330 }
15331
15332 pub fn toggle_indent_guides(
15333 &mut self,
15334 _: &ToggleIndentGuides,
15335 _: &mut Window,
15336 cx: &mut Context<Self>,
15337 ) {
15338 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15339 self.buffer
15340 .read(cx)
15341 .language_settings(cx)
15342 .indent_guides
15343 .enabled
15344 });
15345 self.show_indent_guides = Some(!currently_enabled);
15346 cx.notify();
15347 }
15348
15349 fn should_show_indent_guides(&self) -> Option<bool> {
15350 self.show_indent_guides
15351 }
15352
15353 pub fn toggle_line_numbers(
15354 &mut self,
15355 _: &ToggleLineNumbers,
15356 _: &mut Window,
15357 cx: &mut Context<Self>,
15358 ) {
15359 let mut editor_settings = EditorSettings::get_global(cx).clone();
15360 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15361 EditorSettings::override_global(editor_settings, cx);
15362 }
15363
15364 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15365 if let Some(show_line_numbers) = self.show_line_numbers {
15366 return show_line_numbers;
15367 }
15368 EditorSettings::get_global(cx).gutter.line_numbers
15369 }
15370
15371 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15372 self.use_relative_line_numbers
15373 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15374 }
15375
15376 pub fn toggle_relative_line_numbers(
15377 &mut self,
15378 _: &ToggleRelativeLineNumbers,
15379 _: &mut Window,
15380 cx: &mut Context<Self>,
15381 ) {
15382 let is_relative = self.should_use_relative_line_numbers(cx);
15383 self.set_relative_line_number(Some(!is_relative), cx)
15384 }
15385
15386 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15387 self.use_relative_line_numbers = is_relative;
15388 cx.notify();
15389 }
15390
15391 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15392 self.show_gutter = show_gutter;
15393 cx.notify();
15394 }
15395
15396 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15397 self.show_scrollbars = show_scrollbars;
15398 cx.notify();
15399 }
15400
15401 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15402 self.show_line_numbers = Some(show_line_numbers);
15403 cx.notify();
15404 }
15405
15406 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15407 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15408 cx.notify();
15409 }
15410
15411 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15412 self.show_code_actions = Some(show_code_actions);
15413 cx.notify();
15414 }
15415
15416 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15417 self.show_runnables = Some(show_runnables);
15418 cx.notify();
15419 }
15420
15421 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15422 self.show_breakpoints = Some(show_breakpoints);
15423 cx.notify();
15424 }
15425
15426 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15427 if self.display_map.read(cx).masked != masked {
15428 self.display_map.update(cx, |map, _| map.masked = masked);
15429 }
15430 cx.notify()
15431 }
15432
15433 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15434 self.show_wrap_guides = Some(show_wrap_guides);
15435 cx.notify();
15436 }
15437
15438 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15439 self.show_indent_guides = Some(show_indent_guides);
15440 cx.notify();
15441 }
15442
15443 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15444 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15445 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15446 if let Some(dir) = file.abs_path(cx).parent() {
15447 return Some(dir.to_owned());
15448 }
15449 }
15450
15451 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15452 return Some(project_path.path.to_path_buf());
15453 }
15454 }
15455
15456 None
15457 }
15458
15459 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15460 self.active_excerpt(cx)?
15461 .1
15462 .read(cx)
15463 .file()
15464 .and_then(|f| f.as_local())
15465 }
15466
15467 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15468 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15469 let buffer = buffer.read(cx);
15470 if let Some(project_path) = buffer.project_path(cx) {
15471 let project = self.project.as_ref()?.read(cx);
15472 project.absolute_path(&project_path, cx)
15473 } else {
15474 buffer
15475 .file()
15476 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15477 }
15478 })
15479 }
15480
15481 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15482 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15483 let project_path = buffer.read(cx).project_path(cx)?;
15484 let project = self.project.as_ref()?.read(cx);
15485 let entry = project.entry_for_path(&project_path, cx)?;
15486 let path = entry.path.to_path_buf();
15487 Some(path)
15488 })
15489 }
15490
15491 pub fn reveal_in_finder(
15492 &mut self,
15493 _: &RevealInFileManager,
15494 _window: &mut Window,
15495 cx: &mut Context<Self>,
15496 ) {
15497 if let Some(target) = self.target_file(cx) {
15498 cx.reveal_path(&target.abs_path(cx));
15499 }
15500 }
15501
15502 pub fn copy_path(
15503 &mut self,
15504 _: &zed_actions::workspace::CopyPath,
15505 _window: &mut Window,
15506 cx: &mut Context<Self>,
15507 ) {
15508 if let Some(path) = self.target_file_abs_path(cx) {
15509 if let Some(path) = path.to_str() {
15510 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15511 }
15512 }
15513 }
15514
15515 pub fn copy_relative_path(
15516 &mut self,
15517 _: &zed_actions::workspace::CopyRelativePath,
15518 _window: &mut Window,
15519 cx: &mut Context<Self>,
15520 ) {
15521 if let Some(path) = self.target_file_path(cx) {
15522 if let Some(path) = path.to_str() {
15523 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15524 }
15525 }
15526 }
15527
15528 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
15529 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15530 buffer.read(cx).project_path(cx)
15531 } else {
15532 None
15533 }
15534 }
15535
15536 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15537 let _ = maybe!({
15538 let breakpoint_store = self.breakpoint_store.as_ref()?;
15539
15540 let Some((_, _, active_position)) =
15541 breakpoint_store.read(cx).active_position().cloned()
15542 else {
15543 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15544 return None;
15545 };
15546
15547 let snapshot = self
15548 .project
15549 .as_ref()?
15550 .read(cx)
15551 .buffer_for_id(active_position.buffer_id?, cx)?
15552 .read(cx)
15553 .snapshot();
15554
15555 for (id, ExcerptRange { context, .. }) in self
15556 .buffer
15557 .read(cx)
15558 .excerpts_for_buffer(active_position.buffer_id?, cx)
15559 {
15560 if context.start.cmp(&active_position, &snapshot).is_ge()
15561 || context.end.cmp(&active_position, &snapshot).is_lt()
15562 {
15563 continue;
15564 }
15565 let snapshot = self.buffer.read(cx).snapshot(cx);
15566 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15567
15568 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15569 self.go_to_line::<DebugCurrentRowHighlight>(
15570 multibuffer_anchor,
15571 Some(cx.theme().colors().editor_debugger_active_line_background),
15572 window,
15573 cx,
15574 );
15575
15576 cx.notify();
15577 }
15578
15579 Some(())
15580 });
15581 }
15582
15583 pub fn copy_file_name_without_extension(
15584 &mut self,
15585 _: &CopyFileNameWithoutExtension,
15586 _: &mut Window,
15587 cx: &mut Context<Self>,
15588 ) {
15589 if let Some(file) = self.target_file(cx) {
15590 if let Some(file_stem) = file.path().file_stem() {
15591 if let Some(name) = file_stem.to_str() {
15592 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15593 }
15594 }
15595 }
15596 }
15597
15598 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15599 if let Some(file) = self.target_file(cx) {
15600 if let Some(file_name) = file.path().file_name() {
15601 if let Some(name) = file_name.to_str() {
15602 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15603 }
15604 }
15605 }
15606 }
15607
15608 pub fn toggle_git_blame(
15609 &mut self,
15610 _: &::git::Blame,
15611 window: &mut Window,
15612 cx: &mut Context<Self>,
15613 ) {
15614 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15615
15616 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15617 self.start_git_blame(true, window, cx);
15618 }
15619
15620 cx.notify();
15621 }
15622
15623 pub fn toggle_git_blame_inline(
15624 &mut self,
15625 _: &ToggleGitBlameInline,
15626 window: &mut Window,
15627 cx: &mut Context<Self>,
15628 ) {
15629 self.toggle_git_blame_inline_internal(true, window, cx);
15630 cx.notify();
15631 }
15632
15633 pub fn git_blame_inline_enabled(&self) -> bool {
15634 self.git_blame_inline_enabled
15635 }
15636
15637 pub fn toggle_selection_menu(
15638 &mut self,
15639 _: &ToggleSelectionMenu,
15640 _: &mut Window,
15641 cx: &mut Context<Self>,
15642 ) {
15643 self.show_selection_menu = self
15644 .show_selection_menu
15645 .map(|show_selections_menu| !show_selections_menu)
15646 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15647
15648 cx.notify();
15649 }
15650
15651 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15652 self.show_selection_menu
15653 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15654 }
15655
15656 fn start_git_blame(
15657 &mut self,
15658 user_triggered: bool,
15659 window: &mut Window,
15660 cx: &mut Context<Self>,
15661 ) {
15662 if let Some(project) = self.project.as_ref() {
15663 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15664 return;
15665 };
15666
15667 if buffer.read(cx).file().is_none() {
15668 return;
15669 }
15670
15671 let focused = self.focus_handle(cx).contains_focused(window, cx);
15672
15673 let project = project.clone();
15674 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15675 self.blame_subscription =
15676 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15677 self.blame = Some(blame);
15678 }
15679 }
15680
15681 fn toggle_git_blame_inline_internal(
15682 &mut self,
15683 user_triggered: bool,
15684 window: &mut Window,
15685 cx: &mut Context<Self>,
15686 ) {
15687 if self.git_blame_inline_enabled {
15688 self.git_blame_inline_enabled = false;
15689 self.show_git_blame_inline = false;
15690 self.show_git_blame_inline_delay_task.take();
15691 } else {
15692 self.git_blame_inline_enabled = true;
15693 self.start_git_blame_inline(user_triggered, window, cx);
15694 }
15695
15696 cx.notify();
15697 }
15698
15699 fn start_git_blame_inline(
15700 &mut self,
15701 user_triggered: bool,
15702 window: &mut Window,
15703 cx: &mut Context<Self>,
15704 ) {
15705 self.start_git_blame(user_triggered, window, cx);
15706
15707 if ProjectSettings::get_global(cx)
15708 .git
15709 .inline_blame_delay()
15710 .is_some()
15711 {
15712 self.start_inline_blame_timer(window, cx);
15713 } else {
15714 self.show_git_blame_inline = true
15715 }
15716 }
15717
15718 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15719 self.blame.as_ref()
15720 }
15721
15722 pub fn show_git_blame_gutter(&self) -> bool {
15723 self.show_git_blame_gutter
15724 }
15725
15726 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15727 self.show_git_blame_gutter && self.has_blame_entries(cx)
15728 }
15729
15730 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15731 self.show_git_blame_inline
15732 && (self.focus_handle.is_focused(window)
15733 || self
15734 .git_blame_inline_tooltip
15735 .as_ref()
15736 .and_then(|t| t.upgrade())
15737 .is_some())
15738 && !self.newest_selection_head_on_empty_line(cx)
15739 && self.has_blame_entries(cx)
15740 }
15741
15742 fn has_blame_entries(&self, cx: &App) -> bool {
15743 self.blame()
15744 .map_or(false, |blame| blame.read(cx).has_generated_entries())
15745 }
15746
15747 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15748 let cursor_anchor = self.selections.newest_anchor().head();
15749
15750 let snapshot = self.buffer.read(cx).snapshot(cx);
15751 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15752
15753 snapshot.line_len(buffer_row) == 0
15754 }
15755
15756 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15757 let buffer_and_selection = maybe!({
15758 let selection = self.selections.newest::<Point>(cx);
15759 let selection_range = selection.range();
15760
15761 let multi_buffer = self.buffer().read(cx);
15762 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15763 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15764
15765 let (buffer, range, _) = if selection.reversed {
15766 buffer_ranges.first()
15767 } else {
15768 buffer_ranges.last()
15769 }?;
15770
15771 let selection = text::ToPoint::to_point(&range.start, &buffer).row
15772 ..text::ToPoint::to_point(&range.end, &buffer).row;
15773 Some((
15774 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15775 selection,
15776 ))
15777 });
15778
15779 let Some((buffer, selection)) = buffer_and_selection else {
15780 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15781 };
15782
15783 let Some(project) = self.project.as_ref() else {
15784 return Task::ready(Err(anyhow!("editor does not have project")));
15785 };
15786
15787 project.update(cx, |project, cx| {
15788 project.get_permalink_to_line(&buffer, selection, cx)
15789 })
15790 }
15791
15792 pub fn copy_permalink_to_line(
15793 &mut self,
15794 _: &CopyPermalinkToLine,
15795 window: &mut Window,
15796 cx: &mut Context<Self>,
15797 ) {
15798 let permalink_task = self.get_permalink_to_line(cx);
15799 let workspace = self.workspace();
15800
15801 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15802 Ok(permalink) => {
15803 cx.update(|_, cx| {
15804 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15805 })
15806 .ok();
15807 }
15808 Err(err) => {
15809 let message = format!("Failed to copy permalink: {err}");
15810
15811 Err::<(), anyhow::Error>(err).log_err();
15812
15813 if let Some(workspace) = workspace {
15814 workspace
15815 .update_in(cx, |workspace, _, cx| {
15816 struct CopyPermalinkToLine;
15817
15818 workspace.show_toast(
15819 Toast::new(
15820 NotificationId::unique::<CopyPermalinkToLine>(),
15821 message,
15822 ),
15823 cx,
15824 )
15825 })
15826 .ok();
15827 }
15828 }
15829 })
15830 .detach();
15831 }
15832
15833 pub fn copy_file_location(
15834 &mut self,
15835 _: &CopyFileLocation,
15836 _: &mut Window,
15837 cx: &mut Context<Self>,
15838 ) {
15839 let selection = self.selections.newest::<Point>(cx).start.row + 1;
15840 if let Some(file) = self.target_file(cx) {
15841 if let Some(path) = file.path().to_str() {
15842 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15843 }
15844 }
15845 }
15846
15847 pub fn open_permalink_to_line(
15848 &mut self,
15849 _: &OpenPermalinkToLine,
15850 window: &mut Window,
15851 cx: &mut Context<Self>,
15852 ) {
15853 let permalink_task = self.get_permalink_to_line(cx);
15854 let workspace = self.workspace();
15855
15856 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15857 Ok(permalink) => {
15858 cx.update(|_, cx| {
15859 cx.open_url(permalink.as_ref());
15860 })
15861 .ok();
15862 }
15863 Err(err) => {
15864 let message = format!("Failed to open permalink: {err}");
15865
15866 Err::<(), anyhow::Error>(err).log_err();
15867
15868 if let Some(workspace) = workspace {
15869 workspace
15870 .update(cx, |workspace, cx| {
15871 struct OpenPermalinkToLine;
15872
15873 workspace.show_toast(
15874 Toast::new(
15875 NotificationId::unique::<OpenPermalinkToLine>(),
15876 message,
15877 ),
15878 cx,
15879 )
15880 })
15881 .ok();
15882 }
15883 }
15884 })
15885 .detach();
15886 }
15887
15888 pub fn insert_uuid_v4(
15889 &mut self,
15890 _: &InsertUuidV4,
15891 window: &mut Window,
15892 cx: &mut Context<Self>,
15893 ) {
15894 self.insert_uuid(UuidVersion::V4, window, cx);
15895 }
15896
15897 pub fn insert_uuid_v7(
15898 &mut self,
15899 _: &InsertUuidV7,
15900 window: &mut Window,
15901 cx: &mut Context<Self>,
15902 ) {
15903 self.insert_uuid(UuidVersion::V7, window, cx);
15904 }
15905
15906 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15907 self.transact(window, cx, |this, window, cx| {
15908 let edits = this
15909 .selections
15910 .all::<Point>(cx)
15911 .into_iter()
15912 .map(|selection| {
15913 let uuid = match version {
15914 UuidVersion::V4 => uuid::Uuid::new_v4(),
15915 UuidVersion::V7 => uuid::Uuid::now_v7(),
15916 };
15917
15918 (selection.range(), uuid.to_string())
15919 });
15920 this.edit(edits, cx);
15921 this.refresh_inline_completion(true, false, window, cx);
15922 });
15923 }
15924
15925 pub fn open_selections_in_multibuffer(
15926 &mut self,
15927 _: &OpenSelectionsInMultibuffer,
15928 window: &mut Window,
15929 cx: &mut Context<Self>,
15930 ) {
15931 let multibuffer = self.buffer.read(cx);
15932
15933 let Some(buffer) = multibuffer.as_singleton() else {
15934 return;
15935 };
15936
15937 let Some(workspace) = self.workspace() else {
15938 return;
15939 };
15940
15941 let locations = self
15942 .selections
15943 .disjoint_anchors()
15944 .iter()
15945 .map(|range| Location {
15946 buffer: buffer.clone(),
15947 range: range.start.text_anchor..range.end.text_anchor,
15948 })
15949 .collect::<Vec<_>>();
15950
15951 let title = multibuffer.title(cx).to_string();
15952
15953 cx.spawn_in(window, async move |_, cx| {
15954 workspace.update_in(cx, |workspace, window, cx| {
15955 Self::open_locations_in_multibuffer(
15956 workspace,
15957 locations,
15958 format!("Selections for '{title}'"),
15959 false,
15960 MultibufferSelectionMode::All,
15961 window,
15962 cx,
15963 );
15964 })
15965 })
15966 .detach();
15967 }
15968
15969 /// Adds a row highlight for the given range. If a row has multiple highlights, the
15970 /// last highlight added will be used.
15971 ///
15972 /// If the range ends at the beginning of a line, then that line will not be highlighted.
15973 pub fn highlight_rows<T: 'static>(
15974 &mut self,
15975 range: Range<Anchor>,
15976 color: Hsla,
15977 should_autoscroll: bool,
15978 cx: &mut Context<Self>,
15979 ) {
15980 let snapshot = self.buffer().read(cx).snapshot(cx);
15981 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15982 let ix = row_highlights.binary_search_by(|highlight| {
15983 Ordering::Equal
15984 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15985 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15986 });
15987
15988 if let Err(mut ix) = ix {
15989 let index = post_inc(&mut self.highlight_order);
15990
15991 // If this range intersects with the preceding highlight, then merge it with
15992 // the preceding highlight. Otherwise insert a new highlight.
15993 let mut merged = false;
15994 if ix > 0 {
15995 let prev_highlight = &mut row_highlights[ix - 1];
15996 if prev_highlight
15997 .range
15998 .end
15999 .cmp(&range.start, &snapshot)
16000 .is_ge()
16001 {
16002 ix -= 1;
16003 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16004 prev_highlight.range.end = range.end;
16005 }
16006 merged = true;
16007 prev_highlight.index = index;
16008 prev_highlight.color = color;
16009 prev_highlight.should_autoscroll = should_autoscroll;
16010 }
16011 }
16012
16013 if !merged {
16014 row_highlights.insert(
16015 ix,
16016 RowHighlight {
16017 range: range.clone(),
16018 index,
16019 color,
16020 should_autoscroll,
16021 },
16022 );
16023 }
16024
16025 // If any of the following highlights intersect with this one, merge them.
16026 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16027 let highlight = &row_highlights[ix];
16028 if next_highlight
16029 .range
16030 .start
16031 .cmp(&highlight.range.end, &snapshot)
16032 .is_le()
16033 {
16034 if next_highlight
16035 .range
16036 .end
16037 .cmp(&highlight.range.end, &snapshot)
16038 .is_gt()
16039 {
16040 row_highlights[ix].range.end = next_highlight.range.end;
16041 }
16042 row_highlights.remove(ix + 1);
16043 } else {
16044 break;
16045 }
16046 }
16047 }
16048 }
16049
16050 /// Remove any highlighted row ranges of the given type that intersect the
16051 /// given ranges.
16052 pub fn remove_highlighted_rows<T: 'static>(
16053 &mut self,
16054 ranges_to_remove: Vec<Range<Anchor>>,
16055 cx: &mut Context<Self>,
16056 ) {
16057 let snapshot = self.buffer().read(cx).snapshot(cx);
16058 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16059 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16060 row_highlights.retain(|highlight| {
16061 while let Some(range_to_remove) = ranges_to_remove.peek() {
16062 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16063 Ordering::Less | Ordering::Equal => {
16064 ranges_to_remove.next();
16065 }
16066 Ordering::Greater => {
16067 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16068 Ordering::Less | Ordering::Equal => {
16069 return false;
16070 }
16071 Ordering::Greater => break,
16072 }
16073 }
16074 }
16075 }
16076
16077 true
16078 })
16079 }
16080
16081 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16082 pub fn clear_row_highlights<T: 'static>(&mut self) {
16083 self.highlighted_rows.remove(&TypeId::of::<T>());
16084 }
16085
16086 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16087 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16088 self.highlighted_rows
16089 .get(&TypeId::of::<T>())
16090 .map_or(&[] as &[_], |vec| vec.as_slice())
16091 .iter()
16092 .map(|highlight| (highlight.range.clone(), highlight.color))
16093 }
16094
16095 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16096 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16097 /// Allows to ignore certain kinds of highlights.
16098 pub fn highlighted_display_rows(
16099 &self,
16100 window: &mut Window,
16101 cx: &mut App,
16102 ) -> BTreeMap<DisplayRow, LineHighlight> {
16103 let snapshot = self.snapshot(window, cx);
16104 let mut used_highlight_orders = HashMap::default();
16105 self.highlighted_rows
16106 .iter()
16107 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16108 .fold(
16109 BTreeMap::<DisplayRow, LineHighlight>::new(),
16110 |mut unique_rows, highlight| {
16111 let start = highlight.range.start.to_display_point(&snapshot);
16112 let end = highlight.range.end.to_display_point(&snapshot);
16113 let start_row = start.row().0;
16114 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16115 && end.column() == 0
16116 {
16117 end.row().0.saturating_sub(1)
16118 } else {
16119 end.row().0
16120 };
16121 for row in start_row..=end_row {
16122 let used_index =
16123 used_highlight_orders.entry(row).or_insert(highlight.index);
16124 if highlight.index >= *used_index {
16125 *used_index = highlight.index;
16126 unique_rows.insert(DisplayRow(row), highlight.color.into());
16127 }
16128 }
16129 unique_rows
16130 },
16131 )
16132 }
16133
16134 pub fn highlighted_display_row_for_autoscroll(
16135 &self,
16136 snapshot: &DisplaySnapshot,
16137 ) -> Option<DisplayRow> {
16138 self.highlighted_rows
16139 .values()
16140 .flat_map(|highlighted_rows| highlighted_rows.iter())
16141 .filter_map(|highlight| {
16142 if highlight.should_autoscroll {
16143 Some(highlight.range.start.to_display_point(snapshot).row())
16144 } else {
16145 None
16146 }
16147 })
16148 .min()
16149 }
16150
16151 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16152 self.highlight_background::<SearchWithinRange>(
16153 ranges,
16154 |colors| colors.editor_document_highlight_read_background,
16155 cx,
16156 )
16157 }
16158
16159 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16160 self.breadcrumb_header = Some(new_header);
16161 }
16162
16163 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16164 self.clear_background_highlights::<SearchWithinRange>(cx);
16165 }
16166
16167 pub fn highlight_background<T: 'static>(
16168 &mut self,
16169 ranges: &[Range<Anchor>],
16170 color_fetcher: fn(&ThemeColors) -> Hsla,
16171 cx: &mut Context<Self>,
16172 ) {
16173 self.background_highlights
16174 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16175 self.scrollbar_marker_state.dirty = true;
16176 cx.notify();
16177 }
16178
16179 pub fn clear_background_highlights<T: 'static>(
16180 &mut self,
16181 cx: &mut Context<Self>,
16182 ) -> Option<BackgroundHighlight> {
16183 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16184 if !text_highlights.1.is_empty() {
16185 self.scrollbar_marker_state.dirty = true;
16186 cx.notify();
16187 }
16188 Some(text_highlights)
16189 }
16190
16191 pub fn highlight_gutter<T: 'static>(
16192 &mut self,
16193 ranges: &[Range<Anchor>],
16194 color_fetcher: fn(&App) -> Hsla,
16195 cx: &mut Context<Self>,
16196 ) {
16197 self.gutter_highlights
16198 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16199 cx.notify();
16200 }
16201
16202 pub fn clear_gutter_highlights<T: 'static>(
16203 &mut self,
16204 cx: &mut Context<Self>,
16205 ) -> Option<GutterHighlight> {
16206 cx.notify();
16207 self.gutter_highlights.remove(&TypeId::of::<T>())
16208 }
16209
16210 #[cfg(feature = "test-support")]
16211 pub fn all_text_background_highlights(
16212 &self,
16213 window: &mut Window,
16214 cx: &mut Context<Self>,
16215 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16216 let snapshot = self.snapshot(window, cx);
16217 let buffer = &snapshot.buffer_snapshot;
16218 let start = buffer.anchor_before(0);
16219 let end = buffer.anchor_after(buffer.len());
16220 let theme = cx.theme().colors();
16221 self.background_highlights_in_range(start..end, &snapshot, theme)
16222 }
16223
16224 #[cfg(feature = "test-support")]
16225 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16226 let snapshot = self.buffer().read(cx).snapshot(cx);
16227
16228 let highlights = self
16229 .background_highlights
16230 .get(&TypeId::of::<items::BufferSearchHighlights>());
16231
16232 if let Some((_color, ranges)) = highlights {
16233 ranges
16234 .iter()
16235 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16236 .collect_vec()
16237 } else {
16238 vec![]
16239 }
16240 }
16241
16242 fn document_highlights_for_position<'a>(
16243 &'a self,
16244 position: Anchor,
16245 buffer: &'a MultiBufferSnapshot,
16246 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16247 let read_highlights = self
16248 .background_highlights
16249 .get(&TypeId::of::<DocumentHighlightRead>())
16250 .map(|h| &h.1);
16251 let write_highlights = self
16252 .background_highlights
16253 .get(&TypeId::of::<DocumentHighlightWrite>())
16254 .map(|h| &h.1);
16255 let left_position = position.bias_left(buffer);
16256 let right_position = position.bias_right(buffer);
16257 read_highlights
16258 .into_iter()
16259 .chain(write_highlights)
16260 .flat_map(move |ranges| {
16261 let start_ix = match ranges.binary_search_by(|probe| {
16262 let cmp = probe.end.cmp(&left_position, buffer);
16263 if cmp.is_ge() {
16264 Ordering::Greater
16265 } else {
16266 Ordering::Less
16267 }
16268 }) {
16269 Ok(i) | Err(i) => i,
16270 };
16271
16272 ranges[start_ix..]
16273 .iter()
16274 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16275 })
16276 }
16277
16278 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16279 self.background_highlights
16280 .get(&TypeId::of::<T>())
16281 .map_or(false, |(_, highlights)| !highlights.is_empty())
16282 }
16283
16284 pub fn background_highlights_in_range(
16285 &self,
16286 search_range: Range<Anchor>,
16287 display_snapshot: &DisplaySnapshot,
16288 theme: &ThemeColors,
16289 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16290 let mut results = Vec::new();
16291 for (color_fetcher, ranges) in self.background_highlights.values() {
16292 let color = color_fetcher(theme);
16293 let start_ix = match ranges.binary_search_by(|probe| {
16294 let cmp = probe
16295 .end
16296 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16297 if cmp.is_gt() {
16298 Ordering::Greater
16299 } else {
16300 Ordering::Less
16301 }
16302 }) {
16303 Ok(i) | Err(i) => i,
16304 };
16305 for range in &ranges[start_ix..] {
16306 if range
16307 .start
16308 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16309 .is_ge()
16310 {
16311 break;
16312 }
16313
16314 let start = range.start.to_display_point(display_snapshot);
16315 let end = range.end.to_display_point(display_snapshot);
16316 results.push((start..end, color))
16317 }
16318 }
16319 results
16320 }
16321
16322 pub fn background_highlight_row_ranges<T: 'static>(
16323 &self,
16324 search_range: Range<Anchor>,
16325 display_snapshot: &DisplaySnapshot,
16326 count: usize,
16327 ) -> Vec<RangeInclusive<DisplayPoint>> {
16328 let mut results = Vec::new();
16329 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16330 return vec![];
16331 };
16332
16333 let start_ix = match ranges.binary_search_by(|probe| {
16334 let cmp = probe
16335 .end
16336 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16337 if cmp.is_gt() {
16338 Ordering::Greater
16339 } else {
16340 Ordering::Less
16341 }
16342 }) {
16343 Ok(i) | Err(i) => i,
16344 };
16345 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16346 if let (Some(start_display), Some(end_display)) = (start, end) {
16347 results.push(
16348 start_display.to_display_point(display_snapshot)
16349 ..=end_display.to_display_point(display_snapshot),
16350 );
16351 }
16352 };
16353 let mut start_row: Option<Point> = None;
16354 let mut end_row: Option<Point> = None;
16355 if ranges.len() > count {
16356 return Vec::new();
16357 }
16358 for range in &ranges[start_ix..] {
16359 if range
16360 .start
16361 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16362 .is_ge()
16363 {
16364 break;
16365 }
16366 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16367 if let Some(current_row) = &end_row {
16368 if end.row == current_row.row {
16369 continue;
16370 }
16371 }
16372 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16373 if start_row.is_none() {
16374 assert_eq!(end_row, None);
16375 start_row = Some(start);
16376 end_row = Some(end);
16377 continue;
16378 }
16379 if let Some(current_end) = end_row.as_mut() {
16380 if start.row > current_end.row + 1 {
16381 push_region(start_row, end_row);
16382 start_row = Some(start);
16383 end_row = Some(end);
16384 } else {
16385 // Merge two hunks.
16386 *current_end = end;
16387 }
16388 } else {
16389 unreachable!();
16390 }
16391 }
16392 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16393 push_region(start_row, end_row);
16394 results
16395 }
16396
16397 pub fn gutter_highlights_in_range(
16398 &self,
16399 search_range: Range<Anchor>,
16400 display_snapshot: &DisplaySnapshot,
16401 cx: &App,
16402 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16403 let mut results = Vec::new();
16404 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16405 let color = color_fetcher(cx);
16406 let start_ix = match ranges.binary_search_by(|probe| {
16407 let cmp = probe
16408 .end
16409 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16410 if cmp.is_gt() {
16411 Ordering::Greater
16412 } else {
16413 Ordering::Less
16414 }
16415 }) {
16416 Ok(i) | Err(i) => i,
16417 };
16418 for range in &ranges[start_ix..] {
16419 if range
16420 .start
16421 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16422 .is_ge()
16423 {
16424 break;
16425 }
16426
16427 let start = range.start.to_display_point(display_snapshot);
16428 let end = range.end.to_display_point(display_snapshot);
16429 results.push((start..end, color))
16430 }
16431 }
16432 results
16433 }
16434
16435 /// Get the text ranges corresponding to the redaction query
16436 pub fn redacted_ranges(
16437 &self,
16438 search_range: Range<Anchor>,
16439 display_snapshot: &DisplaySnapshot,
16440 cx: &App,
16441 ) -> Vec<Range<DisplayPoint>> {
16442 display_snapshot
16443 .buffer_snapshot
16444 .redacted_ranges(search_range, |file| {
16445 if let Some(file) = file {
16446 file.is_private()
16447 && EditorSettings::get(
16448 Some(SettingsLocation {
16449 worktree_id: file.worktree_id(cx),
16450 path: file.path().as_ref(),
16451 }),
16452 cx,
16453 )
16454 .redact_private_values
16455 } else {
16456 false
16457 }
16458 })
16459 .map(|range| {
16460 range.start.to_display_point(display_snapshot)
16461 ..range.end.to_display_point(display_snapshot)
16462 })
16463 .collect()
16464 }
16465
16466 pub fn highlight_text<T: 'static>(
16467 &mut self,
16468 ranges: Vec<Range<Anchor>>,
16469 style: HighlightStyle,
16470 cx: &mut Context<Self>,
16471 ) {
16472 self.display_map.update(cx, |map, _| {
16473 map.highlight_text(TypeId::of::<T>(), ranges, style)
16474 });
16475 cx.notify();
16476 }
16477
16478 pub(crate) fn highlight_inlays<T: 'static>(
16479 &mut self,
16480 highlights: Vec<InlayHighlight>,
16481 style: HighlightStyle,
16482 cx: &mut Context<Self>,
16483 ) {
16484 self.display_map.update(cx, |map, _| {
16485 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16486 });
16487 cx.notify();
16488 }
16489
16490 pub fn text_highlights<'a, T: 'static>(
16491 &'a self,
16492 cx: &'a App,
16493 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16494 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16495 }
16496
16497 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16498 let cleared = self
16499 .display_map
16500 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16501 if cleared {
16502 cx.notify();
16503 }
16504 }
16505
16506 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16507 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16508 && self.focus_handle.is_focused(window)
16509 }
16510
16511 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16512 self.show_cursor_when_unfocused = is_enabled;
16513 cx.notify();
16514 }
16515
16516 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16517 cx.notify();
16518 }
16519
16520 fn on_buffer_event(
16521 &mut self,
16522 multibuffer: &Entity<MultiBuffer>,
16523 event: &multi_buffer::Event,
16524 window: &mut Window,
16525 cx: &mut Context<Self>,
16526 ) {
16527 match event {
16528 multi_buffer::Event::Edited {
16529 singleton_buffer_edited,
16530 edited_buffer: buffer_edited,
16531 } => {
16532 self.scrollbar_marker_state.dirty = true;
16533 self.active_indent_guides_state.dirty = true;
16534 self.refresh_active_diagnostics(cx);
16535 self.refresh_code_actions(window, cx);
16536 if self.has_active_inline_completion() {
16537 self.update_visible_inline_completion(window, cx);
16538 }
16539 if let Some(buffer) = buffer_edited {
16540 let buffer_id = buffer.read(cx).remote_id();
16541 if !self.registered_buffers.contains_key(&buffer_id) {
16542 if let Some(project) = self.project.as_ref() {
16543 project.update(cx, |project, cx| {
16544 self.registered_buffers.insert(
16545 buffer_id,
16546 project.register_buffer_with_language_servers(&buffer, cx),
16547 );
16548 })
16549 }
16550 }
16551 }
16552 cx.emit(EditorEvent::BufferEdited);
16553 cx.emit(SearchEvent::MatchesInvalidated);
16554 if *singleton_buffer_edited {
16555 if let Some(project) = &self.project {
16556 #[allow(clippy::mutable_key_type)]
16557 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16558 multibuffer
16559 .all_buffers()
16560 .into_iter()
16561 .filter_map(|buffer| {
16562 buffer.update(cx, |buffer, cx| {
16563 let language = buffer.language()?;
16564 let should_discard = project.update(cx, |project, cx| {
16565 project.is_local()
16566 && !project.has_language_servers_for(buffer, cx)
16567 });
16568 should_discard.not().then_some(language.clone())
16569 })
16570 })
16571 .collect::<HashSet<_>>()
16572 });
16573 if !languages_affected.is_empty() {
16574 self.refresh_inlay_hints(
16575 InlayHintRefreshReason::BufferEdited(languages_affected),
16576 cx,
16577 );
16578 }
16579 }
16580 }
16581
16582 let Some(project) = &self.project else { return };
16583 let (telemetry, is_via_ssh) = {
16584 let project = project.read(cx);
16585 let telemetry = project.client().telemetry().clone();
16586 let is_via_ssh = project.is_via_ssh();
16587 (telemetry, is_via_ssh)
16588 };
16589 refresh_linked_ranges(self, window, cx);
16590 telemetry.log_edit_event("editor", is_via_ssh);
16591 }
16592 multi_buffer::Event::ExcerptsAdded {
16593 buffer,
16594 predecessor,
16595 excerpts,
16596 } => {
16597 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16598 let buffer_id = buffer.read(cx).remote_id();
16599 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16600 if let Some(project) = &self.project {
16601 get_uncommitted_diff_for_buffer(
16602 project,
16603 [buffer.clone()],
16604 self.buffer.clone(),
16605 cx,
16606 )
16607 .detach();
16608 }
16609 }
16610 cx.emit(EditorEvent::ExcerptsAdded {
16611 buffer: buffer.clone(),
16612 predecessor: *predecessor,
16613 excerpts: excerpts.clone(),
16614 });
16615 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16616 }
16617 multi_buffer::Event::ExcerptsRemoved { ids } => {
16618 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16619 let buffer = self.buffer.read(cx);
16620 self.registered_buffers
16621 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16622 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16623 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16624 }
16625 multi_buffer::Event::ExcerptsEdited {
16626 excerpt_ids,
16627 buffer_ids,
16628 } => {
16629 self.display_map.update(cx, |map, cx| {
16630 map.unfold_buffers(buffer_ids.iter().copied(), cx)
16631 });
16632 cx.emit(EditorEvent::ExcerptsEdited {
16633 ids: excerpt_ids.clone(),
16634 })
16635 }
16636 multi_buffer::Event::ExcerptsExpanded { ids } => {
16637 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16638 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16639 }
16640 multi_buffer::Event::Reparsed(buffer_id) => {
16641 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16642 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16643
16644 cx.emit(EditorEvent::Reparsed(*buffer_id));
16645 }
16646 multi_buffer::Event::DiffHunksToggled => {
16647 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16648 }
16649 multi_buffer::Event::LanguageChanged(buffer_id) => {
16650 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16651 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16652 cx.emit(EditorEvent::Reparsed(*buffer_id));
16653 cx.notify();
16654 }
16655 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16656 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16657 multi_buffer::Event::FileHandleChanged
16658 | multi_buffer::Event::Reloaded
16659 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16660 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16661 multi_buffer::Event::DiagnosticsUpdated => {
16662 self.refresh_active_diagnostics(cx);
16663 self.refresh_inline_diagnostics(true, window, cx);
16664 self.scrollbar_marker_state.dirty = true;
16665 cx.notify();
16666 }
16667 _ => {}
16668 };
16669 }
16670
16671 fn on_display_map_changed(
16672 &mut self,
16673 _: Entity<DisplayMap>,
16674 _: &mut Window,
16675 cx: &mut Context<Self>,
16676 ) {
16677 cx.notify();
16678 }
16679
16680 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16681 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16682 self.update_edit_prediction_settings(cx);
16683 self.refresh_inline_completion(true, false, window, cx);
16684 self.refresh_inlay_hints(
16685 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16686 self.selections.newest_anchor().head(),
16687 &self.buffer.read(cx).snapshot(cx),
16688 cx,
16689 )),
16690 cx,
16691 );
16692
16693 let old_cursor_shape = self.cursor_shape;
16694
16695 {
16696 let editor_settings = EditorSettings::get_global(cx);
16697 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16698 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16699 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16700 self.hide_mouse_while_typing = editor_settings.hide_mouse_while_typing.unwrap_or(true);
16701
16702 if !self.hide_mouse_while_typing {
16703 self.mouse_cursor_hidden = false;
16704 }
16705 }
16706
16707 if old_cursor_shape != self.cursor_shape {
16708 cx.emit(EditorEvent::CursorShapeChanged);
16709 }
16710
16711 let project_settings = ProjectSettings::get_global(cx);
16712 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16713
16714 if self.mode == EditorMode::Full {
16715 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16716 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16717 if self.show_inline_diagnostics != show_inline_diagnostics {
16718 self.show_inline_diagnostics = show_inline_diagnostics;
16719 self.refresh_inline_diagnostics(false, window, cx);
16720 }
16721
16722 if self.git_blame_inline_enabled != inline_blame_enabled {
16723 self.toggle_git_blame_inline_internal(false, window, cx);
16724 }
16725 }
16726
16727 cx.notify();
16728 }
16729
16730 pub fn set_searchable(&mut self, searchable: bool) {
16731 self.searchable = searchable;
16732 }
16733
16734 pub fn searchable(&self) -> bool {
16735 self.searchable
16736 }
16737
16738 fn open_proposed_changes_editor(
16739 &mut self,
16740 _: &OpenProposedChangesEditor,
16741 window: &mut Window,
16742 cx: &mut Context<Self>,
16743 ) {
16744 let Some(workspace) = self.workspace() else {
16745 cx.propagate();
16746 return;
16747 };
16748
16749 let selections = self.selections.all::<usize>(cx);
16750 let multi_buffer = self.buffer.read(cx);
16751 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16752 let mut new_selections_by_buffer = HashMap::default();
16753 for selection in selections {
16754 for (buffer, range, _) in
16755 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16756 {
16757 let mut range = range.to_point(buffer);
16758 range.start.column = 0;
16759 range.end.column = buffer.line_len(range.end.row);
16760 new_selections_by_buffer
16761 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16762 .or_insert(Vec::new())
16763 .push(range)
16764 }
16765 }
16766
16767 let proposed_changes_buffers = new_selections_by_buffer
16768 .into_iter()
16769 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16770 .collect::<Vec<_>>();
16771 let proposed_changes_editor = cx.new(|cx| {
16772 ProposedChangesEditor::new(
16773 "Proposed changes",
16774 proposed_changes_buffers,
16775 self.project.clone(),
16776 window,
16777 cx,
16778 )
16779 });
16780
16781 window.defer(cx, move |window, cx| {
16782 workspace.update(cx, |workspace, cx| {
16783 workspace.active_pane().update(cx, |pane, cx| {
16784 pane.add_item(
16785 Box::new(proposed_changes_editor),
16786 true,
16787 true,
16788 None,
16789 window,
16790 cx,
16791 );
16792 });
16793 });
16794 });
16795 }
16796
16797 pub fn open_excerpts_in_split(
16798 &mut self,
16799 _: &OpenExcerptsSplit,
16800 window: &mut Window,
16801 cx: &mut Context<Self>,
16802 ) {
16803 self.open_excerpts_common(None, true, window, cx)
16804 }
16805
16806 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16807 self.open_excerpts_common(None, false, window, cx)
16808 }
16809
16810 fn open_excerpts_common(
16811 &mut self,
16812 jump_data: Option<JumpData>,
16813 split: bool,
16814 window: &mut Window,
16815 cx: &mut Context<Self>,
16816 ) {
16817 let Some(workspace) = self.workspace() else {
16818 cx.propagate();
16819 return;
16820 };
16821
16822 if self.buffer.read(cx).is_singleton() {
16823 cx.propagate();
16824 return;
16825 }
16826
16827 let mut new_selections_by_buffer = HashMap::default();
16828 match &jump_data {
16829 Some(JumpData::MultiBufferPoint {
16830 excerpt_id,
16831 position,
16832 anchor,
16833 line_offset_from_top,
16834 }) => {
16835 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16836 if let Some(buffer) = multi_buffer_snapshot
16837 .buffer_id_for_excerpt(*excerpt_id)
16838 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16839 {
16840 let buffer_snapshot = buffer.read(cx).snapshot();
16841 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16842 language::ToPoint::to_point(anchor, &buffer_snapshot)
16843 } else {
16844 buffer_snapshot.clip_point(*position, Bias::Left)
16845 };
16846 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16847 new_selections_by_buffer.insert(
16848 buffer,
16849 (
16850 vec![jump_to_offset..jump_to_offset],
16851 Some(*line_offset_from_top),
16852 ),
16853 );
16854 }
16855 }
16856 Some(JumpData::MultiBufferRow {
16857 row,
16858 line_offset_from_top,
16859 }) => {
16860 let point = MultiBufferPoint::new(row.0, 0);
16861 if let Some((buffer, buffer_point, _)) =
16862 self.buffer.read(cx).point_to_buffer_point(point, cx)
16863 {
16864 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16865 new_selections_by_buffer
16866 .entry(buffer)
16867 .or_insert((Vec::new(), Some(*line_offset_from_top)))
16868 .0
16869 .push(buffer_offset..buffer_offset)
16870 }
16871 }
16872 None => {
16873 let selections = self.selections.all::<usize>(cx);
16874 let multi_buffer = self.buffer.read(cx);
16875 for selection in selections {
16876 for (snapshot, range, _, anchor) in multi_buffer
16877 .snapshot(cx)
16878 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16879 {
16880 if let Some(anchor) = anchor {
16881 // selection is in a deleted hunk
16882 let Some(buffer_id) = anchor.buffer_id else {
16883 continue;
16884 };
16885 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16886 continue;
16887 };
16888 let offset = text::ToOffset::to_offset(
16889 &anchor.text_anchor,
16890 &buffer_handle.read(cx).snapshot(),
16891 );
16892 let range = offset..offset;
16893 new_selections_by_buffer
16894 .entry(buffer_handle)
16895 .or_insert((Vec::new(), None))
16896 .0
16897 .push(range)
16898 } else {
16899 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16900 else {
16901 continue;
16902 };
16903 new_selections_by_buffer
16904 .entry(buffer_handle)
16905 .or_insert((Vec::new(), None))
16906 .0
16907 .push(range)
16908 }
16909 }
16910 }
16911 }
16912 }
16913
16914 if new_selections_by_buffer.is_empty() {
16915 return;
16916 }
16917
16918 // We defer the pane interaction because we ourselves are a workspace item
16919 // and activating a new item causes the pane to call a method on us reentrantly,
16920 // which panics if we're on the stack.
16921 window.defer(cx, move |window, cx| {
16922 workspace.update(cx, |workspace, cx| {
16923 let pane = if split {
16924 workspace.adjacent_pane(window, cx)
16925 } else {
16926 workspace.active_pane().clone()
16927 };
16928
16929 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16930 let editor = buffer
16931 .read(cx)
16932 .file()
16933 .is_none()
16934 .then(|| {
16935 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16936 // so `workspace.open_project_item` will never find them, always opening a new editor.
16937 // Instead, we try to activate the existing editor in the pane first.
16938 let (editor, pane_item_index) =
16939 pane.read(cx).items().enumerate().find_map(|(i, item)| {
16940 let editor = item.downcast::<Editor>()?;
16941 let singleton_buffer =
16942 editor.read(cx).buffer().read(cx).as_singleton()?;
16943 if singleton_buffer == buffer {
16944 Some((editor, i))
16945 } else {
16946 None
16947 }
16948 })?;
16949 pane.update(cx, |pane, cx| {
16950 pane.activate_item(pane_item_index, true, true, window, cx)
16951 });
16952 Some(editor)
16953 })
16954 .flatten()
16955 .unwrap_or_else(|| {
16956 workspace.open_project_item::<Self>(
16957 pane.clone(),
16958 buffer,
16959 true,
16960 true,
16961 window,
16962 cx,
16963 )
16964 });
16965
16966 editor.update(cx, |editor, cx| {
16967 let autoscroll = match scroll_offset {
16968 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16969 None => Autoscroll::newest(),
16970 };
16971 let nav_history = editor.nav_history.take();
16972 editor.change_selections(Some(autoscroll), window, cx, |s| {
16973 s.select_ranges(ranges);
16974 });
16975 editor.nav_history = nav_history;
16976 });
16977 }
16978 })
16979 });
16980 }
16981
16982 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16983 let snapshot = self.buffer.read(cx).read(cx);
16984 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16985 Some(
16986 ranges
16987 .iter()
16988 .map(move |range| {
16989 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16990 })
16991 .collect(),
16992 )
16993 }
16994
16995 fn selection_replacement_ranges(
16996 &self,
16997 range: Range<OffsetUtf16>,
16998 cx: &mut App,
16999 ) -> Vec<Range<OffsetUtf16>> {
17000 let selections = self.selections.all::<OffsetUtf16>(cx);
17001 let newest_selection = selections
17002 .iter()
17003 .max_by_key(|selection| selection.id)
17004 .unwrap();
17005 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17006 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17007 let snapshot = self.buffer.read(cx).read(cx);
17008 selections
17009 .into_iter()
17010 .map(|mut selection| {
17011 selection.start.0 =
17012 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17013 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17014 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17015 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17016 })
17017 .collect()
17018 }
17019
17020 fn report_editor_event(
17021 &self,
17022 event_type: &'static str,
17023 file_extension: Option<String>,
17024 cx: &App,
17025 ) {
17026 if cfg!(any(test, feature = "test-support")) {
17027 return;
17028 }
17029
17030 let Some(project) = &self.project else { return };
17031
17032 // If None, we are in a file without an extension
17033 let file = self
17034 .buffer
17035 .read(cx)
17036 .as_singleton()
17037 .and_then(|b| b.read(cx).file());
17038 let file_extension = file_extension.or(file
17039 .as_ref()
17040 .and_then(|file| Path::new(file.file_name(cx)).extension())
17041 .and_then(|e| e.to_str())
17042 .map(|a| a.to_string()));
17043
17044 let vim_mode = cx
17045 .global::<SettingsStore>()
17046 .raw_user_settings()
17047 .get("vim_mode")
17048 == Some(&serde_json::Value::Bool(true));
17049
17050 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17051 let copilot_enabled = edit_predictions_provider
17052 == language::language_settings::EditPredictionProvider::Copilot;
17053 let copilot_enabled_for_language = self
17054 .buffer
17055 .read(cx)
17056 .language_settings(cx)
17057 .show_edit_predictions;
17058
17059 let project = project.read(cx);
17060 telemetry::event!(
17061 event_type,
17062 file_extension,
17063 vim_mode,
17064 copilot_enabled,
17065 copilot_enabled_for_language,
17066 edit_predictions_provider,
17067 is_via_ssh = project.is_via_ssh(),
17068 );
17069 }
17070
17071 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17072 /// with each line being an array of {text, highlight} objects.
17073 fn copy_highlight_json(
17074 &mut self,
17075 _: &CopyHighlightJson,
17076 window: &mut Window,
17077 cx: &mut Context<Self>,
17078 ) {
17079 #[derive(Serialize)]
17080 struct Chunk<'a> {
17081 text: String,
17082 highlight: Option<&'a str>,
17083 }
17084
17085 let snapshot = self.buffer.read(cx).snapshot(cx);
17086 let range = self
17087 .selected_text_range(false, window, cx)
17088 .and_then(|selection| {
17089 if selection.range.is_empty() {
17090 None
17091 } else {
17092 Some(selection.range)
17093 }
17094 })
17095 .unwrap_or_else(|| 0..snapshot.len());
17096
17097 let chunks = snapshot.chunks(range, true);
17098 let mut lines = Vec::new();
17099 let mut line: VecDeque<Chunk> = VecDeque::new();
17100
17101 let Some(style) = self.style.as_ref() else {
17102 return;
17103 };
17104
17105 for chunk in chunks {
17106 let highlight = chunk
17107 .syntax_highlight_id
17108 .and_then(|id| id.name(&style.syntax));
17109 let mut chunk_lines = chunk.text.split('\n').peekable();
17110 while let Some(text) = chunk_lines.next() {
17111 let mut merged_with_last_token = false;
17112 if let Some(last_token) = line.back_mut() {
17113 if last_token.highlight == highlight {
17114 last_token.text.push_str(text);
17115 merged_with_last_token = true;
17116 }
17117 }
17118
17119 if !merged_with_last_token {
17120 line.push_back(Chunk {
17121 text: text.into(),
17122 highlight,
17123 });
17124 }
17125
17126 if chunk_lines.peek().is_some() {
17127 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17128 line.pop_front();
17129 }
17130 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17131 line.pop_back();
17132 }
17133
17134 lines.push(mem::take(&mut line));
17135 }
17136 }
17137 }
17138
17139 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17140 return;
17141 };
17142 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17143 }
17144
17145 pub fn open_context_menu(
17146 &mut self,
17147 _: &OpenContextMenu,
17148 window: &mut Window,
17149 cx: &mut Context<Self>,
17150 ) {
17151 self.request_autoscroll(Autoscroll::newest(), cx);
17152 let position = self.selections.newest_display(cx).start;
17153 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17154 }
17155
17156 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17157 &self.inlay_hint_cache
17158 }
17159
17160 pub fn replay_insert_event(
17161 &mut self,
17162 text: &str,
17163 relative_utf16_range: Option<Range<isize>>,
17164 window: &mut Window,
17165 cx: &mut Context<Self>,
17166 ) {
17167 if !self.input_enabled {
17168 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17169 return;
17170 }
17171 if let Some(relative_utf16_range) = relative_utf16_range {
17172 let selections = self.selections.all::<OffsetUtf16>(cx);
17173 self.change_selections(None, window, cx, |s| {
17174 let new_ranges = selections.into_iter().map(|range| {
17175 let start = OffsetUtf16(
17176 range
17177 .head()
17178 .0
17179 .saturating_add_signed(relative_utf16_range.start),
17180 );
17181 let end = OffsetUtf16(
17182 range
17183 .head()
17184 .0
17185 .saturating_add_signed(relative_utf16_range.end),
17186 );
17187 start..end
17188 });
17189 s.select_ranges(new_ranges);
17190 });
17191 }
17192
17193 self.handle_input(text, window, cx);
17194 }
17195
17196 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17197 let Some(provider) = self.semantics_provider.as_ref() else {
17198 return false;
17199 };
17200
17201 let mut supports = false;
17202 self.buffer().update(cx, |this, cx| {
17203 this.for_each_buffer(|buffer| {
17204 supports |= provider.supports_inlay_hints(buffer, cx);
17205 });
17206 });
17207
17208 supports
17209 }
17210
17211 pub fn is_focused(&self, window: &Window) -> bool {
17212 self.focus_handle.is_focused(window)
17213 }
17214
17215 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17216 cx.emit(EditorEvent::Focused);
17217
17218 if let Some(descendant) = self
17219 .last_focused_descendant
17220 .take()
17221 .and_then(|descendant| descendant.upgrade())
17222 {
17223 window.focus(&descendant);
17224 } else {
17225 if let Some(blame) = self.blame.as_ref() {
17226 blame.update(cx, GitBlame::focus)
17227 }
17228
17229 self.blink_manager.update(cx, BlinkManager::enable);
17230 self.show_cursor_names(window, cx);
17231 self.buffer.update(cx, |buffer, cx| {
17232 buffer.finalize_last_transaction(cx);
17233 if self.leader_peer_id.is_none() {
17234 buffer.set_active_selections(
17235 &self.selections.disjoint_anchors(),
17236 self.selections.line_mode,
17237 self.cursor_shape,
17238 cx,
17239 );
17240 }
17241 });
17242 }
17243 }
17244
17245 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17246 cx.emit(EditorEvent::FocusedIn)
17247 }
17248
17249 fn handle_focus_out(
17250 &mut self,
17251 event: FocusOutEvent,
17252 _window: &mut Window,
17253 cx: &mut Context<Self>,
17254 ) {
17255 if event.blurred != self.focus_handle {
17256 self.last_focused_descendant = Some(event.blurred);
17257 }
17258 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17259 }
17260
17261 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17262 self.blink_manager.update(cx, BlinkManager::disable);
17263 self.buffer
17264 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17265
17266 if let Some(blame) = self.blame.as_ref() {
17267 blame.update(cx, GitBlame::blur)
17268 }
17269 if !self.hover_state.focused(window, cx) {
17270 hide_hover(self, cx);
17271 }
17272 if !self
17273 .context_menu
17274 .borrow()
17275 .as_ref()
17276 .is_some_and(|context_menu| context_menu.focused(window, cx))
17277 {
17278 self.hide_context_menu(window, cx);
17279 }
17280 self.discard_inline_completion(false, cx);
17281 cx.emit(EditorEvent::Blurred);
17282 cx.notify();
17283 }
17284
17285 pub fn register_action<A: Action>(
17286 &mut self,
17287 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17288 ) -> Subscription {
17289 let id = self.next_editor_action_id.post_inc();
17290 let listener = Arc::new(listener);
17291 self.editor_actions.borrow_mut().insert(
17292 id,
17293 Box::new(move |window, _| {
17294 let listener = listener.clone();
17295 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17296 let action = action.downcast_ref().unwrap();
17297 if phase == DispatchPhase::Bubble {
17298 listener(action, window, cx)
17299 }
17300 })
17301 }),
17302 );
17303
17304 let editor_actions = self.editor_actions.clone();
17305 Subscription::new(move || {
17306 editor_actions.borrow_mut().remove(&id);
17307 })
17308 }
17309
17310 pub fn file_header_size(&self) -> u32 {
17311 FILE_HEADER_HEIGHT
17312 }
17313
17314 pub fn restore(
17315 &mut self,
17316 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17317 window: &mut Window,
17318 cx: &mut Context<Self>,
17319 ) {
17320 let workspace = self.workspace();
17321 let project = self.project.as_ref();
17322 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17323 let mut tasks = Vec::new();
17324 for (buffer_id, changes) in revert_changes {
17325 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17326 buffer.update(cx, |buffer, cx| {
17327 buffer.edit(
17328 changes
17329 .into_iter()
17330 .map(|(range, text)| (range, text.to_string())),
17331 None,
17332 cx,
17333 );
17334 });
17335
17336 if let Some(project) =
17337 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17338 {
17339 project.update(cx, |project, cx| {
17340 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17341 })
17342 }
17343 }
17344 }
17345 tasks
17346 });
17347 cx.spawn_in(window, async move |_, cx| {
17348 for (buffer, task) in save_tasks {
17349 let result = task.await;
17350 if result.is_err() {
17351 let Some(path) = buffer
17352 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17353 .ok()
17354 else {
17355 continue;
17356 };
17357 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17358 let Some(task) = cx
17359 .update_window_entity(&workspace, |workspace, window, cx| {
17360 workspace
17361 .open_path_preview(path, None, false, false, false, window, cx)
17362 })
17363 .ok()
17364 else {
17365 continue;
17366 };
17367 task.await.log_err();
17368 }
17369 }
17370 }
17371 })
17372 .detach();
17373 self.change_selections(None, window, cx, |selections| selections.refresh());
17374 }
17375
17376 pub fn to_pixel_point(
17377 &self,
17378 source: multi_buffer::Anchor,
17379 editor_snapshot: &EditorSnapshot,
17380 window: &mut Window,
17381 ) -> Option<gpui::Point<Pixels>> {
17382 let source_point = source.to_display_point(editor_snapshot);
17383 self.display_to_pixel_point(source_point, editor_snapshot, window)
17384 }
17385
17386 pub fn display_to_pixel_point(
17387 &self,
17388 source: DisplayPoint,
17389 editor_snapshot: &EditorSnapshot,
17390 window: &mut Window,
17391 ) -> Option<gpui::Point<Pixels>> {
17392 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17393 let text_layout_details = self.text_layout_details(window);
17394 let scroll_top = text_layout_details
17395 .scroll_anchor
17396 .scroll_position(editor_snapshot)
17397 .y;
17398
17399 if source.row().as_f32() < scroll_top.floor() {
17400 return None;
17401 }
17402 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17403 let source_y = line_height * (source.row().as_f32() - scroll_top);
17404 Some(gpui::Point::new(source_x, source_y))
17405 }
17406
17407 pub fn has_visible_completions_menu(&self) -> bool {
17408 !self.edit_prediction_preview_is_active()
17409 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17410 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17411 })
17412 }
17413
17414 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17415 self.addons
17416 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17417 }
17418
17419 pub fn unregister_addon<T: Addon>(&mut self) {
17420 self.addons.remove(&std::any::TypeId::of::<T>());
17421 }
17422
17423 pub fn addon<T: Addon>(&self) -> Option<&T> {
17424 let type_id = std::any::TypeId::of::<T>();
17425 self.addons
17426 .get(&type_id)
17427 .and_then(|item| item.to_any().downcast_ref::<T>())
17428 }
17429
17430 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17431 let text_layout_details = self.text_layout_details(window);
17432 let style = &text_layout_details.editor_style;
17433 let font_id = window.text_system().resolve_font(&style.text.font());
17434 let font_size = style.text.font_size.to_pixels(window.rem_size());
17435 let line_height = style.text.line_height_in_pixels(window.rem_size());
17436 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17437
17438 gpui::Size::new(em_width, line_height)
17439 }
17440
17441 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17442 self.load_diff_task.clone()
17443 }
17444
17445 fn read_metadata_from_db(
17446 &mut self,
17447 item_id: u64,
17448 workspace_id: WorkspaceId,
17449 window: &mut Window,
17450 cx: &mut Context<Editor>,
17451 ) {
17452 if self.is_singleton(cx)
17453 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17454 {
17455 let buffer_snapshot = OnceCell::new();
17456
17457 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17458 if !selections.is_empty() {
17459 let snapshot =
17460 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17461 self.change_selections(None, window, cx, |s| {
17462 s.select_ranges(selections.into_iter().map(|(start, end)| {
17463 snapshot.clip_offset(start, Bias::Left)
17464 ..snapshot.clip_offset(end, Bias::Right)
17465 }));
17466 });
17467 }
17468 };
17469
17470 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17471 if !folds.is_empty() {
17472 let snapshot =
17473 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17474 self.fold_ranges(
17475 folds
17476 .into_iter()
17477 .map(|(start, end)| {
17478 snapshot.clip_offset(start, Bias::Left)
17479 ..snapshot.clip_offset(end, Bias::Right)
17480 })
17481 .collect(),
17482 false,
17483 window,
17484 cx,
17485 );
17486 }
17487 }
17488 }
17489
17490 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17491 }
17492}
17493
17494fn insert_extra_newline_brackets(
17495 buffer: &MultiBufferSnapshot,
17496 range: Range<usize>,
17497 language: &language::LanguageScope,
17498) -> bool {
17499 let leading_whitespace_len = buffer
17500 .reversed_chars_at(range.start)
17501 .take_while(|c| c.is_whitespace() && *c != '\n')
17502 .map(|c| c.len_utf8())
17503 .sum::<usize>();
17504 let trailing_whitespace_len = buffer
17505 .chars_at(range.end)
17506 .take_while(|c| c.is_whitespace() && *c != '\n')
17507 .map(|c| c.len_utf8())
17508 .sum::<usize>();
17509 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17510
17511 language.brackets().any(|(pair, enabled)| {
17512 let pair_start = pair.start.trim_end();
17513 let pair_end = pair.end.trim_start();
17514
17515 enabled
17516 && pair.newline
17517 && buffer.contains_str_at(range.end, pair_end)
17518 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17519 })
17520}
17521
17522fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17523 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17524 [(buffer, range, _)] => (*buffer, range.clone()),
17525 _ => return false,
17526 };
17527 let pair = {
17528 let mut result: Option<BracketMatch> = None;
17529
17530 for pair in buffer
17531 .all_bracket_ranges(range.clone())
17532 .filter(move |pair| {
17533 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17534 })
17535 {
17536 let len = pair.close_range.end - pair.open_range.start;
17537
17538 if let Some(existing) = &result {
17539 let existing_len = existing.close_range.end - existing.open_range.start;
17540 if len > existing_len {
17541 continue;
17542 }
17543 }
17544
17545 result = Some(pair);
17546 }
17547
17548 result
17549 };
17550 let Some(pair) = pair else {
17551 return false;
17552 };
17553 pair.newline_only
17554 && buffer
17555 .chars_for_range(pair.open_range.end..range.start)
17556 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17557 .all(|c| c.is_whitespace() && c != '\n')
17558}
17559
17560fn get_uncommitted_diff_for_buffer(
17561 project: &Entity<Project>,
17562 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17563 buffer: Entity<MultiBuffer>,
17564 cx: &mut App,
17565) -> Task<()> {
17566 let mut tasks = Vec::new();
17567 project.update(cx, |project, cx| {
17568 for buffer in buffers {
17569 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17570 }
17571 });
17572 cx.spawn(async move |cx| {
17573 let diffs = future::join_all(tasks).await;
17574 buffer
17575 .update(cx, |buffer, cx| {
17576 for diff in diffs.into_iter().flatten() {
17577 buffer.add_diff(diff, cx);
17578 }
17579 })
17580 .ok();
17581 })
17582}
17583
17584fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17585 let tab_size = tab_size.get() as usize;
17586 let mut width = offset;
17587
17588 for ch in text.chars() {
17589 width += if ch == '\t' {
17590 tab_size - (width % tab_size)
17591 } else {
17592 1
17593 };
17594 }
17595
17596 width - offset
17597}
17598
17599#[cfg(test)]
17600mod tests {
17601 use super::*;
17602
17603 #[test]
17604 fn test_string_size_with_expanded_tabs() {
17605 let nz = |val| NonZeroU32::new(val).unwrap();
17606 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17607 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17608 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17609 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17610 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17611 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17612 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17613 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17614 }
17615}
17616
17617/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17618struct WordBreakingTokenizer<'a> {
17619 input: &'a str,
17620}
17621
17622impl<'a> WordBreakingTokenizer<'a> {
17623 fn new(input: &'a str) -> Self {
17624 Self { input }
17625 }
17626}
17627
17628fn is_char_ideographic(ch: char) -> bool {
17629 use unicode_script::Script::*;
17630 use unicode_script::UnicodeScript;
17631 matches!(ch.script(), Han | Tangut | Yi)
17632}
17633
17634fn is_grapheme_ideographic(text: &str) -> bool {
17635 text.chars().any(is_char_ideographic)
17636}
17637
17638fn is_grapheme_whitespace(text: &str) -> bool {
17639 text.chars().any(|x| x.is_whitespace())
17640}
17641
17642fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17643 text.chars().next().map_or(false, |ch| {
17644 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17645 })
17646}
17647
17648#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17649enum WordBreakToken<'a> {
17650 Word { token: &'a str, grapheme_len: usize },
17651 InlineWhitespace { token: &'a str, grapheme_len: usize },
17652 Newline,
17653}
17654
17655impl<'a> Iterator for WordBreakingTokenizer<'a> {
17656 /// Yields a span, the count of graphemes in the token, and whether it was
17657 /// whitespace. Note that it also breaks at word boundaries.
17658 type Item = WordBreakToken<'a>;
17659
17660 fn next(&mut self) -> Option<Self::Item> {
17661 use unicode_segmentation::UnicodeSegmentation;
17662 if self.input.is_empty() {
17663 return None;
17664 }
17665
17666 let mut iter = self.input.graphemes(true).peekable();
17667 let mut offset = 0;
17668 let mut grapheme_len = 0;
17669 if let Some(first_grapheme) = iter.next() {
17670 let is_newline = first_grapheme == "\n";
17671 let is_whitespace = is_grapheme_whitespace(first_grapheme);
17672 offset += first_grapheme.len();
17673 grapheme_len += 1;
17674 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17675 if let Some(grapheme) = iter.peek().copied() {
17676 if should_stay_with_preceding_ideograph(grapheme) {
17677 offset += grapheme.len();
17678 grapheme_len += 1;
17679 }
17680 }
17681 } else {
17682 let mut words = self.input[offset..].split_word_bound_indices().peekable();
17683 let mut next_word_bound = words.peek().copied();
17684 if next_word_bound.map_or(false, |(i, _)| i == 0) {
17685 next_word_bound = words.next();
17686 }
17687 while let Some(grapheme) = iter.peek().copied() {
17688 if next_word_bound.map_or(false, |(i, _)| i == offset) {
17689 break;
17690 };
17691 if is_grapheme_whitespace(grapheme) != is_whitespace
17692 || (grapheme == "\n") != is_newline
17693 {
17694 break;
17695 };
17696 offset += grapheme.len();
17697 grapheme_len += 1;
17698 iter.next();
17699 }
17700 }
17701 let token = &self.input[..offset];
17702 self.input = &self.input[offset..];
17703 if token == "\n" {
17704 Some(WordBreakToken::Newline)
17705 } else if is_whitespace {
17706 Some(WordBreakToken::InlineWhitespace {
17707 token,
17708 grapheme_len,
17709 })
17710 } else {
17711 Some(WordBreakToken::Word {
17712 token,
17713 grapheme_len,
17714 })
17715 }
17716 } else {
17717 None
17718 }
17719 }
17720}
17721
17722#[test]
17723fn test_word_breaking_tokenizer() {
17724 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17725 ("", &[]),
17726 (" ", &[whitespace(" ", 2)]),
17727 ("Ʒ", &[word("Ʒ", 1)]),
17728 ("Ǽ", &[word("Ǽ", 1)]),
17729 ("⋑", &[word("⋑", 1)]),
17730 ("⋑⋑", &[word("⋑⋑", 2)]),
17731 (
17732 "原理,进而",
17733 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
17734 ),
17735 (
17736 "hello world",
17737 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17738 ),
17739 (
17740 "hello, world",
17741 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17742 ),
17743 (
17744 " hello world",
17745 &[
17746 whitespace(" ", 2),
17747 word("hello", 5),
17748 whitespace(" ", 1),
17749 word("world", 5),
17750 ],
17751 ),
17752 (
17753 "这是什么 \n 钢笔",
17754 &[
17755 word("这", 1),
17756 word("是", 1),
17757 word("什", 1),
17758 word("么", 1),
17759 whitespace(" ", 1),
17760 newline(),
17761 whitespace(" ", 1),
17762 word("钢", 1),
17763 word("笔", 1),
17764 ],
17765 ),
17766 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
17767 ];
17768
17769 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17770 WordBreakToken::Word {
17771 token,
17772 grapheme_len,
17773 }
17774 }
17775
17776 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17777 WordBreakToken::InlineWhitespace {
17778 token,
17779 grapheme_len,
17780 }
17781 }
17782
17783 fn newline() -> WordBreakToken<'static> {
17784 WordBreakToken::Newline
17785 }
17786
17787 for (input, result) in tests {
17788 assert_eq!(
17789 WordBreakingTokenizer::new(input)
17790 .collect::<Vec<_>>()
17791 .as_slice(),
17792 *result,
17793 );
17794 }
17795}
17796
17797fn wrap_with_prefix(
17798 line_prefix: String,
17799 unwrapped_text: String,
17800 wrap_column: usize,
17801 tab_size: NonZeroU32,
17802 preserve_existing_whitespace: bool,
17803) -> String {
17804 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17805 let mut wrapped_text = String::new();
17806 let mut current_line = line_prefix.clone();
17807
17808 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17809 let mut current_line_len = line_prefix_len;
17810 let mut in_whitespace = false;
17811 for token in tokenizer {
17812 let have_preceding_whitespace = in_whitespace;
17813 match token {
17814 WordBreakToken::Word {
17815 token,
17816 grapheme_len,
17817 } => {
17818 in_whitespace = false;
17819 if current_line_len + grapheme_len > wrap_column
17820 && current_line_len != line_prefix_len
17821 {
17822 wrapped_text.push_str(current_line.trim_end());
17823 wrapped_text.push('\n');
17824 current_line.truncate(line_prefix.len());
17825 current_line_len = line_prefix_len;
17826 }
17827 current_line.push_str(token);
17828 current_line_len += grapheme_len;
17829 }
17830 WordBreakToken::InlineWhitespace {
17831 mut token,
17832 mut grapheme_len,
17833 } => {
17834 in_whitespace = true;
17835 if have_preceding_whitespace && !preserve_existing_whitespace {
17836 continue;
17837 }
17838 if !preserve_existing_whitespace {
17839 token = " ";
17840 grapheme_len = 1;
17841 }
17842 if current_line_len + grapheme_len > wrap_column {
17843 wrapped_text.push_str(current_line.trim_end());
17844 wrapped_text.push('\n');
17845 current_line.truncate(line_prefix.len());
17846 current_line_len = line_prefix_len;
17847 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17848 current_line.push_str(token);
17849 current_line_len += grapheme_len;
17850 }
17851 }
17852 WordBreakToken::Newline => {
17853 in_whitespace = true;
17854 if preserve_existing_whitespace {
17855 wrapped_text.push_str(current_line.trim_end());
17856 wrapped_text.push('\n');
17857 current_line.truncate(line_prefix.len());
17858 current_line_len = line_prefix_len;
17859 } else if have_preceding_whitespace {
17860 continue;
17861 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17862 {
17863 wrapped_text.push_str(current_line.trim_end());
17864 wrapped_text.push('\n');
17865 current_line.truncate(line_prefix.len());
17866 current_line_len = line_prefix_len;
17867 } else if current_line_len != line_prefix_len {
17868 current_line.push(' ');
17869 current_line_len += 1;
17870 }
17871 }
17872 }
17873 }
17874
17875 if !current_line.is_empty() {
17876 wrapped_text.push_str(¤t_line);
17877 }
17878 wrapped_text
17879}
17880
17881#[test]
17882fn test_wrap_with_prefix() {
17883 assert_eq!(
17884 wrap_with_prefix(
17885 "# ".to_string(),
17886 "abcdefg".to_string(),
17887 4,
17888 NonZeroU32::new(4).unwrap(),
17889 false,
17890 ),
17891 "# abcdefg"
17892 );
17893 assert_eq!(
17894 wrap_with_prefix(
17895 "".to_string(),
17896 "\thello world".to_string(),
17897 8,
17898 NonZeroU32::new(4).unwrap(),
17899 false,
17900 ),
17901 "hello\nworld"
17902 );
17903 assert_eq!(
17904 wrap_with_prefix(
17905 "// ".to_string(),
17906 "xx \nyy zz aa bb cc".to_string(),
17907 12,
17908 NonZeroU32::new(4).unwrap(),
17909 false,
17910 ),
17911 "// xx yy zz\n// aa bb cc"
17912 );
17913 assert_eq!(
17914 wrap_with_prefix(
17915 String::new(),
17916 "这是什么 \n 钢笔".to_string(),
17917 3,
17918 NonZeroU32::new(4).unwrap(),
17919 false,
17920 ),
17921 "这是什\n么 钢\n笔"
17922 );
17923}
17924
17925pub trait CollaborationHub {
17926 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17927 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17928 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17929}
17930
17931impl CollaborationHub for Entity<Project> {
17932 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17933 self.read(cx).collaborators()
17934 }
17935
17936 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17937 self.read(cx).user_store().read(cx).participant_indices()
17938 }
17939
17940 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17941 let this = self.read(cx);
17942 let user_ids = this.collaborators().values().map(|c| c.user_id);
17943 this.user_store().read_with(cx, |user_store, cx| {
17944 user_store.participant_names(user_ids, cx)
17945 })
17946 }
17947}
17948
17949pub trait SemanticsProvider {
17950 fn hover(
17951 &self,
17952 buffer: &Entity<Buffer>,
17953 position: text::Anchor,
17954 cx: &mut App,
17955 ) -> Option<Task<Vec<project::Hover>>>;
17956
17957 fn inlay_hints(
17958 &self,
17959 buffer_handle: Entity<Buffer>,
17960 range: Range<text::Anchor>,
17961 cx: &mut App,
17962 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17963
17964 fn resolve_inlay_hint(
17965 &self,
17966 hint: InlayHint,
17967 buffer_handle: Entity<Buffer>,
17968 server_id: LanguageServerId,
17969 cx: &mut App,
17970 ) -> Option<Task<anyhow::Result<InlayHint>>>;
17971
17972 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17973
17974 fn document_highlights(
17975 &self,
17976 buffer: &Entity<Buffer>,
17977 position: text::Anchor,
17978 cx: &mut App,
17979 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17980
17981 fn definitions(
17982 &self,
17983 buffer: &Entity<Buffer>,
17984 position: text::Anchor,
17985 kind: GotoDefinitionKind,
17986 cx: &mut App,
17987 ) -> Option<Task<Result<Vec<LocationLink>>>>;
17988
17989 fn range_for_rename(
17990 &self,
17991 buffer: &Entity<Buffer>,
17992 position: text::Anchor,
17993 cx: &mut App,
17994 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17995
17996 fn perform_rename(
17997 &self,
17998 buffer: &Entity<Buffer>,
17999 position: text::Anchor,
18000 new_name: String,
18001 cx: &mut App,
18002 ) -> Option<Task<Result<ProjectTransaction>>>;
18003}
18004
18005pub trait CompletionProvider {
18006 fn completions(
18007 &self,
18008 excerpt_id: ExcerptId,
18009 buffer: &Entity<Buffer>,
18010 buffer_position: text::Anchor,
18011 trigger: CompletionContext,
18012 window: &mut Window,
18013 cx: &mut Context<Editor>,
18014 ) -> Task<Result<Option<Vec<Completion>>>>;
18015
18016 fn resolve_completions(
18017 &self,
18018 buffer: Entity<Buffer>,
18019 completion_indices: Vec<usize>,
18020 completions: Rc<RefCell<Box<[Completion]>>>,
18021 cx: &mut Context<Editor>,
18022 ) -> Task<Result<bool>>;
18023
18024 fn apply_additional_edits_for_completion(
18025 &self,
18026 _buffer: Entity<Buffer>,
18027 _completions: Rc<RefCell<Box<[Completion]>>>,
18028 _completion_index: usize,
18029 _push_to_history: bool,
18030 _cx: &mut Context<Editor>,
18031 ) -> Task<Result<Option<language::Transaction>>> {
18032 Task::ready(Ok(None))
18033 }
18034
18035 fn is_completion_trigger(
18036 &self,
18037 buffer: &Entity<Buffer>,
18038 position: language::Anchor,
18039 text: &str,
18040 trigger_in_words: bool,
18041 cx: &mut Context<Editor>,
18042 ) -> bool;
18043
18044 fn sort_completions(&self) -> bool {
18045 true
18046 }
18047
18048 fn filter_completions(&self) -> bool {
18049 true
18050 }
18051}
18052
18053pub trait CodeActionProvider {
18054 fn id(&self) -> Arc<str>;
18055
18056 fn code_actions(
18057 &self,
18058 buffer: &Entity<Buffer>,
18059 range: Range<text::Anchor>,
18060 window: &mut Window,
18061 cx: &mut App,
18062 ) -> Task<Result<Vec<CodeAction>>>;
18063
18064 fn apply_code_action(
18065 &self,
18066 buffer_handle: Entity<Buffer>,
18067 action: CodeAction,
18068 excerpt_id: ExcerptId,
18069 push_to_history: bool,
18070 window: &mut Window,
18071 cx: &mut App,
18072 ) -> Task<Result<ProjectTransaction>>;
18073}
18074
18075impl CodeActionProvider for Entity<Project> {
18076 fn id(&self) -> Arc<str> {
18077 "project".into()
18078 }
18079
18080 fn code_actions(
18081 &self,
18082 buffer: &Entity<Buffer>,
18083 range: Range<text::Anchor>,
18084 _window: &mut Window,
18085 cx: &mut App,
18086 ) -> Task<Result<Vec<CodeAction>>> {
18087 self.update(cx, |project, cx| {
18088 let code_lens = project.code_lens(buffer, range.clone(), cx);
18089 let code_actions = project.code_actions(buffer, range, None, cx);
18090 cx.background_spawn(async move {
18091 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18092 Ok(code_lens
18093 .context("code lens fetch")?
18094 .into_iter()
18095 .chain(code_actions.context("code action fetch")?)
18096 .collect())
18097 })
18098 })
18099 }
18100
18101 fn apply_code_action(
18102 &self,
18103 buffer_handle: Entity<Buffer>,
18104 action: CodeAction,
18105 _excerpt_id: ExcerptId,
18106 push_to_history: bool,
18107 _window: &mut Window,
18108 cx: &mut App,
18109 ) -> Task<Result<ProjectTransaction>> {
18110 self.update(cx, |project, cx| {
18111 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18112 })
18113 }
18114}
18115
18116fn snippet_completions(
18117 project: &Project,
18118 buffer: &Entity<Buffer>,
18119 buffer_position: text::Anchor,
18120 cx: &mut App,
18121) -> Task<Result<Vec<Completion>>> {
18122 let language = buffer.read(cx).language_at(buffer_position);
18123 let language_name = language.as_ref().map(|language| language.lsp_id());
18124 let snippet_store = project.snippets().read(cx);
18125 let snippets = snippet_store.snippets_for(language_name, cx);
18126
18127 if snippets.is_empty() {
18128 return Task::ready(Ok(vec![]));
18129 }
18130 let snapshot = buffer.read(cx).text_snapshot();
18131 let chars: String = snapshot
18132 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18133 .collect();
18134
18135 let scope = language.map(|language| language.default_scope());
18136 let executor = cx.background_executor().clone();
18137
18138 cx.background_spawn(async move {
18139 let classifier = CharClassifier::new(scope).for_completion(true);
18140 let mut last_word = chars
18141 .chars()
18142 .take_while(|c| classifier.is_word(*c))
18143 .collect::<String>();
18144 last_word = last_word.chars().rev().collect();
18145
18146 if last_word.is_empty() {
18147 return Ok(vec![]);
18148 }
18149
18150 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18151 let to_lsp = |point: &text::Anchor| {
18152 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18153 point_to_lsp(end)
18154 };
18155 let lsp_end = to_lsp(&buffer_position);
18156
18157 let candidates = snippets
18158 .iter()
18159 .enumerate()
18160 .flat_map(|(ix, snippet)| {
18161 snippet
18162 .prefix
18163 .iter()
18164 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18165 })
18166 .collect::<Vec<StringMatchCandidate>>();
18167
18168 let mut matches = fuzzy::match_strings(
18169 &candidates,
18170 &last_word,
18171 last_word.chars().any(|c| c.is_uppercase()),
18172 100,
18173 &Default::default(),
18174 executor,
18175 )
18176 .await;
18177
18178 // Remove all candidates where the query's start does not match the start of any word in the candidate
18179 if let Some(query_start) = last_word.chars().next() {
18180 matches.retain(|string_match| {
18181 split_words(&string_match.string).any(|word| {
18182 // Check that the first codepoint of the word as lowercase matches the first
18183 // codepoint of the query as lowercase
18184 word.chars()
18185 .flat_map(|codepoint| codepoint.to_lowercase())
18186 .zip(query_start.to_lowercase())
18187 .all(|(word_cp, query_cp)| word_cp == query_cp)
18188 })
18189 });
18190 }
18191
18192 let matched_strings = matches
18193 .into_iter()
18194 .map(|m| m.string)
18195 .collect::<HashSet<_>>();
18196
18197 let result: Vec<Completion> = snippets
18198 .into_iter()
18199 .filter_map(|snippet| {
18200 let matching_prefix = snippet
18201 .prefix
18202 .iter()
18203 .find(|prefix| matched_strings.contains(*prefix))?;
18204 let start = as_offset - last_word.len();
18205 let start = snapshot.anchor_before(start);
18206 let range = start..buffer_position;
18207 let lsp_start = to_lsp(&start);
18208 let lsp_range = lsp::Range {
18209 start: lsp_start,
18210 end: lsp_end,
18211 };
18212 Some(Completion {
18213 old_range: range,
18214 new_text: snippet.body.clone(),
18215 source: CompletionSource::Lsp {
18216 server_id: LanguageServerId(usize::MAX),
18217 resolved: true,
18218 lsp_completion: Box::new(lsp::CompletionItem {
18219 label: snippet.prefix.first().unwrap().clone(),
18220 kind: Some(CompletionItemKind::SNIPPET),
18221 label_details: snippet.description.as_ref().map(|description| {
18222 lsp::CompletionItemLabelDetails {
18223 detail: Some(description.clone()),
18224 description: None,
18225 }
18226 }),
18227 insert_text_format: Some(InsertTextFormat::SNIPPET),
18228 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18229 lsp::InsertReplaceEdit {
18230 new_text: snippet.body.clone(),
18231 insert: lsp_range,
18232 replace: lsp_range,
18233 },
18234 )),
18235 filter_text: Some(snippet.body.clone()),
18236 sort_text: Some(char::MAX.to_string()),
18237 ..lsp::CompletionItem::default()
18238 }),
18239 lsp_defaults: None,
18240 },
18241 label: CodeLabel {
18242 text: matching_prefix.clone(),
18243 runs: Vec::new(),
18244 filter_range: 0..matching_prefix.len(),
18245 },
18246 icon_path: None,
18247 documentation: snippet
18248 .description
18249 .clone()
18250 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18251 confirm: None,
18252 })
18253 })
18254 .collect();
18255
18256 Ok(result)
18257 })
18258}
18259
18260impl CompletionProvider for Entity<Project> {
18261 fn completions(
18262 &self,
18263 _excerpt_id: ExcerptId,
18264 buffer: &Entity<Buffer>,
18265 buffer_position: text::Anchor,
18266 options: CompletionContext,
18267 _window: &mut Window,
18268 cx: &mut Context<Editor>,
18269 ) -> Task<Result<Option<Vec<Completion>>>> {
18270 self.update(cx, |project, cx| {
18271 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18272 let project_completions = project.completions(buffer, buffer_position, options, cx);
18273 cx.background_spawn(async move {
18274 let snippets_completions = snippets.await?;
18275 match project_completions.await? {
18276 Some(mut completions) => {
18277 completions.extend(snippets_completions);
18278 Ok(Some(completions))
18279 }
18280 None => {
18281 if snippets_completions.is_empty() {
18282 Ok(None)
18283 } else {
18284 Ok(Some(snippets_completions))
18285 }
18286 }
18287 }
18288 })
18289 })
18290 }
18291
18292 fn resolve_completions(
18293 &self,
18294 buffer: Entity<Buffer>,
18295 completion_indices: Vec<usize>,
18296 completions: Rc<RefCell<Box<[Completion]>>>,
18297 cx: &mut Context<Editor>,
18298 ) -> Task<Result<bool>> {
18299 self.update(cx, |project, cx| {
18300 project.lsp_store().update(cx, |lsp_store, cx| {
18301 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18302 })
18303 })
18304 }
18305
18306 fn apply_additional_edits_for_completion(
18307 &self,
18308 buffer: Entity<Buffer>,
18309 completions: Rc<RefCell<Box<[Completion]>>>,
18310 completion_index: usize,
18311 push_to_history: bool,
18312 cx: &mut Context<Editor>,
18313 ) -> Task<Result<Option<language::Transaction>>> {
18314 self.update(cx, |project, cx| {
18315 project.lsp_store().update(cx, |lsp_store, cx| {
18316 lsp_store.apply_additional_edits_for_completion(
18317 buffer,
18318 completions,
18319 completion_index,
18320 push_to_history,
18321 cx,
18322 )
18323 })
18324 })
18325 }
18326
18327 fn is_completion_trigger(
18328 &self,
18329 buffer: &Entity<Buffer>,
18330 position: language::Anchor,
18331 text: &str,
18332 trigger_in_words: bool,
18333 cx: &mut Context<Editor>,
18334 ) -> bool {
18335 let mut chars = text.chars();
18336 let char = if let Some(char) = chars.next() {
18337 char
18338 } else {
18339 return false;
18340 };
18341 if chars.next().is_some() {
18342 return false;
18343 }
18344
18345 let buffer = buffer.read(cx);
18346 let snapshot = buffer.snapshot();
18347 if !snapshot.settings_at(position, cx).show_completions_on_input {
18348 return false;
18349 }
18350 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18351 if trigger_in_words && classifier.is_word(char) {
18352 return true;
18353 }
18354
18355 buffer.completion_triggers().contains(text)
18356 }
18357}
18358
18359impl SemanticsProvider for Entity<Project> {
18360 fn hover(
18361 &self,
18362 buffer: &Entity<Buffer>,
18363 position: text::Anchor,
18364 cx: &mut App,
18365 ) -> Option<Task<Vec<project::Hover>>> {
18366 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18367 }
18368
18369 fn document_highlights(
18370 &self,
18371 buffer: &Entity<Buffer>,
18372 position: text::Anchor,
18373 cx: &mut App,
18374 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18375 Some(self.update(cx, |project, cx| {
18376 project.document_highlights(buffer, position, cx)
18377 }))
18378 }
18379
18380 fn definitions(
18381 &self,
18382 buffer: &Entity<Buffer>,
18383 position: text::Anchor,
18384 kind: GotoDefinitionKind,
18385 cx: &mut App,
18386 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18387 Some(self.update(cx, |project, cx| match kind {
18388 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18389 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18390 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18391 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18392 }))
18393 }
18394
18395 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18396 // TODO: make this work for remote projects
18397 self.update(cx, |this, cx| {
18398 buffer.update(cx, |buffer, cx| {
18399 this.any_language_server_supports_inlay_hints(buffer, cx)
18400 })
18401 })
18402 }
18403
18404 fn inlay_hints(
18405 &self,
18406 buffer_handle: Entity<Buffer>,
18407 range: Range<text::Anchor>,
18408 cx: &mut App,
18409 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18410 Some(self.update(cx, |project, cx| {
18411 project.inlay_hints(buffer_handle, range, cx)
18412 }))
18413 }
18414
18415 fn resolve_inlay_hint(
18416 &self,
18417 hint: InlayHint,
18418 buffer_handle: Entity<Buffer>,
18419 server_id: LanguageServerId,
18420 cx: &mut App,
18421 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18422 Some(self.update(cx, |project, cx| {
18423 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18424 }))
18425 }
18426
18427 fn range_for_rename(
18428 &self,
18429 buffer: &Entity<Buffer>,
18430 position: text::Anchor,
18431 cx: &mut App,
18432 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18433 Some(self.update(cx, |project, cx| {
18434 let buffer = buffer.clone();
18435 let task = project.prepare_rename(buffer.clone(), position, cx);
18436 cx.spawn(async move |_, cx| {
18437 Ok(match task.await? {
18438 PrepareRenameResponse::Success(range) => Some(range),
18439 PrepareRenameResponse::InvalidPosition => None,
18440 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18441 // Fallback on using TreeSitter info to determine identifier range
18442 buffer.update(cx, |buffer, _| {
18443 let snapshot = buffer.snapshot();
18444 let (range, kind) = snapshot.surrounding_word(position);
18445 if kind != Some(CharKind::Word) {
18446 return None;
18447 }
18448 Some(
18449 snapshot.anchor_before(range.start)
18450 ..snapshot.anchor_after(range.end),
18451 )
18452 })?
18453 }
18454 })
18455 })
18456 }))
18457 }
18458
18459 fn perform_rename(
18460 &self,
18461 buffer: &Entity<Buffer>,
18462 position: text::Anchor,
18463 new_name: String,
18464 cx: &mut App,
18465 ) -> Option<Task<Result<ProjectTransaction>>> {
18466 Some(self.update(cx, |project, cx| {
18467 project.perform_rename(buffer.clone(), position, new_name, cx)
18468 }))
18469 }
18470}
18471
18472fn inlay_hint_settings(
18473 location: Anchor,
18474 snapshot: &MultiBufferSnapshot,
18475 cx: &mut Context<Editor>,
18476) -> InlayHintSettings {
18477 let file = snapshot.file_at(location);
18478 let language = snapshot.language_at(location).map(|l| l.name());
18479 language_settings(language, file, cx).inlay_hints
18480}
18481
18482fn consume_contiguous_rows(
18483 contiguous_row_selections: &mut Vec<Selection<Point>>,
18484 selection: &Selection<Point>,
18485 display_map: &DisplaySnapshot,
18486 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18487) -> (MultiBufferRow, MultiBufferRow) {
18488 contiguous_row_selections.push(selection.clone());
18489 let start_row = MultiBufferRow(selection.start.row);
18490 let mut end_row = ending_row(selection, display_map);
18491
18492 while let Some(next_selection) = selections.peek() {
18493 if next_selection.start.row <= end_row.0 {
18494 end_row = ending_row(next_selection, display_map);
18495 contiguous_row_selections.push(selections.next().unwrap().clone());
18496 } else {
18497 break;
18498 }
18499 }
18500 (start_row, end_row)
18501}
18502
18503fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18504 if next_selection.end.column > 0 || next_selection.is_empty() {
18505 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18506 } else {
18507 MultiBufferRow(next_selection.end.row)
18508 }
18509}
18510
18511impl EditorSnapshot {
18512 pub fn remote_selections_in_range<'a>(
18513 &'a self,
18514 range: &'a Range<Anchor>,
18515 collaboration_hub: &dyn CollaborationHub,
18516 cx: &'a App,
18517 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18518 let participant_names = collaboration_hub.user_names(cx);
18519 let participant_indices = collaboration_hub.user_participant_indices(cx);
18520 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18521 let collaborators_by_replica_id = collaborators_by_peer_id
18522 .iter()
18523 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18524 .collect::<HashMap<_, _>>();
18525 self.buffer_snapshot
18526 .selections_in_range(range, false)
18527 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18528 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18529 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18530 let user_name = participant_names.get(&collaborator.user_id).cloned();
18531 Some(RemoteSelection {
18532 replica_id,
18533 selection,
18534 cursor_shape,
18535 line_mode,
18536 participant_index,
18537 peer_id: collaborator.peer_id,
18538 user_name,
18539 })
18540 })
18541 }
18542
18543 pub fn hunks_for_ranges(
18544 &self,
18545 ranges: impl IntoIterator<Item = Range<Point>>,
18546 ) -> Vec<MultiBufferDiffHunk> {
18547 let mut hunks = Vec::new();
18548 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18549 HashMap::default();
18550 for query_range in ranges {
18551 let query_rows =
18552 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18553 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18554 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18555 ) {
18556 // Include deleted hunks that are adjacent to the query range, because
18557 // otherwise they would be missed.
18558 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18559 if hunk.status().is_deleted() {
18560 intersects_range |= hunk.row_range.start == query_rows.end;
18561 intersects_range |= hunk.row_range.end == query_rows.start;
18562 }
18563 if intersects_range {
18564 if !processed_buffer_rows
18565 .entry(hunk.buffer_id)
18566 .or_default()
18567 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18568 {
18569 continue;
18570 }
18571 hunks.push(hunk);
18572 }
18573 }
18574 }
18575
18576 hunks
18577 }
18578
18579 fn display_diff_hunks_for_rows<'a>(
18580 &'a self,
18581 display_rows: Range<DisplayRow>,
18582 folded_buffers: &'a HashSet<BufferId>,
18583 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18584 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18585 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18586
18587 self.buffer_snapshot
18588 .diff_hunks_in_range(buffer_start..buffer_end)
18589 .filter_map(|hunk| {
18590 if folded_buffers.contains(&hunk.buffer_id) {
18591 return None;
18592 }
18593
18594 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18595 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18596
18597 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18598 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18599
18600 let display_hunk = if hunk_display_start.column() != 0 {
18601 DisplayDiffHunk::Folded {
18602 display_row: hunk_display_start.row(),
18603 }
18604 } else {
18605 let mut end_row = hunk_display_end.row();
18606 if hunk_display_end.column() > 0 {
18607 end_row.0 += 1;
18608 }
18609 let is_created_file = hunk.is_created_file();
18610 DisplayDiffHunk::Unfolded {
18611 status: hunk.status(),
18612 diff_base_byte_range: hunk.diff_base_byte_range,
18613 display_row_range: hunk_display_start.row()..end_row,
18614 multi_buffer_range: Anchor::range_in_buffer(
18615 hunk.excerpt_id,
18616 hunk.buffer_id,
18617 hunk.buffer_range,
18618 ),
18619 is_created_file,
18620 }
18621 };
18622
18623 Some(display_hunk)
18624 })
18625 }
18626
18627 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18628 self.display_snapshot.buffer_snapshot.language_at(position)
18629 }
18630
18631 pub fn is_focused(&self) -> bool {
18632 self.is_focused
18633 }
18634
18635 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18636 self.placeholder_text.as_ref()
18637 }
18638
18639 pub fn scroll_position(&self) -> gpui::Point<f32> {
18640 self.scroll_anchor.scroll_position(&self.display_snapshot)
18641 }
18642
18643 fn gutter_dimensions(
18644 &self,
18645 font_id: FontId,
18646 font_size: Pixels,
18647 max_line_number_width: Pixels,
18648 cx: &App,
18649 ) -> Option<GutterDimensions> {
18650 if !self.show_gutter {
18651 return None;
18652 }
18653
18654 let descent = cx.text_system().descent(font_id, font_size);
18655 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18656 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18657
18658 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18659 matches!(
18660 ProjectSettings::get_global(cx).git.git_gutter,
18661 Some(GitGutterSetting::TrackedFiles)
18662 )
18663 });
18664 let gutter_settings = EditorSettings::get_global(cx).gutter;
18665 let show_line_numbers = self
18666 .show_line_numbers
18667 .unwrap_or(gutter_settings.line_numbers);
18668 let line_gutter_width = if show_line_numbers {
18669 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18670 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18671 max_line_number_width.max(min_width_for_number_on_gutter)
18672 } else {
18673 0.0.into()
18674 };
18675
18676 let show_code_actions = self
18677 .show_code_actions
18678 .unwrap_or(gutter_settings.code_actions);
18679
18680 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18681 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18682
18683 let git_blame_entries_width =
18684 self.git_blame_gutter_max_author_length
18685 .map(|max_author_length| {
18686 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18687
18688 /// The number of characters to dedicate to gaps and margins.
18689 const SPACING_WIDTH: usize = 4;
18690
18691 let max_char_count = max_author_length
18692 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18693 + ::git::SHORT_SHA_LENGTH
18694 + MAX_RELATIVE_TIMESTAMP.len()
18695 + SPACING_WIDTH;
18696
18697 em_advance * max_char_count
18698 });
18699
18700 let is_singleton = self.buffer_snapshot.is_singleton();
18701
18702 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18703 left_padding += if !is_singleton {
18704 em_width * 4.0
18705 } else if show_code_actions || show_runnables || show_breakpoints {
18706 em_width * 3.0
18707 } else if show_git_gutter && show_line_numbers {
18708 em_width * 2.0
18709 } else if show_git_gutter || show_line_numbers {
18710 em_width
18711 } else {
18712 px(0.)
18713 };
18714
18715 let shows_folds = is_singleton && gutter_settings.folds;
18716
18717 let right_padding = if shows_folds && show_line_numbers {
18718 em_width * 4.0
18719 } else if shows_folds || (!is_singleton && show_line_numbers) {
18720 em_width * 3.0
18721 } else if show_line_numbers {
18722 em_width
18723 } else {
18724 px(0.)
18725 };
18726
18727 Some(GutterDimensions {
18728 left_padding,
18729 right_padding,
18730 width: line_gutter_width + left_padding + right_padding,
18731 margin: -descent,
18732 git_blame_entries_width,
18733 })
18734 }
18735
18736 pub fn render_crease_toggle(
18737 &self,
18738 buffer_row: MultiBufferRow,
18739 row_contains_cursor: bool,
18740 editor: Entity<Editor>,
18741 window: &mut Window,
18742 cx: &mut App,
18743 ) -> Option<AnyElement> {
18744 let folded = self.is_line_folded(buffer_row);
18745 let mut is_foldable = false;
18746
18747 if let Some(crease) = self
18748 .crease_snapshot
18749 .query_row(buffer_row, &self.buffer_snapshot)
18750 {
18751 is_foldable = true;
18752 match crease {
18753 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18754 if let Some(render_toggle) = render_toggle {
18755 let toggle_callback =
18756 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18757 if folded {
18758 editor.update(cx, |editor, cx| {
18759 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18760 });
18761 } else {
18762 editor.update(cx, |editor, cx| {
18763 editor.unfold_at(
18764 &crate::UnfoldAt { buffer_row },
18765 window,
18766 cx,
18767 )
18768 });
18769 }
18770 });
18771 return Some((render_toggle)(
18772 buffer_row,
18773 folded,
18774 toggle_callback,
18775 window,
18776 cx,
18777 ));
18778 }
18779 }
18780 }
18781 }
18782
18783 is_foldable |= self.starts_indent(buffer_row);
18784
18785 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18786 Some(
18787 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18788 .toggle_state(folded)
18789 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18790 if folded {
18791 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18792 } else {
18793 this.fold_at(&FoldAt { buffer_row }, window, cx);
18794 }
18795 }))
18796 .into_any_element(),
18797 )
18798 } else {
18799 None
18800 }
18801 }
18802
18803 pub fn render_crease_trailer(
18804 &self,
18805 buffer_row: MultiBufferRow,
18806 window: &mut Window,
18807 cx: &mut App,
18808 ) -> Option<AnyElement> {
18809 let folded = self.is_line_folded(buffer_row);
18810 if let Crease::Inline { render_trailer, .. } = self
18811 .crease_snapshot
18812 .query_row(buffer_row, &self.buffer_snapshot)?
18813 {
18814 let render_trailer = render_trailer.as_ref()?;
18815 Some(render_trailer(buffer_row, folded, window, cx))
18816 } else {
18817 None
18818 }
18819 }
18820}
18821
18822impl Deref for EditorSnapshot {
18823 type Target = DisplaySnapshot;
18824
18825 fn deref(&self) -> &Self::Target {
18826 &self.display_snapshot
18827 }
18828}
18829
18830#[derive(Clone, Debug, PartialEq, Eq)]
18831pub enum EditorEvent {
18832 InputIgnored {
18833 text: Arc<str>,
18834 },
18835 InputHandled {
18836 utf16_range_to_replace: Option<Range<isize>>,
18837 text: Arc<str>,
18838 },
18839 ExcerptsAdded {
18840 buffer: Entity<Buffer>,
18841 predecessor: ExcerptId,
18842 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18843 },
18844 ExcerptsRemoved {
18845 ids: Vec<ExcerptId>,
18846 },
18847 BufferFoldToggled {
18848 ids: Vec<ExcerptId>,
18849 folded: bool,
18850 },
18851 ExcerptsEdited {
18852 ids: Vec<ExcerptId>,
18853 },
18854 ExcerptsExpanded {
18855 ids: Vec<ExcerptId>,
18856 },
18857 BufferEdited,
18858 Edited {
18859 transaction_id: clock::Lamport,
18860 },
18861 Reparsed(BufferId),
18862 Focused,
18863 FocusedIn,
18864 Blurred,
18865 DirtyChanged,
18866 Saved,
18867 TitleChanged,
18868 DiffBaseChanged,
18869 SelectionsChanged {
18870 local: bool,
18871 },
18872 ScrollPositionChanged {
18873 local: bool,
18874 autoscroll: bool,
18875 },
18876 Closed,
18877 TransactionUndone {
18878 transaction_id: clock::Lamport,
18879 },
18880 TransactionBegun {
18881 transaction_id: clock::Lamport,
18882 },
18883 Reloaded,
18884 CursorShapeChanged,
18885 PushedToNavHistory {
18886 anchor: Anchor,
18887 is_deactivate: bool,
18888 },
18889}
18890
18891impl EventEmitter<EditorEvent> for Editor {}
18892
18893impl Focusable for Editor {
18894 fn focus_handle(&self, _cx: &App) -> FocusHandle {
18895 self.focus_handle.clone()
18896 }
18897}
18898
18899impl Render for Editor {
18900 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
18901 let settings = ThemeSettings::get_global(cx);
18902
18903 let mut text_style = match self.mode {
18904 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18905 color: cx.theme().colors().editor_foreground,
18906 font_family: settings.ui_font.family.clone(),
18907 font_features: settings.ui_font.features.clone(),
18908 font_fallbacks: settings.ui_font.fallbacks.clone(),
18909 font_size: rems(0.875).into(),
18910 font_weight: settings.ui_font.weight,
18911 line_height: relative(settings.buffer_line_height.value()),
18912 ..Default::default()
18913 },
18914 EditorMode::Full => TextStyle {
18915 color: cx.theme().colors().editor_foreground,
18916 font_family: settings.buffer_font.family.clone(),
18917 font_features: settings.buffer_font.features.clone(),
18918 font_fallbacks: settings.buffer_font.fallbacks.clone(),
18919 font_size: settings.buffer_font_size(cx).into(),
18920 font_weight: settings.buffer_font.weight,
18921 line_height: relative(settings.buffer_line_height.value()),
18922 ..Default::default()
18923 },
18924 };
18925 if let Some(text_style_refinement) = &self.text_style_refinement {
18926 text_style.refine(text_style_refinement)
18927 }
18928
18929 let background = match self.mode {
18930 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18931 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18932 EditorMode::Full => cx.theme().colors().editor_background,
18933 };
18934
18935 EditorElement::new(
18936 &cx.entity(),
18937 EditorStyle {
18938 background,
18939 local_player: cx.theme().players().local(),
18940 text: text_style,
18941 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18942 syntax: cx.theme().syntax().clone(),
18943 status: cx.theme().status().clone(),
18944 inlay_hints_style: make_inlay_hints_style(cx),
18945 inline_completion_styles: make_suggestion_styles(cx),
18946 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18947 },
18948 )
18949 }
18950}
18951
18952impl EntityInputHandler for Editor {
18953 fn text_for_range(
18954 &mut self,
18955 range_utf16: Range<usize>,
18956 adjusted_range: &mut Option<Range<usize>>,
18957 _: &mut Window,
18958 cx: &mut Context<Self>,
18959 ) -> Option<String> {
18960 let snapshot = self.buffer.read(cx).read(cx);
18961 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18962 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18963 if (start.0..end.0) != range_utf16 {
18964 adjusted_range.replace(start.0..end.0);
18965 }
18966 Some(snapshot.text_for_range(start..end).collect())
18967 }
18968
18969 fn selected_text_range(
18970 &mut self,
18971 ignore_disabled_input: bool,
18972 _: &mut Window,
18973 cx: &mut Context<Self>,
18974 ) -> Option<UTF16Selection> {
18975 // Prevent the IME menu from appearing when holding down an alphabetic key
18976 // while input is disabled.
18977 if !ignore_disabled_input && !self.input_enabled {
18978 return None;
18979 }
18980
18981 let selection = self.selections.newest::<OffsetUtf16>(cx);
18982 let range = selection.range();
18983
18984 Some(UTF16Selection {
18985 range: range.start.0..range.end.0,
18986 reversed: selection.reversed,
18987 })
18988 }
18989
18990 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18991 let snapshot = self.buffer.read(cx).read(cx);
18992 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18993 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18994 }
18995
18996 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18997 self.clear_highlights::<InputComposition>(cx);
18998 self.ime_transaction.take();
18999 }
19000
19001 fn replace_text_in_range(
19002 &mut self,
19003 range_utf16: Option<Range<usize>>,
19004 text: &str,
19005 window: &mut Window,
19006 cx: &mut Context<Self>,
19007 ) {
19008 if !self.input_enabled {
19009 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19010 return;
19011 }
19012
19013 self.transact(window, cx, |this, window, cx| {
19014 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19015 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19016 Some(this.selection_replacement_ranges(range_utf16, cx))
19017 } else {
19018 this.marked_text_ranges(cx)
19019 };
19020
19021 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19022 let newest_selection_id = this.selections.newest_anchor().id;
19023 this.selections
19024 .all::<OffsetUtf16>(cx)
19025 .iter()
19026 .zip(ranges_to_replace.iter())
19027 .find_map(|(selection, range)| {
19028 if selection.id == newest_selection_id {
19029 Some(
19030 (range.start.0 as isize - selection.head().0 as isize)
19031 ..(range.end.0 as isize - selection.head().0 as isize),
19032 )
19033 } else {
19034 None
19035 }
19036 })
19037 });
19038
19039 cx.emit(EditorEvent::InputHandled {
19040 utf16_range_to_replace: range_to_replace,
19041 text: text.into(),
19042 });
19043
19044 if let Some(new_selected_ranges) = new_selected_ranges {
19045 this.change_selections(None, window, cx, |selections| {
19046 selections.select_ranges(new_selected_ranges)
19047 });
19048 this.backspace(&Default::default(), window, cx);
19049 }
19050
19051 this.handle_input(text, window, cx);
19052 });
19053
19054 if let Some(transaction) = self.ime_transaction {
19055 self.buffer.update(cx, |buffer, cx| {
19056 buffer.group_until_transaction(transaction, cx);
19057 });
19058 }
19059
19060 self.unmark_text(window, cx);
19061 }
19062
19063 fn replace_and_mark_text_in_range(
19064 &mut self,
19065 range_utf16: Option<Range<usize>>,
19066 text: &str,
19067 new_selected_range_utf16: Option<Range<usize>>,
19068 window: &mut Window,
19069 cx: &mut Context<Self>,
19070 ) {
19071 if !self.input_enabled {
19072 return;
19073 }
19074
19075 let transaction = self.transact(window, cx, |this, window, cx| {
19076 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19077 let snapshot = this.buffer.read(cx).read(cx);
19078 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19079 for marked_range in &mut marked_ranges {
19080 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19081 marked_range.start.0 += relative_range_utf16.start;
19082 marked_range.start =
19083 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19084 marked_range.end =
19085 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19086 }
19087 }
19088 Some(marked_ranges)
19089 } else if let Some(range_utf16) = range_utf16 {
19090 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19091 Some(this.selection_replacement_ranges(range_utf16, cx))
19092 } else {
19093 None
19094 };
19095
19096 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19097 let newest_selection_id = this.selections.newest_anchor().id;
19098 this.selections
19099 .all::<OffsetUtf16>(cx)
19100 .iter()
19101 .zip(ranges_to_replace.iter())
19102 .find_map(|(selection, range)| {
19103 if selection.id == newest_selection_id {
19104 Some(
19105 (range.start.0 as isize - selection.head().0 as isize)
19106 ..(range.end.0 as isize - selection.head().0 as isize),
19107 )
19108 } else {
19109 None
19110 }
19111 })
19112 });
19113
19114 cx.emit(EditorEvent::InputHandled {
19115 utf16_range_to_replace: range_to_replace,
19116 text: text.into(),
19117 });
19118
19119 if let Some(ranges) = ranges_to_replace {
19120 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19121 }
19122
19123 let marked_ranges = {
19124 let snapshot = this.buffer.read(cx).read(cx);
19125 this.selections
19126 .disjoint_anchors()
19127 .iter()
19128 .map(|selection| {
19129 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19130 })
19131 .collect::<Vec<_>>()
19132 };
19133
19134 if text.is_empty() {
19135 this.unmark_text(window, cx);
19136 } else {
19137 this.highlight_text::<InputComposition>(
19138 marked_ranges.clone(),
19139 HighlightStyle {
19140 underline: Some(UnderlineStyle {
19141 thickness: px(1.),
19142 color: None,
19143 wavy: false,
19144 }),
19145 ..Default::default()
19146 },
19147 cx,
19148 );
19149 }
19150
19151 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19152 let use_autoclose = this.use_autoclose;
19153 let use_auto_surround = this.use_auto_surround;
19154 this.set_use_autoclose(false);
19155 this.set_use_auto_surround(false);
19156 this.handle_input(text, window, cx);
19157 this.set_use_autoclose(use_autoclose);
19158 this.set_use_auto_surround(use_auto_surround);
19159
19160 if let Some(new_selected_range) = new_selected_range_utf16 {
19161 let snapshot = this.buffer.read(cx).read(cx);
19162 let new_selected_ranges = marked_ranges
19163 .into_iter()
19164 .map(|marked_range| {
19165 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19166 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19167 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19168 snapshot.clip_offset_utf16(new_start, Bias::Left)
19169 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19170 })
19171 .collect::<Vec<_>>();
19172
19173 drop(snapshot);
19174 this.change_selections(None, window, cx, |selections| {
19175 selections.select_ranges(new_selected_ranges)
19176 });
19177 }
19178 });
19179
19180 self.ime_transaction = self.ime_transaction.or(transaction);
19181 if let Some(transaction) = self.ime_transaction {
19182 self.buffer.update(cx, |buffer, cx| {
19183 buffer.group_until_transaction(transaction, cx);
19184 });
19185 }
19186
19187 if self.text_highlights::<InputComposition>(cx).is_none() {
19188 self.ime_transaction.take();
19189 }
19190 }
19191
19192 fn bounds_for_range(
19193 &mut self,
19194 range_utf16: Range<usize>,
19195 element_bounds: gpui::Bounds<Pixels>,
19196 window: &mut Window,
19197 cx: &mut Context<Self>,
19198 ) -> Option<gpui::Bounds<Pixels>> {
19199 let text_layout_details = self.text_layout_details(window);
19200 let gpui::Size {
19201 width: em_width,
19202 height: line_height,
19203 } = self.character_size(window);
19204
19205 let snapshot = self.snapshot(window, cx);
19206 let scroll_position = snapshot.scroll_position();
19207 let scroll_left = scroll_position.x * em_width;
19208
19209 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19210 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19211 + self.gutter_dimensions.width
19212 + self.gutter_dimensions.margin;
19213 let y = line_height * (start.row().as_f32() - scroll_position.y);
19214
19215 Some(Bounds {
19216 origin: element_bounds.origin + point(x, y),
19217 size: size(em_width, line_height),
19218 })
19219 }
19220
19221 fn character_index_for_point(
19222 &mut self,
19223 point: gpui::Point<Pixels>,
19224 _window: &mut Window,
19225 _cx: &mut Context<Self>,
19226 ) -> Option<usize> {
19227 let position_map = self.last_position_map.as_ref()?;
19228 if !position_map.text_hitbox.contains(&point) {
19229 return None;
19230 }
19231 let display_point = position_map.point_for_position(point).previous_valid;
19232 let anchor = position_map
19233 .snapshot
19234 .display_point_to_anchor(display_point, Bias::Left);
19235 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19236 Some(utf16_offset.0)
19237 }
19238}
19239
19240trait SelectionExt {
19241 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19242 fn spanned_rows(
19243 &self,
19244 include_end_if_at_line_start: bool,
19245 map: &DisplaySnapshot,
19246 ) -> Range<MultiBufferRow>;
19247}
19248
19249impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19250 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19251 let start = self
19252 .start
19253 .to_point(&map.buffer_snapshot)
19254 .to_display_point(map);
19255 let end = self
19256 .end
19257 .to_point(&map.buffer_snapshot)
19258 .to_display_point(map);
19259 if self.reversed {
19260 end..start
19261 } else {
19262 start..end
19263 }
19264 }
19265
19266 fn spanned_rows(
19267 &self,
19268 include_end_if_at_line_start: bool,
19269 map: &DisplaySnapshot,
19270 ) -> Range<MultiBufferRow> {
19271 let start = self.start.to_point(&map.buffer_snapshot);
19272 let mut end = self.end.to_point(&map.buffer_snapshot);
19273 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19274 end.row -= 1;
19275 }
19276
19277 let buffer_start = map.prev_line_boundary(start).0;
19278 let buffer_end = map.next_line_boundary(end).0;
19279 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19280 }
19281}
19282
19283impl<T: InvalidationRegion> InvalidationStack<T> {
19284 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19285 where
19286 S: Clone + ToOffset,
19287 {
19288 while let Some(region) = self.last() {
19289 let all_selections_inside_invalidation_ranges =
19290 if selections.len() == region.ranges().len() {
19291 selections
19292 .iter()
19293 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19294 .all(|(selection, invalidation_range)| {
19295 let head = selection.head().to_offset(buffer);
19296 invalidation_range.start <= head && invalidation_range.end >= head
19297 })
19298 } else {
19299 false
19300 };
19301
19302 if all_selections_inside_invalidation_ranges {
19303 break;
19304 } else {
19305 self.pop();
19306 }
19307 }
19308 }
19309}
19310
19311impl<T> Default for InvalidationStack<T> {
19312 fn default() -> Self {
19313 Self(Default::default())
19314 }
19315}
19316
19317impl<T> Deref for InvalidationStack<T> {
19318 type Target = Vec<T>;
19319
19320 fn deref(&self) -> &Self::Target {
19321 &self.0
19322 }
19323}
19324
19325impl<T> DerefMut for InvalidationStack<T> {
19326 fn deref_mut(&mut self) -> &mut Self::Target {
19327 &mut self.0
19328 }
19329}
19330
19331impl InvalidationRegion for SnippetState {
19332 fn ranges(&self) -> &[Range<Anchor>] {
19333 &self.ranges[self.active_index]
19334 }
19335}
19336
19337pub fn diagnostic_block_renderer(
19338 diagnostic: Diagnostic,
19339 max_message_rows: Option<u8>,
19340 allow_closing: bool,
19341) -> RenderBlock {
19342 let (text_without_backticks, code_ranges) =
19343 highlight_diagnostic_message(&diagnostic, max_message_rows);
19344
19345 Arc::new(move |cx: &mut BlockContext| {
19346 let group_id: SharedString = cx.block_id.to_string().into();
19347
19348 let mut text_style = cx.window.text_style().clone();
19349 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19350 let theme_settings = ThemeSettings::get_global(cx);
19351 text_style.font_family = theme_settings.buffer_font.family.clone();
19352 text_style.font_style = theme_settings.buffer_font.style;
19353 text_style.font_features = theme_settings.buffer_font.features.clone();
19354 text_style.font_weight = theme_settings.buffer_font.weight;
19355
19356 let multi_line_diagnostic = diagnostic.message.contains('\n');
19357
19358 let buttons = |diagnostic: &Diagnostic| {
19359 if multi_line_diagnostic {
19360 v_flex()
19361 } else {
19362 h_flex()
19363 }
19364 .when(allow_closing, |div| {
19365 div.children(diagnostic.is_primary.then(|| {
19366 IconButton::new("close-block", IconName::XCircle)
19367 .icon_color(Color::Muted)
19368 .size(ButtonSize::Compact)
19369 .style(ButtonStyle::Transparent)
19370 .visible_on_hover(group_id.clone())
19371 .on_click(move |_click, window, cx| {
19372 window.dispatch_action(Box::new(Cancel), cx)
19373 })
19374 .tooltip(|window, cx| {
19375 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19376 })
19377 }))
19378 })
19379 .child(
19380 IconButton::new("copy-block", IconName::Copy)
19381 .icon_color(Color::Muted)
19382 .size(ButtonSize::Compact)
19383 .style(ButtonStyle::Transparent)
19384 .visible_on_hover(group_id.clone())
19385 .on_click({
19386 let message = diagnostic.message.clone();
19387 move |_click, _, cx| {
19388 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19389 }
19390 })
19391 .tooltip(Tooltip::text("Copy diagnostic message")),
19392 )
19393 };
19394
19395 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19396 AvailableSpace::min_size(),
19397 cx.window,
19398 cx.app,
19399 );
19400
19401 h_flex()
19402 .id(cx.block_id)
19403 .group(group_id.clone())
19404 .relative()
19405 .size_full()
19406 .block_mouse_down()
19407 .pl(cx.gutter_dimensions.width)
19408 .w(cx.max_width - cx.gutter_dimensions.full_width())
19409 .child(
19410 div()
19411 .flex()
19412 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19413 .flex_shrink(),
19414 )
19415 .child(buttons(&diagnostic))
19416 .child(div().flex().flex_shrink_0().child(
19417 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19418 &text_style,
19419 code_ranges.iter().map(|range| {
19420 (
19421 range.clone(),
19422 HighlightStyle {
19423 font_weight: Some(FontWeight::BOLD),
19424 ..Default::default()
19425 },
19426 )
19427 }),
19428 ),
19429 ))
19430 .into_any_element()
19431 })
19432}
19433
19434fn inline_completion_edit_text(
19435 current_snapshot: &BufferSnapshot,
19436 edits: &[(Range<Anchor>, String)],
19437 edit_preview: &EditPreview,
19438 include_deletions: bool,
19439 cx: &App,
19440) -> HighlightedText {
19441 let edits = edits
19442 .iter()
19443 .map(|(anchor, text)| {
19444 (
19445 anchor.start.text_anchor..anchor.end.text_anchor,
19446 text.clone(),
19447 )
19448 })
19449 .collect::<Vec<_>>();
19450
19451 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19452}
19453
19454pub fn highlight_diagnostic_message(
19455 diagnostic: &Diagnostic,
19456 mut max_message_rows: Option<u8>,
19457) -> (SharedString, Vec<Range<usize>>) {
19458 let mut text_without_backticks = String::new();
19459 let mut code_ranges = Vec::new();
19460
19461 if let Some(source) = &diagnostic.source {
19462 text_without_backticks.push_str(source);
19463 code_ranges.push(0..source.len());
19464 text_without_backticks.push_str(": ");
19465 }
19466
19467 let mut prev_offset = 0;
19468 let mut in_code_block = false;
19469 let has_row_limit = max_message_rows.is_some();
19470 let mut newline_indices = diagnostic
19471 .message
19472 .match_indices('\n')
19473 .filter(|_| has_row_limit)
19474 .map(|(ix, _)| ix)
19475 .fuse()
19476 .peekable();
19477
19478 for (quote_ix, _) in diagnostic
19479 .message
19480 .match_indices('`')
19481 .chain([(diagnostic.message.len(), "")])
19482 {
19483 let mut first_newline_ix = None;
19484 let mut last_newline_ix = None;
19485 while let Some(newline_ix) = newline_indices.peek() {
19486 if *newline_ix < quote_ix {
19487 if first_newline_ix.is_none() {
19488 first_newline_ix = Some(*newline_ix);
19489 }
19490 last_newline_ix = Some(*newline_ix);
19491
19492 if let Some(rows_left) = &mut max_message_rows {
19493 if *rows_left == 0 {
19494 break;
19495 } else {
19496 *rows_left -= 1;
19497 }
19498 }
19499 let _ = newline_indices.next();
19500 } else {
19501 break;
19502 }
19503 }
19504 let prev_len = text_without_backticks.len();
19505 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19506 text_without_backticks.push_str(new_text);
19507 if in_code_block {
19508 code_ranges.push(prev_len..text_without_backticks.len());
19509 }
19510 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19511 in_code_block = !in_code_block;
19512 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19513 text_without_backticks.push_str("...");
19514 break;
19515 }
19516 }
19517
19518 (text_without_backticks.into(), code_ranges)
19519}
19520
19521fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19522 match severity {
19523 DiagnosticSeverity::ERROR => colors.error,
19524 DiagnosticSeverity::WARNING => colors.warning,
19525 DiagnosticSeverity::INFORMATION => colors.info,
19526 DiagnosticSeverity::HINT => colors.info,
19527 _ => colors.ignored,
19528 }
19529}
19530
19531pub fn styled_runs_for_code_label<'a>(
19532 label: &'a CodeLabel,
19533 syntax_theme: &'a theme::SyntaxTheme,
19534) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19535 let fade_out = HighlightStyle {
19536 fade_out: Some(0.35),
19537 ..Default::default()
19538 };
19539
19540 let mut prev_end = label.filter_range.end;
19541 label
19542 .runs
19543 .iter()
19544 .enumerate()
19545 .flat_map(move |(ix, (range, highlight_id))| {
19546 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19547 style
19548 } else {
19549 return Default::default();
19550 };
19551 let mut muted_style = style;
19552 muted_style.highlight(fade_out);
19553
19554 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19555 if range.start >= label.filter_range.end {
19556 if range.start > prev_end {
19557 runs.push((prev_end..range.start, fade_out));
19558 }
19559 runs.push((range.clone(), muted_style));
19560 } else if range.end <= label.filter_range.end {
19561 runs.push((range.clone(), style));
19562 } else {
19563 runs.push((range.start..label.filter_range.end, style));
19564 runs.push((label.filter_range.end..range.end, muted_style));
19565 }
19566 prev_end = cmp::max(prev_end, range.end);
19567
19568 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19569 runs.push((prev_end..label.text.len(), fade_out));
19570 }
19571
19572 runs
19573 })
19574}
19575
19576pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19577 let mut prev_index = 0;
19578 let mut prev_codepoint: Option<char> = None;
19579 text.char_indices()
19580 .chain([(text.len(), '\0')])
19581 .filter_map(move |(index, codepoint)| {
19582 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19583 let is_boundary = index == text.len()
19584 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19585 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19586 if is_boundary {
19587 let chunk = &text[prev_index..index];
19588 prev_index = index;
19589 Some(chunk)
19590 } else {
19591 None
19592 }
19593 })
19594}
19595
19596pub trait RangeToAnchorExt: Sized {
19597 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19598
19599 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19600 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19601 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19602 }
19603}
19604
19605impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19606 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19607 let start_offset = self.start.to_offset(snapshot);
19608 let end_offset = self.end.to_offset(snapshot);
19609 if start_offset == end_offset {
19610 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19611 } else {
19612 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19613 }
19614 }
19615}
19616
19617pub trait RowExt {
19618 fn as_f32(&self) -> f32;
19619
19620 fn next_row(&self) -> Self;
19621
19622 fn previous_row(&self) -> Self;
19623
19624 fn minus(&self, other: Self) -> u32;
19625}
19626
19627impl RowExt for DisplayRow {
19628 fn as_f32(&self) -> f32 {
19629 self.0 as f32
19630 }
19631
19632 fn next_row(&self) -> Self {
19633 Self(self.0 + 1)
19634 }
19635
19636 fn previous_row(&self) -> Self {
19637 Self(self.0.saturating_sub(1))
19638 }
19639
19640 fn minus(&self, other: Self) -> u32 {
19641 self.0 - other.0
19642 }
19643}
19644
19645impl RowExt for MultiBufferRow {
19646 fn as_f32(&self) -> f32 {
19647 self.0 as f32
19648 }
19649
19650 fn next_row(&self) -> Self {
19651 Self(self.0 + 1)
19652 }
19653
19654 fn previous_row(&self) -> Self {
19655 Self(self.0.saturating_sub(1))
19656 }
19657
19658 fn minus(&self, other: Self) -> u32 {
19659 self.0 - other.0
19660 }
19661}
19662
19663trait RowRangeExt {
19664 type Row;
19665
19666 fn len(&self) -> usize;
19667
19668 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19669}
19670
19671impl RowRangeExt for Range<MultiBufferRow> {
19672 type Row = MultiBufferRow;
19673
19674 fn len(&self) -> usize {
19675 (self.end.0 - self.start.0) as usize
19676 }
19677
19678 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19679 (self.start.0..self.end.0).map(MultiBufferRow)
19680 }
19681}
19682
19683impl RowRangeExt for Range<DisplayRow> {
19684 type Row = DisplayRow;
19685
19686 fn len(&self) -> usize {
19687 (self.end.0 - self.start.0) as usize
19688 }
19689
19690 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19691 (self.start.0..self.end.0).map(DisplayRow)
19692 }
19693}
19694
19695/// If select range has more than one line, we
19696/// just point the cursor to range.start.
19697fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19698 if range.start.row == range.end.row {
19699 range
19700 } else {
19701 range.start..range.start
19702 }
19703}
19704pub struct KillRing(ClipboardItem);
19705impl Global for KillRing {}
19706
19707const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19708
19709struct BreakpointPromptEditor {
19710 pub(crate) prompt: Entity<Editor>,
19711 editor: WeakEntity<Editor>,
19712 breakpoint_anchor: Anchor,
19713 breakpoint: Breakpoint,
19714 block_ids: HashSet<CustomBlockId>,
19715 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19716 _subscriptions: Vec<Subscription>,
19717}
19718
19719impl BreakpointPromptEditor {
19720 const MAX_LINES: u8 = 4;
19721
19722 fn new(
19723 editor: WeakEntity<Editor>,
19724 breakpoint_anchor: Anchor,
19725 breakpoint: Breakpoint,
19726 window: &mut Window,
19727 cx: &mut Context<Self>,
19728 ) -> Self {
19729 let buffer = cx.new(|cx| {
19730 Buffer::local(
19731 breakpoint
19732 .kind
19733 .log_message()
19734 .map(|msg| msg.to_string())
19735 .unwrap_or_default(),
19736 cx,
19737 )
19738 });
19739 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19740
19741 let prompt = cx.new(|cx| {
19742 let mut prompt = Editor::new(
19743 EditorMode::AutoHeight {
19744 max_lines: Self::MAX_LINES as usize,
19745 },
19746 buffer,
19747 None,
19748 window,
19749 cx,
19750 );
19751 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19752 prompt.set_show_cursor_when_unfocused(false, cx);
19753 prompt.set_placeholder_text(
19754 "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19755 cx,
19756 );
19757
19758 prompt
19759 });
19760
19761 Self {
19762 prompt,
19763 editor,
19764 breakpoint_anchor,
19765 breakpoint,
19766 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19767 block_ids: Default::default(),
19768 _subscriptions: vec![],
19769 }
19770 }
19771
19772 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19773 self.block_ids.extend(block_ids)
19774 }
19775
19776 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19777 if let Some(editor) = self.editor.upgrade() {
19778 let log_message = self
19779 .prompt
19780 .read(cx)
19781 .buffer
19782 .read(cx)
19783 .as_singleton()
19784 .expect("A multi buffer in breakpoint prompt isn't possible")
19785 .read(cx)
19786 .as_rope()
19787 .to_string();
19788
19789 editor.update(cx, |editor, cx| {
19790 editor.edit_breakpoint_at_anchor(
19791 self.breakpoint_anchor,
19792 self.breakpoint.clone(),
19793 BreakpointEditAction::EditLogMessage(log_message.into()),
19794 cx,
19795 );
19796
19797 editor.remove_blocks(self.block_ids.clone(), None, cx);
19798 cx.focus_self(window);
19799 });
19800 }
19801 }
19802
19803 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19804 self.editor
19805 .update(cx, |editor, cx| {
19806 editor.remove_blocks(self.block_ids.clone(), None, cx);
19807 window.focus(&editor.focus_handle);
19808 })
19809 .log_err();
19810 }
19811
19812 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19813 let settings = ThemeSettings::get_global(cx);
19814 let text_style = TextStyle {
19815 color: if self.prompt.read(cx).read_only(cx) {
19816 cx.theme().colors().text_disabled
19817 } else {
19818 cx.theme().colors().text
19819 },
19820 font_family: settings.buffer_font.family.clone(),
19821 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19822 font_size: settings.buffer_font_size(cx).into(),
19823 font_weight: settings.buffer_font.weight,
19824 line_height: relative(settings.buffer_line_height.value()),
19825 ..Default::default()
19826 };
19827 EditorElement::new(
19828 &self.prompt,
19829 EditorStyle {
19830 background: cx.theme().colors().editor_background,
19831 local_player: cx.theme().players().local(),
19832 text: text_style,
19833 ..Default::default()
19834 },
19835 )
19836 }
19837}
19838
19839impl Render for BreakpointPromptEditor {
19840 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19841 let gutter_dimensions = *self.gutter_dimensions.lock();
19842 h_flex()
19843 .key_context("Editor")
19844 .bg(cx.theme().colors().editor_background)
19845 .border_y_1()
19846 .border_color(cx.theme().status().info_border)
19847 .size_full()
19848 .py(window.line_height() / 2.5)
19849 .on_action(cx.listener(Self::confirm))
19850 .on_action(cx.listener(Self::cancel))
19851 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19852 .child(div().flex_1().child(self.render_prompt_editor(cx)))
19853 }
19854}
19855
19856impl Focusable for BreakpointPromptEditor {
19857 fn focus_handle(&self, cx: &App) -> FocusHandle {
19858 self.prompt.focus_handle(cx)
19859 }
19860}
19861
19862fn all_edits_insertions_or_deletions(
19863 edits: &Vec<(Range<Anchor>, String)>,
19864 snapshot: &MultiBufferSnapshot,
19865) -> bool {
19866 let mut all_insertions = true;
19867 let mut all_deletions = true;
19868
19869 for (range, new_text) in edits.iter() {
19870 let range_is_empty = range.to_offset(&snapshot).is_empty();
19871 let text_is_empty = new_text.is_empty();
19872
19873 if range_is_empty != text_is_empty {
19874 if range_is_empty {
19875 all_deletions = false;
19876 } else {
19877 all_insertions = false;
19878 }
19879 } else {
19880 return false;
19881 }
19882
19883 if !all_insertions && !all_deletions {
19884 return false;
19885 }
19886 }
19887 all_insertions || all_deletions
19888}
19889
19890struct MissingEditPredictionKeybindingTooltip;
19891
19892impl Render for MissingEditPredictionKeybindingTooltip {
19893 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19894 ui::tooltip_container(window, cx, |container, _, cx| {
19895 container
19896 .flex_shrink_0()
19897 .max_w_80()
19898 .min_h(rems_from_px(124.))
19899 .justify_between()
19900 .child(
19901 v_flex()
19902 .flex_1()
19903 .text_ui_sm(cx)
19904 .child(Label::new("Conflict with Accept Keybinding"))
19905 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19906 )
19907 .child(
19908 h_flex()
19909 .pb_1()
19910 .gap_1()
19911 .items_end()
19912 .w_full()
19913 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19914 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19915 }))
19916 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19917 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19918 })),
19919 )
19920 })
19921 }
19922}
19923
19924#[derive(Debug, Clone, Copy, PartialEq)]
19925pub struct LineHighlight {
19926 pub background: Background,
19927 pub border: Option<gpui::Hsla>,
19928}
19929
19930impl From<Hsla> for LineHighlight {
19931 fn from(hsla: Hsla) -> Self {
19932 Self {
19933 background: hsla.into(),
19934 border: None,
19935 }
19936 }
19937}
19938
19939impl From<Background> for LineHighlight {
19940 fn from(background: Background) -> Self {
19941 Self {
19942 background,
19943 border: None,
19944 }
19945 }
19946}
19947
19948fn render_diff_hunk_controls(
19949 row: u32,
19950 status: &DiffHunkStatus,
19951 hunk_range: Range<Anchor>,
19952 is_created_file: bool,
19953 line_height: Pixels,
19954 editor: &Entity<Editor>,
19955 cx: &mut App,
19956) -> AnyElement {
19957 h_flex()
19958 .h(line_height)
19959 .mr_1()
19960 .gap_1()
19961 .px_0p5()
19962 .pb_1()
19963 .border_x_1()
19964 .border_b_1()
19965 .border_color(cx.theme().colors().border_variant)
19966 .rounded_b_lg()
19967 .bg(cx.theme().colors().editor_background)
19968 .gap_1()
19969 .occlude()
19970 .shadow_md()
19971 .child(if status.has_secondary_hunk() {
19972 Button::new(("stage", row as u64), "Stage")
19973 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
19974 .tooltip({
19975 let focus_handle = editor.focus_handle(cx);
19976 move |window, cx| {
19977 Tooltip::for_action_in(
19978 "Stage Hunk",
19979 &::git::ToggleStaged,
19980 &focus_handle,
19981 window,
19982 cx,
19983 )
19984 }
19985 })
19986 .on_click({
19987 let editor = editor.clone();
19988 move |_event, _window, cx| {
19989 editor.update(cx, |editor, cx| {
19990 editor.stage_or_unstage_diff_hunks(
19991 true,
19992 vec![hunk_range.start..hunk_range.start],
19993 cx,
19994 );
19995 });
19996 }
19997 })
19998 } else {
19999 Button::new(("unstage", row as u64), "Unstage")
20000 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20001 .tooltip({
20002 let focus_handle = editor.focus_handle(cx);
20003 move |window, cx| {
20004 Tooltip::for_action_in(
20005 "Unstage Hunk",
20006 &::git::ToggleStaged,
20007 &focus_handle,
20008 window,
20009 cx,
20010 )
20011 }
20012 })
20013 .on_click({
20014 let editor = editor.clone();
20015 move |_event, _window, cx| {
20016 editor.update(cx, |editor, cx| {
20017 editor.stage_or_unstage_diff_hunks(
20018 false,
20019 vec![hunk_range.start..hunk_range.start],
20020 cx,
20021 );
20022 });
20023 }
20024 })
20025 })
20026 .child(
20027 Button::new("restore", "Restore")
20028 .tooltip({
20029 let focus_handle = editor.focus_handle(cx);
20030 move |window, cx| {
20031 Tooltip::for_action_in(
20032 "Restore Hunk",
20033 &::git::Restore,
20034 &focus_handle,
20035 window,
20036 cx,
20037 )
20038 }
20039 })
20040 .on_click({
20041 let editor = editor.clone();
20042 move |_event, window, cx| {
20043 editor.update(cx, |editor, cx| {
20044 let snapshot = editor.snapshot(window, cx);
20045 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20046 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20047 });
20048 }
20049 })
20050 .disabled(is_created_file),
20051 )
20052 .when(
20053 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20054 |el| {
20055 el.child(
20056 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20057 .shape(IconButtonShape::Square)
20058 .icon_size(IconSize::Small)
20059 // .disabled(!has_multiple_hunks)
20060 .tooltip({
20061 let focus_handle = editor.focus_handle(cx);
20062 move |window, cx| {
20063 Tooltip::for_action_in(
20064 "Next Hunk",
20065 &GoToHunk,
20066 &focus_handle,
20067 window,
20068 cx,
20069 )
20070 }
20071 })
20072 .on_click({
20073 let editor = editor.clone();
20074 move |_event, window, cx| {
20075 editor.update(cx, |editor, cx| {
20076 let snapshot = editor.snapshot(window, cx);
20077 let position =
20078 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20079 editor.go_to_hunk_before_or_after_position(
20080 &snapshot,
20081 position,
20082 Direction::Next,
20083 window,
20084 cx,
20085 );
20086 editor.expand_selected_diff_hunks(cx);
20087 });
20088 }
20089 }),
20090 )
20091 .child(
20092 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20093 .shape(IconButtonShape::Square)
20094 .icon_size(IconSize::Small)
20095 // .disabled(!has_multiple_hunks)
20096 .tooltip({
20097 let focus_handle = editor.focus_handle(cx);
20098 move |window, cx| {
20099 Tooltip::for_action_in(
20100 "Previous Hunk",
20101 &GoToPreviousHunk,
20102 &focus_handle,
20103 window,
20104 cx,
20105 )
20106 }
20107 })
20108 .on_click({
20109 let editor = editor.clone();
20110 move |_event, window, cx| {
20111 editor.update(cx, |editor, cx| {
20112 let snapshot = editor.snapshot(window, cx);
20113 let point =
20114 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20115 editor.go_to_hunk_before_or_after_position(
20116 &snapshot,
20117 point,
20118 Direction::Prev,
20119 window,
20120 cx,
20121 );
20122 editor.expand_selected_diff_hunks(cx);
20123 });
20124 }
20125 }),
20126 )
20127 },
20128 )
20129 .into_any_element()
20130}