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, IconName, IconSize, Key,
189 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
223const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
224 alt: true,
225 shift: true,
226 control: false,
227 platform: false,
228 function: false,
229};
230
231#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
232pub enum InlayId {
233 InlineCompletion(usize),
234 Hint(usize),
235}
236
237impl InlayId {
238 fn id(&self) -> usize {
239 match self {
240 Self::InlineCompletion(id) => *id,
241 Self::Hint(id) => *id,
242 }
243 }
244}
245
246pub enum DebugCurrentRowHighlight {}
247enum DocumentHighlightRead {}
248enum DocumentHighlightWrite {}
249enum InputComposition {}
250enum SelectedTextHighlight {}
251
252#[derive(Debug, Copy, Clone, PartialEq, Eq)]
253pub enum Navigated {
254 Yes,
255 No,
256}
257
258impl Navigated {
259 pub fn from_bool(yes: bool) -> Navigated {
260 if yes {
261 Navigated::Yes
262 } else {
263 Navigated::No
264 }
265 }
266}
267
268#[derive(Debug, Clone, PartialEq, Eq)]
269enum DisplayDiffHunk {
270 Folded {
271 display_row: DisplayRow,
272 },
273 Unfolded {
274 is_created_file: bool,
275 diff_base_byte_range: Range<usize>,
276 display_row_range: Range<DisplayRow>,
277 multi_buffer_range: Range<Anchor>,
278 status: DiffHunkStatus,
279 },
280}
281
282pub fn init_settings(cx: &mut App) {
283 EditorSettings::register(cx);
284}
285
286pub fn init(cx: &mut App) {
287 init_settings(cx);
288
289 workspace::register_project_item::<Editor>(cx);
290 workspace::FollowableViewRegistry::register::<Editor>(cx);
291 workspace::register_serializable_item::<Editor>(cx);
292
293 cx.observe_new(
294 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
295 workspace.register_action(Editor::new_file);
296 workspace.register_action(Editor::new_file_vertical);
297 workspace.register_action(Editor::new_file_horizontal);
298 workspace.register_action(Editor::cancel_language_server_work);
299 },
300 )
301 .detach();
302
303 cx.on_action(move |_: &workspace::NewFile, cx| {
304 let app_state = workspace::AppState::global(cx);
305 if let Some(app_state) = app_state.upgrade() {
306 workspace::open_new(
307 Default::default(),
308 app_state,
309 cx,
310 |workspace, window, cx| {
311 Editor::new_file(workspace, &Default::default(), window, cx)
312 },
313 )
314 .detach();
315 }
316 });
317 cx.on_action(move |_: &workspace::NewWindow, cx| {
318 let app_state = workspace::AppState::global(cx);
319 if let Some(app_state) = app_state.upgrade() {
320 workspace::open_new(
321 Default::default(),
322 app_state,
323 cx,
324 |workspace, window, cx| {
325 cx.activate(true);
326 Editor::new_file(workspace, &Default::default(), window, cx)
327 },
328 )
329 .detach();
330 }
331 });
332}
333
334pub struct SearchWithinRange;
335
336trait InvalidationRegion {
337 fn ranges(&self) -> &[Range<Anchor>];
338}
339
340#[derive(Clone, Debug, PartialEq)]
341pub enum SelectPhase {
342 Begin {
343 position: DisplayPoint,
344 add: bool,
345 click_count: usize,
346 },
347 BeginColumnar {
348 position: DisplayPoint,
349 reset: bool,
350 goal_column: u32,
351 },
352 Extend {
353 position: DisplayPoint,
354 click_count: usize,
355 },
356 Update {
357 position: DisplayPoint,
358 goal_column: u32,
359 scroll_delta: gpui::Point<f32>,
360 },
361 End,
362}
363
364#[derive(Clone, Debug)]
365pub enum SelectMode {
366 Character,
367 Word(Range<Anchor>),
368 Line(Range<Anchor>),
369 All,
370}
371
372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
373pub enum EditorMode {
374 SingleLine { auto_width: bool },
375 AutoHeight { max_lines: usize },
376 Full,
377}
378
379#[derive(Copy, Clone, Debug)]
380pub enum SoftWrap {
381 /// Prefer not to wrap at all.
382 ///
383 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
384 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
385 GitDiff,
386 /// Prefer a single line generally, unless an overly long line is encountered.
387 None,
388 /// Soft wrap lines that exceed the editor width.
389 EditorWidth,
390 /// Soft wrap lines at the preferred line length.
391 Column(u32),
392 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
393 Bounded(u32),
394}
395
396#[derive(Clone)]
397pub struct EditorStyle {
398 pub background: Hsla,
399 pub local_player: PlayerColor,
400 pub text: TextStyle,
401 pub scrollbar_width: Pixels,
402 pub syntax: Arc<SyntaxTheme>,
403 pub status: StatusColors,
404 pub inlay_hints_style: HighlightStyle,
405 pub inline_completion_styles: InlineCompletionStyles,
406 pub unnecessary_code_fade: f32,
407}
408
409impl Default for EditorStyle {
410 fn default() -> Self {
411 Self {
412 background: Hsla::default(),
413 local_player: PlayerColor::default(),
414 text: TextStyle::default(),
415 scrollbar_width: Pixels::default(),
416 syntax: Default::default(),
417 // HACK: Status colors don't have a real default.
418 // We should look into removing the status colors from the editor
419 // style and retrieve them directly from the theme.
420 status: StatusColors::dark(),
421 inlay_hints_style: HighlightStyle::default(),
422 inline_completion_styles: InlineCompletionStyles {
423 insertion: HighlightStyle::default(),
424 whitespace: HighlightStyle::default(),
425 },
426 unnecessary_code_fade: Default::default(),
427 }
428 }
429}
430
431pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
432 let show_background = language_settings::language_settings(None, None, cx)
433 .inlay_hints
434 .show_background;
435
436 HighlightStyle {
437 color: Some(cx.theme().status().hint),
438 background_color: show_background.then(|| cx.theme().status().hint_background),
439 ..HighlightStyle::default()
440 }
441}
442
443pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
444 InlineCompletionStyles {
445 insertion: HighlightStyle {
446 color: Some(cx.theme().status().predictive),
447 ..HighlightStyle::default()
448 },
449 whitespace: HighlightStyle {
450 background_color: Some(cx.theme().status().created_background),
451 ..HighlightStyle::default()
452 },
453 }
454}
455
456type CompletionId = usize;
457
458pub(crate) enum EditDisplayMode {
459 TabAccept,
460 DiffPopover,
461 Inline,
462}
463
464enum InlineCompletion {
465 Edit {
466 edits: Vec<(Range<Anchor>, String)>,
467 edit_preview: Option<EditPreview>,
468 display_mode: EditDisplayMode,
469 snapshot: BufferSnapshot,
470 },
471 Move {
472 target: Anchor,
473 snapshot: BufferSnapshot,
474 },
475}
476
477struct InlineCompletionState {
478 inlay_ids: Vec<InlayId>,
479 completion: InlineCompletion,
480 completion_id: Option<SharedString>,
481 invalidation_range: Range<Anchor>,
482}
483
484enum EditPredictionSettings {
485 Disabled,
486 Enabled {
487 show_in_menu: bool,
488 preview_requires_modifier: bool,
489 },
490}
491
492enum InlineCompletionHighlight {}
493
494#[derive(Debug, Clone)]
495struct InlineDiagnostic {
496 message: SharedString,
497 group_id: usize,
498 is_primary: bool,
499 start: Point,
500 severity: DiagnosticSeverity,
501}
502
503pub enum MenuInlineCompletionsPolicy {
504 Never,
505 ByProvider,
506}
507
508pub enum EditPredictionPreview {
509 /// Modifier is not pressed
510 Inactive { released_too_fast: bool },
511 /// Modifier pressed
512 Active {
513 since: Instant,
514 previous_scroll_position: Option<ScrollAnchor>,
515 },
516}
517
518impl EditPredictionPreview {
519 pub fn released_too_fast(&self) -> bool {
520 match self {
521 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
522 EditPredictionPreview::Active { .. } => false,
523 }
524 }
525
526 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
527 if let EditPredictionPreview::Active {
528 previous_scroll_position,
529 ..
530 } = self
531 {
532 *previous_scroll_position = scroll_position;
533 }
534 }
535}
536
537pub struct ContextMenuOptions {
538 pub min_entries_visible: usize,
539 pub max_entries_visible: usize,
540 pub placement: Option<ContextMenuPlacement>,
541}
542
543#[derive(Debug, Clone, PartialEq, Eq)]
544pub enum ContextMenuPlacement {
545 Above,
546 Below,
547}
548
549#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
550struct EditorActionId(usize);
551
552impl EditorActionId {
553 pub fn post_inc(&mut self) -> Self {
554 let answer = self.0;
555
556 *self = Self(answer + 1);
557
558 Self(answer)
559 }
560}
561
562// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
563// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
564
565type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
566type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
567
568#[derive(Default)]
569struct ScrollbarMarkerState {
570 scrollbar_size: Size<Pixels>,
571 dirty: bool,
572 markers: Arc<[PaintQuad]>,
573 pending_refresh: Option<Task<Result<()>>>,
574}
575
576impl ScrollbarMarkerState {
577 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
578 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
579 }
580}
581
582#[derive(Clone, Debug)]
583struct RunnableTasks {
584 templates: Vec<(TaskSourceKind, TaskTemplate)>,
585 offset: multi_buffer::Anchor,
586 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
587 column: u32,
588 // Values of all named captures, including those starting with '_'
589 extra_variables: HashMap<String, String>,
590 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
591 context_range: Range<BufferOffset>,
592}
593
594impl RunnableTasks {
595 fn resolve<'a>(
596 &'a self,
597 cx: &'a task::TaskContext,
598 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
599 self.templates.iter().filter_map(|(kind, template)| {
600 template
601 .resolve_task(&kind.to_id_base(), cx)
602 .map(|task| (kind.clone(), task))
603 })
604 }
605}
606
607#[derive(Clone)]
608struct ResolvedTasks {
609 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
610 position: Anchor,
611}
612
613#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
614struct BufferOffset(usize);
615
616// Addons allow storing per-editor state in other crates (e.g. Vim)
617pub trait Addon: 'static {
618 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
619
620 fn render_buffer_header_controls(
621 &self,
622 _: &ExcerptInfo,
623 _: &Window,
624 _: &App,
625 ) -> Option<AnyElement> {
626 None
627 }
628
629 fn to_any(&self) -> &dyn std::any::Any;
630}
631
632/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
633///
634/// See the [module level documentation](self) for more information.
635pub struct Editor {
636 focus_handle: FocusHandle,
637 last_focused_descendant: Option<WeakFocusHandle>,
638 /// The text buffer being edited
639 buffer: Entity<MultiBuffer>,
640 /// Map of how text in the buffer should be displayed.
641 /// Handles soft wraps, folds, fake inlay text insertions, etc.
642 pub display_map: Entity<DisplayMap>,
643 pub selections: SelectionsCollection,
644 pub scroll_manager: ScrollManager,
645 /// When inline assist editors are linked, they all render cursors because
646 /// typing enters text into each of them, even the ones that aren't focused.
647 pub(crate) show_cursor_when_unfocused: bool,
648 columnar_selection_tail: Option<Anchor>,
649 add_selections_state: Option<AddSelectionsState>,
650 select_next_state: Option<SelectNextState>,
651 select_prev_state: Option<SelectNextState>,
652 selection_history: SelectionHistory,
653 autoclose_regions: Vec<AutocloseRegion>,
654 snippet_stack: InvalidationStack<SnippetState>,
655 select_syntax_node_history: SelectSyntaxNodeHistory,
656 ime_transaction: Option<TransactionId>,
657 active_diagnostics: Option<ActiveDiagnosticGroup>,
658 show_inline_diagnostics: bool,
659 inline_diagnostics_update: Task<()>,
660 inline_diagnostics_enabled: bool,
661 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
662 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
663 hard_wrap: Option<usize>,
664
665 // TODO: make this a access method
666 pub project: Option<Entity<Project>>,
667 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
668 completion_provider: Option<Box<dyn CompletionProvider>>,
669 collaboration_hub: Option<Box<dyn CollaborationHub>>,
670 blink_manager: Entity<BlinkManager>,
671 show_cursor_names: bool,
672 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
673 pub show_local_selections: bool,
674 mode: EditorMode,
675 show_breadcrumbs: bool,
676 show_gutter: bool,
677 show_scrollbars: bool,
678 show_line_numbers: Option<bool>,
679 use_relative_line_numbers: Option<bool>,
680 show_git_diff_gutter: Option<bool>,
681 show_code_actions: Option<bool>,
682 show_runnables: Option<bool>,
683 show_breakpoints: Option<bool>,
684 show_wrap_guides: Option<bool>,
685 show_indent_guides: Option<bool>,
686 placeholder_text: Option<Arc<str>>,
687 highlight_order: usize,
688 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
689 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
690 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
691 scrollbar_marker_state: ScrollbarMarkerState,
692 active_indent_guides_state: ActiveIndentGuidesState,
693 nav_history: Option<ItemNavHistory>,
694 context_menu: RefCell<Option<CodeContextMenu>>,
695 context_menu_options: Option<ContextMenuOptions>,
696 mouse_context_menu: Option<MouseContextMenu>,
697 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
698 signature_help_state: SignatureHelpState,
699 auto_signature_help: Option<bool>,
700 find_all_references_task_sources: Vec<Anchor>,
701 next_completion_id: CompletionId,
702 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
703 code_actions_task: Option<Task<Result<()>>>,
704 selection_highlight_task: Option<Task<()>>,
705 document_highlights_task: Option<Task<()>>,
706 linked_editing_range_task: Option<Task<Option<()>>>,
707 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
708 pending_rename: Option<RenameState>,
709 searchable: bool,
710 cursor_shape: CursorShape,
711 current_line_highlight: Option<CurrentLineHighlight>,
712 collapse_matches: bool,
713 autoindent_mode: Option<AutoindentMode>,
714 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
715 input_enabled: bool,
716 use_modal_editing: bool,
717 read_only: bool,
718 leader_peer_id: Option<PeerId>,
719 remote_id: Option<ViewId>,
720 hover_state: HoverState,
721 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
722 gutter_hovered: bool,
723 hovered_link_state: Option<HoveredLinkState>,
724 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
725 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
726 active_inline_completion: Option<InlineCompletionState>,
727 /// Used to prevent flickering as the user types while the menu is open
728 stale_inline_completion_in_menu: Option<InlineCompletionState>,
729 edit_prediction_settings: EditPredictionSettings,
730 inline_completions_hidden_for_vim_mode: bool,
731 show_inline_completions_override: Option<bool>,
732 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
733 edit_prediction_preview: EditPredictionPreview,
734 edit_prediction_indent_conflict: bool,
735 edit_prediction_requires_modifier_in_indent_conflict: bool,
736 inlay_hint_cache: InlayHintCache,
737 next_inlay_id: usize,
738 _subscriptions: Vec<Subscription>,
739 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
740 gutter_dimensions: GutterDimensions,
741 style: Option<EditorStyle>,
742 text_style_refinement: Option<TextStyleRefinement>,
743 next_editor_action_id: EditorActionId,
744 editor_actions:
745 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
746 use_autoclose: bool,
747 use_auto_surround: bool,
748 auto_replace_emoji_shortcode: bool,
749 jsx_tag_auto_close_enabled_in_any_buffer: bool,
750 show_git_blame_gutter: bool,
751 show_git_blame_inline: bool,
752 show_git_blame_inline_delay_task: Option<Task<()>>,
753 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
754 git_blame_inline_enabled: bool,
755 serialize_dirty_buffers: bool,
756 show_selection_menu: Option<bool>,
757 blame: Option<Entity<GitBlame>>,
758 blame_subscription: Option<Subscription>,
759 custom_context_menu: Option<
760 Box<
761 dyn 'static
762 + Fn(
763 &mut Self,
764 DisplayPoint,
765 &mut Window,
766 &mut Context<Self>,
767 ) -> Option<Entity<ui::ContextMenu>>,
768 >,
769 >,
770 last_bounds: Option<Bounds<Pixels>>,
771 last_position_map: Option<Rc<PositionMap>>,
772 expect_bounds_change: Option<Bounds<Pixels>>,
773 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
774 tasks_update_task: Option<Task<()>>,
775 pub breakpoint_store: Option<Entity<BreakpointStore>>,
776 /// Allow's a user to create a breakpoint by selecting this indicator
777 /// It should be None while a user is not hovering over the gutter
778 /// Otherwise it represents the point that the breakpoint will be shown
779 pub gutter_breakpoint_indicator: Option<DisplayPoint>,
780 in_project_search: bool,
781 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
782 breadcrumb_header: Option<String>,
783 focused_block: Option<FocusedBlock>,
784 next_scroll_position: NextScrollCursorCenterTopBottom,
785 addons: HashMap<TypeId, Box<dyn Addon>>,
786 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
787 load_diff_task: Option<Shared<Task<()>>>,
788 selection_mark_mode: bool,
789 toggle_fold_multiple_buffers: Task<()>,
790 _scroll_cursor_center_top_bottom_task: Task<()>,
791 serialize_selections: Task<()>,
792 serialize_folds: Task<()>,
793 mouse_cursor_hidden: bool,
794 hide_mouse_while_typing: bool,
795}
796
797#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
798enum NextScrollCursorCenterTopBottom {
799 #[default]
800 Center,
801 Top,
802 Bottom,
803}
804
805impl NextScrollCursorCenterTopBottom {
806 fn next(&self) -> Self {
807 match self {
808 Self::Center => Self::Top,
809 Self::Top => Self::Bottom,
810 Self::Bottom => Self::Center,
811 }
812 }
813}
814
815#[derive(Clone)]
816pub struct EditorSnapshot {
817 pub mode: EditorMode,
818 show_gutter: bool,
819 show_line_numbers: Option<bool>,
820 show_git_diff_gutter: Option<bool>,
821 show_code_actions: Option<bool>,
822 show_runnables: Option<bool>,
823 show_breakpoints: Option<bool>,
824 git_blame_gutter_max_author_length: Option<usize>,
825 pub display_snapshot: DisplaySnapshot,
826 pub placeholder_text: Option<Arc<str>>,
827 is_focused: bool,
828 scroll_anchor: ScrollAnchor,
829 ongoing_scroll: OngoingScroll,
830 current_line_highlight: CurrentLineHighlight,
831 gutter_hovered: bool,
832}
833
834const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
835
836#[derive(Default, Debug, Clone, Copy)]
837pub struct GutterDimensions {
838 pub left_padding: Pixels,
839 pub right_padding: Pixels,
840 pub width: Pixels,
841 pub margin: Pixels,
842 pub git_blame_entries_width: Option<Pixels>,
843}
844
845impl GutterDimensions {
846 /// The full width of the space taken up by the gutter.
847 pub fn full_width(&self) -> Pixels {
848 self.margin + self.width
849 }
850
851 /// The width of the space reserved for the fold indicators,
852 /// use alongside 'justify_end' and `gutter_width` to
853 /// right align content with the line numbers
854 pub fn fold_area_width(&self) -> Pixels {
855 self.margin + self.right_padding
856 }
857}
858
859#[derive(Debug)]
860pub struct RemoteSelection {
861 pub replica_id: ReplicaId,
862 pub selection: Selection<Anchor>,
863 pub cursor_shape: CursorShape,
864 pub peer_id: PeerId,
865 pub line_mode: bool,
866 pub participant_index: Option<ParticipantIndex>,
867 pub user_name: Option<SharedString>,
868}
869
870#[derive(Clone, Debug)]
871struct SelectionHistoryEntry {
872 selections: Arc<[Selection<Anchor>]>,
873 select_next_state: Option<SelectNextState>,
874 select_prev_state: Option<SelectNextState>,
875 add_selections_state: Option<AddSelectionsState>,
876}
877
878enum SelectionHistoryMode {
879 Normal,
880 Undoing,
881 Redoing,
882}
883
884#[derive(Clone, PartialEq, Eq, Hash)]
885struct HoveredCursor {
886 replica_id: u16,
887 selection_id: usize,
888}
889
890impl Default for SelectionHistoryMode {
891 fn default() -> Self {
892 Self::Normal
893 }
894}
895
896#[derive(Default)]
897struct SelectionHistory {
898 #[allow(clippy::type_complexity)]
899 selections_by_transaction:
900 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
901 mode: SelectionHistoryMode,
902 undo_stack: VecDeque<SelectionHistoryEntry>,
903 redo_stack: VecDeque<SelectionHistoryEntry>,
904}
905
906impl SelectionHistory {
907 fn insert_transaction(
908 &mut self,
909 transaction_id: TransactionId,
910 selections: Arc<[Selection<Anchor>]>,
911 ) {
912 self.selections_by_transaction
913 .insert(transaction_id, (selections, None));
914 }
915
916 #[allow(clippy::type_complexity)]
917 fn transaction(
918 &self,
919 transaction_id: TransactionId,
920 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
921 self.selections_by_transaction.get(&transaction_id)
922 }
923
924 #[allow(clippy::type_complexity)]
925 fn transaction_mut(
926 &mut self,
927 transaction_id: TransactionId,
928 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
929 self.selections_by_transaction.get_mut(&transaction_id)
930 }
931
932 fn push(&mut self, entry: SelectionHistoryEntry) {
933 if !entry.selections.is_empty() {
934 match self.mode {
935 SelectionHistoryMode::Normal => {
936 self.push_undo(entry);
937 self.redo_stack.clear();
938 }
939 SelectionHistoryMode::Undoing => self.push_redo(entry),
940 SelectionHistoryMode::Redoing => self.push_undo(entry),
941 }
942 }
943 }
944
945 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
946 if self
947 .undo_stack
948 .back()
949 .map_or(true, |e| e.selections != entry.selections)
950 {
951 self.undo_stack.push_back(entry);
952 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
953 self.undo_stack.pop_front();
954 }
955 }
956 }
957
958 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
959 if self
960 .redo_stack
961 .back()
962 .map_or(true, |e| e.selections != entry.selections)
963 {
964 self.redo_stack.push_back(entry);
965 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
966 self.redo_stack.pop_front();
967 }
968 }
969 }
970}
971
972struct RowHighlight {
973 index: usize,
974 range: Range<Anchor>,
975 color: Hsla,
976 should_autoscroll: bool,
977}
978
979#[derive(Clone, Debug)]
980struct AddSelectionsState {
981 above: bool,
982 stack: Vec<usize>,
983}
984
985#[derive(Clone)]
986struct SelectNextState {
987 query: AhoCorasick,
988 wordwise: bool,
989 done: bool,
990}
991
992impl std::fmt::Debug for SelectNextState {
993 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
994 f.debug_struct(std::any::type_name::<Self>())
995 .field("wordwise", &self.wordwise)
996 .field("done", &self.done)
997 .finish()
998 }
999}
1000
1001#[derive(Debug)]
1002struct AutocloseRegion {
1003 selection_id: usize,
1004 range: Range<Anchor>,
1005 pair: BracketPair,
1006}
1007
1008#[derive(Debug)]
1009struct SnippetState {
1010 ranges: Vec<Vec<Range<Anchor>>>,
1011 active_index: usize,
1012 choices: Vec<Option<Vec<String>>>,
1013}
1014
1015#[doc(hidden)]
1016pub struct RenameState {
1017 pub range: Range<Anchor>,
1018 pub old_name: Arc<str>,
1019 pub editor: Entity<Editor>,
1020 block_id: CustomBlockId,
1021}
1022
1023struct InvalidationStack<T>(Vec<T>);
1024
1025struct RegisteredInlineCompletionProvider {
1026 provider: Arc<dyn InlineCompletionProviderHandle>,
1027 _subscription: Subscription,
1028}
1029
1030#[derive(Debug, PartialEq, Eq)]
1031struct ActiveDiagnosticGroup {
1032 primary_range: Range<Anchor>,
1033 primary_message: String,
1034 group_id: usize,
1035 blocks: HashMap<CustomBlockId, Diagnostic>,
1036 is_valid: bool,
1037}
1038
1039#[derive(Serialize, Deserialize, Clone, Debug)]
1040pub struct ClipboardSelection {
1041 /// The number of bytes in this selection.
1042 pub len: usize,
1043 /// Whether this was a full-line selection.
1044 pub is_entire_line: bool,
1045 /// The indentation of the first line when this content was originally copied.
1046 pub first_line_indent: u32,
1047}
1048
1049// selections, scroll behavior, was newest selection reversed
1050type SelectSyntaxNodeHistoryState = (
1051 Box<[Selection<usize>]>,
1052 SelectSyntaxNodeScrollBehavior,
1053 bool,
1054);
1055
1056#[derive(Default)]
1057struct SelectSyntaxNodeHistory {
1058 stack: Vec<SelectSyntaxNodeHistoryState>,
1059 // disable temporarily to allow changing selections without losing the stack
1060 pub disable_clearing: bool,
1061}
1062
1063impl SelectSyntaxNodeHistory {
1064 pub fn try_clear(&mut self) {
1065 if !self.disable_clearing {
1066 self.stack.clear();
1067 }
1068 }
1069
1070 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1071 self.stack.push(selection);
1072 }
1073
1074 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1075 self.stack.pop()
1076 }
1077}
1078
1079enum SelectSyntaxNodeScrollBehavior {
1080 CursorTop,
1081 CenterSelection,
1082 CursorBottom,
1083}
1084
1085#[derive(Debug)]
1086pub(crate) struct NavigationData {
1087 cursor_anchor: Anchor,
1088 cursor_position: Point,
1089 scroll_anchor: ScrollAnchor,
1090 scroll_top_row: u32,
1091}
1092
1093#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1094pub enum GotoDefinitionKind {
1095 Symbol,
1096 Declaration,
1097 Type,
1098 Implementation,
1099}
1100
1101#[derive(Debug, Clone)]
1102enum InlayHintRefreshReason {
1103 ModifiersChanged(bool),
1104 Toggle(bool),
1105 SettingsChange(InlayHintSettings),
1106 NewLinesShown,
1107 BufferEdited(HashSet<Arc<Language>>),
1108 RefreshRequested,
1109 ExcerptsRemoved(Vec<ExcerptId>),
1110}
1111
1112impl InlayHintRefreshReason {
1113 fn description(&self) -> &'static str {
1114 match self {
1115 Self::ModifiersChanged(_) => "modifiers changed",
1116 Self::Toggle(_) => "toggle",
1117 Self::SettingsChange(_) => "settings change",
1118 Self::NewLinesShown => "new lines shown",
1119 Self::BufferEdited(_) => "buffer edited",
1120 Self::RefreshRequested => "refresh requested",
1121 Self::ExcerptsRemoved(_) => "excerpts removed",
1122 }
1123 }
1124}
1125
1126pub enum FormatTarget {
1127 Buffers,
1128 Ranges(Vec<Range<MultiBufferPoint>>),
1129}
1130
1131pub(crate) struct FocusedBlock {
1132 id: BlockId,
1133 focus_handle: WeakFocusHandle,
1134}
1135
1136#[derive(Clone)]
1137enum JumpData {
1138 MultiBufferRow {
1139 row: MultiBufferRow,
1140 line_offset_from_top: u32,
1141 },
1142 MultiBufferPoint {
1143 excerpt_id: ExcerptId,
1144 position: Point,
1145 anchor: text::Anchor,
1146 line_offset_from_top: u32,
1147 },
1148}
1149
1150pub enum MultibufferSelectionMode {
1151 First,
1152 All,
1153}
1154
1155#[derive(Clone, Copy, Debug, Default)]
1156pub struct RewrapOptions {
1157 pub override_language_settings: bool,
1158 pub preserve_existing_whitespace: bool,
1159}
1160
1161impl Editor {
1162 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1163 let buffer = cx.new(|cx| Buffer::local("", cx));
1164 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1165 Self::new(
1166 EditorMode::SingleLine { auto_width: false },
1167 buffer,
1168 None,
1169 window,
1170 cx,
1171 )
1172 }
1173
1174 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1175 let buffer = cx.new(|cx| Buffer::local("", cx));
1176 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1177 Self::new(EditorMode::Full, buffer, None, window, cx)
1178 }
1179
1180 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1181 let buffer = cx.new(|cx| Buffer::local("", cx));
1182 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1183 Self::new(
1184 EditorMode::SingleLine { auto_width: true },
1185 buffer,
1186 None,
1187 window,
1188 cx,
1189 )
1190 }
1191
1192 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1193 let buffer = cx.new(|cx| Buffer::local("", cx));
1194 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1195 Self::new(
1196 EditorMode::AutoHeight { max_lines },
1197 buffer,
1198 None,
1199 window,
1200 cx,
1201 )
1202 }
1203
1204 pub fn for_buffer(
1205 buffer: Entity<Buffer>,
1206 project: Option<Entity<Project>>,
1207 window: &mut Window,
1208 cx: &mut Context<Self>,
1209 ) -> Self {
1210 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1211 Self::new(EditorMode::Full, buffer, project, window, cx)
1212 }
1213
1214 pub fn for_multibuffer(
1215 buffer: Entity<MultiBuffer>,
1216 project: Option<Entity<Project>>,
1217 window: &mut Window,
1218 cx: &mut Context<Self>,
1219 ) -> Self {
1220 Self::new(EditorMode::Full, buffer, project, window, cx)
1221 }
1222
1223 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1224 let mut clone = Self::new(
1225 self.mode,
1226 self.buffer.clone(),
1227 self.project.clone(),
1228 window,
1229 cx,
1230 );
1231 self.display_map.update(cx, |display_map, cx| {
1232 let snapshot = display_map.snapshot(cx);
1233 clone.display_map.update(cx, |display_map, cx| {
1234 display_map.set_state(&snapshot, cx);
1235 });
1236 });
1237 clone.folds_did_change(cx);
1238 clone.selections.clone_state(&self.selections);
1239 clone.scroll_manager.clone_state(&self.scroll_manager);
1240 clone.searchable = self.searchable;
1241 clone
1242 }
1243
1244 pub fn new(
1245 mode: EditorMode,
1246 buffer: Entity<MultiBuffer>,
1247 project: Option<Entity<Project>>,
1248 window: &mut Window,
1249 cx: &mut Context<Self>,
1250 ) -> Self {
1251 let style = window.text_style();
1252 let font_size = style.font_size.to_pixels(window.rem_size());
1253 let editor = cx.entity().downgrade();
1254 let fold_placeholder = FoldPlaceholder {
1255 constrain_width: true,
1256 render: Arc::new(move |fold_id, fold_range, cx| {
1257 let editor = editor.clone();
1258 div()
1259 .id(fold_id)
1260 .bg(cx.theme().colors().ghost_element_background)
1261 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1262 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1263 .rounded_xs()
1264 .size_full()
1265 .cursor_pointer()
1266 .child("⋯")
1267 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1268 .on_click(move |_, _window, cx| {
1269 editor
1270 .update(cx, |editor, cx| {
1271 editor.unfold_ranges(
1272 &[fold_range.start..fold_range.end],
1273 true,
1274 false,
1275 cx,
1276 );
1277 cx.stop_propagation();
1278 })
1279 .ok();
1280 })
1281 .into_any()
1282 }),
1283 merge_adjacent: true,
1284 ..Default::default()
1285 };
1286 let display_map = cx.new(|cx| {
1287 DisplayMap::new(
1288 buffer.clone(),
1289 style.font(),
1290 font_size,
1291 None,
1292 FILE_HEADER_HEIGHT,
1293 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1294 fold_placeholder,
1295 cx,
1296 )
1297 });
1298
1299 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1300
1301 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1302
1303 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1304 .then(|| language_settings::SoftWrap::None);
1305
1306 let mut project_subscriptions = Vec::new();
1307 if mode == EditorMode::Full {
1308 if let Some(project) = project.as_ref() {
1309 project_subscriptions.push(cx.subscribe_in(
1310 project,
1311 window,
1312 |editor, _, event, window, cx| match event {
1313 project::Event::RefreshCodeLens => {
1314 // we always query lens with actions, without storing them, always refreshing them
1315 }
1316 project::Event::RefreshInlayHints => {
1317 editor
1318 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1319 }
1320 project::Event::SnippetEdit(id, snippet_edits) => {
1321 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1322 let focus_handle = editor.focus_handle(cx);
1323 if focus_handle.is_focused(window) {
1324 let snapshot = buffer.read(cx).snapshot();
1325 for (range, snippet) in snippet_edits {
1326 let editor_range =
1327 language::range_from_lsp(*range).to_offset(&snapshot);
1328 editor
1329 .insert_snippet(
1330 &[editor_range],
1331 snippet.clone(),
1332 window,
1333 cx,
1334 )
1335 .ok();
1336 }
1337 }
1338 }
1339 }
1340 _ => {}
1341 },
1342 ));
1343 if let Some(task_inventory) = project
1344 .read(cx)
1345 .task_store()
1346 .read(cx)
1347 .task_inventory()
1348 .cloned()
1349 {
1350 project_subscriptions.push(cx.observe_in(
1351 &task_inventory,
1352 window,
1353 |editor, _, window, cx| {
1354 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1355 },
1356 ));
1357 };
1358
1359 project_subscriptions.push(cx.subscribe_in(
1360 &project.read(cx).breakpoint_store(),
1361 window,
1362 |editor, _, event, window, cx| match event {
1363 BreakpointStoreEvent::ActiveDebugLineChanged => {
1364 editor.go_to_active_debug_line(window, cx);
1365 }
1366 _ => {}
1367 },
1368 ));
1369 }
1370 }
1371
1372 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1373
1374 let inlay_hint_settings =
1375 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1376 let focus_handle = cx.focus_handle();
1377 cx.on_focus(&focus_handle, window, Self::handle_focus)
1378 .detach();
1379 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1380 .detach();
1381 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1382 .detach();
1383 cx.on_blur(&focus_handle, window, Self::handle_blur)
1384 .detach();
1385
1386 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1387 Some(false)
1388 } else {
1389 None
1390 };
1391
1392 let breakpoint_store = match (mode, project.as_ref()) {
1393 (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
1394 _ => None,
1395 };
1396
1397 let mut code_action_providers = Vec::new();
1398 let mut load_uncommitted_diff = None;
1399 if let Some(project) = project.clone() {
1400 load_uncommitted_diff = Some(
1401 get_uncommitted_diff_for_buffer(
1402 &project,
1403 buffer.read(cx).all_buffers(),
1404 buffer.clone(),
1405 cx,
1406 )
1407 .shared(),
1408 );
1409 code_action_providers.push(Rc::new(project) as Rc<_>);
1410 }
1411
1412 let mut this = Self {
1413 focus_handle,
1414 show_cursor_when_unfocused: false,
1415 last_focused_descendant: None,
1416 buffer: buffer.clone(),
1417 display_map: display_map.clone(),
1418 selections,
1419 scroll_manager: ScrollManager::new(cx),
1420 columnar_selection_tail: None,
1421 add_selections_state: None,
1422 select_next_state: None,
1423 select_prev_state: None,
1424 selection_history: Default::default(),
1425 autoclose_regions: Default::default(),
1426 snippet_stack: Default::default(),
1427 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1428 ime_transaction: Default::default(),
1429 active_diagnostics: None,
1430 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1431 inline_diagnostics_update: Task::ready(()),
1432 inline_diagnostics: Vec::new(),
1433 soft_wrap_mode_override,
1434 hard_wrap: None,
1435 completion_provider: project.clone().map(|project| Box::new(project) as _),
1436 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1437 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1438 project,
1439 blink_manager: blink_manager.clone(),
1440 show_local_selections: true,
1441 show_scrollbars: true,
1442 mode,
1443 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1444 show_gutter: mode == EditorMode::Full,
1445 show_line_numbers: None,
1446 use_relative_line_numbers: None,
1447 show_git_diff_gutter: None,
1448 show_code_actions: None,
1449 show_runnables: None,
1450 show_breakpoints: None,
1451 show_wrap_guides: None,
1452 show_indent_guides,
1453 placeholder_text: None,
1454 highlight_order: 0,
1455 highlighted_rows: HashMap::default(),
1456 background_highlights: Default::default(),
1457 gutter_highlights: TreeMap::default(),
1458 scrollbar_marker_state: ScrollbarMarkerState::default(),
1459 active_indent_guides_state: ActiveIndentGuidesState::default(),
1460 nav_history: None,
1461 context_menu: RefCell::new(None),
1462 context_menu_options: None,
1463 mouse_context_menu: None,
1464 completion_tasks: Default::default(),
1465 signature_help_state: SignatureHelpState::default(),
1466 auto_signature_help: None,
1467 find_all_references_task_sources: Vec::new(),
1468 next_completion_id: 0,
1469 next_inlay_id: 0,
1470 code_action_providers,
1471 available_code_actions: Default::default(),
1472 code_actions_task: Default::default(),
1473 selection_highlight_task: Default::default(),
1474 document_highlights_task: Default::default(),
1475 linked_editing_range_task: Default::default(),
1476 pending_rename: Default::default(),
1477 searchable: true,
1478 cursor_shape: EditorSettings::get_global(cx)
1479 .cursor_shape
1480 .unwrap_or_default(),
1481 current_line_highlight: None,
1482 autoindent_mode: Some(AutoindentMode::EachLine),
1483 collapse_matches: false,
1484 workspace: None,
1485 input_enabled: true,
1486 use_modal_editing: mode == EditorMode::Full,
1487 read_only: false,
1488 use_autoclose: true,
1489 use_auto_surround: true,
1490 auto_replace_emoji_shortcode: false,
1491 jsx_tag_auto_close_enabled_in_any_buffer: false,
1492 leader_peer_id: None,
1493 remote_id: None,
1494 hover_state: Default::default(),
1495 pending_mouse_down: None,
1496 hovered_link_state: Default::default(),
1497 edit_prediction_provider: None,
1498 active_inline_completion: None,
1499 stale_inline_completion_in_menu: None,
1500 edit_prediction_preview: EditPredictionPreview::Inactive {
1501 released_too_fast: false,
1502 },
1503 inline_diagnostics_enabled: mode == EditorMode::Full,
1504 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1505
1506 gutter_hovered: false,
1507 pixel_position_of_newest_cursor: None,
1508 last_bounds: None,
1509 last_position_map: None,
1510 expect_bounds_change: None,
1511 gutter_dimensions: GutterDimensions::default(),
1512 style: None,
1513 show_cursor_names: false,
1514 hovered_cursors: Default::default(),
1515 next_editor_action_id: EditorActionId::default(),
1516 editor_actions: Rc::default(),
1517 inline_completions_hidden_for_vim_mode: false,
1518 show_inline_completions_override: None,
1519 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1520 edit_prediction_settings: EditPredictionSettings::Disabled,
1521 edit_prediction_indent_conflict: false,
1522 edit_prediction_requires_modifier_in_indent_conflict: true,
1523 custom_context_menu: None,
1524 show_git_blame_gutter: false,
1525 show_git_blame_inline: false,
1526 show_selection_menu: None,
1527 show_git_blame_inline_delay_task: None,
1528 git_blame_inline_tooltip: None,
1529 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1530 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1531 .session
1532 .restore_unsaved_buffers,
1533 blame: None,
1534 blame_subscription: None,
1535 tasks: Default::default(),
1536
1537 breakpoint_store,
1538 gutter_breakpoint_indicator: None,
1539 _subscriptions: vec![
1540 cx.observe(&buffer, Self::on_buffer_changed),
1541 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1542 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1543 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1544 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1545 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1546 cx.observe_window_activation(window, |editor, window, cx| {
1547 let active = window.is_window_active();
1548 editor.blink_manager.update(cx, |blink_manager, cx| {
1549 if active {
1550 blink_manager.enable(cx);
1551 } else {
1552 blink_manager.disable(cx);
1553 }
1554 });
1555 }),
1556 ],
1557 tasks_update_task: None,
1558 linked_edit_ranges: Default::default(),
1559 in_project_search: false,
1560 previous_search_ranges: None,
1561 breadcrumb_header: None,
1562 focused_block: None,
1563 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1564 addons: HashMap::default(),
1565 registered_buffers: HashMap::default(),
1566 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1567 selection_mark_mode: false,
1568 toggle_fold_multiple_buffers: Task::ready(()),
1569 serialize_selections: Task::ready(()),
1570 serialize_folds: Task::ready(()),
1571 text_style_refinement: None,
1572 load_diff_task: load_uncommitted_diff,
1573 mouse_cursor_hidden: false,
1574 hide_mouse_while_typing: EditorSettings::get_global(cx)
1575 .hide_mouse_while_typing
1576 .unwrap_or(true),
1577 };
1578 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1579 this._subscriptions
1580 .push(cx.observe(breakpoints, |_, _, cx| {
1581 cx.notify();
1582 }));
1583 }
1584 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1585 this._subscriptions.extend(project_subscriptions);
1586
1587 this.end_selection(window, cx);
1588 this.scroll_manager.show_scrollbars(window, cx);
1589 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1590
1591 if mode == EditorMode::Full {
1592 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1593 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1594
1595 if this.git_blame_inline_enabled {
1596 this.git_blame_inline_enabled = true;
1597 this.start_git_blame_inline(false, window, cx);
1598 }
1599
1600 this.go_to_active_debug_line(window, cx);
1601
1602 if let Some(buffer) = buffer.read(cx).as_singleton() {
1603 if let Some(project) = this.project.as_ref() {
1604 let handle = project.update(cx, |project, cx| {
1605 project.register_buffer_with_language_servers(&buffer, cx)
1606 });
1607 this.registered_buffers
1608 .insert(buffer.read(cx).remote_id(), handle);
1609 }
1610 }
1611 }
1612
1613 this.report_editor_event("Editor Opened", None, cx);
1614 this
1615 }
1616
1617 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1618 self.mouse_context_menu
1619 .as_ref()
1620 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1621 }
1622
1623 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1624 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1625 }
1626
1627 fn key_context_internal(
1628 &self,
1629 has_active_edit_prediction: bool,
1630 window: &Window,
1631 cx: &App,
1632 ) -> KeyContext {
1633 let mut key_context = KeyContext::new_with_defaults();
1634 key_context.add("Editor");
1635 let mode = match self.mode {
1636 EditorMode::SingleLine { .. } => "single_line",
1637 EditorMode::AutoHeight { .. } => "auto_height",
1638 EditorMode::Full => "full",
1639 };
1640
1641 if EditorSettings::jupyter_enabled(cx) {
1642 key_context.add("jupyter");
1643 }
1644
1645 key_context.set("mode", mode);
1646 if self.pending_rename.is_some() {
1647 key_context.add("renaming");
1648 }
1649
1650 match self.context_menu.borrow().as_ref() {
1651 Some(CodeContextMenu::Completions(_)) => {
1652 key_context.add("menu");
1653 key_context.add("showing_completions");
1654 }
1655 Some(CodeContextMenu::CodeActions(_)) => {
1656 key_context.add("menu");
1657 key_context.add("showing_code_actions")
1658 }
1659 None => {}
1660 }
1661
1662 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1663 if !self.focus_handle(cx).contains_focused(window, cx)
1664 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1665 {
1666 for addon in self.addons.values() {
1667 addon.extend_key_context(&mut key_context, cx)
1668 }
1669 }
1670
1671 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1672 if let Some(extension) = singleton_buffer
1673 .read(cx)
1674 .file()
1675 .and_then(|file| file.path().extension()?.to_str())
1676 {
1677 key_context.set("extension", extension.to_string());
1678 }
1679 } else {
1680 key_context.add("multibuffer");
1681 }
1682
1683 if has_active_edit_prediction {
1684 if self.edit_prediction_in_conflict() {
1685 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1686 } else {
1687 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1688 key_context.add("copilot_suggestion");
1689 }
1690 }
1691
1692 if self.selection_mark_mode {
1693 key_context.add("selection_mode");
1694 }
1695
1696 key_context
1697 }
1698
1699 pub fn edit_prediction_in_conflict(&self) -> bool {
1700 if !self.show_edit_predictions_in_menu() {
1701 return false;
1702 }
1703
1704 let showing_completions = self
1705 .context_menu
1706 .borrow()
1707 .as_ref()
1708 .map_or(false, |context| {
1709 matches!(context, CodeContextMenu::Completions(_))
1710 });
1711
1712 showing_completions
1713 || self.edit_prediction_requires_modifier()
1714 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1715 // bindings to insert tab characters.
1716 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1717 }
1718
1719 pub fn accept_edit_prediction_keybind(
1720 &self,
1721 window: &Window,
1722 cx: &App,
1723 ) -> AcceptEditPredictionBinding {
1724 let key_context = self.key_context_internal(true, window, cx);
1725 let in_conflict = self.edit_prediction_in_conflict();
1726
1727 AcceptEditPredictionBinding(
1728 window
1729 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1730 .into_iter()
1731 .filter(|binding| {
1732 !in_conflict
1733 || binding
1734 .keystrokes()
1735 .first()
1736 .map_or(false, |keystroke| keystroke.modifiers.modified())
1737 })
1738 .rev()
1739 .min_by_key(|binding| {
1740 binding
1741 .keystrokes()
1742 .first()
1743 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1744 }),
1745 )
1746 }
1747
1748 pub fn new_file(
1749 workspace: &mut Workspace,
1750 _: &workspace::NewFile,
1751 window: &mut Window,
1752 cx: &mut Context<Workspace>,
1753 ) {
1754 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1755 "Failed to create buffer",
1756 window,
1757 cx,
1758 |e, _, _| match e.error_code() {
1759 ErrorCode::RemoteUpgradeRequired => Some(format!(
1760 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1761 e.error_tag("required").unwrap_or("the latest version")
1762 )),
1763 _ => None,
1764 },
1765 );
1766 }
1767
1768 pub fn new_in_workspace(
1769 workspace: &mut Workspace,
1770 window: &mut Window,
1771 cx: &mut Context<Workspace>,
1772 ) -> Task<Result<Entity<Editor>>> {
1773 let project = workspace.project().clone();
1774 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1775
1776 cx.spawn_in(window, async move |workspace, cx| {
1777 let buffer = create.await?;
1778 workspace.update_in(cx, |workspace, window, cx| {
1779 let editor =
1780 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1781 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1782 editor
1783 })
1784 })
1785 }
1786
1787 fn new_file_vertical(
1788 workspace: &mut Workspace,
1789 _: &workspace::NewFileSplitVertical,
1790 window: &mut Window,
1791 cx: &mut Context<Workspace>,
1792 ) {
1793 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1794 }
1795
1796 fn new_file_horizontal(
1797 workspace: &mut Workspace,
1798 _: &workspace::NewFileSplitHorizontal,
1799 window: &mut Window,
1800 cx: &mut Context<Workspace>,
1801 ) {
1802 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1803 }
1804
1805 fn new_file_in_direction(
1806 workspace: &mut Workspace,
1807 direction: SplitDirection,
1808 window: &mut Window,
1809 cx: &mut Context<Workspace>,
1810 ) {
1811 let project = workspace.project().clone();
1812 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1813
1814 cx.spawn_in(window, async move |workspace, cx| {
1815 let buffer = create.await?;
1816 workspace.update_in(cx, move |workspace, window, cx| {
1817 workspace.split_item(
1818 direction,
1819 Box::new(
1820 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1821 ),
1822 window,
1823 cx,
1824 )
1825 })?;
1826 anyhow::Ok(())
1827 })
1828 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1829 match e.error_code() {
1830 ErrorCode::RemoteUpgradeRequired => Some(format!(
1831 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1832 e.error_tag("required").unwrap_or("the latest version")
1833 )),
1834 _ => None,
1835 }
1836 });
1837 }
1838
1839 pub fn leader_peer_id(&self) -> Option<PeerId> {
1840 self.leader_peer_id
1841 }
1842
1843 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1844 &self.buffer
1845 }
1846
1847 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1848 self.workspace.as_ref()?.0.upgrade()
1849 }
1850
1851 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1852 self.buffer().read(cx).title(cx)
1853 }
1854
1855 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1856 let git_blame_gutter_max_author_length = self
1857 .render_git_blame_gutter(cx)
1858 .then(|| {
1859 if let Some(blame) = self.blame.as_ref() {
1860 let max_author_length =
1861 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1862 Some(max_author_length)
1863 } else {
1864 None
1865 }
1866 })
1867 .flatten();
1868
1869 EditorSnapshot {
1870 mode: self.mode,
1871 show_gutter: self.show_gutter,
1872 show_line_numbers: self.show_line_numbers,
1873 show_git_diff_gutter: self.show_git_diff_gutter,
1874 show_code_actions: self.show_code_actions,
1875 show_runnables: self.show_runnables,
1876 show_breakpoints: self.show_breakpoints,
1877 git_blame_gutter_max_author_length,
1878 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1879 scroll_anchor: self.scroll_manager.anchor(),
1880 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1881 placeholder_text: self.placeholder_text.clone(),
1882 is_focused: self.focus_handle.is_focused(window),
1883 current_line_highlight: self
1884 .current_line_highlight
1885 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1886 gutter_hovered: self.gutter_hovered,
1887 }
1888 }
1889
1890 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1891 self.buffer.read(cx).language_at(point, cx)
1892 }
1893
1894 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1895 self.buffer.read(cx).read(cx).file_at(point).cloned()
1896 }
1897
1898 pub fn active_excerpt(
1899 &self,
1900 cx: &App,
1901 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1902 self.buffer
1903 .read(cx)
1904 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1905 }
1906
1907 pub fn mode(&self) -> EditorMode {
1908 self.mode
1909 }
1910
1911 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1912 self.collaboration_hub.as_deref()
1913 }
1914
1915 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1916 self.collaboration_hub = Some(hub);
1917 }
1918
1919 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1920 self.in_project_search = in_project_search;
1921 }
1922
1923 pub fn set_custom_context_menu(
1924 &mut self,
1925 f: impl 'static
1926 + Fn(
1927 &mut Self,
1928 DisplayPoint,
1929 &mut Window,
1930 &mut Context<Self>,
1931 ) -> Option<Entity<ui::ContextMenu>>,
1932 ) {
1933 self.custom_context_menu = Some(Box::new(f))
1934 }
1935
1936 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1937 self.completion_provider = provider;
1938 }
1939
1940 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1941 self.semantics_provider.clone()
1942 }
1943
1944 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1945 self.semantics_provider = provider;
1946 }
1947
1948 pub fn set_edit_prediction_provider<T>(
1949 &mut self,
1950 provider: Option<Entity<T>>,
1951 window: &mut Window,
1952 cx: &mut Context<Self>,
1953 ) where
1954 T: EditPredictionProvider,
1955 {
1956 self.edit_prediction_provider =
1957 provider.map(|provider| RegisteredInlineCompletionProvider {
1958 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1959 if this.focus_handle.is_focused(window) {
1960 this.update_visible_inline_completion(window, cx);
1961 }
1962 }),
1963 provider: Arc::new(provider),
1964 });
1965 self.update_edit_prediction_settings(cx);
1966 self.refresh_inline_completion(false, false, window, cx);
1967 }
1968
1969 pub fn placeholder_text(&self) -> Option<&str> {
1970 self.placeholder_text.as_deref()
1971 }
1972
1973 pub fn set_placeholder_text(
1974 &mut self,
1975 placeholder_text: impl Into<Arc<str>>,
1976 cx: &mut Context<Self>,
1977 ) {
1978 let placeholder_text = Some(placeholder_text.into());
1979 if self.placeholder_text != placeholder_text {
1980 self.placeholder_text = placeholder_text;
1981 cx.notify();
1982 }
1983 }
1984
1985 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1986 self.cursor_shape = cursor_shape;
1987
1988 // Disrupt blink for immediate user feedback that the cursor shape has changed
1989 self.blink_manager.update(cx, BlinkManager::show_cursor);
1990
1991 cx.notify();
1992 }
1993
1994 pub fn set_current_line_highlight(
1995 &mut self,
1996 current_line_highlight: Option<CurrentLineHighlight>,
1997 ) {
1998 self.current_line_highlight = current_line_highlight;
1999 }
2000
2001 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2002 self.collapse_matches = collapse_matches;
2003 }
2004
2005 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2006 let buffers = self.buffer.read(cx).all_buffers();
2007 let Some(project) = self.project.as_ref() else {
2008 return;
2009 };
2010 project.update(cx, |project, cx| {
2011 for buffer in buffers {
2012 self.registered_buffers
2013 .entry(buffer.read(cx).remote_id())
2014 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2015 }
2016 })
2017 }
2018
2019 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2020 if self.collapse_matches {
2021 return range.start..range.start;
2022 }
2023 range.clone()
2024 }
2025
2026 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2027 if self.display_map.read(cx).clip_at_line_ends != clip {
2028 self.display_map
2029 .update(cx, |map, _| map.clip_at_line_ends = clip);
2030 }
2031 }
2032
2033 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2034 self.input_enabled = input_enabled;
2035 }
2036
2037 pub fn set_inline_completions_hidden_for_vim_mode(
2038 &mut self,
2039 hidden: bool,
2040 window: &mut Window,
2041 cx: &mut Context<Self>,
2042 ) {
2043 if hidden != self.inline_completions_hidden_for_vim_mode {
2044 self.inline_completions_hidden_for_vim_mode = hidden;
2045 if hidden {
2046 self.update_visible_inline_completion(window, cx);
2047 } else {
2048 self.refresh_inline_completion(true, false, window, cx);
2049 }
2050 }
2051 }
2052
2053 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2054 self.menu_inline_completions_policy = value;
2055 }
2056
2057 pub fn set_autoindent(&mut self, autoindent: bool) {
2058 if autoindent {
2059 self.autoindent_mode = Some(AutoindentMode::EachLine);
2060 } else {
2061 self.autoindent_mode = None;
2062 }
2063 }
2064
2065 pub fn read_only(&self, cx: &App) -> bool {
2066 self.read_only || self.buffer.read(cx).read_only()
2067 }
2068
2069 pub fn set_read_only(&mut self, read_only: bool) {
2070 self.read_only = read_only;
2071 }
2072
2073 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2074 self.use_autoclose = autoclose;
2075 }
2076
2077 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2078 self.use_auto_surround = auto_surround;
2079 }
2080
2081 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2082 self.auto_replace_emoji_shortcode = auto_replace;
2083 }
2084
2085 pub fn toggle_edit_predictions(
2086 &mut self,
2087 _: &ToggleEditPrediction,
2088 window: &mut Window,
2089 cx: &mut Context<Self>,
2090 ) {
2091 if self.show_inline_completions_override.is_some() {
2092 self.set_show_edit_predictions(None, window, cx);
2093 } else {
2094 let show_edit_predictions = !self.edit_predictions_enabled();
2095 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2096 }
2097 }
2098
2099 pub fn set_show_edit_predictions(
2100 &mut self,
2101 show_edit_predictions: Option<bool>,
2102 window: &mut Window,
2103 cx: &mut Context<Self>,
2104 ) {
2105 self.show_inline_completions_override = show_edit_predictions;
2106 self.update_edit_prediction_settings(cx);
2107
2108 if let Some(false) = show_edit_predictions {
2109 self.discard_inline_completion(false, cx);
2110 } else {
2111 self.refresh_inline_completion(false, true, window, cx);
2112 }
2113 }
2114
2115 fn inline_completions_disabled_in_scope(
2116 &self,
2117 buffer: &Entity<Buffer>,
2118 buffer_position: language::Anchor,
2119 cx: &App,
2120 ) -> bool {
2121 let snapshot = buffer.read(cx).snapshot();
2122 let settings = snapshot.settings_at(buffer_position, cx);
2123
2124 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2125 return false;
2126 };
2127
2128 scope.override_name().map_or(false, |scope_name| {
2129 settings
2130 .edit_predictions_disabled_in
2131 .iter()
2132 .any(|s| s == scope_name)
2133 })
2134 }
2135
2136 pub fn set_use_modal_editing(&mut self, to: bool) {
2137 self.use_modal_editing = to;
2138 }
2139
2140 pub fn use_modal_editing(&self) -> bool {
2141 self.use_modal_editing
2142 }
2143
2144 fn selections_did_change(
2145 &mut self,
2146 local: bool,
2147 old_cursor_position: &Anchor,
2148 show_completions: bool,
2149 window: &mut Window,
2150 cx: &mut Context<Self>,
2151 ) {
2152 window.invalidate_character_coordinates();
2153
2154 // Copy selections to primary selection buffer
2155 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2156 if local {
2157 let selections = self.selections.all::<usize>(cx);
2158 let buffer_handle = self.buffer.read(cx).read(cx);
2159
2160 let mut text = String::new();
2161 for (index, selection) in selections.iter().enumerate() {
2162 let text_for_selection = buffer_handle
2163 .text_for_range(selection.start..selection.end)
2164 .collect::<String>();
2165
2166 text.push_str(&text_for_selection);
2167 if index != selections.len() - 1 {
2168 text.push('\n');
2169 }
2170 }
2171
2172 if !text.is_empty() {
2173 cx.write_to_primary(ClipboardItem::new_string(text));
2174 }
2175 }
2176
2177 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2178 self.buffer.update(cx, |buffer, cx| {
2179 buffer.set_active_selections(
2180 &self.selections.disjoint_anchors(),
2181 self.selections.line_mode,
2182 self.cursor_shape,
2183 cx,
2184 )
2185 });
2186 }
2187 let display_map = self
2188 .display_map
2189 .update(cx, |display_map, cx| display_map.snapshot(cx));
2190 let buffer = &display_map.buffer_snapshot;
2191 self.add_selections_state = None;
2192 self.select_next_state = None;
2193 self.select_prev_state = None;
2194 self.select_syntax_node_history.try_clear();
2195 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2196 self.snippet_stack
2197 .invalidate(&self.selections.disjoint_anchors(), buffer);
2198 self.take_rename(false, window, cx);
2199
2200 let new_cursor_position = self.selections.newest_anchor().head();
2201
2202 self.push_to_nav_history(
2203 *old_cursor_position,
2204 Some(new_cursor_position.to_point(buffer)),
2205 false,
2206 cx,
2207 );
2208
2209 if local {
2210 let new_cursor_position = self.selections.newest_anchor().head();
2211 let mut context_menu = self.context_menu.borrow_mut();
2212 let completion_menu = match context_menu.as_ref() {
2213 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2214 _ => {
2215 *context_menu = None;
2216 None
2217 }
2218 };
2219 if let Some(buffer_id) = new_cursor_position.buffer_id {
2220 if !self.registered_buffers.contains_key(&buffer_id) {
2221 if let Some(project) = self.project.as_ref() {
2222 project.update(cx, |project, cx| {
2223 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2224 return;
2225 };
2226 self.registered_buffers.insert(
2227 buffer_id,
2228 project.register_buffer_with_language_servers(&buffer, cx),
2229 );
2230 })
2231 }
2232 }
2233 }
2234
2235 if let Some(completion_menu) = completion_menu {
2236 let cursor_position = new_cursor_position.to_offset(buffer);
2237 let (word_range, kind) =
2238 buffer.surrounding_word(completion_menu.initial_position, true);
2239 if kind == Some(CharKind::Word)
2240 && word_range.to_inclusive().contains(&cursor_position)
2241 {
2242 let mut completion_menu = completion_menu.clone();
2243 drop(context_menu);
2244
2245 let query = Self::completion_query(buffer, cursor_position);
2246 cx.spawn(async move |this, cx| {
2247 completion_menu
2248 .filter(query.as_deref(), cx.background_executor().clone())
2249 .await;
2250
2251 this.update(cx, |this, cx| {
2252 let mut context_menu = this.context_menu.borrow_mut();
2253 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2254 else {
2255 return;
2256 };
2257
2258 if menu.id > completion_menu.id {
2259 return;
2260 }
2261
2262 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2263 drop(context_menu);
2264 cx.notify();
2265 })
2266 })
2267 .detach();
2268
2269 if show_completions {
2270 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2271 }
2272 } else {
2273 drop(context_menu);
2274 self.hide_context_menu(window, cx);
2275 }
2276 } else {
2277 drop(context_menu);
2278 }
2279
2280 hide_hover(self, cx);
2281
2282 if old_cursor_position.to_display_point(&display_map).row()
2283 != new_cursor_position.to_display_point(&display_map).row()
2284 {
2285 self.available_code_actions.take();
2286 }
2287 self.refresh_code_actions(window, cx);
2288 self.refresh_document_highlights(cx);
2289 self.refresh_selected_text_highlights(window, cx);
2290 refresh_matching_bracket_highlights(self, window, cx);
2291 self.update_visible_inline_completion(window, cx);
2292 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2293 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2294 if self.git_blame_inline_enabled {
2295 self.start_inline_blame_timer(window, cx);
2296 }
2297 }
2298
2299 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2300 cx.emit(EditorEvent::SelectionsChanged { local });
2301
2302 let selections = &self.selections.disjoint;
2303 if selections.len() == 1 {
2304 cx.emit(SearchEvent::ActiveMatchChanged)
2305 }
2306 if local
2307 && self.is_singleton(cx)
2308 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2309 {
2310 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2311 let background_executor = cx.background_executor().clone();
2312 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2313 let snapshot = self.buffer().read(cx).snapshot(cx);
2314 let selections = selections.clone();
2315 self.serialize_selections = cx.background_spawn(async move {
2316 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2317 let selections = selections
2318 .iter()
2319 .map(|selection| {
2320 (
2321 selection.start.to_offset(&snapshot),
2322 selection.end.to_offset(&snapshot),
2323 )
2324 })
2325 .collect();
2326
2327 DB.save_editor_selections(editor_id, workspace_id, selections)
2328 .await
2329 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2330 .log_err();
2331 });
2332 }
2333 }
2334
2335 cx.notify();
2336 }
2337
2338 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2339 if !self.is_singleton(cx)
2340 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
2341 {
2342 return;
2343 }
2344
2345 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2346 return;
2347 };
2348 let background_executor = cx.background_executor().clone();
2349 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2350 let snapshot = self.buffer().read(cx).snapshot(cx);
2351 let folds = self.display_map.update(cx, |display_map, cx| {
2352 display_map
2353 .snapshot(cx)
2354 .folds_in_range(0..snapshot.len())
2355 .map(|fold| {
2356 (
2357 fold.range.start.to_offset(&snapshot),
2358 fold.range.end.to_offset(&snapshot),
2359 )
2360 })
2361 .collect()
2362 });
2363 self.serialize_folds = cx.background_spawn(async move {
2364 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2365 DB.save_editor_folds(editor_id, workspace_id, folds)
2366 .await
2367 .with_context(|| format!("persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"))
2368 .log_err();
2369 });
2370 }
2371
2372 pub fn sync_selections(
2373 &mut self,
2374 other: Entity<Editor>,
2375 cx: &mut Context<Self>,
2376 ) -> gpui::Subscription {
2377 let other_selections = other.read(cx).selections.disjoint.to_vec();
2378 self.selections.change_with(cx, |selections| {
2379 selections.select_anchors(other_selections);
2380 });
2381
2382 let other_subscription =
2383 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2384 EditorEvent::SelectionsChanged { local: true } => {
2385 let other_selections = other.read(cx).selections.disjoint.to_vec();
2386 if other_selections.is_empty() {
2387 return;
2388 }
2389 this.selections.change_with(cx, |selections| {
2390 selections.select_anchors(other_selections);
2391 });
2392 }
2393 _ => {}
2394 });
2395
2396 let this_subscription =
2397 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2398 EditorEvent::SelectionsChanged { local: true } => {
2399 let these_selections = this.selections.disjoint.to_vec();
2400 if these_selections.is_empty() {
2401 return;
2402 }
2403 other.update(cx, |other_editor, cx| {
2404 other_editor.selections.change_with(cx, |selections| {
2405 selections.select_anchors(these_selections);
2406 })
2407 });
2408 }
2409 _ => {}
2410 });
2411
2412 Subscription::join(other_subscription, this_subscription)
2413 }
2414
2415 pub fn change_selections<R>(
2416 &mut self,
2417 autoscroll: Option<Autoscroll>,
2418 window: &mut Window,
2419 cx: &mut Context<Self>,
2420 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2421 ) -> R {
2422 self.change_selections_inner(autoscroll, true, window, cx, change)
2423 }
2424
2425 fn change_selections_inner<R>(
2426 &mut self,
2427 autoscroll: Option<Autoscroll>,
2428 request_completions: bool,
2429 window: &mut Window,
2430 cx: &mut Context<Self>,
2431 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2432 ) -> R {
2433 let old_cursor_position = self.selections.newest_anchor().head();
2434 self.push_to_selection_history();
2435
2436 let (changed, result) = self.selections.change_with(cx, change);
2437
2438 if changed {
2439 if let Some(autoscroll) = autoscroll {
2440 self.request_autoscroll(autoscroll, cx);
2441 }
2442 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2443
2444 if self.should_open_signature_help_automatically(
2445 &old_cursor_position,
2446 self.signature_help_state.backspace_pressed(),
2447 cx,
2448 ) {
2449 self.show_signature_help(&ShowSignatureHelp, window, cx);
2450 }
2451 self.signature_help_state.set_backspace_pressed(false);
2452 }
2453
2454 result
2455 }
2456
2457 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2458 where
2459 I: IntoIterator<Item = (Range<S>, T)>,
2460 S: ToOffset,
2461 T: Into<Arc<str>>,
2462 {
2463 if self.read_only(cx) {
2464 return;
2465 }
2466
2467 self.buffer
2468 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2469 }
2470
2471 pub fn edit_with_autoindent<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.update(cx, |buffer, cx| {
2482 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2483 });
2484 }
2485
2486 pub fn edit_with_block_indent<I, S, T>(
2487 &mut self,
2488 edits: I,
2489 original_indent_columns: Vec<Option<u32>>,
2490 cx: &mut Context<Self>,
2491 ) where
2492 I: IntoIterator<Item = (Range<S>, T)>,
2493 S: ToOffset,
2494 T: Into<Arc<str>>,
2495 {
2496 if self.read_only(cx) {
2497 return;
2498 }
2499
2500 self.buffer.update(cx, |buffer, cx| {
2501 buffer.edit(
2502 edits,
2503 Some(AutoindentMode::Block {
2504 original_indent_columns,
2505 }),
2506 cx,
2507 )
2508 });
2509 }
2510
2511 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2512 self.hide_context_menu(window, cx);
2513
2514 match phase {
2515 SelectPhase::Begin {
2516 position,
2517 add,
2518 click_count,
2519 } => self.begin_selection(position, add, click_count, window, cx),
2520 SelectPhase::BeginColumnar {
2521 position,
2522 goal_column,
2523 reset,
2524 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2525 SelectPhase::Extend {
2526 position,
2527 click_count,
2528 } => self.extend_selection(position, click_count, window, cx),
2529 SelectPhase::Update {
2530 position,
2531 goal_column,
2532 scroll_delta,
2533 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2534 SelectPhase::End => self.end_selection(window, cx),
2535 }
2536 }
2537
2538 fn extend_selection(
2539 &mut self,
2540 position: DisplayPoint,
2541 click_count: usize,
2542 window: &mut Window,
2543 cx: &mut Context<Self>,
2544 ) {
2545 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2546 let tail = self.selections.newest::<usize>(cx).tail();
2547 self.begin_selection(position, false, click_count, window, cx);
2548
2549 let position = position.to_offset(&display_map, Bias::Left);
2550 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2551
2552 let mut pending_selection = self
2553 .selections
2554 .pending_anchor()
2555 .expect("extend_selection not called with pending selection");
2556 if position >= tail {
2557 pending_selection.start = tail_anchor;
2558 } else {
2559 pending_selection.end = tail_anchor;
2560 pending_selection.reversed = true;
2561 }
2562
2563 let mut pending_mode = self.selections.pending_mode().unwrap();
2564 match &mut pending_mode {
2565 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2566 _ => {}
2567 }
2568
2569 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2570 s.set_pending(pending_selection, pending_mode)
2571 });
2572 }
2573
2574 fn begin_selection(
2575 &mut self,
2576 position: DisplayPoint,
2577 add: bool,
2578 click_count: usize,
2579 window: &mut Window,
2580 cx: &mut Context<Self>,
2581 ) {
2582 if !self.focus_handle.is_focused(window) {
2583 self.last_focused_descendant = None;
2584 window.focus(&self.focus_handle);
2585 }
2586
2587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2588 let buffer = &display_map.buffer_snapshot;
2589 let newest_selection = self.selections.newest_anchor().clone();
2590 let position = display_map.clip_point(position, Bias::Left);
2591
2592 let start;
2593 let end;
2594 let mode;
2595 let mut auto_scroll;
2596 match click_count {
2597 1 => {
2598 start = buffer.anchor_before(position.to_point(&display_map));
2599 end = start;
2600 mode = SelectMode::Character;
2601 auto_scroll = true;
2602 }
2603 2 => {
2604 let range = movement::surrounding_word(&display_map, position);
2605 start = buffer.anchor_before(range.start.to_point(&display_map));
2606 end = buffer.anchor_before(range.end.to_point(&display_map));
2607 mode = SelectMode::Word(start..end);
2608 auto_scroll = true;
2609 }
2610 3 => {
2611 let position = display_map
2612 .clip_point(position, Bias::Left)
2613 .to_point(&display_map);
2614 let line_start = display_map.prev_line_boundary(position).0;
2615 let next_line_start = buffer.clip_point(
2616 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2617 Bias::Left,
2618 );
2619 start = buffer.anchor_before(line_start);
2620 end = buffer.anchor_before(next_line_start);
2621 mode = SelectMode::Line(start..end);
2622 auto_scroll = true;
2623 }
2624 _ => {
2625 start = buffer.anchor_before(0);
2626 end = buffer.anchor_before(buffer.len());
2627 mode = SelectMode::All;
2628 auto_scroll = false;
2629 }
2630 }
2631 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2632
2633 let point_to_delete: Option<usize> = {
2634 let selected_points: Vec<Selection<Point>> =
2635 self.selections.disjoint_in_range(start..end, cx);
2636
2637 if !add || click_count > 1 {
2638 None
2639 } else if !selected_points.is_empty() {
2640 Some(selected_points[0].id)
2641 } else {
2642 let clicked_point_already_selected =
2643 self.selections.disjoint.iter().find(|selection| {
2644 selection.start.to_point(buffer) == start.to_point(buffer)
2645 || selection.end.to_point(buffer) == end.to_point(buffer)
2646 });
2647
2648 clicked_point_already_selected.map(|selection| selection.id)
2649 }
2650 };
2651
2652 let selections_count = self.selections.count();
2653
2654 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2655 if let Some(point_to_delete) = point_to_delete {
2656 s.delete(point_to_delete);
2657
2658 if selections_count == 1 {
2659 s.set_pending_anchor_range(start..end, mode);
2660 }
2661 } else {
2662 if !add {
2663 s.clear_disjoint();
2664 } else if click_count > 1 {
2665 s.delete(newest_selection.id)
2666 }
2667
2668 s.set_pending_anchor_range(start..end, mode);
2669 }
2670 });
2671 }
2672
2673 fn begin_columnar_selection(
2674 &mut self,
2675 position: DisplayPoint,
2676 goal_column: u32,
2677 reset: bool,
2678 window: &mut Window,
2679 cx: &mut Context<Self>,
2680 ) {
2681 if !self.focus_handle.is_focused(window) {
2682 self.last_focused_descendant = None;
2683 window.focus(&self.focus_handle);
2684 }
2685
2686 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2687
2688 if reset {
2689 let pointer_position = display_map
2690 .buffer_snapshot
2691 .anchor_before(position.to_point(&display_map));
2692
2693 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2694 s.clear_disjoint();
2695 s.set_pending_anchor_range(
2696 pointer_position..pointer_position,
2697 SelectMode::Character,
2698 );
2699 });
2700 }
2701
2702 let tail = self.selections.newest::<Point>(cx).tail();
2703 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2704
2705 if !reset {
2706 self.select_columns(
2707 tail.to_display_point(&display_map),
2708 position,
2709 goal_column,
2710 &display_map,
2711 window,
2712 cx,
2713 );
2714 }
2715 }
2716
2717 fn update_selection(
2718 &mut self,
2719 position: DisplayPoint,
2720 goal_column: u32,
2721 scroll_delta: gpui::Point<f32>,
2722 window: &mut Window,
2723 cx: &mut Context<Self>,
2724 ) {
2725 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2726
2727 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2728 let tail = tail.to_display_point(&display_map);
2729 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2730 } else if let Some(mut pending) = self.selections.pending_anchor() {
2731 let buffer = self.buffer.read(cx).snapshot(cx);
2732 let head;
2733 let tail;
2734 let mode = self.selections.pending_mode().unwrap();
2735 match &mode {
2736 SelectMode::Character => {
2737 head = position.to_point(&display_map);
2738 tail = pending.tail().to_point(&buffer);
2739 }
2740 SelectMode::Word(original_range) => {
2741 let original_display_range = original_range.start.to_display_point(&display_map)
2742 ..original_range.end.to_display_point(&display_map);
2743 let original_buffer_range = original_display_range.start.to_point(&display_map)
2744 ..original_display_range.end.to_point(&display_map);
2745 if movement::is_inside_word(&display_map, position)
2746 || original_display_range.contains(&position)
2747 {
2748 let word_range = movement::surrounding_word(&display_map, position);
2749 if word_range.start < original_display_range.start {
2750 head = word_range.start.to_point(&display_map);
2751 } else {
2752 head = word_range.end.to_point(&display_map);
2753 }
2754 } else {
2755 head = position.to_point(&display_map);
2756 }
2757
2758 if head <= original_buffer_range.start {
2759 tail = original_buffer_range.end;
2760 } else {
2761 tail = original_buffer_range.start;
2762 }
2763 }
2764 SelectMode::Line(original_range) => {
2765 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2766
2767 let position = display_map
2768 .clip_point(position, Bias::Left)
2769 .to_point(&display_map);
2770 let line_start = display_map.prev_line_boundary(position).0;
2771 let next_line_start = buffer.clip_point(
2772 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2773 Bias::Left,
2774 );
2775
2776 if line_start < original_range.start {
2777 head = line_start
2778 } else {
2779 head = next_line_start
2780 }
2781
2782 if head <= original_range.start {
2783 tail = original_range.end;
2784 } else {
2785 tail = original_range.start;
2786 }
2787 }
2788 SelectMode::All => {
2789 return;
2790 }
2791 };
2792
2793 if head < tail {
2794 pending.start = buffer.anchor_before(head);
2795 pending.end = buffer.anchor_before(tail);
2796 pending.reversed = true;
2797 } else {
2798 pending.start = buffer.anchor_before(tail);
2799 pending.end = buffer.anchor_before(head);
2800 pending.reversed = false;
2801 }
2802
2803 self.change_selections(None, window, cx, |s| {
2804 s.set_pending(pending, mode);
2805 });
2806 } else {
2807 log::error!("update_selection dispatched with no pending selection");
2808 return;
2809 }
2810
2811 self.apply_scroll_delta(scroll_delta, window, cx);
2812 cx.notify();
2813 }
2814
2815 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2816 self.columnar_selection_tail.take();
2817 if self.selections.pending_anchor().is_some() {
2818 let selections = self.selections.all::<usize>(cx);
2819 self.change_selections(None, window, cx, |s| {
2820 s.select(selections);
2821 s.clear_pending();
2822 });
2823 }
2824 }
2825
2826 fn select_columns(
2827 &mut self,
2828 tail: DisplayPoint,
2829 head: DisplayPoint,
2830 goal_column: u32,
2831 display_map: &DisplaySnapshot,
2832 window: &mut Window,
2833 cx: &mut Context<Self>,
2834 ) {
2835 let start_row = cmp::min(tail.row(), head.row());
2836 let end_row = cmp::max(tail.row(), head.row());
2837 let start_column = cmp::min(tail.column(), goal_column);
2838 let end_column = cmp::max(tail.column(), goal_column);
2839 let reversed = start_column < tail.column();
2840
2841 let selection_ranges = (start_row.0..=end_row.0)
2842 .map(DisplayRow)
2843 .filter_map(|row| {
2844 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2845 let start = display_map
2846 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2847 .to_point(display_map);
2848 let end = display_map
2849 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2850 .to_point(display_map);
2851 if reversed {
2852 Some(end..start)
2853 } else {
2854 Some(start..end)
2855 }
2856 } else {
2857 None
2858 }
2859 })
2860 .collect::<Vec<_>>();
2861
2862 self.change_selections(None, window, cx, |s| {
2863 s.select_ranges(selection_ranges);
2864 });
2865 cx.notify();
2866 }
2867
2868 pub fn has_pending_nonempty_selection(&self) -> bool {
2869 let pending_nonempty_selection = match self.selections.pending_anchor() {
2870 Some(Selection { start, end, .. }) => start != end,
2871 None => false,
2872 };
2873
2874 pending_nonempty_selection
2875 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2876 }
2877
2878 pub fn has_pending_selection(&self) -> bool {
2879 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2880 }
2881
2882 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2883 self.selection_mark_mode = false;
2884
2885 if self.clear_expanded_diff_hunks(cx) {
2886 cx.notify();
2887 return;
2888 }
2889 if self.dismiss_menus_and_popups(true, window, cx) {
2890 return;
2891 }
2892
2893 if self.mode == EditorMode::Full
2894 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2895 {
2896 return;
2897 }
2898
2899 cx.propagate();
2900 }
2901
2902 pub fn dismiss_menus_and_popups(
2903 &mut self,
2904 is_user_requested: bool,
2905 window: &mut Window,
2906 cx: &mut Context<Self>,
2907 ) -> bool {
2908 if self.take_rename(false, window, cx).is_some() {
2909 return true;
2910 }
2911
2912 if hide_hover(self, cx) {
2913 return true;
2914 }
2915
2916 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2917 return true;
2918 }
2919
2920 if self.hide_context_menu(window, cx).is_some() {
2921 return true;
2922 }
2923
2924 if self.mouse_context_menu.take().is_some() {
2925 return true;
2926 }
2927
2928 if is_user_requested && self.discard_inline_completion(true, cx) {
2929 return true;
2930 }
2931
2932 if self.snippet_stack.pop().is_some() {
2933 return true;
2934 }
2935
2936 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2937 self.dismiss_diagnostics(cx);
2938 return true;
2939 }
2940
2941 false
2942 }
2943
2944 fn linked_editing_ranges_for(
2945 &self,
2946 selection: Range<text::Anchor>,
2947 cx: &App,
2948 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2949 if self.linked_edit_ranges.is_empty() {
2950 return None;
2951 }
2952 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2953 selection.end.buffer_id.and_then(|end_buffer_id| {
2954 if selection.start.buffer_id != Some(end_buffer_id) {
2955 return None;
2956 }
2957 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2958 let snapshot = buffer.read(cx).snapshot();
2959 self.linked_edit_ranges
2960 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2961 .map(|ranges| (ranges, snapshot, buffer))
2962 })?;
2963 use text::ToOffset as TO;
2964 // find offset from the start of current range to current cursor position
2965 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2966
2967 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2968 let start_difference = start_offset - start_byte_offset;
2969 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2970 let end_difference = end_offset - start_byte_offset;
2971 // Current range has associated linked ranges.
2972 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2973 for range in linked_ranges.iter() {
2974 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2975 let end_offset = start_offset + end_difference;
2976 let start_offset = start_offset + start_difference;
2977 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2978 continue;
2979 }
2980 if self.selections.disjoint_anchor_ranges().any(|s| {
2981 if s.start.buffer_id != selection.start.buffer_id
2982 || s.end.buffer_id != selection.end.buffer_id
2983 {
2984 return false;
2985 }
2986 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2987 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2988 }) {
2989 continue;
2990 }
2991 let start = buffer_snapshot.anchor_after(start_offset);
2992 let end = buffer_snapshot.anchor_after(end_offset);
2993 linked_edits
2994 .entry(buffer.clone())
2995 .or_default()
2996 .push(start..end);
2997 }
2998 Some(linked_edits)
2999 }
3000
3001 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3002 let text: Arc<str> = text.into();
3003
3004 if self.read_only(cx) {
3005 return;
3006 }
3007
3008 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3009
3010 let selections = self.selections.all_adjusted(cx);
3011 let mut bracket_inserted = false;
3012 let mut edits = Vec::new();
3013 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3014 let mut new_selections = Vec::with_capacity(selections.len());
3015 let mut new_autoclose_regions = Vec::new();
3016 let snapshot = self.buffer.read(cx).read(cx);
3017
3018 for (selection, autoclose_region) in
3019 self.selections_with_autoclose_regions(selections, &snapshot)
3020 {
3021 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3022 // Determine if the inserted text matches the opening or closing
3023 // bracket of any of this language's bracket pairs.
3024 let mut bracket_pair = None;
3025 let mut is_bracket_pair_start = false;
3026 let mut is_bracket_pair_end = false;
3027 if !text.is_empty() {
3028 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3029 // and they are removing the character that triggered IME popup.
3030 for (pair, enabled) in scope.brackets() {
3031 if !pair.close && !pair.surround {
3032 continue;
3033 }
3034
3035 if enabled && pair.start.ends_with(text.as_ref()) {
3036 let prefix_len = pair.start.len() - text.len();
3037 let preceding_text_matches_prefix = prefix_len == 0
3038 || (selection.start.column >= (prefix_len as u32)
3039 && snapshot.contains_str_at(
3040 Point::new(
3041 selection.start.row,
3042 selection.start.column - (prefix_len as u32),
3043 ),
3044 &pair.start[..prefix_len],
3045 ));
3046 if preceding_text_matches_prefix {
3047 bracket_pair = Some(pair.clone());
3048 is_bracket_pair_start = true;
3049 break;
3050 }
3051 }
3052 if pair.end.as_str() == text.as_ref() {
3053 bracket_pair = Some(pair.clone());
3054 is_bracket_pair_end = true;
3055 break;
3056 }
3057 }
3058 }
3059
3060 if let Some(bracket_pair) = bracket_pair {
3061 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3062 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3063 let auto_surround =
3064 self.use_auto_surround && snapshot_settings.use_auto_surround;
3065 if selection.is_empty() {
3066 if is_bracket_pair_start {
3067 // If the inserted text is a suffix of an opening bracket and the
3068 // selection is preceded by the rest of the opening bracket, then
3069 // insert the closing bracket.
3070 let following_text_allows_autoclose = snapshot
3071 .chars_at(selection.start)
3072 .next()
3073 .map_or(true, |c| scope.should_autoclose_before(c));
3074
3075 let preceding_text_allows_autoclose = selection.start.column == 0
3076 || snapshot.reversed_chars_at(selection.start).next().map_or(
3077 true,
3078 |c| {
3079 bracket_pair.start != bracket_pair.end
3080 || !snapshot
3081 .char_classifier_at(selection.start)
3082 .is_word(c)
3083 },
3084 );
3085
3086 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3087 && bracket_pair.start.len() == 1
3088 {
3089 let target = bracket_pair.start.chars().next().unwrap();
3090 let current_line_count = snapshot
3091 .reversed_chars_at(selection.start)
3092 .take_while(|&c| c != '\n')
3093 .filter(|&c| c == target)
3094 .count();
3095 current_line_count % 2 == 1
3096 } else {
3097 false
3098 };
3099
3100 if autoclose
3101 && bracket_pair.close
3102 && following_text_allows_autoclose
3103 && preceding_text_allows_autoclose
3104 && !is_closing_quote
3105 {
3106 let anchor = snapshot.anchor_before(selection.end);
3107 new_selections.push((selection.map(|_| anchor), text.len()));
3108 new_autoclose_regions.push((
3109 anchor,
3110 text.len(),
3111 selection.id,
3112 bracket_pair.clone(),
3113 ));
3114 edits.push((
3115 selection.range(),
3116 format!("{}{}", text, bracket_pair.end).into(),
3117 ));
3118 bracket_inserted = true;
3119 continue;
3120 }
3121 }
3122
3123 if let Some(region) = autoclose_region {
3124 // If the selection is followed by an auto-inserted closing bracket,
3125 // then don't insert that closing bracket again; just move the selection
3126 // past the closing bracket.
3127 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3128 && text.as_ref() == region.pair.end.as_str();
3129 if should_skip {
3130 let anchor = snapshot.anchor_after(selection.end);
3131 new_selections
3132 .push((selection.map(|_| anchor), region.pair.end.len()));
3133 continue;
3134 }
3135 }
3136
3137 let always_treat_brackets_as_autoclosed = snapshot
3138 .language_settings_at(selection.start, cx)
3139 .always_treat_brackets_as_autoclosed;
3140 if always_treat_brackets_as_autoclosed
3141 && is_bracket_pair_end
3142 && snapshot.contains_str_at(selection.end, text.as_ref())
3143 {
3144 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3145 // and the inserted text is a closing bracket and the selection is followed
3146 // by the closing bracket then move the selection past the closing bracket.
3147 let anchor = snapshot.anchor_after(selection.end);
3148 new_selections.push((selection.map(|_| anchor), text.len()));
3149 continue;
3150 }
3151 }
3152 // If an opening bracket is 1 character long and is typed while
3153 // text is selected, then surround that text with the bracket pair.
3154 else if auto_surround
3155 && bracket_pair.surround
3156 && is_bracket_pair_start
3157 && bracket_pair.start.chars().count() == 1
3158 {
3159 edits.push((selection.start..selection.start, text.clone()));
3160 edits.push((
3161 selection.end..selection.end,
3162 bracket_pair.end.as_str().into(),
3163 ));
3164 bracket_inserted = true;
3165 new_selections.push((
3166 Selection {
3167 id: selection.id,
3168 start: snapshot.anchor_after(selection.start),
3169 end: snapshot.anchor_before(selection.end),
3170 reversed: selection.reversed,
3171 goal: selection.goal,
3172 },
3173 0,
3174 ));
3175 continue;
3176 }
3177 }
3178 }
3179
3180 if self.auto_replace_emoji_shortcode
3181 && selection.is_empty()
3182 && text.as_ref().ends_with(':')
3183 {
3184 if let Some(possible_emoji_short_code) =
3185 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3186 {
3187 if !possible_emoji_short_code.is_empty() {
3188 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3189 let emoji_shortcode_start = Point::new(
3190 selection.start.row,
3191 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3192 );
3193
3194 // Remove shortcode from buffer
3195 edits.push((
3196 emoji_shortcode_start..selection.start,
3197 "".to_string().into(),
3198 ));
3199 new_selections.push((
3200 Selection {
3201 id: selection.id,
3202 start: snapshot.anchor_after(emoji_shortcode_start),
3203 end: snapshot.anchor_before(selection.start),
3204 reversed: selection.reversed,
3205 goal: selection.goal,
3206 },
3207 0,
3208 ));
3209
3210 // Insert emoji
3211 let selection_start_anchor = snapshot.anchor_after(selection.start);
3212 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3213 edits.push((selection.start..selection.end, emoji.to_string().into()));
3214
3215 continue;
3216 }
3217 }
3218 }
3219 }
3220
3221 // If not handling any auto-close operation, then just replace the selected
3222 // text with the given input and move the selection to the end of the
3223 // newly inserted text.
3224 let anchor = snapshot.anchor_after(selection.end);
3225 if !self.linked_edit_ranges.is_empty() {
3226 let start_anchor = snapshot.anchor_before(selection.start);
3227
3228 let is_word_char = text.chars().next().map_or(true, |char| {
3229 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3230 classifier.is_word(char)
3231 });
3232
3233 if is_word_char {
3234 if let Some(ranges) = self
3235 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3236 {
3237 for (buffer, edits) in ranges {
3238 linked_edits
3239 .entry(buffer.clone())
3240 .or_default()
3241 .extend(edits.into_iter().map(|range| (range, text.clone())));
3242 }
3243 }
3244 }
3245 }
3246
3247 new_selections.push((selection.map(|_| anchor), 0));
3248 edits.push((selection.start..selection.end, text.clone()));
3249 }
3250
3251 drop(snapshot);
3252
3253 self.transact(window, cx, |this, window, cx| {
3254 let initial_buffer_versions =
3255 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3256
3257 this.buffer.update(cx, |buffer, cx| {
3258 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3259 });
3260 for (buffer, edits) in linked_edits {
3261 buffer.update(cx, |buffer, cx| {
3262 let snapshot = buffer.snapshot();
3263 let edits = edits
3264 .into_iter()
3265 .map(|(range, text)| {
3266 use text::ToPoint as TP;
3267 let end_point = TP::to_point(&range.end, &snapshot);
3268 let start_point = TP::to_point(&range.start, &snapshot);
3269 (start_point..end_point, text)
3270 })
3271 .sorted_by_key(|(range, _)| range.start);
3272 buffer.edit(edits, None, cx);
3273 })
3274 }
3275 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3276 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3277 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3278 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3279 .zip(new_selection_deltas)
3280 .map(|(selection, delta)| Selection {
3281 id: selection.id,
3282 start: selection.start + delta,
3283 end: selection.end + delta,
3284 reversed: selection.reversed,
3285 goal: SelectionGoal::None,
3286 })
3287 .collect::<Vec<_>>();
3288
3289 let mut i = 0;
3290 for (position, delta, selection_id, pair) in new_autoclose_regions {
3291 let position = position.to_offset(&map.buffer_snapshot) + delta;
3292 let start = map.buffer_snapshot.anchor_before(position);
3293 let end = map.buffer_snapshot.anchor_after(position);
3294 while let Some(existing_state) = this.autoclose_regions.get(i) {
3295 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3296 Ordering::Less => i += 1,
3297 Ordering::Greater => break,
3298 Ordering::Equal => {
3299 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3300 Ordering::Less => i += 1,
3301 Ordering::Equal => break,
3302 Ordering::Greater => break,
3303 }
3304 }
3305 }
3306 }
3307 this.autoclose_regions.insert(
3308 i,
3309 AutocloseRegion {
3310 selection_id,
3311 range: start..end,
3312 pair,
3313 },
3314 );
3315 }
3316
3317 let had_active_inline_completion = this.has_active_inline_completion();
3318 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3319 s.select(new_selections)
3320 });
3321
3322 if !bracket_inserted {
3323 if let Some(on_type_format_task) =
3324 this.trigger_on_type_formatting(text.to_string(), window, cx)
3325 {
3326 on_type_format_task.detach_and_log_err(cx);
3327 }
3328 }
3329
3330 let editor_settings = EditorSettings::get_global(cx);
3331 if bracket_inserted
3332 && (editor_settings.auto_signature_help
3333 || editor_settings.show_signature_help_after_edits)
3334 {
3335 this.show_signature_help(&ShowSignatureHelp, window, cx);
3336 }
3337
3338 let trigger_in_words =
3339 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3340 if this.hard_wrap.is_some() {
3341 let latest: Range<Point> = this.selections.newest(cx).range();
3342 if latest.is_empty()
3343 && this
3344 .buffer()
3345 .read(cx)
3346 .snapshot(cx)
3347 .line_len(MultiBufferRow(latest.start.row))
3348 == latest.start.column
3349 {
3350 this.rewrap_impl(
3351 RewrapOptions {
3352 override_language_settings: true,
3353 preserve_existing_whitespace: true,
3354 },
3355 cx,
3356 )
3357 }
3358 }
3359 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3360 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3361 this.refresh_inline_completion(true, false, window, cx);
3362 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3363 });
3364 }
3365
3366 fn find_possible_emoji_shortcode_at_position(
3367 snapshot: &MultiBufferSnapshot,
3368 position: Point,
3369 ) -> Option<String> {
3370 let mut chars = Vec::new();
3371 let mut found_colon = false;
3372 for char in snapshot.reversed_chars_at(position).take(100) {
3373 // Found a possible emoji shortcode in the middle of the buffer
3374 if found_colon {
3375 if char.is_whitespace() {
3376 chars.reverse();
3377 return Some(chars.iter().collect());
3378 }
3379 // If the previous character is not a whitespace, we are in the middle of a word
3380 // and we only want to complete the shortcode if the word is made up of other emojis
3381 let mut containing_word = String::new();
3382 for ch in snapshot
3383 .reversed_chars_at(position)
3384 .skip(chars.len() + 1)
3385 .take(100)
3386 {
3387 if ch.is_whitespace() {
3388 break;
3389 }
3390 containing_word.push(ch);
3391 }
3392 let containing_word = containing_word.chars().rev().collect::<String>();
3393 if util::word_consists_of_emojis(containing_word.as_str()) {
3394 chars.reverse();
3395 return Some(chars.iter().collect());
3396 }
3397 }
3398
3399 if char.is_whitespace() || !char.is_ascii() {
3400 return None;
3401 }
3402 if char == ':' {
3403 found_colon = true;
3404 } else {
3405 chars.push(char);
3406 }
3407 }
3408 // Found a possible emoji shortcode at the beginning of the buffer
3409 chars.reverse();
3410 Some(chars.iter().collect())
3411 }
3412
3413 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3414 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3415 self.transact(window, cx, |this, window, cx| {
3416 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3417 let selections = this.selections.all::<usize>(cx);
3418 let multi_buffer = this.buffer.read(cx);
3419 let buffer = multi_buffer.snapshot(cx);
3420 selections
3421 .iter()
3422 .map(|selection| {
3423 let start_point = selection.start.to_point(&buffer);
3424 let mut indent =
3425 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3426 indent.len = cmp::min(indent.len, start_point.column);
3427 let start = selection.start;
3428 let end = selection.end;
3429 let selection_is_empty = start == end;
3430 let language_scope = buffer.language_scope_at(start);
3431 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3432 &language_scope
3433 {
3434 let insert_extra_newline =
3435 insert_extra_newline_brackets(&buffer, start..end, language)
3436 || insert_extra_newline_tree_sitter(&buffer, start..end);
3437
3438 // Comment extension on newline is allowed only for cursor selections
3439 let comment_delimiter = maybe!({
3440 if !selection_is_empty {
3441 return None;
3442 }
3443
3444 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3445 return None;
3446 }
3447
3448 let delimiters = language.line_comment_prefixes();
3449 let max_len_of_delimiter =
3450 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3451 let (snapshot, range) =
3452 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3453
3454 let mut index_of_first_non_whitespace = 0;
3455 let comment_candidate = snapshot
3456 .chars_for_range(range)
3457 .skip_while(|c| {
3458 let should_skip = c.is_whitespace();
3459 if should_skip {
3460 index_of_first_non_whitespace += 1;
3461 }
3462 should_skip
3463 })
3464 .take(max_len_of_delimiter)
3465 .collect::<String>();
3466 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3467 comment_candidate.starts_with(comment_prefix.as_ref())
3468 })?;
3469 let cursor_is_placed_after_comment_marker =
3470 index_of_first_non_whitespace + comment_prefix.len()
3471 <= start_point.column as usize;
3472 if cursor_is_placed_after_comment_marker {
3473 Some(comment_prefix.clone())
3474 } else {
3475 None
3476 }
3477 });
3478 (comment_delimiter, insert_extra_newline)
3479 } else {
3480 (None, false)
3481 };
3482
3483 let capacity_for_delimiter = comment_delimiter
3484 .as_deref()
3485 .map(str::len)
3486 .unwrap_or_default();
3487 let mut new_text =
3488 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3489 new_text.push('\n');
3490 new_text.extend(indent.chars());
3491 if let Some(delimiter) = &comment_delimiter {
3492 new_text.push_str(delimiter);
3493 }
3494 if insert_extra_newline {
3495 new_text = new_text.repeat(2);
3496 }
3497
3498 let anchor = buffer.anchor_after(end);
3499 let new_selection = selection.map(|_| anchor);
3500 (
3501 (start..end, new_text),
3502 (insert_extra_newline, new_selection),
3503 )
3504 })
3505 .unzip()
3506 };
3507
3508 this.edit_with_autoindent(edits, cx);
3509 let buffer = this.buffer.read(cx).snapshot(cx);
3510 let new_selections = selection_fixup_info
3511 .into_iter()
3512 .map(|(extra_newline_inserted, new_selection)| {
3513 let mut cursor = new_selection.end.to_point(&buffer);
3514 if extra_newline_inserted {
3515 cursor.row -= 1;
3516 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3517 }
3518 new_selection.map(|_| cursor)
3519 })
3520 .collect();
3521
3522 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3523 s.select(new_selections)
3524 });
3525 this.refresh_inline_completion(true, false, window, cx);
3526 });
3527 }
3528
3529 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3530 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3531
3532 let buffer = self.buffer.read(cx);
3533 let snapshot = buffer.snapshot(cx);
3534
3535 let mut edits = Vec::new();
3536 let mut rows = Vec::new();
3537
3538 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3539 let cursor = selection.head();
3540 let row = cursor.row;
3541
3542 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3543
3544 let newline = "\n".to_string();
3545 edits.push((start_of_line..start_of_line, newline));
3546
3547 rows.push(row + rows_inserted as u32);
3548 }
3549
3550 self.transact(window, cx, |editor, window, cx| {
3551 editor.edit(edits, cx);
3552
3553 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3554 let mut index = 0;
3555 s.move_cursors_with(|map, _, _| {
3556 let row = rows[index];
3557 index += 1;
3558
3559 let point = Point::new(row, 0);
3560 let boundary = map.next_line_boundary(point).1;
3561 let clipped = map.clip_point(boundary, Bias::Left);
3562
3563 (clipped, SelectionGoal::None)
3564 });
3565 });
3566
3567 let mut indent_edits = Vec::new();
3568 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3569 for row in rows {
3570 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3571 for (row, indent) in indents {
3572 if indent.len == 0 {
3573 continue;
3574 }
3575
3576 let text = match indent.kind {
3577 IndentKind::Space => " ".repeat(indent.len as usize),
3578 IndentKind::Tab => "\t".repeat(indent.len as usize),
3579 };
3580 let point = Point::new(row.0, 0);
3581 indent_edits.push((point..point, text));
3582 }
3583 }
3584 editor.edit(indent_edits, cx);
3585 });
3586 }
3587
3588 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3589 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
3590
3591 let buffer = self.buffer.read(cx);
3592 let snapshot = buffer.snapshot(cx);
3593
3594 let mut edits = Vec::new();
3595 let mut rows = Vec::new();
3596 let mut rows_inserted = 0;
3597
3598 for selection in self.selections.all_adjusted(cx) {
3599 let cursor = selection.head();
3600 let row = cursor.row;
3601
3602 let point = Point::new(row + 1, 0);
3603 let start_of_line = snapshot.clip_point(point, Bias::Left);
3604
3605 let newline = "\n".to_string();
3606 edits.push((start_of_line..start_of_line, newline));
3607
3608 rows_inserted += 1;
3609 rows.push(row + rows_inserted);
3610 }
3611
3612 self.transact(window, cx, |editor, window, cx| {
3613 editor.edit(edits, cx);
3614
3615 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3616 let mut index = 0;
3617 s.move_cursors_with(|map, _, _| {
3618 let row = rows[index];
3619 index += 1;
3620
3621 let point = Point::new(row, 0);
3622 let boundary = map.next_line_boundary(point).1;
3623 let clipped = map.clip_point(boundary, Bias::Left);
3624
3625 (clipped, SelectionGoal::None)
3626 });
3627 });
3628
3629 let mut indent_edits = Vec::new();
3630 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3631 for row in rows {
3632 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3633 for (row, indent) in indents {
3634 if indent.len == 0 {
3635 continue;
3636 }
3637
3638 let text = match indent.kind {
3639 IndentKind::Space => " ".repeat(indent.len as usize),
3640 IndentKind::Tab => "\t".repeat(indent.len as usize),
3641 };
3642 let point = Point::new(row.0, 0);
3643 indent_edits.push((point..point, text));
3644 }
3645 }
3646 editor.edit(indent_edits, cx);
3647 });
3648 }
3649
3650 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3651 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3652 original_indent_columns: Vec::new(),
3653 });
3654 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3655 }
3656
3657 fn insert_with_autoindent_mode(
3658 &mut self,
3659 text: &str,
3660 autoindent_mode: Option<AutoindentMode>,
3661 window: &mut Window,
3662 cx: &mut Context<Self>,
3663 ) {
3664 if self.read_only(cx) {
3665 return;
3666 }
3667
3668 let text: Arc<str> = text.into();
3669 self.transact(window, cx, |this, window, cx| {
3670 let old_selections = this.selections.all_adjusted(cx);
3671 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3672 let anchors = {
3673 let snapshot = buffer.read(cx);
3674 old_selections
3675 .iter()
3676 .map(|s| {
3677 let anchor = snapshot.anchor_after(s.head());
3678 s.map(|_| anchor)
3679 })
3680 .collect::<Vec<_>>()
3681 };
3682 buffer.edit(
3683 old_selections
3684 .iter()
3685 .map(|s| (s.start..s.end, text.clone())),
3686 autoindent_mode,
3687 cx,
3688 );
3689 anchors
3690 });
3691
3692 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3693 s.select_anchors(selection_anchors);
3694 });
3695
3696 cx.notify();
3697 });
3698 }
3699
3700 fn trigger_completion_on_input(
3701 &mut self,
3702 text: &str,
3703 trigger_in_words: bool,
3704 window: &mut Window,
3705 cx: &mut Context<Self>,
3706 ) {
3707 let ignore_completion_provider = self
3708 .context_menu
3709 .borrow()
3710 .as_ref()
3711 .map(|menu| match menu {
3712 CodeContextMenu::Completions(completions_menu) => {
3713 completions_menu.ignore_completion_provider
3714 }
3715 CodeContextMenu::CodeActions(_) => false,
3716 })
3717 .unwrap_or(false);
3718
3719 if ignore_completion_provider {
3720 self.show_word_completions(&ShowWordCompletions, window, cx);
3721 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3722 self.show_completions(
3723 &ShowCompletions {
3724 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3725 },
3726 window,
3727 cx,
3728 );
3729 } else {
3730 self.hide_context_menu(window, cx);
3731 }
3732 }
3733
3734 fn is_completion_trigger(
3735 &self,
3736 text: &str,
3737 trigger_in_words: bool,
3738 cx: &mut Context<Self>,
3739 ) -> bool {
3740 let position = self.selections.newest_anchor().head();
3741 let multibuffer = self.buffer.read(cx);
3742 let Some(buffer) = position
3743 .buffer_id
3744 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3745 else {
3746 return false;
3747 };
3748
3749 if let Some(completion_provider) = &self.completion_provider {
3750 completion_provider.is_completion_trigger(
3751 &buffer,
3752 position.text_anchor,
3753 text,
3754 trigger_in_words,
3755 cx,
3756 )
3757 } else {
3758 false
3759 }
3760 }
3761
3762 /// If any empty selections is touching the start of its innermost containing autoclose
3763 /// region, expand it to select the brackets.
3764 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3765 let selections = self.selections.all::<usize>(cx);
3766 let buffer = self.buffer.read(cx).read(cx);
3767 let new_selections = self
3768 .selections_with_autoclose_regions(selections, &buffer)
3769 .map(|(mut selection, region)| {
3770 if !selection.is_empty() {
3771 return selection;
3772 }
3773
3774 if let Some(region) = region {
3775 let mut range = region.range.to_offset(&buffer);
3776 if selection.start == range.start && range.start >= region.pair.start.len() {
3777 range.start -= region.pair.start.len();
3778 if buffer.contains_str_at(range.start, ®ion.pair.start)
3779 && buffer.contains_str_at(range.end, ®ion.pair.end)
3780 {
3781 range.end += region.pair.end.len();
3782 selection.start = range.start;
3783 selection.end = range.end;
3784
3785 return selection;
3786 }
3787 }
3788 }
3789
3790 let always_treat_brackets_as_autoclosed = buffer
3791 .language_settings_at(selection.start, cx)
3792 .always_treat_brackets_as_autoclosed;
3793
3794 if !always_treat_brackets_as_autoclosed {
3795 return selection;
3796 }
3797
3798 if let Some(scope) = buffer.language_scope_at(selection.start) {
3799 for (pair, enabled) in scope.brackets() {
3800 if !enabled || !pair.close {
3801 continue;
3802 }
3803
3804 if buffer.contains_str_at(selection.start, &pair.end) {
3805 let pair_start_len = pair.start.len();
3806 if buffer.contains_str_at(
3807 selection.start.saturating_sub(pair_start_len),
3808 &pair.start,
3809 ) {
3810 selection.start -= pair_start_len;
3811 selection.end += pair.end.len();
3812
3813 return selection;
3814 }
3815 }
3816 }
3817 }
3818
3819 selection
3820 })
3821 .collect();
3822
3823 drop(buffer);
3824 self.change_selections(None, window, cx, |selections| {
3825 selections.select(new_selections)
3826 });
3827 }
3828
3829 /// Iterate the given selections, and for each one, find the smallest surrounding
3830 /// autoclose region. This uses the ordering of the selections and the autoclose
3831 /// regions to avoid repeated comparisons.
3832 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3833 &'a self,
3834 selections: impl IntoIterator<Item = Selection<D>>,
3835 buffer: &'a MultiBufferSnapshot,
3836 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3837 let mut i = 0;
3838 let mut regions = self.autoclose_regions.as_slice();
3839 selections.into_iter().map(move |selection| {
3840 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3841
3842 let mut enclosing = None;
3843 while let Some(pair_state) = regions.get(i) {
3844 if pair_state.range.end.to_offset(buffer) < range.start {
3845 regions = ®ions[i + 1..];
3846 i = 0;
3847 } else if pair_state.range.start.to_offset(buffer) > range.end {
3848 break;
3849 } else {
3850 if pair_state.selection_id == selection.id {
3851 enclosing = Some(pair_state);
3852 }
3853 i += 1;
3854 }
3855 }
3856
3857 (selection, enclosing)
3858 })
3859 }
3860
3861 /// Remove any autoclose regions that no longer contain their selection.
3862 fn invalidate_autoclose_regions(
3863 &mut self,
3864 mut selections: &[Selection<Anchor>],
3865 buffer: &MultiBufferSnapshot,
3866 ) {
3867 self.autoclose_regions.retain(|state| {
3868 let mut i = 0;
3869 while let Some(selection) = selections.get(i) {
3870 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3871 selections = &selections[1..];
3872 continue;
3873 }
3874 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3875 break;
3876 }
3877 if selection.id == state.selection_id {
3878 return true;
3879 } else {
3880 i += 1;
3881 }
3882 }
3883 false
3884 });
3885 }
3886
3887 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3888 let offset = position.to_offset(buffer);
3889 let (word_range, kind) = buffer.surrounding_word(offset, true);
3890 if offset > word_range.start && kind == Some(CharKind::Word) {
3891 Some(
3892 buffer
3893 .text_for_range(word_range.start..offset)
3894 .collect::<String>(),
3895 )
3896 } else {
3897 None
3898 }
3899 }
3900
3901 pub fn toggle_inlay_hints(
3902 &mut self,
3903 _: &ToggleInlayHints,
3904 _: &mut Window,
3905 cx: &mut Context<Self>,
3906 ) {
3907 self.refresh_inlay_hints(
3908 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3909 cx,
3910 );
3911 }
3912
3913 pub fn inlay_hints_enabled(&self) -> bool {
3914 self.inlay_hint_cache.enabled
3915 }
3916
3917 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3918 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3919 return;
3920 }
3921
3922 let reason_description = reason.description();
3923 let ignore_debounce = matches!(
3924 reason,
3925 InlayHintRefreshReason::SettingsChange(_)
3926 | InlayHintRefreshReason::Toggle(_)
3927 | InlayHintRefreshReason::ExcerptsRemoved(_)
3928 | InlayHintRefreshReason::ModifiersChanged(_)
3929 );
3930 let (invalidate_cache, required_languages) = match reason {
3931 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3932 match self.inlay_hint_cache.modifiers_override(enabled) {
3933 Some(enabled) => {
3934 if enabled {
3935 (InvalidationStrategy::RefreshRequested, None)
3936 } else {
3937 self.splice_inlays(
3938 &self
3939 .visible_inlay_hints(cx)
3940 .iter()
3941 .map(|inlay| inlay.id)
3942 .collect::<Vec<InlayId>>(),
3943 Vec::new(),
3944 cx,
3945 );
3946 return;
3947 }
3948 }
3949 None => return,
3950 }
3951 }
3952 InlayHintRefreshReason::Toggle(enabled) => {
3953 if self.inlay_hint_cache.toggle(enabled) {
3954 if enabled {
3955 (InvalidationStrategy::RefreshRequested, None)
3956 } else {
3957 self.splice_inlays(
3958 &self
3959 .visible_inlay_hints(cx)
3960 .iter()
3961 .map(|inlay| inlay.id)
3962 .collect::<Vec<InlayId>>(),
3963 Vec::new(),
3964 cx,
3965 );
3966 return;
3967 }
3968 } else {
3969 return;
3970 }
3971 }
3972 InlayHintRefreshReason::SettingsChange(new_settings) => {
3973 match self.inlay_hint_cache.update_settings(
3974 &self.buffer,
3975 new_settings,
3976 self.visible_inlay_hints(cx),
3977 cx,
3978 ) {
3979 ControlFlow::Break(Some(InlaySplice {
3980 to_remove,
3981 to_insert,
3982 })) => {
3983 self.splice_inlays(&to_remove, to_insert, cx);
3984 return;
3985 }
3986 ControlFlow::Break(None) => return,
3987 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3988 }
3989 }
3990 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3991 if let Some(InlaySplice {
3992 to_remove,
3993 to_insert,
3994 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3995 {
3996 self.splice_inlays(&to_remove, to_insert, cx);
3997 }
3998 return;
3999 }
4000 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4001 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4002 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4003 }
4004 InlayHintRefreshReason::RefreshRequested => {
4005 (InvalidationStrategy::RefreshRequested, None)
4006 }
4007 };
4008
4009 if let Some(InlaySplice {
4010 to_remove,
4011 to_insert,
4012 }) = self.inlay_hint_cache.spawn_hint_refresh(
4013 reason_description,
4014 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4015 invalidate_cache,
4016 ignore_debounce,
4017 cx,
4018 ) {
4019 self.splice_inlays(&to_remove, to_insert, cx);
4020 }
4021 }
4022
4023 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4024 self.display_map
4025 .read(cx)
4026 .current_inlays()
4027 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4028 .cloned()
4029 .collect()
4030 }
4031
4032 pub fn excerpts_for_inlay_hints_query(
4033 &self,
4034 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4035 cx: &mut Context<Editor>,
4036 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4037 let Some(project) = self.project.as_ref() else {
4038 return HashMap::default();
4039 };
4040 let project = project.read(cx);
4041 let multi_buffer = self.buffer().read(cx);
4042 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4043 let multi_buffer_visible_start = self
4044 .scroll_manager
4045 .anchor()
4046 .anchor
4047 .to_point(&multi_buffer_snapshot);
4048 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4049 multi_buffer_visible_start
4050 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4051 Bias::Left,
4052 );
4053 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4054 multi_buffer_snapshot
4055 .range_to_buffer_ranges(multi_buffer_visible_range)
4056 .into_iter()
4057 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4058 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4059 let buffer_file = project::File::from_dyn(buffer.file())?;
4060 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4061 let worktree_entry = buffer_worktree
4062 .read(cx)
4063 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4064 if worktree_entry.is_ignored {
4065 return None;
4066 }
4067
4068 let language = buffer.language()?;
4069 if let Some(restrict_to_languages) = restrict_to_languages {
4070 if !restrict_to_languages.contains(language) {
4071 return None;
4072 }
4073 }
4074 Some((
4075 excerpt_id,
4076 (
4077 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4078 buffer.version().clone(),
4079 excerpt_visible_range,
4080 ),
4081 ))
4082 })
4083 .collect()
4084 }
4085
4086 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4087 TextLayoutDetails {
4088 text_system: window.text_system().clone(),
4089 editor_style: self.style.clone().unwrap(),
4090 rem_size: window.rem_size(),
4091 scroll_anchor: self.scroll_manager.anchor(),
4092 visible_rows: self.visible_line_count(),
4093 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4094 }
4095 }
4096
4097 pub fn splice_inlays(
4098 &self,
4099 to_remove: &[InlayId],
4100 to_insert: Vec<Inlay>,
4101 cx: &mut Context<Self>,
4102 ) {
4103 self.display_map.update(cx, |display_map, cx| {
4104 display_map.splice_inlays(to_remove, to_insert, cx)
4105 });
4106 cx.notify();
4107 }
4108
4109 fn trigger_on_type_formatting(
4110 &self,
4111 input: String,
4112 window: &mut Window,
4113 cx: &mut Context<Self>,
4114 ) -> Option<Task<Result<()>>> {
4115 if input.len() != 1 {
4116 return None;
4117 }
4118
4119 let project = self.project.as_ref()?;
4120 let position = self.selections.newest_anchor().head();
4121 let (buffer, buffer_position) = self
4122 .buffer
4123 .read(cx)
4124 .text_anchor_for_position(position, cx)?;
4125
4126 let settings = language_settings::language_settings(
4127 buffer
4128 .read(cx)
4129 .language_at(buffer_position)
4130 .map(|l| l.name()),
4131 buffer.read(cx).file(),
4132 cx,
4133 );
4134 if !settings.use_on_type_format {
4135 return None;
4136 }
4137
4138 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4139 // hence we do LSP request & edit on host side only — add formats to host's history.
4140 let push_to_lsp_host_history = true;
4141 // If this is not the host, append its history with new edits.
4142 let push_to_client_history = project.read(cx).is_via_collab();
4143
4144 let on_type_formatting = project.update(cx, |project, cx| {
4145 project.on_type_format(
4146 buffer.clone(),
4147 buffer_position,
4148 input,
4149 push_to_lsp_host_history,
4150 cx,
4151 )
4152 });
4153 Some(cx.spawn_in(window, async move |editor, cx| {
4154 if let Some(transaction) = on_type_formatting.await? {
4155 if push_to_client_history {
4156 buffer
4157 .update(cx, |buffer, _| {
4158 buffer.push_transaction(transaction, Instant::now());
4159 })
4160 .ok();
4161 }
4162 editor.update(cx, |editor, cx| {
4163 editor.refresh_document_highlights(cx);
4164 })?;
4165 }
4166 Ok(())
4167 }))
4168 }
4169
4170 pub fn show_word_completions(
4171 &mut self,
4172 _: &ShowWordCompletions,
4173 window: &mut Window,
4174 cx: &mut Context<Self>,
4175 ) {
4176 self.open_completions_menu(true, None, window, cx);
4177 }
4178
4179 pub fn show_completions(
4180 &mut self,
4181 options: &ShowCompletions,
4182 window: &mut Window,
4183 cx: &mut Context<Self>,
4184 ) {
4185 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4186 }
4187
4188 fn open_completions_menu(
4189 &mut self,
4190 ignore_completion_provider: bool,
4191 trigger: Option<&str>,
4192 window: &mut Window,
4193 cx: &mut Context<Self>,
4194 ) {
4195 if self.pending_rename.is_some() {
4196 return;
4197 }
4198 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4199 return;
4200 }
4201
4202 let position = self.selections.newest_anchor().head();
4203 if position.diff_base_anchor.is_some() {
4204 return;
4205 }
4206 let (buffer, buffer_position) =
4207 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4208 output
4209 } else {
4210 return;
4211 };
4212 let buffer_snapshot = buffer.read(cx).snapshot();
4213 let show_completion_documentation = buffer_snapshot
4214 .settings_at(buffer_position, cx)
4215 .show_completion_documentation;
4216
4217 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4218
4219 let trigger_kind = match trigger {
4220 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4221 CompletionTriggerKind::TRIGGER_CHARACTER
4222 }
4223 _ => CompletionTriggerKind::INVOKED,
4224 };
4225 let completion_context = CompletionContext {
4226 trigger_character: trigger.and_then(|trigger| {
4227 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4228 Some(String::from(trigger))
4229 } else {
4230 None
4231 }
4232 }),
4233 trigger_kind,
4234 };
4235
4236 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4237 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4238 let word_to_exclude = buffer_snapshot
4239 .text_for_range(old_range.clone())
4240 .collect::<String>();
4241 (
4242 buffer_snapshot.anchor_before(old_range.start)
4243 ..buffer_snapshot.anchor_after(old_range.end),
4244 Some(word_to_exclude),
4245 )
4246 } else {
4247 (buffer_position..buffer_position, None)
4248 };
4249
4250 let completion_settings = language_settings(
4251 buffer_snapshot
4252 .language_at(buffer_position)
4253 .map(|language| language.name()),
4254 buffer_snapshot.file(),
4255 cx,
4256 )
4257 .completions;
4258
4259 // The document can be large, so stay in reasonable bounds when searching for words,
4260 // otherwise completion pop-up might be slow to appear.
4261 const WORD_LOOKUP_ROWS: u32 = 5_000;
4262 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4263 let min_word_search = buffer_snapshot.clip_point(
4264 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4265 Bias::Left,
4266 );
4267 let max_word_search = buffer_snapshot.clip_point(
4268 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4269 Bias::Right,
4270 );
4271 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4272 ..buffer_snapshot.point_to_offset(max_word_search);
4273
4274 let provider = self
4275 .completion_provider
4276 .as_ref()
4277 .filter(|_| !ignore_completion_provider);
4278 let skip_digits = query
4279 .as_ref()
4280 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4281
4282 let (mut words, provided_completions) = match provider {
4283 Some(provider) => {
4284 let completions = provider.completions(
4285 position.excerpt_id,
4286 &buffer,
4287 buffer_position,
4288 completion_context,
4289 window,
4290 cx,
4291 );
4292
4293 let words = match completion_settings.words {
4294 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4295 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4296 .background_spawn(async move {
4297 buffer_snapshot.words_in_range(WordsQuery {
4298 fuzzy_contents: None,
4299 range: word_search_range,
4300 skip_digits,
4301 })
4302 }),
4303 };
4304
4305 (words, completions)
4306 }
4307 None => (
4308 cx.background_spawn(async move {
4309 buffer_snapshot.words_in_range(WordsQuery {
4310 fuzzy_contents: None,
4311 range: word_search_range,
4312 skip_digits,
4313 })
4314 }),
4315 Task::ready(Ok(None)),
4316 ),
4317 };
4318
4319 let sort_completions = provider
4320 .as_ref()
4321 .map_or(true, |provider| provider.sort_completions());
4322
4323 let id = post_inc(&mut self.next_completion_id);
4324 let task = cx.spawn_in(window, async move |editor, cx| {
4325 async move {
4326 editor.update(cx, |this, _| {
4327 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4328 })?;
4329
4330 let mut completions = Vec::new();
4331 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4332 completions.extend(provided_completions);
4333 if completion_settings.words == WordsCompletionMode::Fallback {
4334 words = Task::ready(HashMap::default());
4335 }
4336 }
4337
4338 let mut words = words.await;
4339 if let Some(word_to_exclude) = &word_to_exclude {
4340 words.remove(word_to_exclude);
4341 }
4342 for lsp_completion in &completions {
4343 words.remove(&lsp_completion.new_text);
4344 }
4345 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4346 old_range: old_range.clone(),
4347 new_text: word.clone(),
4348 label: CodeLabel::plain(word, None),
4349 icon_path: None,
4350 documentation: None,
4351 source: CompletionSource::BufferWord {
4352 word_range,
4353 resolved: false,
4354 },
4355 confirm: None,
4356 }));
4357
4358 let menu = if completions.is_empty() {
4359 None
4360 } else {
4361 let mut menu = CompletionsMenu::new(
4362 id,
4363 sort_completions,
4364 show_completion_documentation,
4365 ignore_completion_provider,
4366 position,
4367 buffer.clone(),
4368 completions.into(),
4369 );
4370
4371 menu.filter(query.as_deref(), cx.background_executor().clone())
4372 .await;
4373
4374 menu.visible().then_some(menu)
4375 };
4376
4377 editor.update_in(cx, |editor, window, cx| {
4378 match editor.context_menu.borrow().as_ref() {
4379 None => {}
4380 Some(CodeContextMenu::Completions(prev_menu)) => {
4381 if prev_menu.id > id {
4382 return;
4383 }
4384 }
4385 _ => return,
4386 }
4387
4388 if editor.focus_handle.is_focused(window) && menu.is_some() {
4389 let mut menu = menu.unwrap();
4390 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4391
4392 *editor.context_menu.borrow_mut() =
4393 Some(CodeContextMenu::Completions(menu));
4394
4395 if editor.show_edit_predictions_in_menu() {
4396 editor.update_visible_inline_completion(window, cx);
4397 } else {
4398 editor.discard_inline_completion(false, cx);
4399 }
4400
4401 cx.notify();
4402 } else if editor.completion_tasks.len() <= 1 {
4403 // If there are no more completion tasks and the last menu was
4404 // empty, we should hide it.
4405 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4406 // If it was already hidden and we don't show inline
4407 // completions in the menu, we should also show the
4408 // inline-completion when available.
4409 if was_hidden && editor.show_edit_predictions_in_menu() {
4410 editor.update_visible_inline_completion(window, cx);
4411 }
4412 }
4413 })?;
4414
4415 anyhow::Ok(())
4416 }
4417 .log_err()
4418 .await
4419 });
4420
4421 self.completion_tasks.push((id, task));
4422 }
4423
4424 #[cfg(feature = "test-support")]
4425 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4426 let menu = self.context_menu.borrow();
4427 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4428 let completions = menu.completions.borrow();
4429 Some(completions.to_vec())
4430 } else {
4431 None
4432 }
4433 }
4434
4435 pub fn confirm_completion(
4436 &mut self,
4437 action: &ConfirmCompletion,
4438 window: &mut Window,
4439 cx: &mut Context<Self>,
4440 ) -> Option<Task<Result<()>>> {
4441 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4442 }
4443
4444 pub fn compose_completion(
4445 &mut self,
4446 action: &ComposeCompletion,
4447 window: &mut Window,
4448 cx: &mut Context<Self>,
4449 ) -> Option<Task<Result<()>>> {
4450 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4451 }
4452
4453 fn do_completion(
4454 &mut self,
4455 item_ix: Option<usize>,
4456 intent: CompletionIntent,
4457 window: &mut Window,
4458 cx: &mut Context<Editor>,
4459 ) -> Option<Task<Result<()>>> {
4460 use language::ToOffset as _;
4461
4462 let completions_menu =
4463 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4464 menu
4465 } else {
4466 return None;
4467 };
4468
4469 let candidate_id = {
4470 let entries = completions_menu.entries.borrow();
4471 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4472 if self.show_edit_predictions_in_menu() {
4473 self.discard_inline_completion(true, cx);
4474 }
4475 mat.candidate_id
4476 };
4477
4478 let buffer_handle = completions_menu.buffer;
4479 let completion = completions_menu
4480 .completions
4481 .borrow()
4482 .get(candidate_id)?
4483 .clone();
4484 cx.stop_propagation();
4485
4486 let snippet;
4487 let new_text;
4488 if completion.is_snippet() {
4489 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4490 new_text = snippet.as_ref().unwrap().text.clone();
4491 } else {
4492 snippet = None;
4493 new_text = completion.new_text.clone();
4494 };
4495 let selections = self.selections.all::<usize>(cx);
4496 let buffer = buffer_handle.read(cx);
4497 let old_range = completion.old_range.to_offset(buffer);
4498 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4499
4500 let newest_selection = self.selections.newest_anchor();
4501 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4502 return None;
4503 }
4504
4505 let lookbehind = newest_selection
4506 .start
4507 .text_anchor
4508 .to_offset(buffer)
4509 .saturating_sub(old_range.start);
4510 let lookahead = old_range
4511 .end
4512 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4513 let mut common_prefix_len = 0;
4514 for (a, b) in old_text.chars().zip(new_text.chars()) {
4515 if a == b {
4516 common_prefix_len += a.len_utf8();
4517 } else {
4518 break;
4519 }
4520 }
4521
4522 let snapshot = self.buffer.read(cx).snapshot(cx);
4523 let mut range_to_replace: Option<Range<usize>> = None;
4524 let mut ranges = Vec::new();
4525 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4526 for selection in &selections {
4527 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4528 let start = selection.start.saturating_sub(lookbehind);
4529 let end = selection.end + lookahead;
4530 if selection.id == newest_selection.id {
4531 range_to_replace = Some(start + common_prefix_len..end);
4532 }
4533 ranges.push(start + common_prefix_len..end);
4534 } else {
4535 common_prefix_len = 0;
4536 ranges.clear();
4537 ranges.extend(selections.iter().map(|s| {
4538 if s.id == newest_selection.id {
4539 range_to_replace = Some(old_range.clone());
4540 old_range.clone()
4541 } else {
4542 s.start..s.end
4543 }
4544 }));
4545 break;
4546 }
4547 if !self.linked_edit_ranges.is_empty() {
4548 let start_anchor = snapshot.anchor_before(selection.head());
4549 let end_anchor = snapshot.anchor_after(selection.tail());
4550 if let Some(ranges) = self
4551 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4552 {
4553 for (buffer, edits) in ranges {
4554 linked_edits.entry(buffer.clone()).or_default().extend(
4555 edits
4556 .into_iter()
4557 .map(|range| (range, new_text[common_prefix_len..].to_owned())),
4558 );
4559 }
4560 }
4561 }
4562 }
4563 let text = &new_text[common_prefix_len..];
4564
4565 let utf16_range_to_replace = range_to_replace.map(|range| {
4566 let newest_selection = self.selections.newest::<OffsetUtf16>(cx).range();
4567 let selection_start_utf16 = newest_selection.start.0 as isize;
4568
4569 range.start.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4570 ..range.end.to_offset_utf16(&snapshot).0 as isize - selection_start_utf16
4571 });
4572 cx.emit(EditorEvent::InputHandled {
4573 utf16_range_to_replace,
4574 text: text.into(),
4575 });
4576
4577 self.transact(window, cx, |this, window, cx| {
4578 if let Some(mut snippet) = snippet {
4579 snippet.text = text.to_string();
4580 for tabstop in snippet
4581 .tabstops
4582 .iter_mut()
4583 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4584 {
4585 tabstop.start -= common_prefix_len as isize;
4586 tabstop.end -= common_prefix_len as isize;
4587 }
4588
4589 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4590 } else {
4591 this.buffer.update(cx, |buffer, cx| {
4592 let edits = ranges.iter().map(|range| (range.clone(), text));
4593 buffer.edit(edits, this.autoindent_mode.clone(), cx);
4594 });
4595 }
4596 for (buffer, edits) in linked_edits {
4597 buffer.update(cx, |buffer, cx| {
4598 let snapshot = buffer.snapshot();
4599 let edits = edits
4600 .into_iter()
4601 .map(|(range, text)| {
4602 use text::ToPoint as TP;
4603 let end_point = TP::to_point(&range.end, &snapshot);
4604 let start_point = TP::to_point(&range.start, &snapshot);
4605 (start_point..end_point, text)
4606 })
4607 .sorted_by_key(|(range, _)| range.start);
4608 buffer.edit(edits, None, cx);
4609 })
4610 }
4611
4612 this.refresh_inline_completion(true, false, window, cx);
4613 });
4614
4615 let show_new_completions_on_confirm = completion
4616 .confirm
4617 .as_ref()
4618 .map_or(false, |confirm| confirm(intent, window, cx));
4619 if show_new_completions_on_confirm {
4620 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4621 }
4622
4623 let provider = self.completion_provider.as_ref()?;
4624 drop(completion);
4625 let apply_edits = provider.apply_additional_edits_for_completion(
4626 buffer_handle,
4627 completions_menu.completions.clone(),
4628 candidate_id,
4629 true,
4630 cx,
4631 );
4632
4633 let editor_settings = EditorSettings::get_global(cx);
4634 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4635 // After the code completion is finished, users often want to know what signatures are needed.
4636 // so we should automatically call signature_help
4637 self.show_signature_help(&ShowSignatureHelp, window, cx);
4638 }
4639
4640 Some(cx.foreground_executor().spawn(async move {
4641 apply_edits.await?;
4642 Ok(())
4643 }))
4644 }
4645
4646 pub fn toggle_code_actions(
4647 &mut self,
4648 action: &ToggleCodeActions,
4649 window: &mut Window,
4650 cx: &mut Context<Self>,
4651 ) {
4652 let mut context_menu = self.context_menu.borrow_mut();
4653 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4654 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4655 // Toggle if we're selecting the same one
4656 *context_menu = None;
4657 cx.notify();
4658 return;
4659 } else {
4660 // Otherwise, clear it and start a new one
4661 *context_menu = None;
4662 cx.notify();
4663 }
4664 }
4665 drop(context_menu);
4666 let snapshot = self.snapshot(window, cx);
4667 let deployed_from_indicator = action.deployed_from_indicator;
4668 let mut task = self.code_actions_task.take();
4669 let action = action.clone();
4670 cx.spawn_in(window, async move |editor, cx| {
4671 while let Some(prev_task) = task {
4672 prev_task.await.log_err();
4673 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4674 }
4675
4676 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4677 if editor.focus_handle.is_focused(window) {
4678 let multibuffer_point = action
4679 .deployed_from_indicator
4680 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4681 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4682 let (buffer, buffer_row) = snapshot
4683 .buffer_snapshot
4684 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4685 .and_then(|(buffer_snapshot, range)| {
4686 editor
4687 .buffer
4688 .read(cx)
4689 .buffer(buffer_snapshot.remote_id())
4690 .map(|buffer| (buffer, range.start.row))
4691 })?;
4692 let (_, code_actions) = editor
4693 .available_code_actions
4694 .clone()
4695 .and_then(|(location, code_actions)| {
4696 let snapshot = location.buffer.read(cx).snapshot();
4697 let point_range = location.range.to_point(&snapshot);
4698 let point_range = point_range.start.row..=point_range.end.row;
4699 if point_range.contains(&buffer_row) {
4700 Some((location, code_actions))
4701 } else {
4702 None
4703 }
4704 })
4705 .unzip();
4706 let buffer_id = buffer.read(cx).remote_id();
4707 let tasks = editor
4708 .tasks
4709 .get(&(buffer_id, buffer_row))
4710 .map(|t| Arc::new(t.to_owned()));
4711 if tasks.is_none() && code_actions.is_none() {
4712 return None;
4713 }
4714
4715 editor.completion_tasks.clear();
4716 editor.discard_inline_completion(false, cx);
4717 let task_context =
4718 tasks
4719 .as_ref()
4720 .zip(editor.project.clone())
4721 .map(|(tasks, project)| {
4722 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4723 });
4724
4725 Some(cx.spawn_in(window, async move |editor, cx| {
4726 let task_context = match task_context {
4727 Some(task_context) => task_context.await,
4728 None => None,
4729 };
4730 let resolved_tasks =
4731 tasks.zip(task_context).map(|(tasks, task_context)| {
4732 Rc::new(ResolvedTasks {
4733 templates: tasks.resolve(&task_context).collect(),
4734 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4735 multibuffer_point.row,
4736 tasks.column,
4737 )),
4738 })
4739 });
4740 let spawn_straight_away = resolved_tasks
4741 .as_ref()
4742 .map_or(false, |tasks| tasks.templates.len() == 1)
4743 && code_actions
4744 .as_ref()
4745 .map_or(true, |actions| actions.is_empty());
4746 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4747 *editor.context_menu.borrow_mut() =
4748 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4749 buffer,
4750 actions: CodeActionContents {
4751 tasks: resolved_tasks,
4752 actions: code_actions,
4753 },
4754 selected_item: Default::default(),
4755 scroll_handle: UniformListScrollHandle::default(),
4756 deployed_from_indicator,
4757 }));
4758 if spawn_straight_away {
4759 if let Some(task) = editor.confirm_code_action(
4760 &ConfirmCodeAction { item_ix: Some(0) },
4761 window,
4762 cx,
4763 ) {
4764 cx.notify();
4765 return task;
4766 }
4767 }
4768 cx.notify();
4769 Task::ready(Ok(()))
4770 }) {
4771 task.await
4772 } else {
4773 Ok(())
4774 }
4775 }))
4776 } else {
4777 Some(Task::ready(Ok(())))
4778 }
4779 })?;
4780 if let Some(task) = spawned_test_task {
4781 task.await?;
4782 }
4783
4784 Ok::<_, anyhow::Error>(())
4785 })
4786 .detach_and_log_err(cx);
4787 }
4788
4789 pub fn confirm_code_action(
4790 &mut self,
4791 action: &ConfirmCodeAction,
4792 window: &mut Window,
4793 cx: &mut Context<Self>,
4794 ) -> Option<Task<Result<()>>> {
4795 let actions_menu =
4796 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4797 menu
4798 } else {
4799 return None;
4800 };
4801 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4802 let action = actions_menu.actions.get(action_ix)?;
4803 let title = action.label();
4804 let buffer = actions_menu.buffer;
4805 let workspace = self.workspace()?;
4806
4807 match action {
4808 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4809 workspace.update(cx, |workspace, cx| {
4810 workspace::tasks::schedule_resolved_task(
4811 workspace,
4812 task_source_kind,
4813 resolved_task,
4814 false,
4815 cx,
4816 );
4817
4818 Some(Task::ready(Ok(())))
4819 })
4820 }
4821 CodeActionsItem::CodeAction {
4822 excerpt_id,
4823 action,
4824 provider,
4825 } => {
4826 let apply_code_action =
4827 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4828 let workspace = workspace.downgrade();
4829 Some(cx.spawn_in(window, async move |editor, cx| {
4830 let project_transaction = apply_code_action.await?;
4831 Self::open_project_transaction(
4832 &editor,
4833 workspace,
4834 project_transaction,
4835 title,
4836 cx,
4837 )
4838 .await
4839 }))
4840 }
4841 }
4842 }
4843
4844 pub async fn open_project_transaction(
4845 this: &WeakEntity<Editor>,
4846 workspace: WeakEntity<Workspace>,
4847 transaction: ProjectTransaction,
4848 title: String,
4849 cx: &mut AsyncWindowContext,
4850 ) -> Result<()> {
4851 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4852 cx.update(|_, cx| {
4853 entries.sort_unstable_by_key(|(buffer, _)| {
4854 buffer.read(cx).file().map(|f| f.path().clone())
4855 });
4856 })?;
4857
4858 // If the project transaction's edits are all contained within this editor, then
4859 // avoid opening a new editor to display them.
4860
4861 if let Some((buffer, transaction)) = entries.first() {
4862 if entries.len() == 1 {
4863 let excerpt = this.update(cx, |editor, cx| {
4864 editor
4865 .buffer()
4866 .read(cx)
4867 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4868 })?;
4869 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4870 if excerpted_buffer == *buffer {
4871 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
4872 let excerpt_range = excerpt_range.to_offset(buffer);
4873 buffer
4874 .edited_ranges_for_transaction::<usize>(transaction)
4875 .all(|range| {
4876 excerpt_range.start <= range.start
4877 && excerpt_range.end >= range.end
4878 })
4879 })?;
4880
4881 if all_edits_within_excerpt {
4882 return Ok(());
4883 }
4884 }
4885 }
4886 }
4887 } else {
4888 return Ok(());
4889 }
4890
4891 let mut ranges_to_highlight = Vec::new();
4892 let excerpt_buffer = cx.new(|cx| {
4893 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4894 for (buffer_handle, transaction) in &entries {
4895 let buffer = buffer_handle.read(cx);
4896 ranges_to_highlight.extend(
4897 multibuffer.push_excerpts_with_context_lines(
4898 buffer_handle.clone(),
4899 buffer
4900 .edited_ranges_for_transaction::<usize>(transaction)
4901 .collect(),
4902 DEFAULT_MULTIBUFFER_CONTEXT,
4903 cx,
4904 ),
4905 );
4906 }
4907 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4908 multibuffer
4909 })?;
4910
4911 workspace.update_in(cx, |workspace, window, cx| {
4912 let project = workspace.project().clone();
4913 let editor =
4914 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
4915 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4916 editor.update(cx, |editor, cx| {
4917 editor.highlight_background::<Self>(
4918 &ranges_to_highlight,
4919 |theme| theme.editor_highlighted_line_background,
4920 cx,
4921 );
4922 });
4923 })?;
4924
4925 Ok(())
4926 }
4927
4928 pub fn clear_code_action_providers(&mut self) {
4929 self.code_action_providers.clear();
4930 self.available_code_actions.take();
4931 }
4932
4933 pub fn add_code_action_provider(
4934 &mut self,
4935 provider: Rc<dyn CodeActionProvider>,
4936 window: &mut Window,
4937 cx: &mut Context<Self>,
4938 ) {
4939 if self
4940 .code_action_providers
4941 .iter()
4942 .any(|existing_provider| existing_provider.id() == provider.id())
4943 {
4944 return;
4945 }
4946
4947 self.code_action_providers.push(provider);
4948 self.refresh_code_actions(window, cx);
4949 }
4950
4951 pub fn remove_code_action_provider(
4952 &mut self,
4953 id: Arc<str>,
4954 window: &mut Window,
4955 cx: &mut Context<Self>,
4956 ) {
4957 self.code_action_providers
4958 .retain(|provider| provider.id() != id);
4959 self.refresh_code_actions(window, cx);
4960 }
4961
4962 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4963 let buffer = self.buffer.read(cx);
4964 let newest_selection = self.selections.newest_anchor().clone();
4965 if newest_selection.head().diff_base_anchor.is_some() {
4966 return None;
4967 }
4968 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4969 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4970 if start_buffer != end_buffer {
4971 return None;
4972 }
4973
4974 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
4975 cx.background_executor()
4976 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4977 .await;
4978
4979 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
4980 let providers = this.code_action_providers.clone();
4981 let tasks = this
4982 .code_action_providers
4983 .iter()
4984 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4985 .collect::<Vec<_>>();
4986 (providers, tasks)
4987 })?;
4988
4989 let mut actions = Vec::new();
4990 for (provider, provider_actions) in
4991 providers.into_iter().zip(future::join_all(tasks).await)
4992 {
4993 if let Some(provider_actions) = provider_actions.log_err() {
4994 actions.extend(provider_actions.into_iter().map(|action| {
4995 AvailableCodeAction {
4996 excerpt_id: newest_selection.start.excerpt_id,
4997 action,
4998 provider: provider.clone(),
4999 }
5000 }));
5001 }
5002 }
5003
5004 this.update(cx, |this, cx| {
5005 this.available_code_actions = if actions.is_empty() {
5006 None
5007 } else {
5008 Some((
5009 Location {
5010 buffer: start_buffer,
5011 range: start..end,
5012 },
5013 actions.into(),
5014 ))
5015 };
5016 cx.notify();
5017 })
5018 }));
5019 None
5020 }
5021
5022 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5023 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5024 self.show_git_blame_inline = false;
5025
5026 self.show_git_blame_inline_delay_task =
5027 Some(cx.spawn_in(window, async move |this, cx| {
5028 cx.background_executor().timer(delay).await;
5029
5030 this.update(cx, |this, cx| {
5031 this.show_git_blame_inline = true;
5032 cx.notify();
5033 })
5034 .log_err();
5035 }));
5036 }
5037 }
5038
5039 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5040 if self.pending_rename.is_some() {
5041 return None;
5042 }
5043
5044 let provider = self.semantics_provider.clone()?;
5045 let buffer = self.buffer.read(cx);
5046 let newest_selection = self.selections.newest_anchor().clone();
5047 let cursor_position = newest_selection.head();
5048 let (cursor_buffer, cursor_buffer_position) =
5049 buffer.text_anchor_for_position(cursor_position, cx)?;
5050 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5051 if cursor_buffer != tail_buffer {
5052 return None;
5053 }
5054 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5055 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5056 cx.background_executor()
5057 .timer(Duration::from_millis(debounce))
5058 .await;
5059
5060 let highlights = if let Some(highlights) = cx
5061 .update(|cx| {
5062 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5063 })
5064 .ok()
5065 .flatten()
5066 {
5067 highlights.await.log_err()
5068 } else {
5069 None
5070 };
5071
5072 if let Some(highlights) = highlights {
5073 this.update(cx, |this, cx| {
5074 if this.pending_rename.is_some() {
5075 return;
5076 }
5077
5078 let buffer_id = cursor_position.buffer_id;
5079 let buffer = this.buffer.read(cx);
5080 if !buffer
5081 .text_anchor_for_position(cursor_position, cx)
5082 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5083 {
5084 return;
5085 }
5086
5087 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5088 let mut write_ranges = Vec::new();
5089 let mut read_ranges = Vec::new();
5090 for highlight in highlights {
5091 for (excerpt_id, excerpt_range) in
5092 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5093 {
5094 let start = highlight
5095 .range
5096 .start
5097 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5098 let end = highlight
5099 .range
5100 .end
5101 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5102 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5103 continue;
5104 }
5105
5106 let range = Anchor {
5107 buffer_id,
5108 excerpt_id,
5109 text_anchor: start,
5110 diff_base_anchor: None,
5111 }..Anchor {
5112 buffer_id,
5113 excerpt_id,
5114 text_anchor: end,
5115 diff_base_anchor: None,
5116 };
5117 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5118 write_ranges.push(range);
5119 } else {
5120 read_ranges.push(range);
5121 }
5122 }
5123 }
5124
5125 this.highlight_background::<DocumentHighlightRead>(
5126 &read_ranges,
5127 |theme| theme.editor_document_highlight_read_background,
5128 cx,
5129 );
5130 this.highlight_background::<DocumentHighlightWrite>(
5131 &write_ranges,
5132 |theme| theme.editor_document_highlight_write_background,
5133 cx,
5134 );
5135 cx.notify();
5136 })
5137 .log_err();
5138 }
5139 }));
5140 None
5141 }
5142
5143 pub fn refresh_selected_text_highlights(
5144 &mut self,
5145 window: &mut Window,
5146 cx: &mut Context<Editor>,
5147 ) {
5148 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5149 return;
5150 }
5151 self.selection_highlight_task.take();
5152 if !EditorSettings::get_global(cx).selection_highlight {
5153 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5154 return;
5155 }
5156 if self.selections.count() != 1 || self.selections.line_mode {
5157 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5158 return;
5159 }
5160 let selection = self.selections.newest::<Point>(cx);
5161 if selection.is_empty() || selection.start.row != selection.end.row {
5162 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5163 return;
5164 }
5165 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5166 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5167 cx.background_executor()
5168 .timer(Duration::from_millis(debounce))
5169 .await;
5170 let Some(Some(matches_task)) = editor
5171 .update_in(cx, |editor, _, cx| {
5172 if editor.selections.count() != 1 || editor.selections.line_mode {
5173 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5174 return None;
5175 }
5176 let selection = editor.selections.newest::<Point>(cx);
5177 if selection.is_empty() || selection.start.row != selection.end.row {
5178 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5179 return None;
5180 }
5181 let buffer = editor.buffer().read(cx).snapshot(cx);
5182 let query = buffer.text_for_range(selection.range()).collect::<String>();
5183 if query.trim().is_empty() {
5184 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5185 return None;
5186 }
5187 Some(cx.background_spawn(async move {
5188 let mut ranges = Vec::new();
5189 let selection_anchors = selection.range().to_anchors(&buffer);
5190 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5191 for (search_buffer, search_range, excerpt_id) in
5192 buffer.range_to_buffer_ranges(range)
5193 {
5194 ranges.extend(
5195 project::search::SearchQuery::text(
5196 query.clone(),
5197 false,
5198 false,
5199 false,
5200 Default::default(),
5201 Default::default(),
5202 None,
5203 )
5204 .unwrap()
5205 .search(search_buffer, Some(search_range.clone()))
5206 .await
5207 .into_iter()
5208 .filter_map(
5209 |match_range| {
5210 let start = search_buffer.anchor_after(
5211 search_range.start + match_range.start,
5212 );
5213 let end = search_buffer.anchor_before(
5214 search_range.start + match_range.end,
5215 );
5216 let range = Anchor::range_in_buffer(
5217 excerpt_id,
5218 search_buffer.remote_id(),
5219 start..end,
5220 );
5221 (range != selection_anchors).then_some(range)
5222 },
5223 ),
5224 );
5225 }
5226 }
5227 ranges
5228 }))
5229 })
5230 .log_err()
5231 else {
5232 return;
5233 };
5234 let matches = matches_task.await;
5235 editor
5236 .update_in(cx, |editor, _, cx| {
5237 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5238 if !matches.is_empty() {
5239 editor.highlight_background::<SelectedTextHighlight>(
5240 &matches,
5241 |theme| theme.editor_document_highlight_bracket_background,
5242 cx,
5243 )
5244 }
5245 })
5246 .log_err();
5247 }));
5248 }
5249
5250 pub fn refresh_inline_completion(
5251 &mut self,
5252 debounce: bool,
5253 user_requested: bool,
5254 window: &mut Window,
5255 cx: &mut Context<Self>,
5256 ) -> Option<()> {
5257 let provider = self.edit_prediction_provider()?;
5258 let cursor = self.selections.newest_anchor().head();
5259 let (buffer, cursor_buffer_position) =
5260 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5261
5262 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5263 self.discard_inline_completion(false, cx);
5264 return None;
5265 }
5266
5267 if !user_requested
5268 && (!self.should_show_edit_predictions()
5269 || !self.is_focused(window)
5270 || buffer.read(cx).is_empty())
5271 {
5272 self.discard_inline_completion(false, cx);
5273 return None;
5274 }
5275
5276 self.update_visible_inline_completion(window, cx);
5277 provider.refresh(
5278 self.project.clone(),
5279 buffer,
5280 cursor_buffer_position,
5281 debounce,
5282 cx,
5283 );
5284 Some(())
5285 }
5286
5287 fn show_edit_predictions_in_menu(&self) -> bool {
5288 match self.edit_prediction_settings {
5289 EditPredictionSettings::Disabled => false,
5290 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5291 }
5292 }
5293
5294 pub fn edit_predictions_enabled(&self) -> bool {
5295 match self.edit_prediction_settings {
5296 EditPredictionSettings::Disabled => false,
5297 EditPredictionSettings::Enabled { .. } => true,
5298 }
5299 }
5300
5301 fn edit_prediction_requires_modifier(&self) -> bool {
5302 match self.edit_prediction_settings {
5303 EditPredictionSettings::Disabled => false,
5304 EditPredictionSettings::Enabled {
5305 preview_requires_modifier,
5306 ..
5307 } => preview_requires_modifier,
5308 }
5309 }
5310
5311 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5312 if self.edit_prediction_provider.is_none() {
5313 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5314 } else {
5315 let selection = self.selections.newest_anchor();
5316 let cursor = selection.head();
5317
5318 if let Some((buffer, cursor_buffer_position)) =
5319 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5320 {
5321 self.edit_prediction_settings =
5322 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5323 }
5324 }
5325 }
5326
5327 fn edit_prediction_settings_at_position(
5328 &self,
5329 buffer: &Entity<Buffer>,
5330 buffer_position: language::Anchor,
5331 cx: &App,
5332 ) -> EditPredictionSettings {
5333 if self.mode != EditorMode::Full
5334 || !self.show_inline_completions_override.unwrap_or(true)
5335 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5336 {
5337 return EditPredictionSettings::Disabled;
5338 }
5339
5340 let buffer = buffer.read(cx);
5341
5342 let file = buffer.file();
5343
5344 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5345 return EditPredictionSettings::Disabled;
5346 };
5347
5348 let by_provider = matches!(
5349 self.menu_inline_completions_policy,
5350 MenuInlineCompletionsPolicy::ByProvider
5351 );
5352
5353 let show_in_menu = by_provider
5354 && self
5355 .edit_prediction_provider
5356 .as_ref()
5357 .map_or(false, |provider| {
5358 provider.provider.show_completions_in_menu()
5359 });
5360
5361 let preview_requires_modifier =
5362 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5363
5364 EditPredictionSettings::Enabled {
5365 show_in_menu,
5366 preview_requires_modifier,
5367 }
5368 }
5369
5370 fn should_show_edit_predictions(&self) -> bool {
5371 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5372 }
5373
5374 pub fn edit_prediction_preview_is_active(&self) -> bool {
5375 matches!(
5376 self.edit_prediction_preview,
5377 EditPredictionPreview::Active { .. }
5378 )
5379 }
5380
5381 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5382 let cursor = self.selections.newest_anchor().head();
5383 if let Some((buffer, cursor_position)) =
5384 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5385 {
5386 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5387 } else {
5388 false
5389 }
5390 }
5391
5392 fn edit_predictions_enabled_in_buffer(
5393 &self,
5394 buffer: &Entity<Buffer>,
5395 buffer_position: language::Anchor,
5396 cx: &App,
5397 ) -> bool {
5398 maybe!({
5399 if self.read_only(cx) {
5400 return Some(false);
5401 }
5402 let provider = self.edit_prediction_provider()?;
5403 if !provider.is_enabled(&buffer, buffer_position, cx) {
5404 return Some(false);
5405 }
5406 let buffer = buffer.read(cx);
5407 let Some(file) = buffer.file() else {
5408 return Some(true);
5409 };
5410 let settings = all_language_settings(Some(file), cx);
5411 Some(settings.edit_predictions_enabled_for_file(file, cx))
5412 })
5413 .unwrap_or(false)
5414 }
5415
5416 fn cycle_inline_completion(
5417 &mut self,
5418 direction: Direction,
5419 window: &mut Window,
5420 cx: &mut Context<Self>,
5421 ) -> Option<()> {
5422 let provider = self.edit_prediction_provider()?;
5423 let cursor = self.selections.newest_anchor().head();
5424 let (buffer, cursor_buffer_position) =
5425 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5426 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5427 return None;
5428 }
5429
5430 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5431 self.update_visible_inline_completion(window, cx);
5432
5433 Some(())
5434 }
5435
5436 pub fn show_inline_completion(
5437 &mut self,
5438 _: &ShowEditPrediction,
5439 window: &mut Window,
5440 cx: &mut Context<Self>,
5441 ) {
5442 if !self.has_active_inline_completion() {
5443 self.refresh_inline_completion(false, true, window, cx);
5444 return;
5445 }
5446
5447 self.update_visible_inline_completion(window, cx);
5448 }
5449
5450 pub fn display_cursor_names(
5451 &mut self,
5452 _: &DisplayCursorNames,
5453 window: &mut Window,
5454 cx: &mut Context<Self>,
5455 ) {
5456 self.show_cursor_names(window, cx);
5457 }
5458
5459 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5460 self.show_cursor_names = true;
5461 cx.notify();
5462 cx.spawn_in(window, async move |this, cx| {
5463 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5464 this.update(cx, |this, cx| {
5465 this.show_cursor_names = false;
5466 cx.notify()
5467 })
5468 .ok()
5469 })
5470 .detach();
5471 }
5472
5473 pub fn next_edit_prediction(
5474 &mut self,
5475 _: &NextEditPrediction,
5476 window: &mut Window,
5477 cx: &mut Context<Self>,
5478 ) {
5479 if self.has_active_inline_completion() {
5480 self.cycle_inline_completion(Direction::Next, window, cx);
5481 } else {
5482 let is_copilot_disabled = self
5483 .refresh_inline_completion(false, true, window, cx)
5484 .is_none();
5485 if is_copilot_disabled {
5486 cx.propagate();
5487 }
5488 }
5489 }
5490
5491 pub fn previous_edit_prediction(
5492 &mut self,
5493 _: &PreviousEditPrediction,
5494 window: &mut Window,
5495 cx: &mut Context<Self>,
5496 ) {
5497 if self.has_active_inline_completion() {
5498 self.cycle_inline_completion(Direction::Prev, window, cx);
5499 } else {
5500 let is_copilot_disabled = self
5501 .refresh_inline_completion(false, true, window, cx)
5502 .is_none();
5503 if is_copilot_disabled {
5504 cx.propagate();
5505 }
5506 }
5507 }
5508
5509 pub fn accept_edit_prediction(
5510 &mut self,
5511 _: &AcceptEditPrediction,
5512 window: &mut Window,
5513 cx: &mut Context<Self>,
5514 ) {
5515 if self.show_edit_predictions_in_menu() {
5516 self.hide_context_menu(window, cx);
5517 }
5518
5519 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5520 return;
5521 };
5522
5523 self.report_inline_completion_event(
5524 active_inline_completion.completion_id.clone(),
5525 true,
5526 cx,
5527 );
5528
5529 match &active_inline_completion.completion {
5530 InlineCompletion::Move { target, .. } => {
5531 let target = *target;
5532
5533 if let Some(position_map) = &self.last_position_map {
5534 if position_map
5535 .visible_row_range
5536 .contains(&target.to_display_point(&position_map.snapshot).row())
5537 || !self.edit_prediction_requires_modifier()
5538 {
5539 self.unfold_ranges(&[target..target], true, false, cx);
5540 // Note that this is also done in vim's handler of the Tab action.
5541 self.change_selections(
5542 Some(Autoscroll::newest()),
5543 window,
5544 cx,
5545 |selections| {
5546 selections.select_anchor_ranges([target..target]);
5547 },
5548 );
5549 self.clear_row_highlights::<EditPredictionPreview>();
5550
5551 self.edit_prediction_preview
5552 .set_previous_scroll_position(None);
5553 } else {
5554 self.edit_prediction_preview
5555 .set_previous_scroll_position(Some(
5556 position_map.snapshot.scroll_anchor,
5557 ));
5558
5559 self.highlight_rows::<EditPredictionPreview>(
5560 target..target,
5561 cx.theme().colors().editor_highlighted_line_background,
5562 true,
5563 cx,
5564 );
5565 self.request_autoscroll(Autoscroll::fit(), cx);
5566 }
5567 }
5568 }
5569 InlineCompletion::Edit { edits, .. } => {
5570 if let Some(provider) = self.edit_prediction_provider() {
5571 provider.accept(cx);
5572 }
5573
5574 let snapshot = self.buffer.read(cx).snapshot(cx);
5575 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5576
5577 self.buffer.update(cx, |buffer, cx| {
5578 buffer.edit(edits.iter().cloned(), None, cx)
5579 });
5580
5581 self.change_selections(None, window, cx, |s| {
5582 s.select_anchor_ranges([last_edit_end..last_edit_end])
5583 });
5584
5585 self.update_visible_inline_completion(window, cx);
5586 if self.active_inline_completion.is_none() {
5587 self.refresh_inline_completion(true, true, window, cx);
5588 }
5589
5590 cx.notify();
5591 }
5592 }
5593
5594 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5595 }
5596
5597 pub fn accept_partial_inline_completion(
5598 &mut self,
5599 _: &AcceptPartialEditPrediction,
5600 window: &mut Window,
5601 cx: &mut Context<Self>,
5602 ) {
5603 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5604 return;
5605 };
5606 if self.selections.count() != 1 {
5607 return;
5608 }
5609
5610 self.report_inline_completion_event(
5611 active_inline_completion.completion_id.clone(),
5612 true,
5613 cx,
5614 );
5615
5616 match &active_inline_completion.completion {
5617 InlineCompletion::Move { target, .. } => {
5618 let target = *target;
5619 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5620 selections.select_anchor_ranges([target..target]);
5621 });
5622 }
5623 InlineCompletion::Edit { edits, .. } => {
5624 // Find an insertion that starts at the cursor position.
5625 let snapshot = self.buffer.read(cx).snapshot(cx);
5626 let cursor_offset = self.selections.newest::<usize>(cx).head();
5627 let insertion = edits.iter().find_map(|(range, text)| {
5628 let range = range.to_offset(&snapshot);
5629 if range.is_empty() && range.start == cursor_offset {
5630 Some(text)
5631 } else {
5632 None
5633 }
5634 });
5635
5636 if let Some(text) = insertion {
5637 let mut partial_completion = text
5638 .chars()
5639 .by_ref()
5640 .take_while(|c| c.is_alphabetic())
5641 .collect::<String>();
5642 if partial_completion.is_empty() {
5643 partial_completion = text
5644 .chars()
5645 .by_ref()
5646 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5647 .collect::<String>();
5648 }
5649
5650 cx.emit(EditorEvent::InputHandled {
5651 utf16_range_to_replace: None,
5652 text: partial_completion.clone().into(),
5653 });
5654
5655 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5656
5657 self.refresh_inline_completion(true, true, window, cx);
5658 cx.notify();
5659 } else {
5660 self.accept_edit_prediction(&Default::default(), window, cx);
5661 }
5662 }
5663 }
5664 }
5665
5666 fn discard_inline_completion(
5667 &mut self,
5668 should_report_inline_completion_event: bool,
5669 cx: &mut Context<Self>,
5670 ) -> bool {
5671 if should_report_inline_completion_event {
5672 let completion_id = self
5673 .active_inline_completion
5674 .as_ref()
5675 .and_then(|active_completion| active_completion.completion_id.clone());
5676
5677 self.report_inline_completion_event(completion_id, false, cx);
5678 }
5679
5680 if let Some(provider) = self.edit_prediction_provider() {
5681 provider.discard(cx);
5682 }
5683
5684 self.take_active_inline_completion(cx)
5685 }
5686
5687 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5688 let Some(provider) = self.edit_prediction_provider() else {
5689 return;
5690 };
5691
5692 let Some((_, buffer, _)) = self
5693 .buffer
5694 .read(cx)
5695 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5696 else {
5697 return;
5698 };
5699
5700 let extension = buffer
5701 .read(cx)
5702 .file()
5703 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5704
5705 let event_type = match accepted {
5706 true => "Edit Prediction Accepted",
5707 false => "Edit Prediction Discarded",
5708 };
5709 telemetry::event!(
5710 event_type,
5711 provider = provider.name(),
5712 prediction_id = id,
5713 suggestion_accepted = accepted,
5714 file_extension = extension,
5715 );
5716 }
5717
5718 pub fn has_active_inline_completion(&self) -> bool {
5719 self.active_inline_completion.is_some()
5720 }
5721
5722 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5723 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5724 return false;
5725 };
5726
5727 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5728 self.clear_highlights::<InlineCompletionHighlight>(cx);
5729 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5730 true
5731 }
5732
5733 /// Returns true when we're displaying the edit prediction popover below the cursor
5734 /// like we are not previewing and the LSP autocomplete menu is visible
5735 /// or we are in `when_holding_modifier` mode.
5736 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5737 if self.edit_prediction_preview_is_active()
5738 || !self.show_edit_predictions_in_menu()
5739 || !self.edit_predictions_enabled()
5740 {
5741 return false;
5742 }
5743
5744 if self.has_visible_completions_menu() {
5745 return true;
5746 }
5747
5748 has_completion && self.edit_prediction_requires_modifier()
5749 }
5750
5751 fn handle_modifiers_changed(
5752 &mut self,
5753 modifiers: Modifiers,
5754 position_map: &PositionMap,
5755 window: &mut Window,
5756 cx: &mut Context<Self>,
5757 ) {
5758 if self.show_edit_predictions_in_menu() {
5759 self.update_edit_prediction_preview(&modifiers, window, cx);
5760 }
5761
5762 self.update_selection_mode(&modifiers, position_map, window, cx);
5763
5764 let mouse_position = window.mouse_position();
5765 if !position_map.text_hitbox.is_hovered(window) {
5766 return;
5767 }
5768
5769 self.update_hovered_link(
5770 position_map.point_for_position(mouse_position),
5771 &position_map.snapshot,
5772 modifiers,
5773 window,
5774 cx,
5775 )
5776 }
5777
5778 fn update_selection_mode(
5779 &mut self,
5780 modifiers: &Modifiers,
5781 position_map: &PositionMap,
5782 window: &mut Window,
5783 cx: &mut Context<Self>,
5784 ) {
5785 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5786 return;
5787 }
5788
5789 let mouse_position = window.mouse_position();
5790 let point_for_position = position_map.point_for_position(mouse_position);
5791 let position = point_for_position.previous_valid;
5792
5793 self.select(
5794 SelectPhase::BeginColumnar {
5795 position,
5796 reset: false,
5797 goal_column: point_for_position.exact_unclipped.column(),
5798 },
5799 window,
5800 cx,
5801 );
5802 }
5803
5804 fn update_edit_prediction_preview(
5805 &mut self,
5806 modifiers: &Modifiers,
5807 window: &mut Window,
5808 cx: &mut Context<Self>,
5809 ) {
5810 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5811 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5812 return;
5813 };
5814
5815 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5816 if matches!(
5817 self.edit_prediction_preview,
5818 EditPredictionPreview::Inactive { .. }
5819 ) {
5820 self.edit_prediction_preview = EditPredictionPreview::Active {
5821 previous_scroll_position: None,
5822 since: Instant::now(),
5823 };
5824
5825 self.update_visible_inline_completion(window, cx);
5826 cx.notify();
5827 }
5828 } else if let EditPredictionPreview::Active {
5829 previous_scroll_position,
5830 since,
5831 } = self.edit_prediction_preview
5832 {
5833 if let (Some(previous_scroll_position), Some(position_map)) =
5834 (previous_scroll_position, self.last_position_map.as_ref())
5835 {
5836 self.set_scroll_position(
5837 previous_scroll_position
5838 .scroll_position(&position_map.snapshot.display_snapshot),
5839 window,
5840 cx,
5841 );
5842 }
5843
5844 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5845 released_too_fast: since.elapsed() < Duration::from_millis(200),
5846 };
5847 self.clear_row_highlights::<EditPredictionPreview>();
5848 self.update_visible_inline_completion(window, cx);
5849 cx.notify();
5850 }
5851 }
5852
5853 fn update_visible_inline_completion(
5854 &mut self,
5855 _window: &mut Window,
5856 cx: &mut Context<Self>,
5857 ) -> Option<()> {
5858 let selection = self.selections.newest_anchor();
5859 let cursor = selection.head();
5860 let multibuffer = self.buffer.read(cx).snapshot(cx);
5861 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5862 let excerpt_id = cursor.excerpt_id;
5863
5864 let show_in_menu = self.show_edit_predictions_in_menu();
5865 let completions_menu_has_precedence = !show_in_menu
5866 && (self.context_menu.borrow().is_some()
5867 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5868
5869 if completions_menu_has_precedence
5870 || !offset_selection.is_empty()
5871 || self
5872 .active_inline_completion
5873 .as_ref()
5874 .map_or(false, |completion| {
5875 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5876 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5877 !invalidation_range.contains(&offset_selection.head())
5878 })
5879 {
5880 self.discard_inline_completion(false, cx);
5881 return None;
5882 }
5883
5884 self.take_active_inline_completion(cx);
5885 let Some(provider) = self.edit_prediction_provider() else {
5886 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5887 return None;
5888 };
5889
5890 let (buffer, cursor_buffer_position) =
5891 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5892
5893 self.edit_prediction_settings =
5894 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5895
5896 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5897
5898 if self.edit_prediction_indent_conflict {
5899 let cursor_point = cursor.to_point(&multibuffer);
5900
5901 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5902
5903 if let Some((_, indent)) = indents.iter().next() {
5904 if indent.len == cursor_point.column {
5905 self.edit_prediction_indent_conflict = false;
5906 }
5907 }
5908 }
5909
5910 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5911 let edits = inline_completion
5912 .edits
5913 .into_iter()
5914 .flat_map(|(range, new_text)| {
5915 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5916 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5917 Some((start..end, new_text))
5918 })
5919 .collect::<Vec<_>>();
5920 if edits.is_empty() {
5921 return None;
5922 }
5923
5924 let first_edit_start = edits.first().unwrap().0.start;
5925 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5926 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5927
5928 let last_edit_end = edits.last().unwrap().0.end;
5929 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5930 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5931
5932 let cursor_row = cursor.to_point(&multibuffer).row;
5933
5934 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5935
5936 let mut inlay_ids = Vec::new();
5937 let invalidation_row_range;
5938 let move_invalidation_row_range = if cursor_row < edit_start_row {
5939 Some(cursor_row..edit_end_row)
5940 } else if cursor_row > edit_end_row {
5941 Some(edit_start_row..cursor_row)
5942 } else {
5943 None
5944 };
5945 let is_move =
5946 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5947 let completion = if is_move {
5948 invalidation_row_range =
5949 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5950 let target = first_edit_start;
5951 InlineCompletion::Move { target, snapshot }
5952 } else {
5953 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5954 && !self.inline_completions_hidden_for_vim_mode;
5955
5956 if show_completions_in_buffer {
5957 if edits
5958 .iter()
5959 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5960 {
5961 let mut inlays = Vec::new();
5962 for (range, new_text) in &edits {
5963 let inlay = Inlay::inline_completion(
5964 post_inc(&mut self.next_inlay_id),
5965 range.start,
5966 new_text.as_str(),
5967 );
5968 inlay_ids.push(inlay.id);
5969 inlays.push(inlay);
5970 }
5971
5972 self.splice_inlays(&[], inlays, cx);
5973 } else {
5974 let background_color = cx.theme().status().deleted_background;
5975 self.highlight_text::<InlineCompletionHighlight>(
5976 edits.iter().map(|(range, _)| range.clone()).collect(),
5977 HighlightStyle {
5978 background_color: Some(background_color),
5979 ..Default::default()
5980 },
5981 cx,
5982 );
5983 }
5984 }
5985
5986 invalidation_row_range = edit_start_row..edit_end_row;
5987
5988 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5989 if provider.show_tab_accept_marker() {
5990 EditDisplayMode::TabAccept
5991 } else {
5992 EditDisplayMode::Inline
5993 }
5994 } else {
5995 EditDisplayMode::DiffPopover
5996 };
5997
5998 InlineCompletion::Edit {
5999 edits,
6000 edit_preview: inline_completion.edit_preview,
6001 display_mode,
6002 snapshot,
6003 }
6004 };
6005
6006 let invalidation_range = multibuffer
6007 .anchor_before(Point::new(invalidation_row_range.start, 0))
6008 ..multibuffer.anchor_after(Point::new(
6009 invalidation_row_range.end,
6010 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6011 ));
6012
6013 self.stale_inline_completion_in_menu = None;
6014 self.active_inline_completion = Some(InlineCompletionState {
6015 inlay_ids,
6016 completion,
6017 completion_id: inline_completion.id,
6018 invalidation_range,
6019 });
6020
6021 cx.notify();
6022
6023 Some(())
6024 }
6025
6026 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6027 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6028 }
6029
6030 fn render_code_actions_indicator(
6031 &self,
6032 _style: &EditorStyle,
6033 row: DisplayRow,
6034 is_active: bool,
6035 breakpoint: Option<&(Anchor, Breakpoint)>,
6036 cx: &mut Context<Self>,
6037 ) -> Option<IconButton> {
6038 let color = Color::Muted;
6039 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6040
6041 if self.available_code_actions.is_some() {
6042 Some(
6043 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6044 .shape(ui::IconButtonShape::Square)
6045 .icon_size(IconSize::XSmall)
6046 .icon_color(color)
6047 .toggle_state(is_active)
6048 .tooltip({
6049 let focus_handle = self.focus_handle.clone();
6050 move |window, cx| {
6051 Tooltip::for_action_in(
6052 "Toggle Code Actions",
6053 &ToggleCodeActions {
6054 deployed_from_indicator: None,
6055 },
6056 &focus_handle,
6057 window,
6058 cx,
6059 )
6060 }
6061 })
6062 .on_click(cx.listener(move |editor, _e, window, cx| {
6063 window.focus(&editor.focus_handle(cx));
6064 editor.toggle_code_actions(
6065 &ToggleCodeActions {
6066 deployed_from_indicator: Some(row),
6067 },
6068 window,
6069 cx,
6070 );
6071 }))
6072 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6073 editor.set_breakpoint_context_menu(
6074 row,
6075 position,
6076 event.down.position,
6077 window,
6078 cx,
6079 );
6080 })),
6081 )
6082 } else {
6083 None
6084 }
6085 }
6086
6087 fn clear_tasks(&mut self) {
6088 self.tasks.clear()
6089 }
6090
6091 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6092 if self.tasks.insert(key, value).is_some() {
6093 // This case should hopefully be rare, but just in case...
6094 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
6095 }
6096 }
6097
6098 /// Get all display points of breakpoints that will be rendered within editor
6099 ///
6100 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6101 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6102 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6103 fn active_breakpoints(
6104 &mut self,
6105 range: Range<DisplayRow>,
6106 window: &mut Window,
6107 cx: &mut Context<Self>,
6108 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6109 let mut breakpoint_display_points = HashMap::default();
6110
6111 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6112 return breakpoint_display_points;
6113 };
6114
6115 let snapshot = self.snapshot(window, cx);
6116
6117 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6118 let Some(project) = self.project.as_ref() else {
6119 return breakpoint_display_points;
6120 };
6121
6122 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
6123 let buffer_snapshot = buffer.read(cx).snapshot();
6124
6125 for breakpoint in
6126 breakpoint_store
6127 .read(cx)
6128 .breakpoints(&buffer, None, &buffer_snapshot, cx)
6129 {
6130 let point = buffer_snapshot.summary_for_anchor::<Point>(&breakpoint.0);
6131 let mut anchor = multi_buffer_snapshot.anchor_before(point);
6132 anchor.text_anchor = breakpoint.0;
6133
6134 breakpoint_display_points.insert(
6135 snapshot
6136 .point_to_display_point(
6137 MultiBufferPoint {
6138 row: point.row,
6139 column: point.column,
6140 },
6141 Bias::Left,
6142 )
6143 .row(),
6144 (anchor, breakpoint.1.clone()),
6145 );
6146 }
6147
6148 return breakpoint_display_points;
6149 }
6150
6151 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6152 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6153
6154 for (buffer_snapshot, range, excerpt_id) in
6155 multi_buffer_snapshot.range_to_buffer_ranges(range)
6156 {
6157 let Some(buffer) = project.read_with(cx, |this, cx| {
6158 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6159 }) else {
6160 continue;
6161 };
6162 let breakpoints = breakpoint_store.read(cx).breakpoints(
6163 &buffer,
6164 Some(
6165 buffer_snapshot.anchor_before(range.start)
6166 ..buffer_snapshot.anchor_after(range.end),
6167 ),
6168 buffer_snapshot,
6169 cx,
6170 );
6171 for (anchor, breakpoint) in breakpoints {
6172 let multi_buffer_anchor =
6173 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6174 let position = multi_buffer_anchor
6175 .to_point(&multi_buffer_snapshot)
6176 .to_display_point(&snapshot);
6177
6178 breakpoint_display_points
6179 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6180 }
6181 }
6182
6183 breakpoint_display_points
6184 }
6185
6186 fn breakpoint_context_menu(
6187 &self,
6188 anchor: Anchor,
6189 window: &mut Window,
6190 cx: &mut Context<Self>,
6191 ) -> Entity<ui::ContextMenu> {
6192 let weak_editor = cx.weak_entity();
6193 let focus_handle = self.focus_handle(cx);
6194
6195 let row = self
6196 .buffer
6197 .read(cx)
6198 .snapshot(cx)
6199 .summary_for_anchor::<Point>(&anchor)
6200 .row;
6201
6202 let breakpoint = self
6203 .breakpoint_at_row(row, window, cx)
6204 .map(|(_, bp)| Arc::from(bp));
6205
6206 let log_breakpoint_msg = if breakpoint
6207 .as_ref()
6208 .is_some_and(|bp| bp.kind.log_message().is_some())
6209 {
6210 "Edit Log Breakpoint"
6211 } else {
6212 "Set Log Breakpoint"
6213 };
6214
6215 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6216 "Unset Breakpoint"
6217 } else {
6218 "Set Breakpoint"
6219 };
6220
6221 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.state {
6222 BreakpointState::Enabled => Some("Disable"),
6223 BreakpointState::Disabled => Some("Enable"),
6224 });
6225
6226 let breakpoint = breakpoint.unwrap_or_else(|| {
6227 Arc::new(Breakpoint {
6228 state: BreakpointState::Enabled,
6229 kind: BreakpointKind::Standard,
6230 })
6231 });
6232
6233 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6234 menu.on_blur_subscription(Subscription::new(|| {}))
6235 .context(focus_handle)
6236 .when_some(toggle_state_msg, |this, msg| {
6237 this.entry(msg, None, {
6238 let weak_editor = weak_editor.clone();
6239 let breakpoint = breakpoint.clone();
6240 move |_window, cx| {
6241 weak_editor
6242 .update(cx, |this, cx| {
6243 this.edit_breakpoint_at_anchor(
6244 anchor,
6245 breakpoint.as_ref().clone(),
6246 BreakpointEditAction::InvertState,
6247 cx,
6248 );
6249 })
6250 .log_err();
6251 }
6252 })
6253 })
6254 .entry(set_breakpoint_msg, None, {
6255 let weak_editor = weak_editor.clone();
6256 let breakpoint = breakpoint.clone();
6257 move |_window, cx| {
6258 weak_editor
6259 .update(cx, |this, cx| {
6260 this.edit_breakpoint_at_anchor(
6261 anchor,
6262 breakpoint.as_ref().clone(),
6263 BreakpointEditAction::Toggle,
6264 cx,
6265 );
6266 })
6267 .log_err();
6268 }
6269 })
6270 .entry(log_breakpoint_msg, None, move |window, cx| {
6271 weak_editor
6272 .update(cx, |this, cx| {
6273 this.add_edit_breakpoint_block(anchor, breakpoint.as_ref(), window, cx);
6274 })
6275 .log_err();
6276 })
6277 })
6278 }
6279
6280 fn render_breakpoint(
6281 &self,
6282 position: Anchor,
6283 row: DisplayRow,
6284 breakpoint: &Breakpoint,
6285 cx: &mut Context<Self>,
6286 ) -> IconButton {
6287 let (color, icon) = {
6288 let color = if self
6289 .gutter_breakpoint_indicator
6290 .is_some_and(|point| point.row() == row)
6291 {
6292 Color::Hint
6293 } else if breakpoint.is_disabled() {
6294 Color::Custom(Color::Debugger.color(cx).opacity(0.5))
6295 } else {
6296 Color::Debugger
6297 };
6298 let icon = match &breakpoint.kind {
6299 BreakpointKind::Standard => ui::IconName::DebugBreakpoint,
6300 BreakpointKind::Log(_) => ui::IconName::DebugLogBreakpoint,
6301 };
6302 (color, icon)
6303 };
6304
6305 let breakpoint = Arc::from(breakpoint.clone());
6306
6307 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6308 .icon_size(IconSize::XSmall)
6309 .size(ui::ButtonSize::None)
6310 .icon_color(color)
6311 .style(ButtonStyle::Transparent)
6312 .on_click(cx.listener({
6313 let breakpoint = breakpoint.clone();
6314
6315 move |editor, _e, window, cx| {
6316 window.focus(&editor.focus_handle(cx));
6317 editor.edit_breakpoint_at_anchor(
6318 position,
6319 breakpoint.as_ref().clone(),
6320 BreakpointEditAction::Toggle,
6321 cx,
6322 );
6323 }
6324 }))
6325 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6326 editor.set_breakpoint_context_menu(
6327 row,
6328 Some(position),
6329 event.down.position,
6330 window,
6331 cx,
6332 );
6333 }))
6334 }
6335
6336 fn build_tasks_context(
6337 project: &Entity<Project>,
6338 buffer: &Entity<Buffer>,
6339 buffer_row: u32,
6340 tasks: &Arc<RunnableTasks>,
6341 cx: &mut Context<Self>,
6342 ) -> Task<Option<task::TaskContext>> {
6343 let position = Point::new(buffer_row, tasks.column);
6344 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6345 let location = Location {
6346 buffer: buffer.clone(),
6347 range: range_start..range_start,
6348 };
6349 // Fill in the environmental variables from the tree-sitter captures
6350 let mut captured_task_variables = TaskVariables::default();
6351 for (capture_name, value) in tasks.extra_variables.clone() {
6352 captured_task_variables.insert(
6353 task::VariableName::Custom(capture_name.into()),
6354 value.clone(),
6355 );
6356 }
6357 project.update(cx, |project, cx| {
6358 project.task_store().update(cx, |task_store, cx| {
6359 task_store.task_context_for_location(captured_task_variables, location, cx)
6360 })
6361 })
6362 }
6363
6364 pub fn spawn_nearest_task(
6365 &mut self,
6366 action: &SpawnNearestTask,
6367 window: &mut Window,
6368 cx: &mut Context<Self>,
6369 ) {
6370 let Some((workspace, _)) = self.workspace.clone() else {
6371 return;
6372 };
6373 let Some(project) = self.project.clone() else {
6374 return;
6375 };
6376
6377 // Try to find a closest, enclosing node using tree-sitter that has a
6378 // task
6379 let Some((buffer, buffer_row, tasks)) = self
6380 .find_enclosing_node_task(cx)
6381 // Or find the task that's closest in row-distance.
6382 .or_else(|| self.find_closest_task(cx))
6383 else {
6384 return;
6385 };
6386
6387 let reveal_strategy = action.reveal;
6388 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6389 cx.spawn_in(window, async move |_, cx| {
6390 let context = task_context.await?;
6391 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6392
6393 let resolved = resolved_task.resolved.as_mut()?;
6394 resolved.reveal = reveal_strategy;
6395
6396 workspace
6397 .update(cx, |workspace, cx| {
6398 workspace::tasks::schedule_resolved_task(
6399 workspace,
6400 task_source_kind,
6401 resolved_task,
6402 false,
6403 cx,
6404 );
6405 })
6406 .ok()
6407 })
6408 .detach();
6409 }
6410
6411 fn find_closest_task(
6412 &mut self,
6413 cx: &mut Context<Self>,
6414 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6415 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6416
6417 let ((buffer_id, row), tasks) = self
6418 .tasks
6419 .iter()
6420 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6421
6422 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6423 let tasks = Arc::new(tasks.to_owned());
6424 Some((buffer, *row, tasks))
6425 }
6426
6427 fn find_enclosing_node_task(
6428 &mut self,
6429 cx: &mut Context<Self>,
6430 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6431 let snapshot = self.buffer.read(cx).snapshot(cx);
6432 let offset = self.selections.newest::<usize>(cx).head();
6433 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6434 let buffer_id = excerpt.buffer().remote_id();
6435
6436 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6437 let mut cursor = layer.node().walk();
6438
6439 while cursor.goto_first_child_for_byte(offset).is_some() {
6440 if cursor.node().end_byte() == offset {
6441 cursor.goto_next_sibling();
6442 }
6443 }
6444
6445 // Ascend to the smallest ancestor that contains the range and has a task.
6446 loop {
6447 let node = cursor.node();
6448 let node_range = node.byte_range();
6449 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6450
6451 // Check if this node contains our offset
6452 if node_range.start <= offset && node_range.end >= offset {
6453 // If it contains offset, check for task
6454 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6455 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6456 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6457 }
6458 }
6459
6460 if !cursor.goto_parent() {
6461 break;
6462 }
6463 }
6464 None
6465 }
6466
6467 fn render_run_indicator(
6468 &self,
6469 _style: &EditorStyle,
6470 is_active: bool,
6471 row: DisplayRow,
6472 breakpoint: Option<(Anchor, Breakpoint)>,
6473 cx: &mut Context<Self>,
6474 ) -> IconButton {
6475 let color = Color::Muted;
6476 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6477
6478 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6479 .shape(ui::IconButtonShape::Square)
6480 .icon_size(IconSize::XSmall)
6481 .icon_color(color)
6482 .toggle_state(is_active)
6483 .on_click(cx.listener(move |editor, _e, window, cx| {
6484 window.focus(&editor.focus_handle(cx));
6485 editor.toggle_code_actions(
6486 &ToggleCodeActions {
6487 deployed_from_indicator: Some(row),
6488 },
6489 window,
6490 cx,
6491 );
6492 }))
6493 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6494 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6495 }))
6496 }
6497
6498 pub fn context_menu_visible(&self) -> bool {
6499 !self.edit_prediction_preview_is_active()
6500 && self
6501 .context_menu
6502 .borrow()
6503 .as_ref()
6504 .map_or(false, |menu| menu.visible())
6505 }
6506
6507 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6508 self.context_menu
6509 .borrow()
6510 .as_ref()
6511 .map(|menu| menu.origin())
6512 }
6513
6514 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6515 self.context_menu_options = Some(options);
6516 }
6517
6518 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6519 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6520
6521 fn render_edit_prediction_popover(
6522 &mut self,
6523 text_bounds: &Bounds<Pixels>,
6524 content_origin: gpui::Point<Pixels>,
6525 editor_snapshot: &EditorSnapshot,
6526 visible_row_range: Range<DisplayRow>,
6527 scroll_top: f32,
6528 scroll_bottom: f32,
6529 line_layouts: &[LineWithInvisibles],
6530 line_height: Pixels,
6531 scroll_pixel_position: gpui::Point<Pixels>,
6532 newest_selection_head: Option<DisplayPoint>,
6533 editor_width: Pixels,
6534 style: &EditorStyle,
6535 window: &mut Window,
6536 cx: &mut App,
6537 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6538 let active_inline_completion = self.active_inline_completion.as_ref()?;
6539
6540 if self.edit_prediction_visible_in_cursor_popover(true) {
6541 return None;
6542 }
6543
6544 match &active_inline_completion.completion {
6545 InlineCompletion::Move { target, .. } => {
6546 let target_display_point = target.to_display_point(editor_snapshot);
6547
6548 if self.edit_prediction_requires_modifier() {
6549 if !self.edit_prediction_preview_is_active() {
6550 return None;
6551 }
6552
6553 self.render_edit_prediction_modifier_jump_popover(
6554 text_bounds,
6555 content_origin,
6556 visible_row_range,
6557 line_layouts,
6558 line_height,
6559 scroll_pixel_position,
6560 newest_selection_head,
6561 target_display_point,
6562 window,
6563 cx,
6564 )
6565 } else {
6566 self.render_edit_prediction_eager_jump_popover(
6567 text_bounds,
6568 content_origin,
6569 editor_snapshot,
6570 visible_row_range,
6571 scroll_top,
6572 scroll_bottom,
6573 line_height,
6574 scroll_pixel_position,
6575 target_display_point,
6576 editor_width,
6577 window,
6578 cx,
6579 )
6580 }
6581 }
6582 InlineCompletion::Edit {
6583 display_mode: EditDisplayMode::Inline,
6584 ..
6585 } => None,
6586 InlineCompletion::Edit {
6587 display_mode: EditDisplayMode::TabAccept,
6588 edits,
6589 ..
6590 } => {
6591 let range = &edits.first()?.0;
6592 let target_display_point = range.end.to_display_point(editor_snapshot);
6593
6594 self.render_edit_prediction_end_of_line_popover(
6595 "Accept",
6596 editor_snapshot,
6597 visible_row_range,
6598 target_display_point,
6599 line_height,
6600 scroll_pixel_position,
6601 content_origin,
6602 editor_width,
6603 window,
6604 cx,
6605 )
6606 }
6607 InlineCompletion::Edit {
6608 edits,
6609 edit_preview,
6610 display_mode: EditDisplayMode::DiffPopover,
6611 snapshot,
6612 } => self.render_edit_prediction_diff_popover(
6613 text_bounds,
6614 content_origin,
6615 editor_snapshot,
6616 visible_row_range,
6617 line_layouts,
6618 line_height,
6619 scroll_pixel_position,
6620 newest_selection_head,
6621 editor_width,
6622 style,
6623 edits,
6624 edit_preview,
6625 snapshot,
6626 window,
6627 cx,
6628 ),
6629 }
6630 }
6631
6632 fn render_edit_prediction_modifier_jump_popover(
6633 &mut self,
6634 text_bounds: &Bounds<Pixels>,
6635 content_origin: gpui::Point<Pixels>,
6636 visible_row_range: Range<DisplayRow>,
6637 line_layouts: &[LineWithInvisibles],
6638 line_height: Pixels,
6639 scroll_pixel_position: gpui::Point<Pixels>,
6640 newest_selection_head: Option<DisplayPoint>,
6641 target_display_point: DisplayPoint,
6642 window: &mut Window,
6643 cx: &mut App,
6644 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6645 let scrolled_content_origin =
6646 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6647
6648 const SCROLL_PADDING_Y: Pixels = px(12.);
6649
6650 if target_display_point.row() < visible_row_range.start {
6651 return self.render_edit_prediction_scroll_popover(
6652 |_| SCROLL_PADDING_Y,
6653 IconName::ArrowUp,
6654 visible_row_range,
6655 line_layouts,
6656 newest_selection_head,
6657 scrolled_content_origin,
6658 window,
6659 cx,
6660 );
6661 } else if target_display_point.row() >= visible_row_range.end {
6662 return self.render_edit_prediction_scroll_popover(
6663 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6664 IconName::ArrowDown,
6665 visible_row_range,
6666 line_layouts,
6667 newest_selection_head,
6668 scrolled_content_origin,
6669 window,
6670 cx,
6671 );
6672 }
6673
6674 const POLE_WIDTH: Pixels = px(2.);
6675
6676 let line_layout =
6677 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6678 let target_column = target_display_point.column() as usize;
6679
6680 let target_x = line_layout.x_for_index(target_column);
6681 let target_y =
6682 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6683
6684 let flag_on_right = target_x < text_bounds.size.width / 2.;
6685
6686 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6687 border_color.l += 0.001;
6688
6689 let mut element = v_flex()
6690 .items_end()
6691 .when(flag_on_right, |el| el.items_start())
6692 .child(if flag_on_right {
6693 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6694 .rounded_bl(px(0.))
6695 .rounded_tl(px(0.))
6696 .border_l_2()
6697 .border_color(border_color)
6698 } else {
6699 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6700 .rounded_br(px(0.))
6701 .rounded_tr(px(0.))
6702 .border_r_2()
6703 .border_color(border_color)
6704 })
6705 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6706 .into_any();
6707
6708 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6709
6710 let mut origin = scrolled_content_origin + point(target_x, target_y)
6711 - point(
6712 if flag_on_right {
6713 POLE_WIDTH
6714 } else {
6715 size.width - POLE_WIDTH
6716 },
6717 size.height - line_height,
6718 );
6719
6720 origin.x = origin.x.max(content_origin.x);
6721
6722 element.prepaint_at(origin, window, cx);
6723
6724 Some((element, origin))
6725 }
6726
6727 fn render_edit_prediction_scroll_popover(
6728 &mut self,
6729 to_y: impl Fn(Size<Pixels>) -> Pixels,
6730 scroll_icon: IconName,
6731 visible_row_range: Range<DisplayRow>,
6732 line_layouts: &[LineWithInvisibles],
6733 newest_selection_head: Option<DisplayPoint>,
6734 scrolled_content_origin: gpui::Point<Pixels>,
6735 window: &mut Window,
6736 cx: &mut App,
6737 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6738 let mut element = self
6739 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6740 .into_any();
6741
6742 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6743
6744 let cursor = newest_selection_head?;
6745 let cursor_row_layout =
6746 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6747 let cursor_column = cursor.column() as usize;
6748
6749 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6750
6751 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6752
6753 element.prepaint_at(origin, window, cx);
6754 Some((element, origin))
6755 }
6756
6757 fn render_edit_prediction_eager_jump_popover(
6758 &mut self,
6759 text_bounds: &Bounds<Pixels>,
6760 content_origin: gpui::Point<Pixels>,
6761 editor_snapshot: &EditorSnapshot,
6762 visible_row_range: Range<DisplayRow>,
6763 scroll_top: f32,
6764 scroll_bottom: f32,
6765 line_height: Pixels,
6766 scroll_pixel_position: gpui::Point<Pixels>,
6767 target_display_point: DisplayPoint,
6768 editor_width: Pixels,
6769 window: &mut Window,
6770 cx: &mut App,
6771 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6772 if target_display_point.row().as_f32() < scroll_top {
6773 let mut element = self
6774 .render_edit_prediction_line_popover(
6775 "Jump to Edit",
6776 Some(IconName::ArrowUp),
6777 window,
6778 cx,
6779 )?
6780 .into_any();
6781
6782 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6783 let offset = point(
6784 (text_bounds.size.width - size.width) / 2.,
6785 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6786 );
6787
6788 let origin = text_bounds.origin + offset;
6789 element.prepaint_at(origin, window, cx);
6790 Some((element, origin))
6791 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6792 let mut element = self
6793 .render_edit_prediction_line_popover(
6794 "Jump to Edit",
6795 Some(IconName::ArrowDown),
6796 window,
6797 cx,
6798 )?
6799 .into_any();
6800
6801 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6802 let offset = point(
6803 (text_bounds.size.width - size.width) / 2.,
6804 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6805 );
6806
6807 let origin = text_bounds.origin + offset;
6808 element.prepaint_at(origin, window, cx);
6809 Some((element, origin))
6810 } else {
6811 self.render_edit_prediction_end_of_line_popover(
6812 "Jump to Edit",
6813 editor_snapshot,
6814 visible_row_range,
6815 target_display_point,
6816 line_height,
6817 scroll_pixel_position,
6818 content_origin,
6819 editor_width,
6820 window,
6821 cx,
6822 )
6823 }
6824 }
6825
6826 fn render_edit_prediction_end_of_line_popover(
6827 self: &mut Editor,
6828 label: &'static str,
6829 editor_snapshot: &EditorSnapshot,
6830 visible_row_range: Range<DisplayRow>,
6831 target_display_point: DisplayPoint,
6832 line_height: Pixels,
6833 scroll_pixel_position: gpui::Point<Pixels>,
6834 content_origin: gpui::Point<Pixels>,
6835 editor_width: Pixels,
6836 window: &mut Window,
6837 cx: &mut App,
6838 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6839 let target_line_end = DisplayPoint::new(
6840 target_display_point.row(),
6841 editor_snapshot.line_len(target_display_point.row()),
6842 );
6843
6844 let mut element = self
6845 .render_edit_prediction_line_popover(label, None, window, cx)?
6846 .into_any();
6847
6848 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6849
6850 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6851
6852 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6853 let mut origin = start_point
6854 + line_origin
6855 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6856 origin.x = origin.x.max(content_origin.x);
6857
6858 let max_x = content_origin.x + editor_width - size.width;
6859
6860 if origin.x > max_x {
6861 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6862
6863 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6864 origin.y += offset;
6865 IconName::ArrowUp
6866 } else {
6867 origin.y -= offset;
6868 IconName::ArrowDown
6869 };
6870
6871 element = self
6872 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6873 .into_any();
6874
6875 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6876
6877 origin.x = content_origin.x + editor_width - size.width - px(2.);
6878 }
6879
6880 element.prepaint_at(origin, window, cx);
6881 Some((element, origin))
6882 }
6883
6884 fn render_edit_prediction_diff_popover(
6885 self: &Editor,
6886 text_bounds: &Bounds<Pixels>,
6887 content_origin: gpui::Point<Pixels>,
6888 editor_snapshot: &EditorSnapshot,
6889 visible_row_range: Range<DisplayRow>,
6890 line_layouts: &[LineWithInvisibles],
6891 line_height: Pixels,
6892 scroll_pixel_position: gpui::Point<Pixels>,
6893 newest_selection_head: Option<DisplayPoint>,
6894 editor_width: Pixels,
6895 style: &EditorStyle,
6896 edits: &Vec<(Range<Anchor>, String)>,
6897 edit_preview: &Option<language::EditPreview>,
6898 snapshot: &language::BufferSnapshot,
6899 window: &mut Window,
6900 cx: &mut App,
6901 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6902 let edit_start = edits
6903 .first()
6904 .unwrap()
6905 .0
6906 .start
6907 .to_display_point(editor_snapshot);
6908 let edit_end = edits
6909 .last()
6910 .unwrap()
6911 .0
6912 .end
6913 .to_display_point(editor_snapshot);
6914
6915 let is_visible = visible_row_range.contains(&edit_start.row())
6916 || visible_row_range.contains(&edit_end.row());
6917 if !is_visible {
6918 return None;
6919 }
6920
6921 let highlighted_edits =
6922 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6923
6924 let styled_text = highlighted_edits.to_styled_text(&style.text);
6925 let line_count = highlighted_edits.text.lines().count();
6926
6927 const BORDER_WIDTH: Pixels = px(1.);
6928
6929 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6930 let has_keybind = keybind.is_some();
6931
6932 let mut element = h_flex()
6933 .items_start()
6934 .child(
6935 h_flex()
6936 .bg(cx.theme().colors().editor_background)
6937 .border(BORDER_WIDTH)
6938 .shadow_sm()
6939 .border_color(cx.theme().colors().border)
6940 .rounded_l_lg()
6941 .when(line_count > 1, |el| el.rounded_br_lg())
6942 .pr_1()
6943 .child(styled_text),
6944 )
6945 .child(
6946 h_flex()
6947 .h(line_height + BORDER_WIDTH * 2.)
6948 .px_1p5()
6949 .gap_1()
6950 // Workaround: For some reason, there's a gap if we don't do this
6951 .ml(-BORDER_WIDTH)
6952 .shadow(smallvec![gpui::BoxShadow {
6953 color: gpui::black().opacity(0.05),
6954 offset: point(px(1.), px(1.)),
6955 blur_radius: px(2.),
6956 spread_radius: px(0.),
6957 }])
6958 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6959 .border(BORDER_WIDTH)
6960 .border_color(cx.theme().colors().border)
6961 .rounded_r_lg()
6962 .id("edit_prediction_diff_popover_keybind")
6963 .when(!has_keybind, |el| {
6964 let status_colors = cx.theme().status();
6965
6966 el.bg(status_colors.error_background)
6967 .border_color(status_colors.error.opacity(0.6))
6968 .child(Icon::new(IconName::Info).color(Color::Error))
6969 .cursor_default()
6970 .hoverable_tooltip(move |_window, cx| {
6971 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6972 })
6973 })
6974 .children(keybind),
6975 )
6976 .into_any();
6977
6978 let longest_row =
6979 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6980 let longest_line_width = if visible_row_range.contains(&longest_row) {
6981 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6982 } else {
6983 layout_line(
6984 longest_row,
6985 editor_snapshot,
6986 style,
6987 editor_width,
6988 |_| false,
6989 window,
6990 cx,
6991 )
6992 .width
6993 };
6994
6995 let viewport_bounds =
6996 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6997 right: -EditorElement::SCROLLBAR_WIDTH,
6998 ..Default::default()
6999 });
7000
7001 let x_after_longest =
7002 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7003 - scroll_pixel_position.x;
7004
7005 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7006
7007 // Fully visible if it can be displayed within the window (allow overlapping other
7008 // panes). However, this is only allowed if the popover starts within text_bounds.
7009 let can_position_to_the_right = x_after_longest < text_bounds.right()
7010 && x_after_longest + element_bounds.width < viewport_bounds.right();
7011
7012 let mut origin = if can_position_to_the_right {
7013 point(
7014 x_after_longest,
7015 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7016 - scroll_pixel_position.y,
7017 )
7018 } else {
7019 let cursor_row = newest_selection_head.map(|head| head.row());
7020 let above_edit = edit_start
7021 .row()
7022 .0
7023 .checked_sub(line_count as u32)
7024 .map(DisplayRow);
7025 let below_edit = Some(edit_end.row() + 1);
7026 let above_cursor =
7027 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7028 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7029
7030 // Place the edit popover adjacent to the edit if there is a location
7031 // available that is onscreen and does not obscure the cursor. Otherwise,
7032 // place it adjacent to the cursor.
7033 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7034 .into_iter()
7035 .flatten()
7036 .find(|&start_row| {
7037 let end_row = start_row + line_count as u32;
7038 visible_row_range.contains(&start_row)
7039 && visible_row_range.contains(&end_row)
7040 && cursor_row.map_or(true, |cursor_row| {
7041 !((start_row..end_row).contains(&cursor_row))
7042 })
7043 })?;
7044
7045 content_origin
7046 + point(
7047 -scroll_pixel_position.x,
7048 row_target.as_f32() * line_height - scroll_pixel_position.y,
7049 )
7050 };
7051
7052 origin.x -= BORDER_WIDTH;
7053
7054 window.defer_draw(element, origin, 1);
7055
7056 // Do not return an element, since it will already be drawn due to defer_draw.
7057 None
7058 }
7059
7060 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7061 px(30.)
7062 }
7063
7064 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7065 if self.read_only(cx) {
7066 cx.theme().players().read_only()
7067 } else {
7068 self.style.as_ref().unwrap().local_player
7069 }
7070 }
7071
7072 fn render_edit_prediction_accept_keybind(
7073 &self,
7074 window: &mut Window,
7075 cx: &App,
7076 ) -> Option<AnyElement> {
7077 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7078 let accept_keystroke = accept_binding.keystroke()?;
7079
7080 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7081
7082 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7083 Color::Accent
7084 } else {
7085 Color::Muted
7086 };
7087
7088 h_flex()
7089 .px_0p5()
7090 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7091 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7092 .text_size(TextSize::XSmall.rems(cx))
7093 .child(h_flex().children(ui::render_modifiers(
7094 &accept_keystroke.modifiers,
7095 PlatformStyle::platform(),
7096 Some(modifiers_color),
7097 Some(IconSize::XSmall.rems().into()),
7098 true,
7099 )))
7100 .when(is_platform_style_mac, |parent| {
7101 parent.child(accept_keystroke.key.clone())
7102 })
7103 .when(!is_platform_style_mac, |parent| {
7104 parent.child(
7105 Key::new(
7106 util::capitalize(&accept_keystroke.key),
7107 Some(Color::Default),
7108 )
7109 .size(Some(IconSize::XSmall.rems().into())),
7110 )
7111 })
7112 .into_any()
7113 .into()
7114 }
7115
7116 fn render_edit_prediction_line_popover(
7117 &self,
7118 label: impl Into<SharedString>,
7119 icon: Option<IconName>,
7120 window: &mut Window,
7121 cx: &App,
7122 ) -> Option<Stateful<Div>> {
7123 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7124
7125 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7126 let has_keybind = keybind.is_some();
7127
7128 let result = h_flex()
7129 .id("ep-line-popover")
7130 .py_0p5()
7131 .pl_1()
7132 .pr(padding_right)
7133 .gap_1()
7134 .rounded_md()
7135 .border_1()
7136 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7137 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7138 .shadow_sm()
7139 .when(!has_keybind, |el| {
7140 let status_colors = cx.theme().status();
7141
7142 el.bg(status_colors.error_background)
7143 .border_color(status_colors.error.opacity(0.6))
7144 .pl_2()
7145 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7146 .cursor_default()
7147 .hoverable_tooltip(move |_window, cx| {
7148 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7149 })
7150 })
7151 .children(keybind)
7152 .child(
7153 Label::new(label)
7154 .size(LabelSize::Small)
7155 .when(!has_keybind, |el| {
7156 el.color(cx.theme().status().error.into()).strikethrough()
7157 }),
7158 )
7159 .when(!has_keybind, |el| {
7160 el.child(
7161 h_flex().ml_1().child(
7162 Icon::new(IconName::Info)
7163 .size(IconSize::Small)
7164 .color(cx.theme().status().error.into()),
7165 ),
7166 )
7167 })
7168 .when_some(icon, |element, icon| {
7169 element.child(
7170 div()
7171 .mt(px(1.5))
7172 .child(Icon::new(icon).size(IconSize::Small)),
7173 )
7174 });
7175
7176 Some(result)
7177 }
7178
7179 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7180 let accent_color = cx.theme().colors().text_accent;
7181 let editor_bg_color = cx.theme().colors().editor_background;
7182 editor_bg_color.blend(accent_color.opacity(0.1))
7183 }
7184
7185 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7186 let accent_color = cx.theme().colors().text_accent;
7187 let editor_bg_color = cx.theme().colors().editor_background;
7188 editor_bg_color.blend(accent_color.opacity(0.6))
7189 }
7190
7191 fn render_edit_prediction_cursor_popover(
7192 &self,
7193 min_width: Pixels,
7194 max_width: Pixels,
7195 cursor_point: Point,
7196 style: &EditorStyle,
7197 accept_keystroke: Option<&gpui::Keystroke>,
7198 _window: &Window,
7199 cx: &mut Context<Editor>,
7200 ) -> Option<AnyElement> {
7201 let provider = self.edit_prediction_provider.as_ref()?;
7202
7203 if provider.provider.needs_terms_acceptance(cx) {
7204 return Some(
7205 h_flex()
7206 .min_w(min_width)
7207 .flex_1()
7208 .px_2()
7209 .py_1()
7210 .gap_3()
7211 .elevation_2(cx)
7212 .hover(|style| style.bg(cx.theme().colors().element_hover))
7213 .id("accept-terms")
7214 .cursor_pointer()
7215 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7216 .on_click(cx.listener(|this, _event, window, cx| {
7217 cx.stop_propagation();
7218 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7219 window.dispatch_action(
7220 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7221 cx,
7222 );
7223 }))
7224 .child(
7225 h_flex()
7226 .flex_1()
7227 .gap_2()
7228 .child(Icon::new(IconName::ZedPredict))
7229 .child(Label::new("Accept Terms of Service"))
7230 .child(div().w_full())
7231 .child(
7232 Icon::new(IconName::ArrowUpRight)
7233 .color(Color::Muted)
7234 .size(IconSize::Small),
7235 )
7236 .into_any_element(),
7237 )
7238 .into_any(),
7239 );
7240 }
7241
7242 let is_refreshing = provider.provider.is_refreshing(cx);
7243
7244 fn pending_completion_container() -> Div {
7245 h_flex()
7246 .h_full()
7247 .flex_1()
7248 .gap_2()
7249 .child(Icon::new(IconName::ZedPredict))
7250 }
7251
7252 let completion = match &self.active_inline_completion {
7253 Some(prediction) => {
7254 if !self.has_visible_completions_menu() {
7255 const RADIUS: Pixels = px(6.);
7256 const BORDER_WIDTH: Pixels = px(1.);
7257
7258 return Some(
7259 h_flex()
7260 .elevation_2(cx)
7261 .border(BORDER_WIDTH)
7262 .border_color(cx.theme().colors().border)
7263 .when(accept_keystroke.is_none(), |el| {
7264 el.border_color(cx.theme().status().error)
7265 })
7266 .rounded(RADIUS)
7267 .rounded_tl(px(0.))
7268 .overflow_hidden()
7269 .child(div().px_1p5().child(match &prediction.completion {
7270 InlineCompletion::Move { target, snapshot } => {
7271 use text::ToPoint as _;
7272 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7273 {
7274 Icon::new(IconName::ZedPredictDown)
7275 } else {
7276 Icon::new(IconName::ZedPredictUp)
7277 }
7278 }
7279 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7280 }))
7281 .child(
7282 h_flex()
7283 .gap_1()
7284 .py_1()
7285 .px_2()
7286 .rounded_r(RADIUS - BORDER_WIDTH)
7287 .border_l_1()
7288 .border_color(cx.theme().colors().border)
7289 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7290 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7291 el.child(
7292 Label::new("Hold")
7293 .size(LabelSize::Small)
7294 .when(accept_keystroke.is_none(), |el| {
7295 el.strikethrough()
7296 })
7297 .line_height_style(LineHeightStyle::UiLabel),
7298 )
7299 })
7300 .id("edit_prediction_cursor_popover_keybind")
7301 .when(accept_keystroke.is_none(), |el| {
7302 let status_colors = cx.theme().status();
7303
7304 el.bg(status_colors.error_background)
7305 .border_color(status_colors.error.opacity(0.6))
7306 .child(Icon::new(IconName::Info).color(Color::Error))
7307 .cursor_default()
7308 .hoverable_tooltip(move |_window, cx| {
7309 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7310 .into()
7311 })
7312 })
7313 .when_some(
7314 accept_keystroke.as_ref(),
7315 |el, accept_keystroke| {
7316 el.child(h_flex().children(ui::render_modifiers(
7317 &accept_keystroke.modifiers,
7318 PlatformStyle::platform(),
7319 Some(Color::Default),
7320 Some(IconSize::XSmall.rems().into()),
7321 false,
7322 )))
7323 },
7324 ),
7325 )
7326 .into_any(),
7327 );
7328 }
7329
7330 self.render_edit_prediction_cursor_popover_preview(
7331 prediction,
7332 cursor_point,
7333 style,
7334 cx,
7335 )?
7336 }
7337
7338 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7339 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7340 stale_completion,
7341 cursor_point,
7342 style,
7343 cx,
7344 )?,
7345
7346 None => {
7347 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7348 }
7349 },
7350
7351 None => pending_completion_container().child(Label::new("No Prediction")),
7352 };
7353
7354 let completion = if is_refreshing {
7355 completion
7356 .with_animation(
7357 "loading-completion",
7358 Animation::new(Duration::from_secs(2))
7359 .repeat()
7360 .with_easing(pulsating_between(0.4, 0.8)),
7361 |label, delta| label.opacity(delta),
7362 )
7363 .into_any_element()
7364 } else {
7365 completion.into_any_element()
7366 };
7367
7368 let has_completion = self.active_inline_completion.is_some();
7369
7370 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7371 Some(
7372 h_flex()
7373 .min_w(min_width)
7374 .max_w(max_width)
7375 .flex_1()
7376 .elevation_2(cx)
7377 .border_color(cx.theme().colors().border)
7378 .child(
7379 div()
7380 .flex_1()
7381 .py_1()
7382 .px_2()
7383 .overflow_hidden()
7384 .child(completion),
7385 )
7386 .when_some(accept_keystroke, |el, accept_keystroke| {
7387 if !accept_keystroke.modifiers.modified() {
7388 return el;
7389 }
7390
7391 el.child(
7392 h_flex()
7393 .h_full()
7394 .border_l_1()
7395 .rounded_r_lg()
7396 .border_color(cx.theme().colors().border)
7397 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7398 .gap_1()
7399 .py_1()
7400 .px_2()
7401 .child(
7402 h_flex()
7403 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7404 .when(is_platform_style_mac, |parent| parent.gap_1())
7405 .child(h_flex().children(ui::render_modifiers(
7406 &accept_keystroke.modifiers,
7407 PlatformStyle::platform(),
7408 Some(if !has_completion {
7409 Color::Muted
7410 } else {
7411 Color::Default
7412 }),
7413 None,
7414 false,
7415 ))),
7416 )
7417 .child(Label::new("Preview").into_any_element())
7418 .opacity(if has_completion { 1.0 } else { 0.4 }),
7419 )
7420 })
7421 .into_any(),
7422 )
7423 }
7424
7425 fn render_edit_prediction_cursor_popover_preview(
7426 &self,
7427 completion: &InlineCompletionState,
7428 cursor_point: Point,
7429 style: &EditorStyle,
7430 cx: &mut Context<Editor>,
7431 ) -> Option<Div> {
7432 use text::ToPoint as _;
7433
7434 fn render_relative_row_jump(
7435 prefix: impl Into<String>,
7436 current_row: u32,
7437 target_row: u32,
7438 ) -> Div {
7439 let (row_diff, arrow) = if target_row < current_row {
7440 (current_row - target_row, IconName::ArrowUp)
7441 } else {
7442 (target_row - current_row, IconName::ArrowDown)
7443 };
7444
7445 h_flex()
7446 .child(
7447 Label::new(format!("{}{}", prefix.into(), row_diff))
7448 .color(Color::Muted)
7449 .size(LabelSize::Small),
7450 )
7451 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7452 }
7453
7454 match &completion.completion {
7455 InlineCompletion::Move {
7456 target, snapshot, ..
7457 } => Some(
7458 h_flex()
7459 .px_2()
7460 .gap_2()
7461 .flex_1()
7462 .child(
7463 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7464 Icon::new(IconName::ZedPredictDown)
7465 } else {
7466 Icon::new(IconName::ZedPredictUp)
7467 },
7468 )
7469 .child(Label::new("Jump to Edit")),
7470 ),
7471
7472 InlineCompletion::Edit {
7473 edits,
7474 edit_preview,
7475 snapshot,
7476 display_mode: _,
7477 } => {
7478 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7479
7480 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7481 &snapshot,
7482 &edits,
7483 edit_preview.as_ref()?,
7484 true,
7485 cx,
7486 )
7487 .first_line_preview();
7488
7489 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7490 .with_default_highlights(&style.text, highlighted_edits.highlights);
7491
7492 let preview = h_flex()
7493 .gap_1()
7494 .min_w_16()
7495 .child(styled_text)
7496 .when(has_more_lines, |parent| parent.child("…"));
7497
7498 let left = if first_edit_row != cursor_point.row {
7499 render_relative_row_jump("", cursor_point.row, first_edit_row)
7500 .into_any_element()
7501 } else {
7502 Icon::new(IconName::ZedPredict).into_any_element()
7503 };
7504
7505 Some(
7506 h_flex()
7507 .h_full()
7508 .flex_1()
7509 .gap_2()
7510 .pr_1()
7511 .overflow_x_hidden()
7512 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7513 .child(left)
7514 .child(preview),
7515 )
7516 }
7517 }
7518 }
7519
7520 fn render_context_menu(
7521 &self,
7522 style: &EditorStyle,
7523 max_height_in_lines: u32,
7524 y_flipped: bool,
7525 window: &mut Window,
7526 cx: &mut Context<Editor>,
7527 ) -> Option<AnyElement> {
7528 let menu = self.context_menu.borrow();
7529 let menu = menu.as_ref()?;
7530 if !menu.visible() {
7531 return None;
7532 };
7533 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7534 }
7535
7536 fn render_context_menu_aside(
7537 &mut self,
7538 max_size: Size<Pixels>,
7539 window: &mut Window,
7540 cx: &mut Context<Editor>,
7541 ) -> Option<AnyElement> {
7542 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7543 if menu.visible() {
7544 menu.render_aside(self, max_size, window, cx)
7545 } else {
7546 None
7547 }
7548 })
7549 }
7550
7551 fn hide_context_menu(
7552 &mut self,
7553 window: &mut Window,
7554 cx: &mut Context<Self>,
7555 ) -> Option<CodeContextMenu> {
7556 cx.notify();
7557 self.completion_tasks.clear();
7558 let context_menu = self.context_menu.borrow_mut().take();
7559 self.stale_inline_completion_in_menu.take();
7560 self.update_visible_inline_completion(window, cx);
7561 context_menu
7562 }
7563
7564 fn show_snippet_choices(
7565 &mut self,
7566 choices: &Vec<String>,
7567 selection: Range<Anchor>,
7568 cx: &mut Context<Self>,
7569 ) {
7570 if selection.start.buffer_id.is_none() {
7571 return;
7572 }
7573 let buffer_id = selection.start.buffer_id.unwrap();
7574 let buffer = self.buffer().read(cx).buffer(buffer_id);
7575 let id = post_inc(&mut self.next_completion_id);
7576
7577 if let Some(buffer) = buffer {
7578 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7579 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7580 ));
7581 }
7582 }
7583
7584 pub fn insert_snippet(
7585 &mut self,
7586 insertion_ranges: &[Range<usize>],
7587 snippet: Snippet,
7588 window: &mut Window,
7589 cx: &mut Context<Self>,
7590 ) -> Result<()> {
7591 struct Tabstop<T> {
7592 is_end_tabstop: bool,
7593 ranges: Vec<Range<T>>,
7594 choices: Option<Vec<String>>,
7595 }
7596
7597 let tabstops = self.buffer.update(cx, |buffer, cx| {
7598 let snippet_text: Arc<str> = snippet.text.clone().into();
7599 let edits = insertion_ranges
7600 .iter()
7601 .cloned()
7602 .map(|range| (range, snippet_text.clone()));
7603 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
7604
7605 let snapshot = &*buffer.read(cx);
7606 let snippet = &snippet;
7607 snippet
7608 .tabstops
7609 .iter()
7610 .map(|tabstop| {
7611 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7612 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7613 });
7614 let mut tabstop_ranges = tabstop
7615 .ranges
7616 .iter()
7617 .flat_map(|tabstop_range| {
7618 let mut delta = 0_isize;
7619 insertion_ranges.iter().map(move |insertion_range| {
7620 let insertion_start = insertion_range.start as isize + delta;
7621 delta +=
7622 snippet.text.len() as isize - insertion_range.len() as isize;
7623
7624 let start = ((insertion_start + tabstop_range.start) as usize)
7625 .min(snapshot.len());
7626 let end = ((insertion_start + tabstop_range.end) as usize)
7627 .min(snapshot.len());
7628 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7629 })
7630 })
7631 .collect::<Vec<_>>();
7632 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7633
7634 Tabstop {
7635 is_end_tabstop,
7636 ranges: tabstop_ranges,
7637 choices: tabstop.choices.clone(),
7638 }
7639 })
7640 .collect::<Vec<_>>()
7641 });
7642 if let Some(tabstop) = tabstops.first() {
7643 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7644 s.select_ranges(tabstop.ranges.iter().cloned());
7645 });
7646
7647 if let Some(choices) = &tabstop.choices {
7648 if let Some(selection) = tabstop.ranges.first() {
7649 self.show_snippet_choices(choices, selection.clone(), cx)
7650 }
7651 }
7652
7653 // If we're already at the last tabstop and it's at the end of the snippet,
7654 // we're done, we don't need to keep the state around.
7655 if !tabstop.is_end_tabstop {
7656 let choices = tabstops
7657 .iter()
7658 .map(|tabstop| tabstop.choices.clone())
7659 .collect();
7660
7661 let ranges = tabstops
7662 .into_iter()
7663 .map(|tabstop| tabstop.ranges)
7664 .collect::<Vec<_>>();
7665
7666 self.snippet_stack.push(SnippetState {
7667 active_index: 0,
7668 ranges,
7669 choices,
7670 });
7671 }
7672
7673 // Check whether the just-entered snippet ends with an auto-closable bracket.
7674 if self.autoclose_regions.is_empty() {
7675 let snapshot = self.buffer.read(cx).snapshot(cx);
7676 for selection in &mut self.selections.all::<Point>(cx) {
7677 let selection_head = selection.head();
7678 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7679 continue;
7680 };
7681
7682 let mut bracket_pair = None;
7683 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7684 let prev_chars = snapshot
7685 .reversed_chars_at(selection_head)
7686 .collect::<String>();
7687 for (pair, enabled) in scope.brackets() {
7688 if enabled
7689 && pair.close
7690 && prev_chars.starts_with(pair.start.as_str())
7691 && next_chars.starts_with(pair.end.as_str())
7692 {
7693 bracket_pair = Some(pair.clone());
7694 break;
7695 }
7696 }
7697 if let Some(pair) = bracket_pair {
7698 let start = snapshot.anchor_after(selection_head);
7699 let end = snapshot.anchor_after(selection_head);
7700 self.autoclose_regions.push(AutocloseRegion {
7701 selection_id: selection.id,
7702 range: start..end,
7703 pair,
7704 });
7705 }
7706 }
7707 }
7708 }
7709 Ok(())
7710 }
7711
7712 pub fn move_to_next_snippet_tabstop(
7713 &mut self,
7714 window: &mut Window,
7715 cx: &mut Context<Self>,
7716 ) -> bool {
7717 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7718 }
7719
7720 pub fn move_to_prev_snippet_tabstop(
7721 &mut self,
7722 window: &mut Window,
7723 cx: &mut Context<Self>,
7724 ) -> bool {
7725 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7726 }
7727
7728 pub fn move_to_snippet_tabstop(
7729 &mut self,
7730 bias: Bias,
7731 window: &mut Window,
7732 cx: &mut Context<Self>,
7733 ) -> bool {
7734 if let Some(mut snippet) = self.snippet_stack.pop() {
7735 match bias {
7736 Bias::Left => {
7737 if snippet.active_index > 0 {
7738 snippet.active_index -= 1;
7739 } else {
7740 self.snippet_stack.push(snippet);
7741 return false;
7742 }
7743 }
7744 Bias::Right => {
7745 if snippet.active_index + 1 < snippet.ranges.len() {
7746 snippet.active_index += 1;
7747 } else {
7748 self.snippet_stack.push(snippet);
7749 return false;
7750 }
7751 }
7752 }
7753 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7754 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7755 s.select_anchor_ranges(current_ranges.iter().cloned())
7756 });
7757
7758 if let Some(choices) = &snippet.choices[snippet.active_index] {
7759 if let Some(selection) = current_ranges.first() {
7760 self.show_snippet_choices(&choices, selection.clone(), cx);
7761 }
7762 }
7763
7764 // If snippet state is not at the last tabstop, push it back on the stack
7765 if snippet.active_index + 1 < snippet.ranges.len() {
7766 self.snippet_stack.push(snippet);
7767 }
7768 return true;
7769 }
7770 }
7771
7772 false
7773 }
7774
7775 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7776 self.transact(window, cx, |this, window, cx| {
7777 this.select_all(&SelectAll, window, cx);
7778 this.insert("", window, cx);
7779 });
7780 }
7781
7782 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7783 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7784 self.transact(window, cx, |this, window, cx| {
7785 this.select_autoclose_pair(window, cx);
7786 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7787 if !this.linked_edit_ranges.is_empty() {
7788 let selections = this.selections.all::<MultiBufferPoint>(cx);
7789 let snapshot = this.buffer.read(cx).snapshot(cx);
7790
7791 for selection in selections.iter() {
7792 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7793 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7794 if selection_start.buffer_id != selection_end.buffer_id {
7795 continue;
7796 }
7797 if let Some(ranges) =
7798 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7799 {
7800 for (buffer, entries) in ranges {
7801 linked_ranges.entry(buffer).or_default().extend(entries);
7802 }
7803 }
7804 }
7805 }
7806
7807 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7808 if !this.selections.line_mode {
7809 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7810 for selection in &mut selections {
7811 if selection.is_empty() {
7812 let old_head = selection.head();
7813 let mut new_head =
7814 movement::left(&display_map, old_head.to_display_point(&display_map))
7815 .to_point(&display_map);
7816 if let Some((buffer, line_buffer_range)) = display_map
7817 .buffer_snapshot
7818 .buffer_line_for_row(MultiBufferRow(old_head.row))
7819 {
7820 let indent_size =
7821 buffer.indent_size_for_line(line_buffer_range.start.row);
7822 let indent_len = match indent_size.kind {
7823 IndentKind::Space => {
7824 buffer.settings_at(line_buffer_range.start, cx).tab_size
7825 }
7826 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7827 };
7828 if old_head.column <= indent_size.len && old_head.column > 0 {
7829 let indent_len = indent_len.get();
7830 new_head = cmp::min(
7831 new_head,
7832 MultiBufferPoint::new(
7833 old_head.row,
7834 ((old_head.column - 1) / indent_len) * indent_len,
7835 ),
7836 );
7837 }
7838 }
7839
7840 selection.set_head(new_head, SelectionGoal::None);
7841 }
7842 }
7843 }
7844
7845 this.signature_help_state.set_backspace_pressed(true);
7846 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7847 s.select(selections)
7848 });
7849 this.insert("", window, cx);
7850 let empty_str: Arc<str> = Arc::from("");
7851 for (buffer, edits) in linked_ranges {
7852 let snapshot = buffer.read(cx).snapshot();
7853 use text::ToPoint as TP;
7854
7855 let edits = edits
7856 .into_iter()
7857 .map(|range| {
7858 let end_point = TP::to_point(&range.end, &snapshot);
7859 let mut start_point = TP::to_point(&range.start, &snapshot);
7860
7861 if end_point == start_point {
7862 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7863 .saturating_sub(1);
7864 start_point =
7865 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7866 };
7867
7868 (start_point..end_point, empty_str.clone())
7869 })
7870 .sorted_by_key(|(range, _)| range.start)
7871 .collect::<Vec<_>>();
7872 buffer.update(cx, |this, cx| {
7873 this.edit(edits, None, cx);
7874 })
7875 }
7876 this.refresh_inline_completion(true, false, window, cx);
7877 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7878 });
7879 }
7880
7881 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7882 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7883 self.transact(window, cx, |this, window, cx| {
7884 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7885 let line_mode = s.line_mode;
7886 s.move_with(|map, selection| {
7887 if selection.is_empty() && !line_mode {
7888 let cursor = movement::right(map, selection.head());
7889 selection.end = cursor;
7890 selection.reversed = true;
7891 selection.goal = SelectionGoal::None;
7892 }
7893 })
7894 });
7895 this.insert("", window, cx);
7896 this.refresh_inline_completion(true, false, window, cx);
7897 });
7898 }
7899
7900 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7901 if self.move_to_prev_snippet_tabstop(window, cx) {
7902 return;
7903 }
7904 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7905 self.outdent(&Outdent, window, cx);
7906 }
7907
7908 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7909 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7910 return;
7911 }
7912 self.mouse_cursor_hidden = self.hide_mouse_while_typing;
7913 let mut selections = self.selections.all_adjusted(cx);
7914 let buffer = self.buffer.read(cx);
7915 let snapshot = buffer.snapshot(cx);
7916 let rows_iter = selections.iter().map(|s| s.head().row);
7917 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7918
7919 let mut edits = Vec::new();
7920 let mut prev_edited_row = 0;
7921 let mut row_delta = 0;
7922 for selection in &mut selections {
7923 if selection.start.row != prev_edited_row {
7924 row_delta = 0;
7925 }
7926 prev_edited_row = selection.end.row;
7927
7928 // If the selection is non-empty, then increase the indentation of the selected lines.
7929 if !selection.is_empty() {
7930 row_delta =
7931 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7932 continue;
7933 }
7934
7935 // If the selection is empty and the cursor is in the leading whitespace before the
7936 // suggested indentation, then auto-indent the line.
7937 let cursor = selection.head();
7938 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7939 if let Some(suggested_indent) =
7940 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7941 {
7942 if cursor.column < suggested_indent.len
7943 && cursor.column <= current_indent.len
7944 && current_indent.len <= suggested_indent.len
7945 {
7946 selection.start = Point::new(cursor.row, suggested_indent.len);
7947 selection.end = selection.start;
7948 if row_delta == 0 {
7949 edits.extend(Buffer::edit_for_indent_size_adjustment(
7950 cursor.row,
7951 current_indent,
7952 suggested_indent,
7953 ));
7954 row_delta = suggested_indent.len - current_indent.len;
7955 }
7956 continue;
7957 }
7958 }
7959
7960 // Otherwise, insert a hard or soft tab.
7961 let settings = buffer.language_settings_at(cursor, cx);
7962 let tab_size = if settings.hard_tabs {
7963 IndentSize::tab()
7964 } else {
7965 let tab_size = settings.tab_size.get();
7966 let char_column = snapshot
7967 .text_for_range(Point::new(cursor.row, 0)..cursor)
7968 .flat_map(str::chars)
7969 .count()
7970 + row_delta as usize;
7971 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7972 IndentSize::spaces(chars_to_next_tab_stop)
7973 };
7974 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7975 selection.end = selection.start;
7976 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7977 row_delta += tab_size.len;
7978 }
7979
7980 self.transact(window, cx, |this, window, cx| {
7981 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7982 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7983 s.select(selections)
7984 });
7985 this.refresh_inline_completion(true, false, window, cx);
7986 });
7987 }
7988
7989 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7990 if self.read_only(cx) {
7991 return;
7992 }
7993 let mut selections = self.selections.all::<Point>(cx);
7994 let mut prev_edited_row = 0;
7995 let mut row_delta = 0;
7996 let mut edits = Vec::new();
7997 let buffer = self.buffer.read(cx);
7998 let snapshot = buffer.snapshot(cx);
7999 for selection in &mut selections {
8000 if selection.start.row != prev_edited_row {
8001 row_delta = 0;
8002 }
8003 prev_edited_row = selection.end.row;
8004
8005 row_delta =
8006 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8007 }
8008
8009 self.transact(window, cx, |this, window, cx| {
8010 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8011 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8012 s.select(selections)
8013 });
8014 });
8015 }
8016
8017 fn indent_selection(
8018 buffer: &MultiBuffer,
8019 snapshot: &MultiBufferSnapshot,
8020 selection: &mut Selection<Point>,
8021 edits: &mut Vec<(Range<Point>, String)>,
8022 delta_for_start_row: u32,
8023 cx: &App,
8024 ) -> u32 {
8025 let settings = buffer.language_settings_at(selection.start, cx);
8026 let tab_size = settings.tab_size.get();
8027 let indent_kind = if settings.hard_tabs {
8028 IndentKind::Tab
8029 } else {
8030 IndentKind::Space
8031 };
8032 let mut start_row = selection.start.row;
8033 let mut end_row = selection.end.row + 1;
8034
8035 // If a selection ends at the beginning of a line, don't indent
8036 // that last line.
8037 if selection.end.column == 0 && selection.end.row > selection.start.row {
8038 end_row -= 1;
8039 }
8040
8041 // Avoid re-indenting a row that has already been indented by a
8042 // previous selection, but still update this selection's column
8043 // to reflect that indentation.
8044 if delta_for_start_row > 0 {
8045 start_row += 1;
8046 selection.start.column += delta_for_start_row;
8047 if selection.end.row == selection.start.row {
8048 selection.end.column += delta_for_start_row;
8049 }
8050 }
8051
8052 let mut delta_for_end_row = 0;
8053 let has_multiple_rows = start_row + 1 != end_row;
8054 for row in start_row..end_row {
8055 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8056 let indent_delta = match (current_indent.kind, indent_kind) {
8057 (IndentKind::Space, IndentKind::Space) => {
8058 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8059 IndentSize::spaces(columns_to_next_tab_stop)
8060 }
8061 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8062 (_, IndentKind::Tab) => IndentSize::tab(),
8063 };
8064
8065 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8066 0
8067 } else {
8068 selection.start.column
8069 };
8070 let row_start = Point::new(row, start);
8071 edits.push((
8072 row_start..row_start,
8073 indent_delta.chars().collect::<String>(),
8074 ));
8075
8076 // Update this selection's endpoints to reflect the indentation.
8077 if row == selection.start.row {
8078 selection.start.column += indent_delta.len;
8079 }
8080 if row == selection.end.row {
8081 selection.end.column += indent_delta.len;
8082 delta_for_end_row = indent_delta.len;
8083 }
8084 }
8085
8086 if selection.start.row == selection.end.row {
8087 delta_for_start_row + delta_for_end_row
8088 } else {
8089 delta_for_end_row
8090 }
8091 }
8092
8093 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8094 if self.read_only(cx) {
8095 return;
8096 }
8097 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8098 let selections = self.selections.all::<Point>(cx);
8099 let mut deletion_ranges = Vec::new();
8100 let mut last_outdent = None;
8101 {
8102 let buffer = self.buffer.read(cx);
8103 let snapshot = buffer.snapshot(cx);
8104 for selection in &selections {
8105 let settings = buffer.language_settings_at(selection.start, cx);
8106 let tab_size = settings.tab_size.get();
8107 let mut rows = selection.spanned_rows(false, &display_map);
8108
8109 // Avoid re-outdenting a row that has already been outdented by a
8110 // previous selection.
8111 if let Some(last_row) = last_outdent {
8112 if last_row == rows.start {
8113 rows.start = rows.start.next_row();
8114 }
8115 }
8116 let has_multiple_rows = rows.len() > 1;
8117 for row in rows.iter_rows() {
8118 let indent_size = snapshot.indent_size_for_line(row);
8119 if indent_size.len > 0 {
8120 let deletion_len = match indent_size.kind {
8121 IndentKind::Space => {
8122 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8123 if columns_to_prev_tab_stop == 0 {
8124 tab_size
8125 } else {
8126 columns_to_prev_tab_stop
8127 }
8128 }
8129 IndentKind::Tab => 1,
8130 };
8131 let start = if has_multiple_rows
8132 || deletion_len > selection.start.column
8133 || indent_size.len < selection.start.column
8134 {
8135 0
8136 } else {
8137 selection.start.column - deletion_len
8138 };
8139 deletion_ranges.push(
8140 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8141 );
8142 last_outdent = Some(row);
8143 }
8144 }
8145 }
8146 }
8147
8148 self.transact(window, cx, |this, window, cx| {
8149 this.buffer.update(cx, |buffer, cx| {
8150 let empty_str: Arc<str> = Arc::default();
8151 buffer.edit(
8152 deletion_ranges
8153 .into_iter()
8154 .map(|range| (range, empty_str.clone())),
8155 None,
8156 cx,
8157 );
8158 });
8159 let selections = this.selections.all::<usize>(cx);
8160 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8161 s.select(selections)
8162 });
8163 });
8164 }
8165
8166 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8167 if self.read_only(cx) {
8168 return;
8169 }
8170 let selections = self
8171 .selections
8172 .all::<usize>(cx)
8173 .into_iter()
8174 .map(|s| s.range());
8175
8176 self.transact(window, cx, |this, window, cx| {
8177 this.buffer.update(cx, |buffer, cx| {
8178 buffer.autoindent_ranges(selections, cx);
8179 });
8180 let selections = this.selections.all::<usize>(cx);
8181 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8182 s.select(selections)
8183 });
8184 });
8185 }
8186
8187 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8188 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8189 let selections = self.selections.all::<Point>(cx);
8190
8191 let mut new_cursors = Vec::new();
8192 let mut edit_ranges = Vec::new();
8193 let mut selections = selections.iter().peekable();
8194 while let Some(selection) = selections.next() {
8195 let mut rows = selection.spanned_rows(false, &display_map);
8196 let goal_display_column = selection.head().to_display_point(&display_map).column();
8197
8198 // Accumulate contiguous regions of rows that we want to delete.
8199 while let Some(next_selection) = selections.peek() {
8200 let next_rows = next_selection.spanned_rows(false, &display_map);
8201 if next_rows.start <= rows.end {
8202 rows.end = next_rows.end;
8203 selections.next().unwrap();
8204 } else {
8205 break;
8206 }
8207 }
8208
8209 let buffer = &display_map.buffer_snapshot;
8210 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8211 let edit_end;
8212 let cursor_buffer_row;
8213 if buffer.max_point().row >= rows.end.0 {
8214 // If there's a line after the range, delete the \n from the end of the row range
8215 // and position the cursor on the next line.
8216 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8217 cursor_buffer_row = rows.end;
8218 } else {
8219 // If there isn't a line after the range, delete the \n from the line before the
8220 // start of the row range and position the cursor there.
8221 edit_start = edit_start.saturating_sub(1);
8222 edit_end = buffer.len();
8223 cursor_buffer_row = rows.start.previous_row();
8224 }
8225
8226 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8227 *cursor.column_mut() =
8228 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8229
8230 new_cursors.push((
8231 selection.id,
8232 buffer.anchor_after(cursor.to_point(&display_map)),
8233 ));
8234 edit_ranges.push(edit_start..edit_end);
8235 }
8236
8237 self.transact(window, cx, |this, window, cx| {
8238 let buffer = this.buffer.update(cx, |buffer, cx| {
8239 let empty_str: Arc<str> = Arc::default();
8240 buffer.edit(
8241 edit_ranges
8242 .into_iter()
8243 .map(|range| (range, empty_str.clone())),
8244 None,
8245 cx,
8246 );
8247 buffer.snapshot(cx)
8248 });
8249 let new_selections = new_cursors
8250 .into_iter()
8251 .map(|(id, cursor)| {
8252 let cursor = cursor.to_point(&buffer);
8253 Selection {
8254 id,
8255 start: cursor,
8256 end: cursor,
8257 reversed: false,
8258 goal: SelectionGoal::None,
8259 }
8260 })
8261 .collect();
8262
8263 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8264 s.select(new_selections);
8265 });
8266 });
8267 }
8268
8269 pub fn join_lines_impl(
8270 &mut self,
8271 insert_whitespace: bool,
8272 window: &mut Window,
8273 cx: &mut Context<Self>,
8274 ) {
8275 if self.read_only(cx) {
8276 return;
8277 }
8278 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8279 for selection in self.selections.all::<Point>(cx) {
8280 let start = MultiBufferRow(selection.start.row);
8281 // Treat single line selections as if they include the next line. Otherwise this action
8282 // would do nothing for single line selections individual cursors.
8283 let end = if selection.start.row == selection.end.row {
8284 MultiBufferRow(selection.start.row + 1)
8285 } else {
8286 MultiBufferRow(selection.end.row)
8287 };
8288
8289 if let Some(last_row_range) = row_ranges.last_mut() {
8290 if start <= last_row_range.end {
8291 last_row_range.end = end;
8292 continue;
8293 }
8294 }
8295 row_ranges.push(start..end);
8296 }
8297
8298 let snapshot = self.buffer.read(cx).snapshot(cx);
8299 let mut cursor_positions = Vec::new();
8300 for row_range in &row_ranges {
8301 let anchor = snapshot.anchor_before(Point::new(
8302 row_range.end.previous_row().0,
8303 snapshot.line_len(row_range.end.previous_row()),
8304 ));
8305 cursor_positions.push(anchor..anchor);
8306 }
8307
8308 self.transact(window, cx, |this, window, cx| {
8309 for row_range in row_ranges.into_iter().rev() {
8310 for row in row_range.iter_rows().rev() {
8311 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8312 let next_line_row = row.next_row();
8313 let indent = snapshot.indent_size_for_line(next_line_row);
8314 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8315
8316 let replace =
8317 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8318 " "
8319 } else {
8320 ""
8321 };
8322
8323 this.buffer.update(cx, |buffer, cx| {
8324 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8325 });
8326 }
8327 }
8328
8329 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8330 s.select_anchor_ranges(cursor_positions)
8331 });
8332 });
8333 }
8334
8335 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8336 self.join_lines_impl(true, window, cx);
8337 }
8338
8339 pub fn sort_lines_case_sensitive(
8340 &mut self,
8341 _: &SortLinesCaseSensitive,
8342 window: &mut Window,
8343 cx: &mut Context<Self>,
8344 ) {
8345 self.manipulate_lines(window, cx, |lines| lines.sort())
8346 }
8347
8348 pub fn sort_lines_case_insensitive(
8349 &mut self,
8350 _: &SortLinesCaseInsensitive,
8351 window: &mut Window,
8352 cx: &mut Context<Self>,
8353 ) {
8354 self.manipulate_lines(window, cx, |lines| {
8355 lines.sort_by_key(|line| line.to_lowercase())
8356 })
8357 }
8358
8359 pub fn unique_lines_case_insensitive(
8360 &mut self,
8361 _: &UniqueLinesCaseInsensitive,
8362 window: &mut Window,
8363 cx: &mut Context<Self>,
8364 ) {
8365 self.manipulate_lines(window, cx, |lines| {
8366 let mut seen = HashSet::default();
8367 lines.retain(|line| seen.insert(line.to_lowercase()));
8368 })
8369 }
8370
8371 pub fn unique_lines_case_sensitive(
8372 &mut self,
8373 _: &UniqueLinesCaseSensitive,
8374 window: &mut Window,
8375 cx: &mut Context<Self>,
8376 ) {
8377 self.manipulate_lines(window, cx, |lines| {
8378 let mut seen = HashSet::default();
8379 lines.retain(|line| seen.insert(*line));
8380 })
8381 }
8382
8383 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8384 let Some(project) = self.project.clone() else {
8385 return;
8386 };
8387 self.reload(project, window, cx)
8388 .detach_and_notify_err(window, cx);
8389 }
8390
8391 pub fn restore_file(
8392 &mut self,
8393 _: &::git::RestoreFile,
8394 window: &mut Window,
8395 cx: &mut Context<Self>,
8396 ) {
8397 let mut buffer_ids = HashSet::default();
8398 let snapshot = self.buffer().read(cx).snapshot(cx);
8399 for selection in self.selections.all::<usize>(cx) {
8400 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8401 }
8402
8403 let buffer = self.buffer().read(cx);
8404 let ranges = buffer_ids
8405 .into_iter()
8406 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8407 .collect::<Vec<_>>();
8408
8409 self.restore_hunks_in_ranges(ranges, window, cx);
8410 }
8411
8412 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8413 let selections = self
8414 .selections
8415 .all(cx)
8416 .into_iter()
8417 .map(|s| s.range())
8418 .collect();
8419 self.restore_hunks_in_ranges(selections, window, cx);
8420 }
8421
8422 fn restore_hunks_in_ranges(
8423 &mut self,
8424 ranges: Vec<Range<Point>>,
8425 window: &mut Window,
8426 cx: &mut Context<Editor>,
8427 ) {
8428 let mut revert_changes = HashMap::default();
8429 let chunk_by = self
8430 .snapshot(window, cx)
8431 .hunks_for_ranges(ranges)
8432 .into_iter()
8433 .chunk_by(|hunk| hunk.buffer_id);
8434 for (buffer_id, hunks) in &chunk_by {
8435 let hunks = hunks.collect::<Vec<_>>();
8436 for hunk in &hunks {
8437 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8438 }
8439 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8440 }
8441 drop(chunk_by);
8442 if !revert_changes.is_empty() {
8443 self.transact(window, cx, |editor, window, cx| {
8444 editor.restore(revert_changes, window, cx);
8445 });
8446 }
8447 }
8448
8449 pub fn open_active_item_in_terminal(
8450 &mut self,
8451 _: &OpenInTerminal,
8452 window: &mut Window,
8453 cx: &mut Context<Self>,
8454 ) {
8455 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8456 let project_path = buffer.read(cx).project_path(cx)?;
8457 let project = self.project.as_ref()?.read(cx);
8458 let entry = project.entry_for_path(&project_path, cx)?;
8459 let parent = match &entry.canonical_path {
8460 Some(canonical_path) => canonical_path.to_path_buf(),
8461 None => project.absolute_path(&project_path, cx)?,
8462 }
8463 .parent()?
8464 .to_path_buf();
8465 Some(parent)
8466 }) {
8467 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8468 }
8469 }
8470
8471 fn set_breakpoint_context_menu(
8472 &mut self,
8473 display_row: DisplayRow,
8474 position: Option<Anchor>,
8475 clicked_point: gpui::Point<Pixels>,
8476 window: &mut Window,
8477 cx: &mut Context<Self>,
8478 ) {
8479 if !cx.has_flag::<Debugger>() {
8480 return;
8481 }
8482 let source = self
8483 .buffer
8484 .read(cx)
8485 .snapshot(cx)
8486 .anchor_before(Point::new(display_row.0, 0u32));
8487
8488 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8489
8490 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8491 self,
8492 source,
8493 clicked_point,
8494 context_menu,
8495 window,
8496 cx,
8497 );
8498 }
8499
8500 fn add_edit_breakpoint_block(
8501 &mut self,
8502 anchor: Anchor,
8503 breakpoint: &Breakpoint,
8504 window: &mut Window,
8505 cx: &mut Context<Self>,
8506 ) {
8507 let weak_editor = cx.weak_entity();
8508 let bp_prompt = cx.new(|cx| {
8509 BreakpointPromptEditor::new(weak_editor, anchor, breakpoint.clone(), window, cx)
8510 });
8511
8512 let height = bp_prompt.update(cx, |this, cx| {
8513 this.prompt
8514 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8515 });
8516 let cloned_prompt = bp_prompt.clone();
8517 let blocks = vec![BlockProperties {
8518 style: BlockStyle::Sticky,
8519 placement: BlockPlacement::Above(anchor),
8520 height,
8521 render: Arc::new(move |cx| {
8522 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8523 cloned_prompt.clone().into_any_element()
8524 }),
8525 priority: 0,
8526 }];
8527
8528 let focus_handle = bp_prompt.focus_handle(cx);
8529 window.focus(&focus_handle);
8530
8531 let block_ids = self.insert_blocks(blocks, None, cx);
8532 bp_prompt.update(cx, |prompt, _| {
8533 prompt.add_block_ids(block_ids);
8534 });
8535 }
8536
8537 fn breakpoint_at_cursor_head(
8538 &self,
8539 window: &mut Window,
8540 cx: &mut Context<Self>,
8541 ) -> Option<(Anchor, Breakpoint)> {
8542 let cursor_position: Point = self.selections.newest(cx).head();
8543 self.breakpoint_at_row(cursor_position.row, window, cx)
8544 }
8545
8546 pub(crate) fn breakpoint_at_row(
8547 &self,
8548 row: u32,
8549 window: &mut Window,
8550 cx: &mut Context<Self>,
8551 ) -> Option<(Anchor, Breakpoint)> {
8552 let snapshot = self.snapshot(window, cx);
8553 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
8554
8555 let project = self.project.clone()?;
8556
8557 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
8558 snapshot
8559 .buffer_snapshot
8560 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
8561 })?;
8562
8563 let enclosing_excerpt = breakpoint_position.excerpt_id;
8564 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8565 let buffer_snapshot = buffer.read(cx).snapshot();
8566
8567 let row = buffer_snapshot
8568 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
8569 .row;
8570
8571 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
8572 let anchor_end = snapshot
8573 .buffer_snapshot
8574 .anchor_before(Point::new(row, line_len));
8575
8576 let bp = self
8577 .breakpoint_store
8578 .as_ref()?
8579 .read_with(cx, |breakpoint_store, cx| {
8580 breakpoint_store
8581 .breakpoints(
8582 &buffer,
8583 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
8584 &buffer_snapshot,
8585 cx,
8586 )
8587 .next()
8588 .and_then(|(anchor, bp)| {
8589 let breakpoint_row = buffer_snapshot
8590 .summary_for_anchor::<text::PointUtf16>(anchor)
8591 .row;
8592
8593 if breakpoint_row == row {
8594 snapshot
8595 .buffer_snapshot
8596 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8597 .map(|anchor| (anchor, bp.clone()))
8598 } else {
8599 None
8600 }
8601 })
8602 });
8603 bp
8604 }
8605
8606 pub fn edit_log_breakpoint(
8607 &mut self,
8608 _: &EditLogBreakpoint,
8609 window: &mut Window,
8610 cx: &mut Context<Self>,
8611 ) {
8612 let (anchor, bp) = self
8613 .breakpoint_at_cursor_head(window, cx)
8614 .unwrap_or_else(|| {
8615 let cursor_position: Point = self.selections.newest(cx).head();
8616
8617 let breakpoint_position = self
8618 .snapshot(window, cx)
8619 .display_snapshot
8620 .buffer_snapshot
8621 .anchor_before(Point::new(cursor_position.row, 0));
8622
8623 (
8624 breakpoint_position,
8625 Breakpoint {
8626 kind: BreakpointKind::Standard,
8627 state: BreakpointState::Enabled,
8628 },
8629 )
8630 });
8631
8632 self.add_edit_breakpoint_block(anchor, &bp, window, cx);
8633 }
8634
8635 pub fn enable_breakpoint(
8636 &mut self,
8637 _: &crate::actions::EnableBreakpoint,
8638 window: &mut Window,
8639 cx: &mut Context<Self>,
8640 ) {
8641 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8642 if breakpoint.is_disabled() {
8643 self.edit_breakpoint_at_anchor(
8644 anchor,
8645 breakpoint,
8646 BreakpointEditAction::InvertState,
8647 cx,
8648 );
8649 }
8650 }
8651 }
8652
8653 pub fn disable_breakpoint(
8654 &mut self,
8655 _: &crate::actions::DisableBreakpoint,
8656 window: &mut Window,
8657 cx: &mut Context<Self>,
8658 ) {
8659 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8660 if breakpoint.is_enabled() {
8661 self.edit_breakpoint_at_anchor(
8662 anchor,
8663 breakpoint,
8664 BreakpointEditAction::InvertState,
8665 cx,
8666 );
8667 }
8668 }
8669 }
8670
8671 pub fn toggle_breakpoint(
8672 &mut self,
8673 _: &crate::actions::ToggleBreakpoint,
8674 window: &mut Window,
8675 cx: &mut Context<Self>,
8676 ) {
8677 let edit_action = BreakpointEditAction::Toggle;
8678
8679 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8680 self.edit_breakpoint_at_anchor(anchor, breakpoint, edit_action, cx);
8681 } else {
8682 let cursor_position: Point = self.selections.newest(cx).head();
8683
8684 let breakpoint_position = self
8685 .snapshot(window, cx)
8686 .display_snapshot
8687 .buffer_snapshot
8688 .anchor_before(Point::new(cursor_position.row, 0));
8689
8690 self.edit_breakpoint_at_anchor(
8691 breakpoint_position,
8692 Breakpoint::new_standard(),
8693 edit_action,
8694 cx,
8695 );
8696 }
8697 }
8698
8699 pub fn edit_breakpoint_at_anchor(
8700 &mut self,
8701 breakpoint_position: Anchor,
8702 breakpoint: Breakpoint,
8703 edit_action: BreakpointEditAction,
8704 cx: &mut Context<Self>,
8705 ) {
8706 let Some(breakpoint_store) = &self.breakpoint_store else {
8707 return;
8708 };
8709
8710 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8711 if breakpoint_position == Anchor::min() {
8712 self.buffer()
8713 .read(cx)
8714 .excerpt_buffer_ids()
8715 .into_iter()
8716 .next()
8717 } else {
8718 None
8719 }
8720 }) else {
8721 return;
8722 };
8723
8724 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8725 return;
8726 };
8727
8728 breakpoint_store.update(cx, |breakpoint_store, cx| {
8729 breakpoint_store.toggle_breakpoint(
8730 buffer,
8731 (breakpoint_position.text_anchor, breakpoint),
8732 edit_action,
8733 cx,
8734 );
8735 });
8736
8737 cx.notify();
8738 }
8739
8740 #[cfg(any(test, feature = "test-support"))]
8741 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8742 self.breakpoint_store.clone()
8743 }
8744
8745 pub fn prepare_restore_change(
8746 &self,
8747 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8748 hunk: &MultiBufferDiffHunk,
8749 cx: &mut App,
8750 ) -> Option<()> {
8751 if hunk.is_created_file() {
8752 return None;
8753 }
8754 let buffer = self.buffer.read(cx);
8755 let diff = buffer.diff_for(hunk.buffer_id)?;
8756 let buffer = buffer.buffer(hunk.buffer_id)?;
8757 let buffer = buffer.read(cx);
8758 let original_text = diff
8759 .read(cx)
8760 .base_text()
8761 .as_rope()
8762 .slice(hunk.diff_base_byte_range.clone());
8763 let buffer_snapshot = buffer.snapshot();
8764 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8765 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8766 probe
8767 .0
8768 .start
8769 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8770 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8771 }) {
8772 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8773 Some(())
8774 } else {
8775 None
8776 }
8777 }
8778
8779 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8780 self.manipulate_lines(window, cx, |lines| lines.reverse())
8781 }
8782
8783 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8784 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8785 }
8786
8787 fn manipulate_lines<Fn>(
8788 &mut self,
8789 window: &mut Window,
8790 cx: &mut Context<Self>,
8791 mut callback: Fn,
8792 ) where
8793 Fn: FnMut(&mut Vec<&str>),
8794 {
8795 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8796 let buffer = self.buffer.read(cx).snapshot(cx);
8797
8798 let mut edits = Vec::new();
8799
8800 let selections = self.selections.all::<Point>(cx);
8801 let mut selections = selections.iter().peekable();
8802 let mut contiguous_row_selections = Vec::new();
8803 let mut new_selections = Vec::new();
8804 let mut added_lines = 0;
8805 let mut removed_lines = 0;
8806
8807 while let Some(selection) = selections.next() {
8808 let (start_row, end_row) = consume_contiguous_rows(
8809 &mut contiguous_row_selections,
8810 selection,
8811 &display_map,
8812 &mut selections,
8813 );
8814
8815 let start_point = Point::new(start_row.0, 0);
8816 let end_point = Point::new(
8817 end_row.previous_row().0,
8818 buffer.line_len(end_row.previous_row()),
8819 );
8820 let text = buffer
8821 .text_for_range(start_point..end_point)
8822 .collect::<String>();
8823
8824 let mut lines = text.split('\n').collect_vec();
8825
8826 let lines_before = lines.len();
8827 callback(&mut lines);
8828 let lines_after = lines.len();
8829
8830 edits.push((start_point..end_point, lines.join("\n")));
8831
8832 // Selections must change based on added and removed line count
8833 let start_row =
8834 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8835 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8836 new_selections.push(Selection {
8837 id: selection.id,
8838 start: start_row,
8839 end: end_row,
8840 goal: SelectionGoal::None,
8841 reversed: selection.reversed,
8842 });
8843
8844 if lines_after > lines_before {
8845 added_lines += lines_after - lines_before;
8846 } else if lines_before > lines_after {
8847 removed_lines += lines_before - lines_after;
8848 }
8849 }
8850
8851 self.transact(window, cx, |this, window, cx| {
8852 let buffer = this.buffer.update(cx, |buffer, cx| {
8853 buffer.edit(edits, None, cx);
8854 buffer.snapshot(cx)
8855 });
8856
8857 // Recalculate offsets on newly edited buffer
8858 let new_selections = new_selections
8859 .iter()
8860 .map(|s| {
8861 let start_point = Point::new(s.start.0, 0);
8862 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8863 Selection {
8864 id: s.id,
8865 start: buffer.point_to_offset(start_point),
8866 end: buffer.point_to_offset(end_point),
8867 goal: s.goal,
8868 reversed: s.reversed,
8869 }
8870 })
8871 .collect();
8872
8873 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8874 s.select(new_selections);
8875 });
8876
8877 this.request_autoscroll(Autoscroll::fit(), cx);
8878 });
8879 }
8880
8881 pub fn convert_to_upper_case(
8882 &mut self,
8883 _: &ConvertToUpperCase,
8884 window: &mut Window,
8885 cx: &mut Context<Self>,
8886 ) {
8887 self.manipulate_text(window, cx, |text| text.to_uppercase())
8888 }
8889
8890 pub fn convert_to_lower_case(
8891 &mut self,
8892 _: &ConvertToLowerCase,
8893 window: &mut Window,
8894 cx: &mut Context<Self>,
8895 ) {
8896 self.manipulate_text(window, cx, |text| text.to_lowercase())
8897 }
8898
8899 pub fn convert_to_title_case(
8900 &mut self,
8901 _: &ConvertToTitleCase,
8902 window: &mut Window,
8903 cx: &mut Context<Self>,
8904 ) {
8905 self.manipulate_text(window, cx, |text| {
8906 text.split('\n')
8907 .map(|line| line.to_case(Case::Title))
8908 .join("\n")
8909 })
8910 }
8911
8912 pub fn convert_to_snake_case(
8913 &mut self,
8914 _: &ConvertToSnakeCase,
8915 window: &mut Window,
8916 cx: &mut Context<Self>,
8917 ) {
8918 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8919 }
8920
8921 pub fn convert_to_kebab_case(
8922 &mut self,
8923 _: &ConvertToKebabCase,
8924 window: &mut Window,
8925 cx: &mut Context<Self>,
8926 ) {
8927 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8928 }
8929
8930 pub fn convert_to_upper_camel_case(
8931 &mut self,
8932 _: &ConvertToUpperCamelCase,
8933 window: &mut Window,
8934 cx: &mut Context<Self>,
8935 ) {
8936 self.manipulate_text(window, cx, |text| {
8937 text.split('\n')
8938 .map(|line| line.to_case(Case::UpperCamel))
8939 .join("\n")
8940 })
8941 }
8942
8943 pub fn convert_to_lower_camel_case(
8944 &mut self,
8945 _: &ConvertToLowerCamelCase,
8946 window: &mut Window,
8947 cx: &mut Context<Self>,
8948 ) {
8949 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8950 }
8951
8952 pub fn convert_to_opposite_case(
8953 &mut self,
8954 _: &ConvertToOppositeCase,
8955 window: &mut Window,
8956 cx: &mut Context<Self>,
8957 ) {
8958 self.manipulate_text(window, cx, |text| {
8959 text.chars()
8960 .fold(String::with_capacity(text.len()), |mut t, c| {
8961 if c.is_uppercase() {
8962 t.extend(c.to_lowercase());
8963 } else {
8964 t.extend(c.to_uppercase());
8965 }
8966 t
8967 })
8968 })
8969 }
8970
8971 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8972 where
8973 Fn: FnMut(&str) -> String,
8974 {
8975 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8976 let buffer = self.buffer.read(cx).snapshot(cx);
8977
8978 let mut new_selections = Vec::new();
8979 let mut edits = Vec::new();
8980 let mut selection_adjustment = 0i32;
8981
8982 for selection in self.selections.all::<usize>(cx) {
8983 let selection_is_empty = selection.is_empty();
8984
8985 let (start, end) = if selection_is_empty {
8986 let word_range = movement::surrounding_word(
8987 &display_map,
8988 selection.start.to_display_point(&display_map),
8989 );
8990 let start = word_range.start.to_offset(&display_map, Bias::Left);
8991 let end = word_range.end.to_offset(&display_map, Bias::Left);
8992 (start, end)
8993 } else {
8994 (selection.start, selection.end)
8995 };
8996
8997 let text = buffer.text_for_range(start..end).collect::<String>();
8998 let old_length = text.len() as i32;
8999 let text = callback(&text);
9000
9001 new_selections.push(Selection {
9002 start: (start as i32 - selection_adjustment) as usize,
9003 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9004 goal: SelectionGoal::None,
9005 ..selection
9006 });
9007
9008 selection_adjustment += old_length - text.len() as i32;
9009
9010 edits.push((start..end, text));
9011 }
9012
9013 self.transact(window, cx, |this, window, cx| {
9014 this.buffer.update(cx, |buffer, cx| {
9015 buffer.edit(edits, None, cx);
9016 });
9017
9018 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9019 s.select(new_selections);
9020 });
9021
9022 this.request_autoscroll(Autoscroll::fit(), cx);
9023 });
9024 }
9025
9026 pub fn duplicate(
9027 &mut self,
9028 upwards: bool,
9029 whole_lines: bool,
9030 window: &mut Window,
9031 cx: &mut Context<Self>,
9032 ) {
9033 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9034 let buffer = &display_map.buffer_snapshot;
9035 let selections = self.selections.all::<Point>(cx);
9036
9037 let mut edits = Vec::new();
9038 let mut selections_iter = selections.iter().peekable();
9039 while let Some(selection) = selections_iter.next() {
9040 let mut rows = selection.spanned_rows(false, &display_map);
9041 // duplicate line-wise
9042 if whole_lines || selection.start == selection.end {
9043 // Avoid duplicating the same lines twice.
9044 while let Some(next_selection) = selections_iter.peek() {
9045 let next_rows = next_selection.spanned_rows(false, &display_map);
9046 if next_rows.start < rows.end {
9047 rows.end = next_rows.end;
9048 selections_iter.next().unwrap();
9049 } else {
9050 break;
9051 }
9052 }
9053
9054 // Copy the text from the selected row region and splice it either at the start
9055 // or end of the region.
9056 let start = Point::new(rows.start.0, 0);
9057 let end = Point::new(
9058 rows.end.previous_row().0,
9059 buffer.line_len(rows.end.previous_row()),
9060 );
9061 let text = buffer
9062 .text_for_range(start..end)
9063 .chain(Some("\n"))
9064 .collect::<String>();
9065 let insert_location = if upwards {
9066 Point::new(rows.end.0, 0)
9067 } else {
9068 start
9069 };
9070 edits.push((insert_location..insert_location, text));
9071 } else {
9072 // duplicate character-wise
9073 let start = selection.start;
9074 let end = selection.end;
9075 let text = buffer.text_for_range(start..end).collect::<String>();
9076 edits.push((selection.end..selection.end, text));
9077 }
9078 }
9079
9080 self.transact(window, cx, |this, _, cx| {
9081 this.buffer.update(cx, |buffer, cx| {
9082 buffer.edit(edits, None, cx);
9083 });
9084
9085 this.request_autoscroll(Autoscroll::fit(), cx);
9086 });
9087 }
9088
9089 pub fn duplicate_line_up(
9090 &mut self,
9091 _: &DuplicateLineUp,
9092 window: &mut Window,
9093 cx: &mut Context<Self>,
9094 ) {
9095 self.duplicate(true, true, window, cx);
9096 }
9097
9098 pub fn duplicate_line_down(
9099 &mut self,
9100 _: &DuplicateLineDown,
9101 window: &mut Window,
9102 cx: &mut Context<Self>,
9103 ) {
9104 self.duplicate(false, true, window, cx);
9105 }
9106
9107 pub fn duplicate_selection(
9108 &mut self,
9109 _: &DuplicateSelection,
9110 window: &mut Window,
9111 cx: &mut Context<Self>,
9112 ) {
9113 self.duplicate(false, false, window, cx);
9114 }
9115
9116 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9117 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9118 let buffer = self.buffer.read(cx).snapshot(cx);
9119
9120 let mut edits = Vec::new();
9121 let mut unfold_ranges = Vec::new();
9122 let mut refold_creases = Vec::new();
9123
9124 let selections = self.selections.all::<Point>(cx);
9125 let mut selections = selections.iter().peekable();
9126 let mut contiguous_row_selections = Vec::new();
9127 let mut new_selections = Vec::new();
9128
9129 while let Some(selection) = selections.next() {
9130 // Find all the selections that span a contiguous row range
9131 let (start_row, end_row) = consume_contiguous_rows(
9132 &mut contiguous_row_selections,
9133 selection,
9134 &display_map,
9135 &mut selections,
9136 );
9137
9138 // Move the text spanned by the row range to be before the line preceding the row range
9139 if start_row.0 > 0 {
9140 let range_to_move = Point::new(
9141 start_row.previous_row().0,
9142 buffer.line_len(start_row.previous_row()),
9143 )
9144 ..Point::new(
9145 end_row.previous_row().0,
9146 buffer.line_len(end_row.previous_row()),
9147 );
9148 let insertion_point = display_map
9149 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9150 .0;
9151
9152 // Don't move lines across excerpts
9153 if buffer
9154 .excerpt_containing(insertion_point..range_to_move.end)
9155 .is_some()
9156 {
9157 let text = buffer
9158 .text_for_range(range_to_move.clone())
9159 .flat_map(|s| s.chars())
9160 .skip(1)
9161 .chain(['\n'])
9162 .collect::<String>();
9163
9164 edits.push((
9165 buffer.anchor_after(range_to_move.start)
9166 ..buffer.anchor_before(range_to_move.end),
9167 String::new(),
9168 ));
9169 let insertion_anchor = buffer.anchor_after(insertion_point);
9170 edits.push((insertion_anchor..insertion_anchor, text));
9171
9172 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9173
9174 // Move selections up
9175 new_selections.extend(contiguous_row_selections.drain(..).map(
9176 |mut selection| {
9177 selection.start.row -= row_delta;
9178 selection.end.row -= row_delta;
9179 selection
9180 },
9181 ));
9182
9183 // Move folds up
9184 unfold_ranges.push(range_to_move.clone());
9185 for fold in display_map.folds_in_range(
9186 buffer.anchor_before(range_to_move.start)
9187 ..buffer.anchor_after(range_to_move.end),
9188 ) {
9189 let mut start = fold.range.start.to_point(&buffer);
9190 let mut end = fold.range.end.to_point(&buffer);
9191 start.row -= row_delta;
9192 end.row -= row_delta;
9193 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9194 }
9195 }
9196 }
9197
9198 // If we didn't move line(s), preserve the existing selections
9199 new_selections.append(&mut contiguous_row_selections);
9200 }
9201
9202 self.transact(window, cx, |this, window, cx| {
9203 this.unfold_ranges(&unfold_ranges, true, true, cx);
9204 this.buffer.update(cx, |buffer, cx| {
9205 for (range, text) in edits {
9206 buffer.edit([(range, text)], None, cx);
9207 }
9208 });
9209 this.fold_creases(refold_creases, true, window, cx);
9210 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9211 s.select(new_selections);
9212 })
9213 });
9214 }
9215
9216 pub fn move_line_down(
9217 &mut self,
9218 _: &MoveLineDown,
9219 window: &mut Window,
9220 cx: &mut Context<Self>,
9221 ) {
9222 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9223 let buffer = self.buffer.read(cx).snapshot(cx);
9224
9225 let mut edits = Vec::new();
9226 let mut unfold_ranges = Vec::new();
9227 let mut refold_creases = Vec::new();
9228
9229 let selections = self.selections.all::<Point>(cx);
9230 let mut selections = selections.iter().peekable();
9231 let mut contiguous_row_selections = Vec::new();
9232 let mut new_selections = Vec::new();
9233
9234 while let Some(selection) = selections.next() {
9235 // Find all the selections that span a contiguous row range
9236 let (start_row, end_row) = consume_contiguous_rows(
9237 &mut contiguous_row_selections,
9238 selection,
9239 &display_map,
9240 &mut selections,
9241 );
9242
9243 // Move the text spanned by the row range to be after the last line of the row range
9244 if end_row.0 <= buffer.max_point().row {
9245 let range_to_move =
9246 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9247 let insertion_point = display_map
9248 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9249 .0;
9250
9251 // Don't move lines across excerpt boundaries
9252 if buffer
9253 .excerpt_containing(range_to_move.start..insertion_point)
9254 .is_some()
9255 {
9256 let mut text = String::from("\n");
9257 text.extend(buffer.text_for_range(range_to_move.clone()));
9258 text.pop(); // Drop trailing newline
9259 edits.push((
9260 buffer.anchor_after(range_to_move.start)
9261 ..buffer.anchor_before(range_to_move.end),
9262 String::new(),
9263 ));
9264 let insertion_anchor = buffer.anchor_after(insertion_point);
9265 edits.push((insertion_anchor..insertion_anchor, text));
9266
9267 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9268
9269 // Move selections down
9270 new_selections.extend(contiguous_row_selections.drain(..).map(
9271 |mut selection| {
9272 selection.start.row += row_delta;
9273 selection.end.row += row_delta;
9274 selection
9275 },
9276 ));
9277
9278 // Move folds down
9279 unfold_ranges.push(range_to_move.clone());
9280 for fold in display_map.folds_in_range(
9281 buffer.anchor_before(range_to_move.start)
9282 ..buffer.anchor_after(range_to_move.end),
9283 ) {
9284 let mut start = fold.range.start.to_point(&buffer);
9285 let mut end = fold.range.end.to_point(&buffer);
9286 start.row += row_delta;
9287 end.row += row_delta;
9288 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9289 }
9290 }
9291 }
9292
9293 // If we didn't move line(s), preserve the existing selections
9294 new_selections.append(&mut contiguous_row_selections);
9295 }
9296
9297 self.transact(window, cx, |this, window, cx| {
9298 this.unfold_ranges(&unfold_ranges, true, true, cx);
9299 this.buffer.update(cx, |buffer, cx| {
9300 for (range, text) in edits {
9301 buffer.edit([(range, text)], None, cx);
9302 }
9303 });
9304 this.fold_creases(refold_creases, true, window, cx);
9305 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9306 s.select(new_selections)
9307 });
9308 });
9309 }
9310
9311 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9312 let text_layout_details = &self.text_layout_details(window);
9313 self.transact(window, cx, |this, window, cx| {
9314 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9315 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9316 let line_mode = s.line_mode;
9317 s.move_with(|display_map, selection| {
9318 if !selection.is_empty() || line_mode {
9319 return;
9320 }
9321
9322 let mut head = selection.head();
9323 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9324 if head.column() == display_map.line_len(head.row()) {
9325 transpose_offset = display_map
9326 .buffer_snapshot
9327 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9328 }
9329
9330 if transpose_offset == 0 {
9331 return;
9332 }
9333
9334 *head.column_mut() += 1;
9335 head = display_map.clip_point(head, Bias::Right);
9336 let goal = SelectionGoal::HorizontalPosition(
9337 display_map
9338 .x_for_display_point(head, text_layout_details)
9339 .into(),
9340 );
9341 selection.collapse_to(head, goal);
9342
9343 let transpose_start = display_map
9344 .buffer_snapshot
9345 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9346 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9347 let transpose_end = display_map
9348 .buffer_snapshot
9349 .clip_offset(transpose_offset + 1, Bias::Right);
9350 if let Some(ch) =
9351 display_map.buffer_snapshot.chars_at(transpose_start).next()
9352 {
9353 edits.push((transpose_start..transpose_offset, String::new()));
9354 edits.push((transpose_end..transpose_end, ch.to_string()));
9355 }
9356 }
9357 });
9358 edits
9359 });
9360 this.buffer
9361 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9362 let selections = this.selections.all::<usize>(cx);
9363 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9364 s.select(selections);
9365 });
9366 });
9367 }
9368
9369 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9370 self.rewrap_impl(RewrapOptions::default(), cx)
9371 }
9372
9373 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9374 let buffer = self.buffer.read(cx).snapshot(cx);
9375 let selections = self.selections.all::<Point>(cx);
9376 let mut selections = selections.iter().peekable();
9377
9378 let mut edits = Vec::new();
9379 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9380
9381 while let Some(selection) = selections.next() {
9382 let mut start_row = selection.start.row;
9383 let mut end_row = selection.end.row;
9384
9385 // Skip selections that overlap with a range that has already been rewrapped.
9386 let selection_range = start_row..end_row;
9387 if rewrapped_row_ranges
9388 .iter()
9389 .any(|range| range.overlaps(&selection_range))
9390 {
9391 continue;
9392 }
9393
9394 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9395
9396 // Since not all lines in the selection may be at the same indent
9397 // level, choose the indent size that is the most common between all
9398 // of the lines.
9399 //
9400 // If there is a tie, we use the deepest indent.
9401 let (indent_size, indent_end) = {
9402 let mut indent_size_occurrences = HashMap::default();
9403 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9404
9405 for row in start_row..=end_row {
9406 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9407 rows_by_indent_size.entry(indent).or_default().push(row);
9408 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9409 }
9410
9411 let indent_size = indent_size_occurrences
9412 .into_iter()
9413 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9414 .map(|(indent, _)| indent)
9415 .unwrap_or_default();
9416 let row = rows_by_indent_size[&indent_size][0];
9417 let indent_end = Point::new(row, indent_size.len);
9418
9419 (indent_size, indent_end)
9420 };
9421
9422 let mut line_prefix = indent_size.chars().collect::<String>();
9423
9424 let mut inside_comment = false;
9425 if let Some(comment_prefix) =
9426 buffer
9427 .language_scope_at(selection.head())
9428 .and_then(|language| {
9429 language
9430 .line_comment_prefixes()
9431 .iter()
9432 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9433 .cloned()
9434 })
9435 {
9436 line_prefix.push_str(&comment_prefix);
9437 inside_comment = true;
9438 }
9439
9440 let language_settings = buffer.language_settings_at(selection.head(), cx);
9441 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9442 RewrapBehavior::InComments => inside_comment,
9443 RewrapBehavior::InSelections => !selection.is_empty(),
9444 RewrapBehavior::Anywhere => true,
9445 };
9446
9447 let should_rewrap = options.override_language_settings
9448 || allow_rewrap_based_on_language
9449 || self.hard_wrap.is_some();
9450 if !should_rewrap {
9451 continue;
9452 }
9453
9454 if selection.is_empty() {
9455 'expand_upwards: while start_row > 0 {
9456 let prev_row = start_row - 1;
9457 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9458 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9459 {
9460 start_row = prev_row;
9461 } else {
9462 break 'expand_upwards;
9463 }
9464 }
9465
9466 'expand_downwards: while end_row < buffer.max_point().row {
9467 let next_row = end_row + 1;
9468 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9469 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9470 {
9471 end_row = next_row;
9472 } else {
9473 break 'expand_downwards;
9474 }
9475 }
9476 }
9477
9478 let start = Point::new(start_row, 0);
9479 let start_offset = start.to_offset(&buffer);
9480 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9481 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9482 let Some(lines_without_prefixes) = selection_text
9483 .lines()
9484 .map(|line| {
9485 line.strip_prefix(&line_prefix)
9486 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9487 .ok_or_else(|| {
9488 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9489 })
9490 })
9491 .collect::<Result<Vec<_>, _>>()
9492 .log_err()
9493 else {
9494 continue;
9495 };
9496
9497 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9498 buffer
9499 .language_settings_at(Point::new(start_row, 0), cx)
9500 .preferred_line_length as usize
9501 });
9502 let wrapped_text = wrap_with_prefix(
9503 line_prefix,
9504 lines_without_prefixes.join("\n"),
9505 wrap_column,
9506 tab_size,
9507 options.preserve_existing_whitespace,
9508 );
9509
9510 // TODO: should always use char-based diff while still supporting cursor behavior that
9511 // matches vim.
9512 let mut diff_options = DiffOptions::default();
9513 if options.override_language_settings {
9514 diff_options.max_word_diff_len = 0;
9515 diff_options.max_word_diff_line_count = 0;
9516 } else {
9517 diff_options.max_word_diff_len = usize::MAX;
9518 diff_options.max_word_diff_line_count = usize::MAX;
9519 }
9520
9521 for (old_range, new_text) in
9522 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9523 {
9524 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9525 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9526 edits.push((edit_start..edit_end, new_text));
9527 }
9528
9529 rewrapped_row_ranges.push(start_row..=end_row);
9530 }
9531
9532 self.buffer
9533 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9534 }
9535
9536 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9537 let mut text = String::new();
9538 let buffer = self.buffer.read(cx).snapshot(cx);
9539 let mut selections = self.selections.all::<Point>(cx);
9540 let mut clipboard_selections = Vec::with_capacity(selections.len());
9541 {
9542 let max_point = buffer.max_point();
9543 let mut is_first = true;
9544 for selection in &mut selections {
9545 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9546 if is_entire_line {
9547 selection.start = Point::new(selection.start.row, 0);
9548 if !selection.is_empty() && selection.end.column == 0 {
9549 selection.end = cmp::min(max_point, selection.end);
9550 } else {
9551 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9552 }
9553 selection.goal = SelectionGoal::None;
9554 }
9555 if is_first {
9556 is_first = false;
9557 } else {
9558 text += "\n";
9559 }
9560 let mut len = 0;
9561 for chunk in buffer.text_for_range(selection.start..selection.end) {
9562 text.push_str(chunk);
9563 len += chunk.len();
9564 }
9565 clipboard_selections.push(ClipboardSelection {
9566 len,
9567 is_entire_line,
9568 first_line_indent: buffer
9569 .indent_size_for_line(MultiBufferRow(selection.start.row))
9570 .len,
9571 });
9572 }
9573 }
9574
9575 self.transact(window, cx, |this, window, cx| {
9576 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9577 s.select(selections);
9578 });
9579 this.insert("", window, cx);
9580 });
9581 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9582 }
9583
9584 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9585 let item = self.cut_common(window, cx);
9586 cx.write_to_clipboard(item);
9587 }
9588
9589 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9590 self.change_selections(None, window, cx, |s| {
9591 s.move_with(|snapshot, sel| {
9592 if sel.is_empty() {
9593 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9594 }
9595 });
9596 });
9597 let item = self.cut_common(window, cx);
9598 cx.set_global(KillRing(item))
9599 }
9600
9601 pub fn kill_ring_yank(
9602 &mut self,
9603 _: &KillRingYank,
9604 window: &mut Window,
9605 cx: &mut Context<Self>,
9606 ) {
9607 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9608 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9609 (kill_ring.text().to_string(), kill_ring.metadata_json())
9610 } else {
9611 return;
9612 }
9613 } else {
9614 return;
9615 };
9616 self.do_paste(&text, metadata, false, window, cx);
9617 }
9618
9619 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
9620 self.do_copy(true, cx);
9621 }
9622
9623 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9624 self.do_copy(false, cx);
9625 }
9626
9627 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
9628 let selections = self.selections.all::<Point>(cx);
9629 let buffer = self.buffer.read(cx).read(cx);
9630 let mut text = String::new();
9631
9632 let mut clipboard_selections = Vec::with_capacity(selections.len());
9633 {
9634 let max_point = buffer.max_point();
9635 let mut is_first = true;
9636 for selection in &selections {
9637 let mut start = selection.start;
9638 let mut end = selection.end;
9639 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9640 if is_entire_line {
9641 start = Point::new(start.row, 0);
9642 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9643 }
9644
9645 let mut trimmed_selections = Vec::new();
9646 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
9647 let row = MultiBufferRow(start.row);
9648 let first_indent = buffer.indent_size_for_line(row);
9649 if first_indent.len == 0 || start.column > first_indent.len {
9650 trimmed_selections.push(start..end);
9651 } else {
9652 trimmed_selections.push(
9653 Point::new(row.0, first_indent.len)
9654 ..Point::new(row.0, buffer.line_len(row)),
9655 );
9656 for row in start.row + 1..=end.row {
9657 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
9658 if row_indent_size.len >= first_indent.len {
9659 trimmed_selections.push(
9660 Point::new(row, first_indent.len)
9661 ..Point::new(row, buffer.line_len(MultiBufferRow(row))),
9662 );
9663 } else {
9664 trimmed_selections.clear();
9665 trimmed_selections.push(start..end);
9666 break;
9667 }
9668 }
9669 }
9670 } else {
9671 trimmed_selections.push(start..end);
9672 }
9673
9674 for trimmed_range in trimmed_selections {
9675 if is_first {
9676 is_first = false;
9677 } else {
9678 text += "\n";
9679 }
9680 let mut len = 0;
9681 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
9682 text.push_str(chunk);
9683 len += chunk.len();
9684 }
9685 clipboard_selections.push(ClipboardSelection {
9686 len,
9687 is_entire_line,
9688 first_line_indent: buffer
9689 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
9690 .len,
9691 });
9692 }
9693 }
9694 }
9695
9696 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9697 text,
9698 clipboard_selections,
9699 ));
9700 }
9701
9702 pub fn do_paste(
9703 &mut self,
9704 text: &String,
9705 clipboard_selections: Option<Vec<ClipboardSelection>>,
9706 handle_entire_lines: bool,
9707 window: &mut Window,
9708 cx: &mut Context<Self>,
9709 ) {
9710 if self.read_only(cx) {
9711 return;
9712 }
9713
9714 let clipboard_text = Cow::Borrowed(text);
9715
9716 self.transact(window, cx, |this, window, cx| {
9717 if let Some(mut clipboard_selections) = clipboard_selections {
9718 let old_selections = this.selections.all::<usize>(cx);
9719 let all_selections_were_entire_line =
9720 clipboard_selections.iter().all(|s| s.is_entire_line);
9721 let first_selection_indent_column =
9722 clipboard_selections.first().map(|s| s.first_line_indent);
9723 if clipboard_selections.len() != old_selections.len() {
9724 clipboard_selections.drain(..);
9725 }
9726 let cursor_offset = this.selections.last::<usize>(cx).head();
9727 let mut auto_indent_on_paste = true;
9728
9729 this.buffer.update(cx, |buffer, cx| {
9730 let snapshot = buffer.read(cx);
9731 auto_indent_on_paste = snapshot
9732 .language_settings_at(cursor_offset, cx)
9733 .auto_indent_on_paste;
9734
9735 let mut start_offset = 0;
9736 let mut edits = Vec::new();
9737 let mut original_indent_columns = Vec::new();
9738 for (ix, selection) in old_selections.iter().enumerate() {
9739 let to_insert;
9740 let entire_line;
9741 let original_indent_column;
9742 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
9743 let end_offset = start_offset + clipboard_selection.len;
9744 to_insert = &clipboard_text[start_offset..end_offset];
9745 entire_line = clipboard_selection.is_entire_line;
9746 start_offset = end_offset + 1;
9747 original_indent_column = Some(clipboard_selection.first_line_indent);
9748 } else {
9749 to_insert = clipboard_text.as_str();
9750 entire_line = all_selections_were_entire_line;
9751 original_indent_column = first_selection_indent_column
9752 }
9753
9754 // If the corresponding selection was empty when this slice of the
9755 // clipboard text was written, then the entire line containing the
9756 // selection was copied. If this selection is also currently empty,
9757 // then paste the line before the current line of the buffer.
9758 let range = if selection.is_empty() && handle_entire_lines && entire_line {
9759 let column = selection.start.to_point(&snapshot).column as usize;
9760 let line_start = selection.start - column;
9761 line_start..line_start
9762 } else {
9763 selection.range()
9764 };
9765
9766 edits.push((range, to_insert));
9767 original_indent_columns.push(original_indent_column);
9768 }
9769 drop(snapshot);
9770
9771 buffer.edit(
9772 edits,
9773 if auto_indent_on_paste {
9774 Some(AutoindentMode::Block {
9775 original_indent_columns,
9776 })
9777 } else {
9778 None
9779 },
9780 cx,
9781 );
9782 });
9783
9784 let selections = this.selections.all::<usize>(cx);
9785 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9786 s.select(selections)
9787 });
9788 } else {
9789 this.insert(&clipboard_text, window, cx);
9790 }
9791 });
9792 }
9793
9794 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
9795 if let Some(item) = cx.read_from_clipboard() {
9796 let entries = item.entries();
9797
9798 match entries.first() {
9799 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
9800 // of all the pasted entries.
9801 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9802 .do_paste(
9803 clipboard_string.text(),
9804 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9805 true,
9806 window,
9807 cx,
9808 ),
9809 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9810 }
9811 }
9812 }
9813
9814 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9815 if self.read_only(cx) {
9816 return;
9817 }
9818
9819 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9820 if let Some((selections, _)) =
9821 self.selection_history.transaction(transaction_id).cloned()
9822 {
9823 self.change_selections(None, window, cx, |s| {
9824 s.select_anchors(selections.to_vec());
9825 });
9826 } else {
9827 log::error!(
9828 "No entry in selection_history found for undo. \
9829 This may correspond to a bug where undo does not update the selection. \
9830 If this is occurring, please add details to \
9831 https://github.com/zed-industries/zed/issues/22692"
9832 );
9833 }
9834 self.request_autoscroll(Autoscroll::fit(), cx);
9835 self.unmark_text(window, cx);
9836 self.refresh_inline_completion(true, false, window, cx);
9837 cx.emit(EditorEvent::Edited { transaction_id });
9838 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9839 }
9840 }
9841
9842 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9843 if self.read_only(cx) {
9844 return;
9845 }
9846
9847 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9848 if let Some((_, Some(selections))) =
9849 self.selection_history.transaction(transaction_id).cloned()
9850 {
9851 self.change_selections(None, window, cx, |s| {
9852 s.select_anchors(selections.to_vec());
9853 });
9854 } else {
9855 log::error!(
9856 "No entry in selection_history found for redo. \
9857 This may correspond to a bug where undo does not update the selection. \
9858 If this is occurring, please add details to \
9859 https://github.com/zed-industries/zed/issues/22692"
9860 );
9861 }
9862 self.request_autoscroll(Autoscroll::fit(), cx);
9863 self.unmark_text(window, cx);
9864 self.refresh_inline_completion(true, false, window, cx);
9865 cx.emit(EditorEvent::Edited { transaction_id });
9866 }
9867 }
9868
9869 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9870 self.buffer
9871 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9872 }
9873
9874 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9875 self.buffer
9876 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9877 }
9878
9879 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9880 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9881 let line_mode = s.line_mode;
9882 s.move_with(|map, selection| {
9883 let cursor = if selection.is_empty() && !line_mode {
9884 movement::left(map, selection.start)
9885 } else {
9886 selection.start
9887 };
9888 selection.collapse_to(cursor, SelectionGoal::None);
9889 });
9890 })
9891 }
9892
9893 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9894 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9895 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9896 })
9897 }
9898
9899 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9900 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9901 let line_mode = s.line_mode;
9902 s.move_with(|map, selection| {
9903 let cursor = if selection.is_empty() && !line_mode {
9904 movement::right(map, selection.end)
9905 } else {
9906 selection.end
9907 };
9908 selection.collapse_to(cursor, SelectionGoal::None)
9909 });
9910 })
9911 }
9912
9913 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9914 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9915 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9916 })
9917 }
9918
9919 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9920 if self.take_rename(true, window, cx).is_some() {
9921 return;
9922 }
9923
9924 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9925 cx.propagate();
9926 return;
9927 }
9928
9929 let text_layout_details = &self.text_layout_details(window);
9930 let selection_count = self.selections.count();
9931 let first_selection = self.selections.first_anchor();
9932
9933 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9934 let line_mode = s.line_mode;
9935 s.move_with(|map, selection| {
9936 if !selection.is_empty() && !line_mode {
9937 selection.goal = SelectionGoal::None;
9938 }
9939 let (cursor, goal) = movement::up(
9940 map,
9941 selection.start,
9942 selection.goal,
9943 false,
9944 text_layout_details,
9945 );
9946 selection.collapse_to(cursor, goal);
9947 });
9948 });
9949
9950 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9951 {
9952 cx.propagate();
9953 }
9954 }
9955
9956 pub fn move_up_by_lines(
9957 &mut self,
9958 action: &MoveUpByLines,
9959 window: &mut Window,
9960 cx: &mut Context<Self>,
9961 ) {
9962 if self.take_rename(true, window, cx).is_some() {
9963 return;
9964 }
9965
9966 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9967 cx.propagate();
9968 return;
9969 }
9970
9971 let text_layout_details = &self.text_layout_details(window);
9972
9973 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9974 let line_mode = s.line_mode;
9975 s.move_with(|map, selection| {
9976 if !selection.is_empty() && !line_mode {
9977 selection.goal = SelectionGoal::None;
9978 }
9979 let (cursor, goal) = movement::up_by_rows(
9980 map,
9981 selection.start,
9982 action.lines,
9983 selection.goal,
9984 false,
9985 text_layout_details,
9986 );
9987 selection.collapse_to(cursor, goal);
9988 });
9989 })
9990 }
9991
9992 pub fn move_down_by_lines(
9993 &mut self,
9994 action: &MoveDownByLines,
9995 window: &mut Window,
9996 cx: &mut Context<Self>,
9997 ) {
9998 if self.take_rename(true, window, cx).is_some() {
9999 return;
10000 }
10001
10002 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10003 cx.propagate();
10004 return;
10005 }
10006
10007 let text_layout_details = &self.text_layout_details(window);
10008
10009 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10010 let line_mode = s.line_mode;
10011 s.move_with(|map, selection| {
10012 if !selection.is_empty() && !line_mode {
10013 selection.goal = SelectionGoal::None;
10014 }
10015 let (cursor, goal) = movement::down_by_rows(
10016 map,
10017 selection.start,
10018 action.lines,
10019 selection.goal,
10020 false,
10021 text_layout_details,
10022 );
10023 selection.collapse_to(cursor, goal);
10024 });
10025 })
10026 }
10027
10028 pub fn select_down_by_lines(
10029 &mut self,
10030 action: &SelectDownByLines,
10031 window: &mut Window,
10032 cx: &mut Context<Self>,
10033 ) {
10034 let text_layout_details = &self.text_layout_details(window);
10035 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10036 s.move_heads_with(|map, head, goal| {
10037 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10038 })
10039 })
10040 }
10041
10042 pub fn select_up_by_lines(
10043 &mut self,
10044 action: &SelectUpByLines,
10045 window: &mut Window,
10046 cx: &mut Context<Self>,
10047 ) {
10048 let text_layout_details = &self.text_layout_details(window);
10049 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10050 s.move_heads_with(|map, head, goal| {
10051 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10052 })
10053 })
10054 }
10055
10056 pub fn select_page_up(
10057 &mut self,
10058 _: &SelectPageUp,
10059 window: &mut Window,
10060 cx: &mut Context<Self>,
10061 ) {
10062 let Some(row_count) = self.visible_row_count() else {
10063 return;
10064 };
10065
10066 let text_layout_details = &self.text_layout_details(window);
10067
10068 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10069 s.move_heads_with(|map, head, goal| {
10070 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10071 })
10072 })
10073 }
10074
10075 pub fn move_page_up(
10076 &mut self,
10077 action: &MovePageUp,
10078 window: &mut Window,
10079 cx: &mut Context<Self>,
10080 ) {
10081 if self.take_rename(true, window, cx).is_some() {
10082 return;
10083 }
10084
10085 if self
10086 .context_menu
10087 .borrow_mut()
10088 .as_mut()
10089 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10090 .unwrap_or(false)
10091 {
10092 return;
10093 }
10094
10095 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10096 cx.propagate();
10097 return;
10098 }
10099
10100 let Some(row_count) = self.visible_row_count() else {
10101 return;
10102 };
10103
10104 let autoscroll = if action.center_cursor {
10105 Autoscroll::center()
10106 } else {
10107 Autoscroll::fit()
10108 };
10109
10110 let text_layout_details = &self.text_layout_details(window);
10111
10112 self.change_selections(Some(autoscroll), window, cx, |s| {
10113 let line_mode = s.line_mode;
10114 s.move_with(|map, selection| {
10115 if !selection.is_empty() && !line_mode {
10116 selection.goal = SelectionGoal::None;
10117 }
10118 let (cursor, goal) = movement::up_by_rows(
10119 map,
10120 selection.end,
10121 row_count,
10122 selection.goal,
10123 false,
10124 text_layout_details,
10125 );
10126 selection.collapse_to(cursor, goal);
10127 });
10128 });
10129 }
10130
10131 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10132 let text_layout_details = &self.text_layout_details(window);
10133 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10134 s.move_heads_with(|map, head, goal| {
10135 movement::up(map, head, goal, false, text_layout_details)
10136 })
10137 })
10138 }
10139
10140 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10141 self.take_rename(true, window, cx);
10142
10143 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10144 cx.propagate();
10145 return;
10146 }
10147
10148 let text_layout_details = &self.text_layout_details(window);
10149 let selection_count = self.selections.count();
10150 let first_selection = self.selections.first_anchor();
10151
10152 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10153 let line_mode = s.line_mode;
10154 s.move_with(|map, selection| {
10155 if !selection.is_empty() && !line_mode {
10156 selection.goal = SelectionGoal::None;
10157 }
10158 let (cursor, goal) = movement::down(
10159 map,
10160 selection.end,
10161 selection.goal,
10162 false,
10163 text_layout_details,
10164 );
10165 selection.collapse_to(cursor, goal);
10166 });
10167 });
10168
10169 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10170 {
10171 cx.propagate();
10172 }
10173 }
10174
10175 pub fn select_page_down(
10176 &mut self,
10177 _: &SelectPageDown,
10178 window: &mut Window,
10179 cx: &mut Context<Self>,
10180 ) {
10181 let Some(row_count) = self.visible_row_count() else {
10182 return;
10183 };
10184
10185 let text_layout_details = &self.text_layout_details(window);
10186
10187 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10188 s.move_heads_with(|map, head, goal| {
10189 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10190 })
10191 })
10192 }
10193
10194 pub fn move_page_down(
10195 &mut self,
10196 action: &MovePageDown,
10197 window: &mut Window,
10198 cx: &mut Context<Self>,
10199 ) {
10200 if self.take_rename(true, window, cx).is_some() {
10201 return;
10202 }
10203
10204 if self
10205 .context_menu
10206 .borrow_mut()
10207 .as_mut()
10208 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10209 .unwrap_or(false)
10210 {
10211 return;
10212 }
10213
10214 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10215 cx.propagate();
10216 return;
10217 }
10218
10219 let Some(row_count) = self.visible_row_count() else {
10220 return;
10221 };
10222
10223 let autoscroll = if action.center_cursor {
10224 Autoscroll::center()
10225 } else {
10226 Autoscroll::fit()
10227 };
10228
10229 let text_layout_details = &self.text_layout_details(window);
10230 self.change_selections(Some(autoscroll), window, cx, |s| {
10231 let line_mode = s.line_mode;
10232 s.move_with(|map, selection| {
10233 if !selection.is_empty() && !line_mode {
10234 selection.goal = SelectionGoal::None;
10235 }
10236 let (cursor, goal) = movement::down_by_rows(
10237 map,
10238 selection.end,
10239 row_count,
10240 selection.goal,
10241 false,
10242 text_layout_details,
10243 );
10244 selection.collapse_to(cursor, goal);
10245 });
10246 });
10247 }
10248
10249 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10250 let text_layout_details = &self.text_layout_details(window);
10251 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10252 s.move_heads_with(|map, head, goal| {
10253 movement::down(map, head, goal, false, text_layout_details)
10254 })
10255 });
10256 }
10257
10258 pub fn context_menu_first(
10259 &mut self,
10260 _: &ContextMenuFirst,
10261 _window: &mut Window,
10262 cx: &mut Context<Self>,
10263 ) {
10264 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10265 context_menu.select_first(self.completion_provider.as_deref(), cx);
10266 }
10267 }
10268
10269 pub fn context_menu_prev(
10270 &mut self,
10271 _: &ContextMenuPrevious,
10272 _window: &mut Window,
10273 cx: &mut Context<Self>,
10274 ) {
10275 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10276 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10277 }
10278 }
10279
10280 pub fn context_menu_next(
10281 &mut self,
10282 _: &ContextMenuNext,
10283 _window: &mut Window,
10284 cx: &mut Context<Self>,
10285 ) {
10286 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10287 context_menu.select_next(self.completion_provider.as_deref(), cx);
10288 }
10289 }
10290
10291 pub fn context_menu_last(
10292 &mut self,
10293 _: &ContextMenuLast,
10294 _window: &mut Window,
10295 cx: &mut Context<Self>,
10296 ) {
10297 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10298 context_menu.select_last(self.completion_provider.as_deref(), cx);
10299 }
10300 }
10301
10302 pub fn move_to_previous_word_start(
10303 &mut self,
10304 _: &MoveToPreviousWordStart,
10305 window: &mut Window,
10306 cx: &mut Context<Self>,
10307 ) {
10308 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10309 s.move_cursors_with(|map, head, _| {
10310 (
10311 movement::previous_word_start(map, head),
10312 SelectionGoal::None,
10313 )
10314 });
10315 })
10316 }
10317
10318 pub fn move_to_previous_subword_start(
10319 &mut self,
10320 _: &MoveToPreviousSubwordStart,
10321 window: &mut Window,
10322 cx: &mut Context<Self>,
10323 ) {
10324 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10325 s.move_cursors_with(|map, head, _| {
10326 (
10327 movement::previous_subword_start(map, head),
10328 SelectionGoal::None,
10329 )
10330 });
10331 })
10332 }
10333
10334 pub fn select_to_previous_word_start(
10335 &mut self,
10336 _: &SelectToPreviousWordStart,
10337 window: &mut Window,
10338 cx: &mut Context<Self>,
10339 ) {
10340 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10341 s.move_heads_with(|map, head, _| {
10342 (
10343 movement::previous_word_start(map, head),
10344 SelectionGoal::None,
10345 )
10346 });
10347 })
10348 }
10349
10350 pub fn select_to_previous_subword_start(
10351 &mut self,
10352 _: &SelectToPreviousSubwordStart,
10353 window: &mut Window,
10354 cx: &mut Context<Self>,
10355 ) {
10356 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10357 s.move_heads_with(|map, head, _| {
10358 (
10359 movement::previous_subword_start(map, head),
10360 SelectionGoal::None,
10361 )
10362 });
10363 })
10364 }
10365
10366 pub fn delete_to_previous_word_start(
10367 &mut self,
10368 action: &DeleteToPreviousWordStart,
10369 window: &mut Window,
10370 cx: &mut Context<Self>,
10371 ) {
10372 self.transact(window, cx, |this, window, cx| {
10373 this.select_autoclose_pair(window, cx);
10374 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10375 let line_mode = s.line_mode;
10376 s.move_with(|map, selection| {
10377 if selection.is_empty() && !line_mode {
10378 let cursor = if action.ignore_newlines {
10379 movement::previous_word_start(map, selection.head())
10380 } else {
10381 movement::previous_word_start_or_newline(map, selection.head())
10382 };
10383 selection.set_head(cursor, SelectionGoal::None);
10384 }
10385 });
10386 });
10387 this.insert("", window, cx);
10388 });
10389 }
10390
10391 pub fn delete_to_previous_subword_start(
10392 &mut self,
10393 _: &DeleteToPreviousSubwordStart,
10394 window: &mut Window,
10395 cx: &mut Context<Self>,
10396 ) {
10397 self.transact(window, cx, |this, window, cx| {
10398 this.select_autoclose_pair(window, cx);
10399 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10400 let line_mode = s.line_mode;
10401 s.move_with(|map, selection| {
10402 if selection.is_empty() && !line_mode {
10403 let cursor = movement::previous_subword_start(map, selection.head());
10404 selection.set_head(cursor, SelectionGoal::None);
10405 }
10406 });
10407 });
10408 this.insert("", window, cx);
10409 });
10410 }
10411
10412 pub fn move_to_next_word_end(
10413 &mut self,
10414 _: &MoveToNextWordEnd,
10415 window: &mut Window,
10416 cx: &mut Context<Self>,
10417 ) {
10418 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10419 s.move_cursors_with(|map, head, _| {
10420 (movement::next_word_end(map, head), SelectionGoal::None)
10421 });
10422 })
10423 }
10424
10425 pub fn move_to_next_subword_end(
10426 &mut self,
10427 _: &MoveToNextSubwordEnd,
10428 window: &mut Window,
10429 cx: &mut Context<Self>,
10430 ) {
10431 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10432 s.move_cursors_with(|map, head, _| {
10433 (movement::next_subword_end(map, head), SelectionGoal::None)
10434 });
10435 })
10436 }
10437
10438 pub fn select_to_next_word_end(
10439 &mut self,
10440 _: &SelectToNextWordEnd,
10441 window: &mut Window,
10442 cx: &mut Context<Self>,
10443 ) {
10444 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10445 s.move_heads_with(|map, head, _| {
10446 (movement::next_word_end(map, head), SelectionGoal::None)
10447 });
10448 })
10449 }
10450
10451 pub fn select_to_next_subword_end(
10452 &mut self,
10453 _: &SelectToNextSubwordEnd,
10454 window: &mut Window,
10455 cx: &mut Context<Self>,
10456 ) {
10457 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10458 s.move_heads_with(|map, head, _| {
10459 (movement::next_subword_end(map, head), SelectionGoal::None)
10460 });
10461 })
10462 }
10463
10464 pub fn delete_to_next_word_end(
10465 &mut self,
10466 action: &DeleteToNextWordEnd,
10467 window: &mut Window,
10468 cx: &mut Context<Self>,
10469 ) {
10470 self.transact(window, cx, |this, window, cx| {
10471 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10472 let line_mode = s.line_mode;
10473 s.move_with(|map, selection| {
10474 if selection.is_empty() && !line_mode {
10475 let cursor = if action.ignore_newlines {
10476 movement::next_word_end(map, selection.head())
10477 } else {
10478 movement::next_word_end_or_newline(map, selection.head())
10479 };
10480 selection.set_head(cursor, SelectionGoal::None);
10481 }
10482 });
10483 });
10484 this.insert("", window, cx);
10485 });
10486 }
10487
10488 pub fn delete_to_next_subword_end(
10489 &mut self,
10490 _: &DeleteToNextSubwordEnd,
10491 window: &mut Window,
10492 cx: &mut Context<Self>,
10493 ) {
10494 self.transact(window, cx, |this, window, cx| {
10495 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10496 s.move_with(|map, selection| {
10497 if selection.is_empty() {
10498 let cursor = movement::next_subword_end(map, selection.head());
10499 selection.set_head(cursor, SelectionGoal::None);
10500 }
10501 });
10502 });
10503 this.insert("", window, cx);
10504 });
10505 }
10506
10507 pub fn move_to_beginning_of_line(
10508 &mut self,
10509 action: &MoveToBeginningOfLine,
10510 window: &mut Window,
10511 cx: &mut Context<Self>,
10512 ) {
10513 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10514 s.move_cursors_with(|map, head, _| {
10515 (
10516 movement::indented_line_beginning(
10517 map,
10518 head,
10519 action.stop_at_soft_wraps,
10520 action.stop_at_indent,
10521 ),
10522 SelectionGoal::None,
10523 )
10524 });
10525 })
10526 }
10527
10528 pub fn select_to_beginning_of_line(
10529 &mut self,
10530 action: &SelectToBeginningOfLine,
10531 window: &mut Window,
10532 cx: &mut Context<Self>,
10533 ) {
10534 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10535 s.move_heads_with(|map, head, _| {
10536 (
10537 movement::indented_line_beginning(
10538 map,
10539 head,
10540 action.stop_at_soft_wraps,
10541 action.stop_at_indent,
10542 ),
10543 SelectionGoal::None,
10544 )
10545 });
10546 });
10547 }
10548
10549 pub fn delete_to_beginning_of_line(
10550 &mut self,
10551 action: &DeleteToBeginningOfLine,
10552 window: &mut Window,
10553 cx: &mut Context<Self>,
10554 ) {
10555 self.transact(window, cx, |this, window, cx| {
10556 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10557 s.move_with(|_, selection| {
10558 selection.reversed = true;
10559 });
10560 });
10561
10562 this.select_to_beginning_of_line(
10563 &SelectToBeginningOfLine {
10564 stop_at_soft_wraps: false,
10565 stop_at_indent: action.stop_at_indent,
10566 },
10567 window,
10568 cx,
10569 );
10570 this.backspace(&Backspace, window, cx);
10571 });
10572 }
10573
10574 pub fn move_to_end_of_line(
10575 &mut self,
10576 action: &MoveToEndOfLine,
10577 window: &mut Window,
10578 cx: &mut Context<Self>,
10579 ) {
10580 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10581 s.move_cursors_with(|map, head, _| {
10582 (
10583 movement::line_end(map, head, action.stop_at_soft_wraps),
10584 SelectionGoal::None,
10585 )
10586 });
10587 })
10588 }
10589
10590 pub fn select_to_end_of_line(
10591 &mut self,
10592 action: &SelectToEndOfLine,
10593 window: &mut Window,
10594 cx: &mut Context<Self>,
10595 ) {
10596 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10597 s.move_heads_with(|map, head, _| {
10598 (
10599 movement::line_end(map, head, action.stop_at_soft_wraps),
10600 SelectionGoal::None,
10601 )
10602 });
10603 })
10604 }
10605
10606 pub fn delete_to_end_of_line(
10607 &mut self,
10608 _: &DeleteToEndOfLine,
10609 window: &mut Window,
10610 cx: &mut Context<Self>,
10611 ) {
10612 self.transact(window, cx, |this, window, cx| {
10613 this.select_to_end_of_line(
10614 &SelectToEndOfLine {
10615 stop_at_soft_wraps: false,
10616 },
10617 window,
10618 cx,
10619 );
10620 this.delete(&Delete, window, cx);
10621 });
10622 }
10623
10624 pub fn cut_to_end_of_line(
10625 &mut self,
10626 _: &CutToEndOfLine,
10627 window: &mut Window,
10628 cx: &mut Context<Self>,
10629 ) {
10630 self.transact(window, cx, |this, window, cx| {
10631 this.select_to_end_of_line(
10632 &SelectToEndOfLine {
10633 stop_at_soft_wraps: false,
10634 },
10635 window,
10636 cx,
10637 );
10638 this.cut(&Cut, window, cx);
10639 });
10640 }
10641
10642 pub fn move_to_start_of_paragraph(
10643 &mut self,
10644 _: &MoveToStartOfParagraph,
10645 window: &mut Window,
10646 cx: &mut Context<Self>,
10647 ) {
10648 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10649 cx.propagate();
10650 return;
10651 }
10652
10653 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10654 s.move_with(|map, selection| {
10655 selection.collapse_to(
10656 movement::start_of_paragraph(map, selection.head(), 1),
10657 SelectionGoal::None,
10658 )
10659 });
10660 })
10661 }
10662
10663 pub fn move_to_end_of_paragraph(
10664 &mut self,
10665 _: &MoveToEndOfParagraph,
10666 window: &mut Window,
10667 cx: &mut Context<Self>,
10668 ) {
10669 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10670 cx.propagate();
10671 return;
10672 }
10673
10674 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10675 s.move_with(|map, selection| {
10676 selection.collapse_to(
10677 movement::end_of_paragraph(map, selection.head(), 1),
10678 SelectionGoal::None,
10679 )
10680 });
10681 })
10682 }
10683
10684 pub fn select_to_start_of_paragraph(
10685 &mut self,
10686 _: &SelectToStartOfParagraph,
10687 window: &mut Window,
10688 cx: &mut Context<Self>,
10689 ) {
10690 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10691 cx.propagate();
10692 return;
10693 }
10694
10695 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10696 s.move_heads_with(|map, head, _| {
10697 (
10698 movement::start_of_paragraph(map, head, 1),
10699 SelectionGoal::None,
10700 )
10701 });
10702 })
10703 }
10704
10705 pub fn select_to_end_of_paragraph(
10706 &mut self,
10707 _: &SelectToEndOfParagraph,
10708 window: &mut Window,
10709 cx: &mut Context<Self>,
10710 ) {
10711 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10712 cx.propagate();
10713 return;
10714 }
10715
10716 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10717 s.move_heads_with(|map, head, _| {
10718 (
10719 movement::end_of_paragraph(map, head, 1),
10720 SelectionGoal::None,
10721 )
10722 });
10723 })
10724 }
10725
10726 pub fn move_to_start_of_excerpt(
10727 &mut self,
10728 _: &MoveToStartOfExcerpt,
10729 window: &mut Window,
10730 cx: &mut Context<Self>,
10731 ) {
10732 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10733 cx.propagate();
10734 return;
10735 }
10736
10737 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10738 s.move_with(|map, selection| {
10739 selection.collapse_to(
10740 movement::start_of_excerpt(
10741 map,
10742 selection.head(),
10743 workspace::searchable::Direction::Prev,
10744 ),
10745 SelectionGoal::None,
10746 )
10747 });
10748 })
10749 }
10750
10751 pub fn move_to_start_of_next_excerpt(
10752 &mut self,
10753 _: &MoveToStartOfNextExcerpt,
10754 window: &mut Window,
10755 cx: &mut Context<Self>,
10756 ) {
10757 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10758 cx.propagate();
10759 return;
10760 }
10761
10762 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10763 s.move_with(|map, selection| {
10764 selection.collapse_to(
10765 movement::start_of_excerpt(
10766 map,
10767 selection.head(),
10768 workspace::searchable::Direction::Next,
10769 ),
10770 SelectionGoal::None,
10771 )
10772 });
10773 })
10774 }
10775
10776 pub fn move_to_end_of_excerpt(
10777 &mut self,
10778 _: &MoveToEndOfExcerpt,
10779 window: &mut Window,
10780 cx: &mut Context<Self>,
10781 ) {
10782 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10783 cx.propagate();
10784 return;
10785 }
10786
10787 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10788 s.move_with(|map, selection| {
10789 selection.collapse_to(
10790 movement::end_of_excerpt(
10791 map,
10792 selection.head(),
10793 workspace::searchable::Direction::Next,
10794 ),
10795 SelectionGoal::None,
10796 )
10797 });
10798 })
10799 }
10800
10801 pub fn move_to_end_of_previous_excerpt(
10802 &mut self,
10803 _: &MoveToEndOfPreviousExcerpt,
10804 window: &mut Window,
10805 cx: &mut Context<Self>,
10806 ) {
10807 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10808 cx.propagate();
10809 return;
10810 }
10811
10812 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10813 s.move_with(|map, selection| {
10814 selection.collapse_to(
10815 movement::end_of_excerpt(
10816 map,
10817 selection.head(),
10818 workspace::searchable::Direction::Prev,
10819 ),
10820 SelectionGoal::None,
10821 )
10822 });
10823 })
10824 }
10825
10826 pub fn select_to_start_of_excerpt(
10827 &mut self,
10828 _: &SelectToStartOfExcerpt,
10829 window: &mut Window,
10830 cx: &mut Context<Self>,
10831 ) {
10832 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10833 cx.propagate();
10834 return;
10835 }
10836
10837 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10838 s.move_heads_with(|map, head, _| {
10839 (
10840 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10841 SelectionGoal::None,
10842 )
10843 });
10844 })
10845 }
10846
10847 pub fn select_to_start_of_next_excerpt(
10848 &mut self,
10849 _: &SelectToStartOfNextExcerpt,
10850 window: &mut Window,
10851 cx: &mut Context<Self>,
10852 ) {
10853 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10854 cx.propagate();
10855 return;
10856 }
10857
10858 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10859 s.move_heads_with(|map, head, _| {
10860 (
10861 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10862 SelectionGoal::None,
10863 )
10864 });
10865 })
10866 }
10867
10868 pub fn select_to_end_of_excerpt(
10869 &mut self,
10870 _: &SelectToEndOfExcerpt,
10871 window: &mut Window,
10872 cx: &mut Context<Self>,
10873 ) {
10874 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10875 cx.propagate();
10876 return;
10877 }
10878
10879 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10880 s.move_heads_with(|map, head, _| {
10881 (
10882 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10883 SelectionGoal::None,
10884 )
10885 });
10886 })
10887 }
10888
10889 pub fn select_to_end_of_previous_excerpt(
10890 &mut self,
10891 _: &SelectToEndOfPreviousExcerpt,
10892 window: &mut Window,
10893 cx: &mut Context<Self>,
10894 ) {
10895 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10896 cx.propagate();
10897 return;
10898 }
10899
10900 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10901 s.move_heads_with(|map, head, _| {
10902 (
10903 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10904 SelectionGoal::None,
10905 )
10906 });
10907 })
10908 }
10909
10910 pub fn move_to_beginning(
10911 &mut self,
10912 _: &MoveToBeginning,
10913 window: &mut Window,
10914 cx: &mut Context<Self>,
10915 ) {
10916 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10917 cx.propagate();
10918 return;
10919 }
10920
10921 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10922 s.select_ranges(vec![0..0]);
10923 });
10924 }
10925
10926 pub fn select_to_beginning(
10927 &mut self,
10928 _: &SelectToBeginning,
10929 window: &mut Window,
10930 cx: &mut Context<Self>,
10931 ) {
10932 let mut selection = self.selections.last::<Point>(cx);
10933 selection.set_head(Point::zero(), SelectionGoal::None);
10934
10935 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10936 s.select(vec![selection]);
10937 });
10938 }
10939
10940 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10941 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10942 cx.propagate();
10943 return;
10944 }
10945
10946 let cursor = self.buffer.read(cx).read(cx).len();
10947 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10948 s.select_ranges(vec![cursor..cursor])
10949 });
10950 }
10951
10952 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10953 self.nav_history = nav_history;
10954 }
10955
10956 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10957 self.nav_history.as_ref()
10958 }
10959
10960 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
10961 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
10962 }
10963
10964 fn push_to_nav_history(
10965 &mut self,
10966 cursor_anchor: Anchor,
10967 new_position: Option<Point>,
10968 is_deactivate: bool,
10969 cx: &mut Context<Self>,
10970 ) {
10971 if let Some(nav_history) = self.nav_history.as_mut() {
10972 let buffer = self.buffer.read(cx).read(cx);
10973 let cursor_position = cursor_anchor.to_point(&buffer);
10974 let scroll_state = self.scroll_manager.anchor();
10975 let scroll_top_row = scroll_state.top_row(&buffer);
10976 drop(buffer);
10977
10978 if let Some(new_position) = new_position {
10979 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10980 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10981 return;
10982 }
10983 }
10984
10985 nav_history.push(
10986 Some(NavigationData {
10987 cursor_anchor,
10988 cursor_position,
10989 scroll_anchor: scroll_state,
10990 scroll_top_row,
10991 }),
10992 cx,
10993 );
10994 cx.emit(EditorEvent::PushedToNavHistory {
10995 anchor: cursor_anchor,
10996 is_deactivate,
10997 })
10998 }
10999 }
11000
11001 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11002 let buffer = self.buffer.read(cx).snapshot(cx);
11003 let mut selection = self.selections.first::<usize>(cx);
11004 selection.set_head(buffer.len(), SelectionGoal::None);
11005 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11006 s.select(vec![selection]);
11007 });
11008 }
11009
11010 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11011 let end = self.buffer.read(cx).read(cx).len();
11012 self.change_selections(None, window, cx, |s| {
11013 s.select_ranges(vec![0..end]);
11014 });
11015 }
11016
11017 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11018 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11019 let mut selections = self.selections.all::<Point>(cx);
11020 let max_point = display_map.buffer_snapshot.max_point();
11021 for selection in &mut selections {
11022 let rows = selection.spanned_rows(true, &display_map);
11023 selection.start = Point::new(rows.start.0, 0);
11024 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11025 selection.reversed = false;
11026 }
11027 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11028 s.select(selections);
11029 });
11030 }
11031
11032 pub fn split_selection_into_lines(
11033 &mut self,
11034 _: &SplitSelectionIntoLines,
11035 window: &mut Window,
11036 cx: &mut Context<Self>,
11037 ) {
11038 let selections = self
11039 .selections
11040 .all::<Point>(cx)
11041 .into_iter()
11042 .map(|selection| selection.start..selection.end)
11043 .collect::<Vec<_>>();
11044 self.unfold_ranges(&selections, true, true, cx);
11045
11046 let mut new_selection_ranges = Vec::new();
11047 {
11048 let buffer = self.buffer.read(cx).read(cx);
11049 for selection in selections {
11050 for row in selection.start.row..selection.end.row {
11051 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11052 new_selection_ranges.push(cursor..cursor);
11053 }
11054
11055 let is_multiline_selection = selection.start.row != selection.end.row;
11056 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11057 // so this action feels more ergonomic when paired with other selection operations
11058 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11059 if !should_skip_last {
11060 new_selection_ranges.push(selection.end..selection.end);
11061 }
11062 }
11063 }
11064 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11065 s.select_ranges(new_selection_ranges);
11066 });
11067 }
11068
11069 pub fn add_selection_above(
11070 &mut self,
11071 _: &AddSelectionAbove,
11072 window: &mut Window,
11073 cx: &mut Context<Self>,
11074 ) {
11075 self.add_selection(true, window, cx);
11076 }
11077
11078 pub fn add_selection_below(
11079 &mut self,
11080 _: &AddSelectionBelow,
11081 window: &mut Window,
11082 cx: &mut Context<Self>,
11083 ) {
11084 self.add_selection(false, window, cx);
11085 }
11086
11087 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11088 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11089 let mut selections = self.selections.all::<Point>(cx);
11090 let text_layout_details = self.text_layout_details(window);
11091 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11092 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11093 let range = oldest_selection.display_range(&display_map).sorted();
11094
11095 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11096 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11097 let positions = start_x.min(end_x)..start_x.max(end_x);
11098
11099 selections.clear();
11100 let mut stack = Vec::new();
11101 for row in range.start.row().0..=range.end.row().0 {
11102 if let Some(selection) = self.selections.build_columnar_selection(
11103 &display_map,
11104 DisplayRow(row),
11105 &positions,
11106 oldest_selection.reversed,
11107 &text_layout_details,
11108 ) {
11109 stack.push(selection.id);
11110 selections.push(selection);
11111 }
11112 }
11113
11114 if above {
11115 stack.reverse();
11116 }
11117
11118 AddSelectionsState { above, stack }
11119 });
11120
11121 let last_added_selection = *state.stack.last().unwrap();
11122 let mut new_selections = Vec::new();
11123 if above == state.above {
11124 let end_row = if above {
11125 DisplayRow(0)
11126 } else {
11127 display_map.max_point().row()
11128 };
11129
11130 'outer: for selection in selections {
11131 if selection.id == last_added_selection {
11132 let range = selection.display_range(&display_map).sorted();
11133 debug_assert_eq!(range.start.row(), range.end.row());
11134 let mut row = range.start.row();
11135 let positions =
11136 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11137 px(start)..px(end)
11138 } else {
11139 let start_x =
11140 display_map.x_for_display_point(range.start, &text_layout_details);
11141 let end_x =
11142 display_map.x_for_display_point(range.end, &text_layout_details);
11143 start_x.min(end_x)..start_x.max(end_x)
11144 };
11145
11146 while row != end_row {
11147 if above {
11148 row.0 -= 1;
11149 } else {
11150 row.0 += 1;
11151 }
11152
11153 if let Some(new_selection) = self.selections.build_columnar_selection(
11154 &display_map,
11155 row,
11156 &positions,
11157 selection.reversed,
11158 &text_layout_details,
11159 ) {
11160 state.stack.push(new_selection.id);
11161 if above {
11162 new_selections.push(new_selection);
11163 new_selections.push(selection);
11164 } else {
11165 new_selections.push(selection);
11166 new_selections.push(new_selection);
11167 }
11168
11169 continue 'outer;
11170 }
11171 }
11172 }
11173
11174 new_selections.push(selection);
11175 }
11176 } else {
11177 new_selections = selections;
11178 new_selections.retain(|s| s.id != last_added_selection);
11179 state.stack.pop();
11180 }
11181
11182 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11183 s.select(new_selections);
11184 });
11185 if state.stack.len() > 1 {
11186 self.add_selections_state = Some(state);
11187 }
11188 }
11189
11190 pub fn select_next_match_internal(
11191 &mut self,
11192 display_map: &DisplaySnapshot,
11193 replace_newest: bool,
11194 autoscroll: Option<Autoscroll>,
11195 window: &mut Window,
11196 cx: &mut Context<Self>,
11197 ) -> Result<()> {
11198 fn select_next_match_ranges(
11199 this: &mut Editor,
11200 range: Range<usize>,
11201 replace_newest: bool,
11202 auto_scroll: Option<Autoscroll>,
11203 window: &mut Window,
11204 cx: &mut Context<Editor>,
11205 ) {
11206 this.unfold_ranges(&[range.clone()], false, true, cx);
11207 this.change_selections(auto_scroll, window, cx, |s| {
11208 if replace_newest {
11209 s.delete(s.newest_anchor().id);
11210 }
11211 s.insert_range(range.clone());
11212 });
11213 }
11214
11215 let buffer = &display_map.buffer_snapshot;
11216 let mut selections = self.selections.all::<usize>(cx);
11217 if let Some(mut select_next_state) = self.select_next_state.take() {
11218 let query = &select_next_state.query;
11219 if !select_next_state.done {
11220 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11221 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11222 let mut next_selected_range = None;
11223
11224 let bytes_after_last_selection =
11225 buffer.bytes_in_range(last_selection.end..buffer.len());
11226 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11227 let query_matches = query
11228 .stream_find_iter(bytes_after_last_selection)
11229 .map(|result| (last_selection.end, result))
11230 .chain(
11231 query
11232 .stream_find_iter(bytes_before_first_selection)
11233 .map(|result| (0, result)),
11234 );
11235
11236 for (start_offset, query_match) in query_matches {
11237 let query_match = query_match.unwrap(); // can only fail due to I/O
11238 let offset_range =
11239 start_offset + query_match.start()..start_offset + query_match.end();
11240 let display_range = offset_range.start.to_display_point(display_map)
11241 ..offset_range.end.to_display_point(display_map);
11242
11243 if !select_next_state.wordwise
11244 || (!movement::is_inside_word(display_map, display_range.start)
11245 && !movement::is_inside_word(display_map, display_range.end))
11246 {
11247 // TODO: This is n^2, because we might check all the selections
11248 if !selections
11249 .iter()
11250 .any(|selection| selection.range().overlaps(&offset_range))
11251 {
11252 next_selected_range = Some(offset_range);
11253 break;
11254 }
11255 }
11256 }
11257
11258 if let Some(next_selected_range) = next_selected_range {
11259 select_next_match_ranges(
11260 self,
11261 next_selected_range,
11262 replace_newest,
11263 autoscroll,
11264 window,
11265 cx,
11266 );
11267 } else {
11268 select_next_state.done = true;
11269 }
11270 }
11271
11272 self.select_next_state = Some(select_next_state);
11273 } else {
11274 let mut only_carets = true;
11275 let mut same_text_selected = true;
11276 let mut selected_text = None;
11277
11278 let mut selections_iter = selections.iter().peekable();
11279 while let Some(selection) = selections_iter.next() {
11280 if selection.start != selection.end {
11281 only_carets = false;
11282 }
11283
11284 if same_text_selected {
11285 if selected_text.is_none() {
11286 selected_text =
11287 Some(buffer.text_for_range(selection.range()).collect::<String>());
11288 }
11289
11290 if let Some(next_selection) = selections_iter.peek() {
11291 if next_selection.range().len() == selection.range().len() {
11292 let next_selected_text = buffer
11293 .text_for_range(next_selection.range())
11294 .collect::<String>();
11295 if Some(next_selected_text) != selected_text {
11296 same_text_selected = false;
11297 selected_text = None;
11298 }
11299 } else {
11300 same_text_selected = false;
11301 selected_text = None;
11302 }
11303 }
11304 }
11305 }
11306
11307 if only_carets {
11308 for selection in &mut selections {
11309 let word_range = movement::surrounding_word(
11310 display_map,
11311 selection.start.to_display_point(display_map),
11312 );
11313 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11314 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11315 selection.goal = SelectionGoal::None;
11316 selection.reversed = false;
11317 select_next_match_ranges(
11318 self,
11319 selection.start..selection.end,
11320 replace_newest,
11321 autoscroll,
11322 window,
11323 cx,
11324 );
11325 }
11326
11327 if selections.len() == 1 {
11328 let selection = selections
11329 .last()
11330 .expect("ensured that there's only one selection");
11331 let query = buffer
11332 .text_for_range(selection.start..selection.end)
11333 .collect::<String>();
11334 let is_empty = query.is_empty();
11335 let select_state = SelectNextState {
11336 query: AhoCorasick::new(&[query])?,
11337 wordwise: true,
11338 done: is_empty,
11339 };
11340 self.select_next_state = Some(select_state);
11341 } else {
11342 self.select_next_state = None;
11343 }
11344 } else if let Some(selected_text) = selected_text {
11345 self.select_next_state = Some(SelectNextState {
11346 query: AhoCorasick::new(&[selected_text])?,
11347 wordwise: false,
11348 done: false,
11349 });
11350 self.select_next_match_internal(
11351 display_map,
11352 replace_newest,
11353 autoscroll,
11354 window,
11355 cx,
11356 )?;
11357 }
11358 }
11359 Ok(())
11360 }
11361
11362 pub fn select_all_matches(
11363 &mut self,
11364 _action: &SelectAllMatches,
11365 window: &mut Window,
11366 cx: &mut Context<Self>,
11367 ) -> Result<()> {
11368 self.push_to_selection_history();
11369 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11370
11371 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11372 let Some(select_next_state) = self.select_next_state.as_mut() else {
11373 return Ok(());
11374 };
11375 if select_next_state.done {
11376 return Ok(());
11377 }
11378
11379 let mut new_selections = self.selections.all::<usize>(cx);
11380
11381 let buffer = &display_map.buffer_snapshot;
11382 let query_matches = select_next_state
11383 .query
11384 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11385
11386 for query_match in query_matches {
11387 let query_match = query_match.unwrap(); // can only fail due to I/O
11388 let offset_range = query_match.start()..query_match.end();
11389 let display_range = offset_range.start.to_display_point(&display_map)
11390 ..offset_range.end.to_display_point(&display_map);
11391
11392 if !select_next_state.wordwise
11393 || (!movement::is_inside_word(&display_map, display_range.start)
11394 && !movement::is_inside_word(&display_map, display_range.end))
11395 {
11396 self.selections.change_with(cx, |selections| {
11397 new_selections.push(Selection {
11398 id: selections.new_selection_id(),
11399 start: offset_range.start,
11400 end: offset_range.end,
11401 reversed: false,
11402 goal: SelectionGoal::None,
11403 });
11404 });
11405 }
11406 }
11407
11408 new_selections.sort_by_key(|selection| selection.start);
11409 let mut ix = 0;
11410 while ix + 1 < new_selections.len() {
11411 let current_selection = &new_selections[ix];
11412 let next_selection = &new_selections[ix + 1];
11413 if current_selection.range().overlaps(&next_selection.range()) {
11414 if current_selection.id < next_selection.id {
11415 new_selections.remove(ix + 1);
11416 } else {
11417 new_selections.remove(ix);
11418 }
11419 } else {
11420 ix += 1;
11421 }
11422 }
11423
11424 let reversed = self.selections.oldest::<usize>(cx).reversed;
11425
11426 for selection in new_selections.iter_mut() {
11427 selection.reversed = reversed;
11428 }
11429
11430 select_next_state.done = true;
11431 self.unfold_ranges(
11432 &new_selections
11433 .iter()
11434 .map(|selection| selection.range())
11435 .collect::<Vec<_>>(),
11436 false,
11437 false,
11438 cx,
11439 );
11440 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11441 selections.select(new_selections)
11442 });
11443
11444 Ok(())
11445 }
11446
11447 pub fn select_next(
11448 &mut self,
11449 action: &SelectNext,
11450 window: &mut Window,
11451 cx: &mut Context<Self>,
11452 ) -> Result<()> {
11453 self.push_to_selection_history();
11454 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11455 self.select_next_match_internal(
11456 &display_map,
11457 action.replace_newest,
11458 Some(Autoscroll::newest()),
11459 window,
11460 cx,
11461 )?;
11462 Ok(())
11463 }
11464
11465 pub fn select_previous(
11466 &mut self,
11467 action: &SelectPrevious,
11468 window: &mut Window,
11469 cx: &mut Context<Self>,
11470 ) -> Result<()> {
11471 self.push_to_selection_history();
11472 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11473 let buffer = &display_map.buffer_snapshot;
11474 let mut selections = self.selections.all::<usize>(cx);
11475 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11476 let query = &select_prev_state.query;
11477 if !select_prev_state.done {
11478 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11479 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11480 let mut next_selected_range = None;
11481 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11482 let bytes_before_last_selection =
11483 buffer.reversed_bytes_in_range(0..last_selection.start);
11484 let bytes_after_first_selection =
11485 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11486 let query_matches = query
11487 .stream_find_iter(bytes_before_last_selection)
11488 .map(|result| (last_selection.start, result))
11489 .chain(
11490 query
11491 .stream_find_iter(bytes_after_first_selection)
11492 .map(|result| (buffer.len(), result)),
11493 );
11494 for (end_offset, query_match) in query_matches {
11495 let query_match = query_match.unwrap(); // can only fail due to I/O
11496 let offset_range =
11497 end_offset - query_match.end()..end_offset - query_match.start();
11498 let display_range = offset_range.start.to_display_point(&display_map)
11499 ..offset_range.end.to_display_point(&display_map);
11500
11501 if !select_prev_state.wordwise
11502 || (!movement::is_inside_word(&display_map, display_range.start)
11503 && !movement::is_inside_word(&display_map, display_range.end))
11504 {
11505 next_selected_range = Some(offset_range);
11506 break;
11507 }
11508 }
11509
11510 if let Some(next_selected_range) = next_selected_range {
11511 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11512 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11513 if action.replace_newest {
11514 s.delete(s.newest_anchor().id);
11515 }
11516 s.insert_range(next_selected_range);
11517 });
11518 } else {
11519 select_prev_state.done = true;
11520 }
11521 }
11522
11523 self.select_prev_state = Some(select_prev_state);
11524 } else {
11525 let mut only_carets = true;
11526 let mut same_text_selected = true;
11527 let mut selected_text = None;
11528
11529 let mut selections_iter = selections.iter().peekable();
11530 while let Some(selection) = selections_iter.next() {
11531 if selection.start != selection.end {
11532 only_carets = false;
11533 }
11534
11535 if same_text_selected {
11536 if selected_text.is_none() {
11537 selected_text =
11538 Some(buffer.text_for_range(selection.range()).collect::<String>());
11539 }
11540
11541 if let Some(next_selection) = selections_iter.peek() {
11542 if next_selection.range().len() == selection.range().len() {
11543 let next_selected_text = buffer
11544 .text_for_range(next_selection.range())
11545 .collect::<String>();
11546 if Some(next_selected_text) != selected_text {
11547 same_text_selected = false;
11548 selected_text = None;
11549 }
11550 } else {
11551 same_text_selected = false;
11552 selected_text = None;
11553 }
11554 }
11555 }
11556 }
11557
11558 if only_carets {
11559 for selection in &mut selections {
11560 let word_range = movement::surrounding_word(
11561 &display_map,
11562 selection.start.to_display_point(&display_map),
11563 );
11564 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11565 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11566 selection.goal = SelectionGoal::None;
11567 selection.reversed = false;
11568 }
11569 if selections.len() == 1 {
11570 let selection = selections
11571 .last()
11572 .expect("ensured that there's only one selection");
11573 let query = buffer
11574 .text_for_range(selection.start..selection.end)
11575 .collect::<String>();
11576 let is_empty = query.is_empty();
11577 let select_state = SelectNextState {
11578 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11579 wordwise: true,
11580 done: is_empty,
11581 };
11582 self.select_prev_state = Some(select_state);
11583 } else {
11584 self.select_prev_state = None;
11585 }
11586
11587 self.unfold_ranges(
11588 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11589 false,
11590 true,
11591 cx,
11592 );
11593 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11594 s.select(selections);
11595 });
11596 } else if let Some(selected_text) = selected_text {
11597 self.select_prev_state = Some(SelectNextState {
11598 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11599 wordwise: false,
11600 done: false,
11601 });
11602 self.select_previous(action, window, cx)?;
11603 }
11604 }
11605 Ok(())
11606 }
11607
11608 pub fn toggle_comments(
11609 &mut self,
11610 action: &ToggleComments,
11611 window: &mut Window,
11612 cx: &mut Context<Self>,
11613 ) {
11614 if self.read_only(cx) {
11615 return;
11616 }
11617 let text_layout_details = &self.text_layout_details(window);
11618 self.transact(window, cx, |this, window, cx| {
11619 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11620 let mut edits = Vec::new();
11621 let mut selection_edit_ranges = Vec::new();
11622 let mut last_toggled_row = None;
11623 let snapshot = this.buffer.read(cx).read(cx);
11624 let empty_str: Arc<str> = Arc::default();
11625 let mut suffixes_inserted = Vec::new();
11626 let ignore_indent = action.ignore_indent;
11627
11628 fn comment_prefix_range(
11629 snapshot: &MultiBufferSnapshot,
11630 row: MultiBufferRow,
11631 comment_prefix: &str,
11632 comment_prefix_whitespace: &str,
11633 ignore_indent: bool,
11634 ) -> Range<Point> {
11635 let indent_size = if ignore_indent {
11636 0
11637 } else {
11638 snapshot.indent_size_for_line(row).len
11639 };
11640
11641 let start = Point::new(row.0, indent_size);
11642
11643 let mut line_bytes = snapshot
11644 .bytes_in_range(start..snapshot.max_point())
11645 .flatten()
11646 .copied();
11647
11648 // If this line currently begins with the line comment prefix, then record
11649 // the range containing the prefix.
11650 if line_bytes
11651 .by_ref()
11652 .take(comment_prefix.len())
11653 .eq(comment_prefix.bytes())
11654 {
11655 // Include any whitespace that matches the comment prefix.
11656 let matching_whitespace_len = line_bytes
11657 .zip(comment_prefix_whitespace.bytes())
11658 .take_while(|(a, b)| a == b)
11659 .count() as u32;
11660 let end = Point::new(
11661 start.row,
11662 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11663 );
11664 start..end
11665 } else {
11666 start..start
11667 }
11668 }
11669
11670 fn comment_suffix_range(
11671 snapshot: &MultiBufferSnapshot,
11672 row: MultiBufferRow,
11673 comment_suffix: &str,
11674 comment_suffix_has_leading_space: bool,
11675 ) -> Range<Point> {
11676 let end = Point::new(row.0, snapshot.line_len(row));
11677 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11678
11679 let mut line_end_bytes = snapshot
11680 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11681 .flatten()
11682 .copied();
11683
11684 let leading_space_len = if suffix_start_column > 0
11685 && line_end_bytes.next() == Some(b' ')
11686 && comment_suffix_has_leading_space
11687 {
11688 1
11689 } else {
11690 0
11691 };
11692
11693 // If this line currently begins with the line comment prefix, then record
11694 // the range containing the prefix.
11695 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11696 let start = Point::new(end.row, suffix_start_column - leading_space_len);
11697 start..end
11698 } else {
11699 end..end
11700 }
11701 }
11702
11703 // TODO: Handle selections that cross excerpts
11704 for selection in &mut selections {
11705 let start_column = snapshot
11706 .indent_size_for_line(MultiBufferRow(selection.start.row))
11707 .len;
11708 let language = if let Some(language) =
11709 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11710 {
11711 language
11712 } else {
11713 continue;
11714 };
11715
11716 selection_edit_ranges.clear();
11717
11718 // If multiple selections contain a given row, avoid processing that
11719 // row more than once.
11720 let mut start_row = MultiBufferRow(selection.start.row);
11721 if last_toggled_row == Some(start_row) {
11722 start_row = start_row.next_row();
11723 }
11724 let end_row =
11725 if selection.end.row > selection.start.row && selection.end.column == 0 {
11726 MultiBufferRow(selection.end.row - 1)
11727 } else {
11728 MultiBufferRow(selection.end.row)
11729 };
11730 last_toggled_row = Some(end_row);
11731
11732 if start_row > end_row {
11733 continue;
11734 }
11735
11736 // If the language has line comments, toggle those.
11737 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11738
11739 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11740 if ignore_indent {
11741 full_comment_prefixes = full_comment_prefixes
11742 .into_iter()
11743 .map(|s| Arc::from(s.trim_end()))
11744 .collect();
11745 }
11746
11747 if !full_comment_prefixes.is_empty() {
11748 let first_prefix = full_comment_prefixes
11749 .first()
11750 .expect("prefixes is non-empty");
11751 let prefix_trimmed_lengths = full_comment_prefixes
11752 .iter()
11753 .map(|p| p.trim_end_matches(' ').len())
11754 .collect::<SmallVec<[usize; 4]>>();
11755
11756 let mut all_selection_lines_are_comments = true;
11757
11758 for row in start_row.0..=end_row.0 {
11759 let row = MultiBufferRow(row);
11760 if start_row < end_row && snapshot.is_line_blank(row) {
11761 continue;
11762 }
11763
11764 let prefix_range = full_comment_prefixes
11765 .iter()
11766 .zip(prefix_trimmed_lengths.iter().copied())
11767 .map(|(prefix, trimmed_prefix_len)| {
11768 comment_prefix_range(
11769 snapshot.deref(),
11770 row,
11771 &prefix[..trimmed_prefix_len],
11772 &prefix[trimmed_prefix_len..],
11773 ignore_indent,
11774 )
11775 })
11776 .max_by_key(|range| range.end.column - range.start.column)
11777 .expect("prefixes is non-empty");
11778
11779 if prefix_range.is_empty() {
11780 all_selection_lines_are_comments = false;
11781 }
11782
11783 selection_edit_ranges.push(prefix_range);
11784 }
11785
11786 if all_selection_lines_are_comments {
11787 edits.extend(
11788 selection_edit_ranges
11789 .iter()
11790 .cloned()
11791 .map(|range| (range, empty_str.clone())),
11792 );
11793 } else {
11794 let min_column = selection_edit_ranges
11795 .iter()
11796 .map(|range| range.start.column)
11797 .min()
11798 .unwrap_or(0);
11799 edits.extend(selection_edit_ranges.iter().map(|range| {
11800 let position = Point::new(range.start.row, min_column);
11801 (position..position, first_prefix.clone())
11802 }));
11803 }
11804 } else if let Some((full_comment_prefix, comment_suffix)) =
11805 language.block_comment_delimiters()
11806 {
11807 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11808 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11809 let prefix_range = comment_prefix_range(
11810 snapshot.deref(),
11811 start_row,
11812 comment_prefix,
11813 comment_prefix_whitespace,
11814 ignore_indent,
11815 );
11816 let suffix_range = comment_suffix_range(
11817 snapshot.deref(),
11818 end_row,
11819 comment_suffix.trim_start_matches(' '),
11820 comment_suffix.starts_with(' '),
11821 );
11822
11823 if prefix_range.is_empty() || suffix_range.is_empty() {
11824 edits.push((
11825 prefix_range.start..prefix_range.start,
11826 full_comment_prefix.clone(),
11827 ));
11828 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11829 suffixes_inserted.push((end_row, comment_suffix.len()));
11830 } else {
11831 edits.push((prefix_range, empty_str.clone()));
11832 edits.push((suffix_range, empty_str.clone()));
11833 }
11834 } else {
11835 continue;
11836 }
11837 }
11838
11839 drop(snapshot);
11840 this.buffer.update(cx, |buffer, cx| {
11841 buffer.edit(edits, None, cx);
11842 });
11843
11844 // Adjust selections so that they end before any comment suffixes that
11845 // were inserted.
11846 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11847 let mut selections = this.selections.all::<Point>(cx);
11848 let snapshot = this.buffer.read(cx).read(cx);
11849 for selection in &mut selections {
11850 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11851 match row.cmp(&MultiBufferRow(selection.end.row)) {
11852 Ordering::Less => {
11853 suffixes_inserted.next();
11854 continue;
11855 }
11856 Ordering::Greater => break,
11857 Ordering::Equal => {
11858 if selection.end.column == snapshot.line_len(row) {
11859 if selection.is_empty() {
11860 selection.start.column -= suffix_len as u32;
11861 }
11862 selection.end.column -= suffix_len as u32;
11863 }
11864 break;
11865 }
11866 }
11867 }
11868 }
11869
11870 drop(snapshot);
11871 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11872 s.select(selections)
11873 });
11874
11875 let selections = this.selections.all::<Point>(cx);
11876 let selections_on_single_row = selections.windows(2).all(|selections| {
11877 selections[0].start.row == selections[1].start.row
11878 && selections[0].end.row == selections[1].end.row
11879 && selections[0].start.row == selections[0].end.row
11880 });
11881 let selections_selecting = selections
11882 .iter()
11883 .any(|selection| selection.start != selection.end);
11884 let advance_downwards = action.advance_downwards
11885 && selections_on_single_row
11886 && !selections_selecting
11887 && !matches!(this.mode, EditorMode::SingleLine { .. });
11888
11889 if advance_downwards {
11890 let snapshot = this.buffer.read(cx).snapshot(cx);
11891
11892 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11893 s.move_cursors_with(|display_snapshot, display_point, _| {
11894 let mut point = display_point.to_point(display_snapshot);
11895 point.row += 1;
11896 point = snapshot.clip_point(point, Bias::Left);
11897 let display_point = point.to_display_point(display_snapshot);
11898 let goal = SelectionGoal::HorizontalPosition(
11899 display_snapshot
11900 .x_for_display_point(display_point, text_layout_details)
11901 .into(),
11902 );
11903 (display_point, goal)
11904 })
11905 });
11906 }
11907 });
11908 }
11909
11910 pub fn select_enclosing_symbol(
11911 &mut self,
11912 _: &SelectEnclosingSymbol,
11913 window: &mut Window,
11914 cx: &mut Context<Self>,
11915 ) {
11916 let buffer = self.buffer.read(cx).snapshot(cx);
11917 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11918
11919 fn update_selection(
11920 selection: &Selection<usize>,
11921 buffer_snap: &MultiBufferSnapshot,
11922 ) -> Option<Selection<usize>> {
11923 let cursor = selection.head();
11924 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11925 for symbol in symbols.iter().rev() {
11926 let start = symbol.range.start.to_offset(buffer_snap);
11927 let end = symbol.range.end.to_offset(buffer_snap);
11928 let new_range = start..end;
11929 if start < selection.start || end > selection.end {
11930 return Some(Selection {
11931 id: selection.id,
11932 start: new_range.start,
11933 end: new_range.end,
11934 goal: SelectionGoal::None,
11935 reversed: selection.reversed,
11936 });
11937 }
11938 }
11939 None
11940 }
11941
11942 let mut selected_larger_symbol = false;
11943 let new_selections = old_selections
11944 .iter()
11945 .map(|selection| match update_selection(selection, &buffer) {
11946 Some(new_selection) => {
11947 if new_selection.range() != selection.range() {
11948 selected_larger_symbol = true;
11949 }
11950 new_selection
11951 }
11952 None => selection.clone(),
11953 })
11954 .collect::<Vec<_>>();
11955
11956 if selected_larger_symbol {
11957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11958 s.select(new_selections);
11959 });
11960 }
11961 }
11962
11963 pub fn select_larger_syntax_node(
11964 &mut self,
11965 _: &SelectLargerSyntaxNode,
11966 window: &mut Window,
11967 cx: &mut Context<Self>,
11968 ) {
11969 let Some(visible_row_count) = self.visible_row_count() else {
11970 return;
11971 };
11972 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
11973 if old_selections.is_empty() {
11974 return;
11975 }
11976
11977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11978 let buffer = self.buffer.read(cx).snapshot(cx);
11979
11980 let mut selected_larger_node = false;
11981 let mut new_selections = old_selections
11982 .iter()
11983 .map(|selection| {
11984 let old_range = selection.start..selection.end;
11985 let mut new_range = old_range.clone();
11986 let mut new_node = None;
11987 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11988 {
11989 new_node = Some(node);
11990 new_range = match containing_range {
11991 MultiOrSingleBufferOffsetRange::Single(_) => break,
11992 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11993 };
11994 if !display_map.intersects_fold(new_range.start)
11995 && !display_map.intersects_fold(new_range.end)
11996 {
11997 break;
11998 }
11999 }
12000
12001 if let Some(node) = new_node {
12002 // Log the ancestor, to support using this action as a way to explore TreeSitter
12003 // nodes. Parent and grandparent are also logged because this operation will not
12004 // visit nodes that have the same range as their parent.
12005 log::info!("Node: {node:?}");
12006 let parent = node.parent();
12007 log::info!("Parent: {parent:?}");
12008 let grandparent = parent.and_then(|x| x.parent());
12009 log::info!("Grandparent: {grandparent:?}");
12010 }
12011
12012 selected_larger_node |= new_range != old_range;
12013 Selection {
12014 id: selection.id,
12015 start: new_range.start,
12016 end: new_range.end,
12017 goal: SelectionGoal::None,
12018 reversed: selection.reversed,
12019 }
12020 })
12021 .collect::<Vec<_>>();
12022
12023 if !selected_larger_node {
12024 return; // don't put this call in the history
12025 }
12026
12027 // scroll based on transformation done to the last selection created by the user
12028 let (last_old, last_new) = old_selections
12029 .last()
12030 .zip(new_selections.last().cloned())
12031 .expect("old_selections isn't empty");
12032
12033 // revert selection
12034 let is_selection_reversed = {
12035 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12036 new_selections.last_mut().expect("checked above").reversed =
12037 should_newest_selection_be_reversed;
12038 should_newest_selection_be_reversed
12039 };
12040
12041 if selected_larger_node {
12042 self.select_syntax_node_history.disable_clearing = true;
12043 self.change_selections(None, window, cx, |s| {
12044 s.select(new_selections.clone());
12045 });
12046 self.select_syntax_node_history.disable_clearing = false;
12047 }
12048
12049 let start_row = last_new.start.to_display_point(&display_map).row().0;
12050 let end_row = last_new.end.to_display_point(&display_map).row().0;
12051 let selection_height = end_row - start_row + 1;
12052 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12053
12054 // if fits on screen (considering margin), keep it in the middle, else, scroll to selection head
12055 let scroll_behavior = if visible_row_count >= selection_height + scroll_margin_rows * 2 {
12056 let middle_row = (end_row + start_row) / 2;
12057 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12058 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12059 SelectSyntaxNodeScrollBehavior::CenterSelection
12060 } else if is_selection_reversed {
12061 self.scroll_cursor_top(&Default::default(), window, cx);
12062 SelectSyntaxNodeScrollBehavior::CursorTop
12063 } else {
12064 self.scroll_cursor_bottom(&Default::default(), window, cx);
12065 SelectSyntaxNodeScrollBehavior::CursorBottom
12066 };
12067
12068 self.select_syntax_node_history.push((
12069 old_selections,
12070 scroll_behavior,
12071 is_selection_reversed,
12072 ));
12073 }
12074
12075 pub fn select_smaller_syntax_node(
12076 &mut self,
12077 _: &SelectSmallerSyntaxNode,
12078 window: &mut Window,
12079 cx: &mut Context<Self>,
12080 ) {
12081 let Some(visible_row_count) = self.visible_row_count() else {
12082 return;
12083 };
12084
12085 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12086 self.select_syntax_node_history.pop()
12087 {
12088 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12089
12090 if let Some(selection) = selections.last_mut() {
12091 selection.reversed = is_selection_reversed;
12092 }
12093
12094 self.select_syntax_node_history.disable_clearing = true;
12095 self.change_selections(None, window, cx, |s| {
12096 s.select(selections.to_vec());
12097 });
12098 self.select_syntax_node_history.disable_clearing = false;
12099
12100 let newest = self.selections.newest::<usize>(cx);
12101 let start_row = newest.start.to_display_point(&display_map).row().0;
12102 let end_row = newest.end.to_display_point(&display_map).row().0;
12103
12104 match scroll_behavior {
12105 SelectSyntaxNodeScrollBehavior::CursorTop => {
12106 self.scroll_cursor_top(&Default::default(), window, cx);
12107 }
12108 SelectSyntaxNodeScrollBehavior::CenterSelection => {
12109 let middle_row = (end_row + start_row) / 2;
12110 let selection_center = middle_row.saturating_sub(visible_row_count / 2);
12111 // centralize the selection, not the cursor
12112 self.set_scroll_top_row(DisplayRow(selection_center), window, cx);
12113 }
12114 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12115 self.scroll_cursor_bottom(&Default::default(), window, cx);
12116 }
12117 }
12118 }
12119 }
12120
12121 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12122 if !EditorSettings::get_global(cx).gutter.runnables {
12123 self.clear_tasks();
12124 return Task::ready(());
12125 }
12126 let project = self.project.as_ref().map(Entity::downgrade);
12127 cx.spawn_in(window, async move |this, cx| {
12128 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12129 let Some(project) = project.and_then(|p| p.upgrade()) else {
12130 return;
12131 };
12132 let Ok(display_snapshot) = this.update(cx, |this, cx| {
12133 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12134 }) else {
12135 return;
12136 };
12137
12138 let hide_runnables = project
12139 .update(cx, |project, cx| {
12140 // Do not display any test indicators in non-dev server remote projects.
12141 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12142 })
12143 .unwrap_or(true);
12144 if hide_runnables {
12145 return;
12146 }
12147 let new_rows =
12148 cx.background_spawn({
12149 let snapshot = display_snapshot.clone();
12150 async move {
12151 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12152 }
12153 })
12154 .await;
12155
12156 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12157 this.update(cx, |this, _| {
12158 this.clear_tasks();
12159 for (key, value) in rows {
12160 this.insert_tasks(key, value);
12161 }
12162 })
12163 .ok();
12164 })
12165 }
12166 fn fetch_runnable_ranges(
12167 snapshot: &DisplaySnapshot,
12168 range: Range<Anchor>,
12169 ) -> Vec<language::RunnableRange> {
12170 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12171 }
12172
12173 fn runnable_rows(
12174 project: Entity<Project>,
12175 snapshot: DisplaySnapshot,
12176 runnable_ranges: Vec<RunnableRange>,
12177 mut cx: AsyncWindowContext,
12178 ) -> Vec<((BufferId, u32), RunnableTasks)> {
12179 runnable_ranges
12180 .into_iter()
12181 .filter_map(|mut runnable| {
12182 let tasks = cx
12183 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12184 .ok()?;
12185 if tasks.is_empty() {
12186 return None;
12187 }
12188
12189 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12190
12191 let row = snapshot
12192 .buffer_snapshot
12193 .buffer_line_for_row(MultiBufferRow(point.row))?
12194 .1
12195 .start
12196 .row;
12197
12198 let context_range =
12199 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12200 Some((
12201 (runnable.buffer_id, row),
12202 RunnableTasks {
12203 templates: tasks,
12204 offset: snapshot
12205 .buffer_snapshot
12206 .anchor_before(runnable.run_range.start),
12207 context_range,
12208 column: point.column,
12209 extra_variables: runnable.extra_captures,
12210 },
12211 ))
12212 })
12213 .collect()
12214 }
12215
12216 fn templates_with_tags(
12217 project: &Entity<Project>,
12218 runnable: &mut Runnable,
12219 cx: &mut App,
12220 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12221 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12222 let (worktree_id, file) = project
12223 .buffer_for_id(runnable.buffer, cx)
12224 .and_then(|buffer| buffer.read(cx).file())
12225 .map(|file| (file.worktree_id(cx), file.clone()))
12226 .unzip();
12227
12228 (
12229 project.task_store().read(cx).task_inventory().cloned(),
12230 worktree_id,
12231 file,
12232 )
12233 });
12234
12235 let tags = mem::take(&mut runnable.tags);
12236 let mut tags: Vec<_> = tags
12237 .into_iter()
12238 .flat_map(|tag| {
12239 let tag = tag.0.clone();
12240 inventory
12241 .as_ref()
12242 .into_iter()
12243 .flat_map(|inventory| {
12244 inventory.read(cx).list_tasks(
12245 file.clone(),
12246 Some(runnable.language.clone()),
12247 worktree_id,
12248 cx,
12249 )
12250 })
12251 .filter(move |(_, template)| {
12252 template.tags.iter().any(|source_tag| source_tag == &tag)
12253 })
12254 })
12255 .sorted_by_key(|(kind, _)| kind.to_owned())
12256 .collect();
12257 if let Some((leading_tag_source, _)) = tags.first() {
12258 // Strongest source wins; if we have worktree tag binding, prefer that to
12259 // global and language bindings;
12260 // if we have a global binding, prefer that to language binding.
12261 let first_mismatch = tags
12262 .iter()
12263 .position(|(tag_source, _)| tag_source != leading_tag_source);
12264 if let Some(index) = first_mismatch {
12265 tags.truncate(index);
12266 }
12267 }
12268
12269 tags
12270 }
12271
12272 pub fn move_to_enclosing_bracket(
12273 &mut self,
12274 _: &MoveToEnclosingBracket,
12275 window: &mut Window,
12276 cx: &mut Context<Self>,
12277 ) {
12278 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12279 s.move_offsets_with(|snapshot, selection| {
12280 let Some(enclosing_bracket_ranges) =
12281 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
12282 else {
12283 return;
12284 };
12285
12286 let mut best_length = usize::MAX;
12287 let mut best_inside = false;
12288 let mut best_in_bracket_range = false;
12289 let mut best_destination = None;
12290 for (open, close) in enclosing_bracket_ranges {
12291 let close = close.to_inclusive();
12292 let length = close.end() - open.start;
12293 let inside = selection.start >= open.end && selection.end <= *close.start();
12294 let in_bracket_range = open.to_inclusive().contains(&selection.head())
12295 || close.contains(&selection.head());
12296
12297 // If best is next to a bracket and current isn't, skip
12298 if !in_bracket_range && best_in_bracket_range {
12299 continue;
12300 }
12301
12302 // Prefer smaller lengths unless best is inside and current isn't
12303 if length > best_length && (best_inside || !inside) {
12304 continue;
12305 }
12306
12307 best_length = length;
12308 best_inside = inside;
12309 best_in_bracket_range = in_bracket_range;
12310 best_destination = Some(
12311 if close.contains(&selection.start) && close.contains(&selection.end) {
12312 if inside {
12313 open.end
12314 } else {
12315 open.start
12316 }
12317 } else if inside {
12318 *close.start()
12319 } else {
12320 *close.end()
12321 },
12322 );
12323 }
12324
12325 if let Some(destination) = best_destination {
12326 selection.collapse_to(destination, SelectionGoal::None);
12327 }
12328 })
12329 });
12330 }
12331
12332 pub fn undo_selection(
12333 &mut self,
12334 _: &UndoSelection,
12335 window: &mut Window,
12336 cx: &mut Context<Self>,
12337 ) {
12338 self.end_selection(window, cx);
12339 self.selection_history.mode = SelectionHistoryMode::Undoing;
12340 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12341 self.change_selections(None, window, cx, |s| {
12342 s.select_anchors(entry.selections.to_vec())
12343 });
12344 self.select_next_state = entry.select_next_state;
12345 self.select_prev_state = entry.select_prev_state;
12346 self.add_selections_state = entry.add_selections_state;
12347 self.request_autoscroll(Autoscroll::newest(), cx);
12348 }
12349 self.selection_history.mode = SelectionHistoryMode::Normal;
12350 }
12351
12352 pub fn redo_selection(
12353 &mut self,
12354 _: &RedoSelection,
12355 window: &mut Window,
12356 cx: &mut Context<Self>,
12357 ) {
12358 self.end_selection(window, cx);
12359 self.selection_history.mode = SelectionHistoryMode::Redoing;
12360 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12361 self.change_selections(None, window, cx, |s| {
12362 s.select_anchors(entry.selections.to_vec())
12363 });
12364 self.select_next_state = entry.select_next_state;
12365 self.select_prev_state = entry.select_prev_state;
12366 self.add_selections_state = entry.add_selections_state;
12367 self.request_autoscroll(Autoscroll::newest(), cx);
12368 }
12369 self.selection_history.mode = SelectionHistoryMode::Normal;
12370 }
12371
12372 pub fn expand_excerpts(
12373 &mut self,
12374 action: &ExpandExcerpts,
12375 _: &mut Window,
12376 cx: &mut Context<Self>,
12377 ) {
12378 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12379 }
12380
12381 pub fn expand_excerpts_down(
12382 &mut self,
12383 action: &ExpandExcerptsDown,
12384 _: &mut Window,
12385 cx: &mut Context<Self>,
12386 ) {
12387 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12388 }
12389
12390 pub fn expand_excerpts_up(
12391 &mut self,
12392 action: &ExpandExcerptsUp,
12393 _: &mut Window,
12394 cx: &mut Context<Self>,
12395 ) {
12396 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12397 }
12398
12399 pub fn expand_excerpts_for_direction(
12400 &mut self,
12401 lines: u32,
12402 direction: ExpandExcerptDirection,
12403
12404 cx: &mut Context<Self>,
12405 ) {
12406 let selections = self.selections.disjoint_anchors();
12407
12408 let lines = if lines == 0 {
12409 EditorSettings::get_global(cx).expand_excerpt_lines
12410 } else {
12411 lines
12412 };
12413
12414 self.buffer.update(cx, |buffer, cx| {
12415 let snapshot = buffer.snapshot(cx);
12416 let mut excerpt_ids = selections
12417 .iter()
12418 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12419 .collect::<Vec<_>>();
12420 excerpt_ids.sort();
12421 excerpt_ids.dedup();
12422 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12423 })
12424 }
12425
12426 pub fn expand_excerpt(
12427 &mut self,
12428 excerpt: ExcerptId,
12429 direction: ExpandExcerptDirection,
12430 window: &mut Window,
12431 cx: &mut Context<Self>,
12432 ) {
12433 let current_scroll_position = self.scroll_position(cx);
12434 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12435 self.buffer.update(cx, |buffer, cx| {
12436 buffer.expand_excerpts([excerpt], lines, direction, cx)
12437 });
12438 if direction == ExpandExcerptDirection::Down {
12439 let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12440 self.set_scroll_position(new_scroll_position, window, cx);
12441 }
12442 }
12443
12444 pub fn go_to_singleton_buffer_point(
12445 &mut self,
12446 point: Point,
12447 window: &mut Window,
12448 cx: &mut Context<Self>,
12449 ) {
12450 self.go_to_singleton_buffer_range(point..point, window, cx);
12451 }
12452
12453 pub fn go_to_singleton_buffer_range(
12454 &mut self,
12455 range: Range<Point>,
12456 window: &mut Window,
12457 cx: &mut Context<Self>,
12458 ) {
12459 let multibuffer = self.buffer().read(cx);
12460 let Some(buffer) = multibuffer.as_singleton() else {
12461 return;
12462 };
12463 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12464 return;
12465 };
12466 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12467 return;
12468 };
12469 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12470 s.select_anchor_ranges([start..end])
12471 });
12472 }
12473
12474 fn go_to_diagnostic(
12475 &mut self,
12476 _: &GoToDiagnostic,
12477 window: &mut Window,
12478 cx: &mut Context<Self>,
12479 ) {
12480 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12481 }
12482
12483 fn go_to_prev_diagnostic(
12484 &mut self,
12485 _: &GoToPreviousDiagnostic,
12486 window: &mut Window,
12487 cx: &mut Context<Self>,
12488 ) {
12489 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12490 }
12491
12492 pub fn go_to_diagnostic_impl(
12493 &mut self,
12494 direction: Direction,
12495 window: &mut Window,
12496 cx: &mut Context<Self>,
12497 ) {
12498 let buffer = self.buffer.read(cx).snapshot(cx);
12499 let selection = self.selections.newest::<usize>(cx);
12500
12501 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12502 if direction == Direction::Next {
12503 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12504 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12505 return;
12506 };
12507 self.activate_diagnostics(
12508 buffer_id,
12509 popover.local_diagnostic.diagnostic.group_id,
12510 window,
12511 cx,
12512 );
12513 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12514 let primary_range_start = active_diagnostics.primary_range.start;
12515 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12516 let mut new_selection = s.newest_anchor().clone();
12517 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12518 s.select_anchors(vec![new_selection.clone()]);
12519 });
12520 self.refresh_inline_completion(false, true, window, cx);
12521 }
12522 return;
12523 }
12524 }
12525
12526 let active_group_id = self
12527 .active_diagnostics
12528 .as_ref()
12529 .map(|active_group| active_group.group_id);
12530 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12531 active_diagnostics
12532 .primary_range
12533 .to_offset(&buffer)
12534 .to_inclusive()
12535 });
12536 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12537 if active_primary_range.contains(&selection.head()) {
12538 *active_primary_range.start()
12539 } else {
12540 selection.head()
12541 }
12542 } else {
12543 selection.head()
12544 };
12545
12546 let snapshot = self.snapshot(window, cx);
12547 let primary_diagnostics_before = buffer
12548 .diagnostics_in_range::<usize>(0..search_start)
12549 .filter(|entry| entry.diagnostic.is_primary)
12550 .filter(|entry| entry.range.start != entry.range.end)
12551 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12552 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12553 .collect::<Vec<_>>();
12554 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12555 primary_diagnostics_before
12556 .iter()
12557 .position(|entry| entry.diagnostic.group_id == active_group_id)
12558 });
12559
12560 let primary_diagnostics_after = buffer
12561 .diagnostics_in_range::<usize>(search_start..buffer.len())
12562 .filter(|entry| entry.diagnostic.is_primary)
12563 .filter(|entry| entry.range.start != entry.range.end)
12564 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12565 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12566 .collect::<Vec<_>>();
12567 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12568 primary_diagnostics_after
12569 .iter()
12570 .enumerate()
12571 .rev()
12572 .find_map(|(i, entry)| {
12573 if entry.diagnostic.group_id == active_group_id {
12574 Some(i)
12575 } else {
12576 None
12577 }
12578 })
12579 });
12580
12581 let next_primary_diagnostic = match direction {
12582 Direction::Prev => primary_diagnostics_before
12583 .iter()
12584 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12585 .rev()
12586 .next(),
12587 Direction::Next => primary_diagnostics_after
12588 .iter()
12589 .skip(
12590 last_same_group_diagnostic_after
12591 .map(|index| index + 1)
12592 .unwrap_or(0),
12593 )
12594 .next(),
12595 };
12596
12597 // Cycle around to the start of the buffer, potentially moving back to the start of
12598 // the currently active diagnostic.
12599 let cycle_around = || match direction {
12600 Direction::Prev => primary_diagnostics_after
12601 .iter()
12602 .rev()
12603 .chain(primary_diagnostics_before.iter().rev())
12604 .next(),
12605 Direction::Next => primary_diagnostics_before
12606 .iter()
12607 .chain(primary_diagnostics_after.iter())
12608 .next(),
12609 };
12610
12611 if let Some((primary_range, group_id)) = next_primary_diagnostic
12612 .or_else(cycle_around)
12613 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12614 {
12615 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12616 return;
12617 };
12618 self.activate_diagnostics(buffer_id, group_id, window, cx);
12619 if self.active_diagnostics.is_some() {
12620 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12621 s.select(vec![Selection {
12622 id: selection.id,
12623 start: primary_range.start,
12624 end: primary_range.start,
12625 reversed: false,
12626 goal: SelectionGoal::None,
12627 }]);
12628 });
12629 self.refresh_inline_completion(false, true, window, cx);
12630 }
12631 }
12632 }
12633
12634 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12635 let snapshot = self.snapshot(window, cx);
12636 let selection = self.selections.newest::<Point>(cx);
12637 self.go_to_hunk_before_or_after_position(
12638 &snapshot,
12639 selection.head(),
12640 Direction::Next,
12641 window,
12642 cx,
12643 );
12644 }
12645
12646 fn go_to_hunk_before_or_after_position(
12647 &mut self,
12648 snapshot: &EditorSnapshot,
12649 position: Point,
12650 direction: Direction,
12651 window: &mut Window,
12652 cx: &mut Context<Editor>,
12653 ) {
12654 let row = if direction == Direction::Next {
12655 self.hunk_after_position(snapshot, position)
12656 .map(|hunk| hunk.row_range.start)
12657 } else {
12658 self.hunk_before_position(snapshot, position)
12659 };
12660
12661 if let Some(row) = row {
12662 let destination = Point::new(row.0, 0);
12663 let autoscroll = Autoscroll::center();
12664
12665 self.unfold_ranges(&[destination..destination], false, false, cx);
12666 self.change_selections(Some(autoscroll), window, cx, |s| {
12667 s.select_ranges([destination..destination]);
12668 });
12669 }
12670 }
12671
12672 fn hunk_after_position(
12673 &mut self,
12674 snapshot: &EditorSnapshot,
12675 position: Point,
12676 ) -> Option<MultiBufferDiffHunk> {
12677 snapshot
12678 .buffer_snapshot
12679 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12680 .find(|hunk| hunk.row_range.start.0 > position.row)
12681 .or_else(|| {
12682 snapshot
12683 .buffer_snapshot
12684 .diff_hunks_in_range(Point::zero()..position)
12685 .find(|hunk| hunk.row_range.end.0 < position.row)
12686 })
12687 }
12688
12689 fn go_to_prev_hunk(
12690 &mut self,
12691 _: &GoToPreviousHunk,
12692 window: &mut Window,
12693 cx: &mut Context<Self>,
12694 ) {
12695 let snapshot = self.snapshot(window, cx);
12696 let selection = self.selections.newest::<Point>(cx);
12697 self.go_to_hunk_before_or_after_position(
12698 &snapshot,
12699 selection.head(),
12700 Direction::Prev,
12701 window,
12702 cx,
12703 );
12704 }
12705
12706 fn hunk_before_position(
12707 &mut self,
12708 snapshot: &EditorSnapshot,
12709 position: Point,
12710 ) -> Option<MultiBufferRow> {
12711 snapshot
12712 .buffer_snapshot
12713 .diff_hunk_before(position)
12714 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12715 }
12716
12717 fn go_to_line<T: 'static>(
12718 &mut self,
12719 position: Anchor,
12720 highlight_color: Option<Hsla>,
12721 window: &mut Window,
12722 cx: &mut Context<Self>,
12723 ) {
12724 let snapshot = self.snapshot(window, cx).display_snapshot;
12725 let position = position.to_point(&snapshot.buffer_snapshot);
12726 let start = snapshot
12727 .buffer_snapshot
12728 .clip_point(Point::new(position.row, 0), Bias::Left);
12729 let end = start + Point::new(1, 0);
12730 let start = snapshot.buffer_snapshot.anchor_before(start);
12731 let end = snapshot.buffer_snapshot.anchor_before(end);
12732
12733 self.highlight_rows::<T>(
12734 start..end,
12735 highlight_color
12736 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12737 false,
12738 cx,
12739 );
12740 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
12741 }
12742
12743 pub fn go_to_definition(
12744 &mut self,
12745 _: &GoToDefinition,
12746 window: &mut Window,
12747 cx: &mut Context<Self>,
12748 ) -> Task<Result<Navigated>> {
12749 let definition =
12750 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12751 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
12752 cx.spawn_in(window, async move |editor, cx| {
12753 if definition.await? == Navigated::Yes {
12754 return Ok(Navigated::Yes);
12755 }
12756 match fallback_strategy {
12757 GoToDefinitionFallback::None => Ok(Navigated::No),
12758 GoToDefinitionFallback::FindAllReferences => {
12759 match editor.update_in(cx, |editor, window, cx| {
12760 editor.find_all_references(&FindAllReferences, window, cx)
12761 })? {
12762 Some(references) => references.await,
12763 None => Ok(Navigated::No),
12764 }
12765 }
12766 }
12767 })
12768 }
12769
12770 pub fn go_to_declaration(
12771 &mut self,
12772 _: &GoToDeclaration,
12773 window: &mut Window,
12774 cx: &mut Context<Self>,
12775 ) -> Task<Result<Navigated>> {
12776 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12777 }
12778
12779 pub fn go_to_declaration_split(
12780 &mut self,
12781 _: &GoToDeclaration,
12782 window: &mut Window,
12783 cx: &mut Context<Self>,
12784 ) -> Task<Result<Navigated>> {
12785 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12786 }
12787
12788 pub fn go_to_implementation(
12789 &mut self,
12790 _: &GoToImplementation,
12791 window: &mut Window,
12792 cx: &mut Context<Self>,
12793 ) -> Task<Result<Navigated>> {
12794 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12795 }
12796
12797 pub fn go_to_implementation_split(
12798 &mut self,
12799 _: &GoToImplementationSplit,
12800 window: &mut Window,
12801 cx: &mut Context<Self>,
12802 ) -> Task<Result<Navigated>> {
12803 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12804 }
12805
12806 pub fn go_to_type_definition(
12807 &mut self,
12808 _: &GoToTypeDefinition,
12809 window: &mut Window,
12810 cx: &mut Context<Self>,
12811 ) -> Task<Result<Navigated>> {
12812 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12813 }
12814
12815 pub fn go_to_definition_split(
12816 &mut self,
12817 _: &GoToDefinitionSplit,
12818 window: &mut Window,
12819 cx: &mut Context<Self>,
12820 ) -> Task<Result<Navigated>> {
12821 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12822 }
12823
12824 pub fn go_to_type_definition_split(
12825 &mut self,
12826 _: &GoToTypeDefinitionSplit,
12827 window: &mut Window,
12828 cx: &mut Context<Self>,
12829 ) -> Task<Result<Navigated>> {
12830 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12831 }
12832
12833 fn go_to_definition_of_kind(
12834 &mut self,
12835 kind: GotoDefinitionKind,
12836 split: bool,
12837 window: &mut Window,
12838 cx: &mut Context<Self>,
12839 ) -> Task<Result<Navigated>> {
12840 let Some(provider) = self.semantics_provider.clone() else {
12841 return Task::ready(Ok(Navigated::No));
12842 };
12843 let head = self.selections.newest::<usize>(cx).head();
12844 let buffer = self.buffer.read(cx);
12845 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12846 text_anchor
12847 } else {
12848 return Task::ready(Ok(Navigated::No));
12849 };
12850
12851 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12852 return Task::ready(Ok(Navigated::No));
12853 };
12854
12855 cx.spawn_in(window, async move |editor, cx| {
12856 let definitions = definitions.await?;
12857 let navigated = editor
12858 .update_in(cx, |editor, window, cx| {
12859 editor.navigate_to_hover_links(
12860 Some(kind),
12861 definitions
12862 .into_iter()
12863 .filter(|location| {
12864 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12865 })
12866 .map(HoverLink::Text)
12867 .collect::<Vec<_>>(),
12868 split,
12869 window,
12870 cx,
12871 )
12872 })?
12873 .await?;
12874 anyhow::Ok(navigated)
12875 })
12876 }
12877
12878 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12879 let selection = self.selections.newest_anchor();
12880 let head = selection.head();
12881 let tail = selection.tail();
12882
12883 let Some((buffer, start_position)) =
12884 self.buffer.read(cx).text_anchor_for_position(head, cx)
12885 else {
12886 return;
12887 };
12888
12889 let end_position = if head != tail {
12890 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12891 return;
12892 };
12893 Some(pos)
12894 } else {
12895 None
12896 };
12897
12898 let url_finder = cx.spawn_in(window, async move |editor, cx| {
12899 let url = if let Some(end_pos) = end_position {
12900 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12901 } else {
12902 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12903 };
12904
12905 if let Some(url) = url {
12906 editor.update(cx, |_, cx| {
12907 cx.open_url(&url);
12908 })
12909 } else {
12910 Ok(())
12911 }
12912 });
12913
12914 url_finder.detach();
12915 }
12916
12917 pub fn open_selected_filename(
12918 &mut self,
12919 _: &OpenSelectedFilename,
12920 window: &mut Window,
12921 cx: &mut Context<Self>,
12922 ) {
12923 let Some(workspace) = self.workspace() else {
12924 return;
12925 };
12926
12927 let position = self.selections.newest_anchor().head();
12928
12929 let Some((buffer, buffer_position)) =
12930 self.buffer.read(cx).text_anchor_for_position(position, cx)
12931 else {
12932 return;
12933 };
12934
12935 let project = self.project.clone();
12936
12937 cx.spawn_in(window, async move |_, cx| {
12938 let result = find_file(&buffer, project, buffer_position, cx).await;
12939
12940 if let Some((_, path)) = result {
12941 workspace
12942 .update_in(cx, |workspace, window, cx| {
12943 workspace.open_resolved_path(path, window, cx)
12944 })?
12945 .await?;
12946 }
12947 anyhow::Ok(())
12948 })
12949 .detach();
12950 }
12951
12952 pub(crate) fn navigate_to_hover_links(
12953 &mut self,
12954 kind: Option<GotoDefinitionKind>,
12955 mut definitions: Vec<HoverLink>,
12956 split: bool,
12957 window: &mut Window,
12958 cx: &mut Context<Editor>,
12959 ) -> Task<Result<Navigated>> {
12960 // If there is one definition, just open it directly
12961 if definitions.len() == 1 {
12962 let definition = definitions.pop().unwrap();
12963
12964 enum TargetTaskResult {
12965 Location(Option<Location>),
12966 AlreadyNavigated,
12967 }
12968
12969 let target_task = match definition {
12970 HoverLink::Text(link) => {
12971 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12972 }
12973 HoverLink::InlayHint(lsp_location, server_id) => {
12974 let computation =
12975 self.compute_target_location(lsp_location, server_id, window, cx);
12976 cx.background_spawn(async move {
12977 let location = computation.await?;
12978 Ok(TargetTaskResult::Location(location))
12979 })
12980 }
12981 HoverLink::Url(url) => {
12982 cx.open_url(&url);
12983 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12984 }
12985 HoverLink::File(path) => {
12986 if let Some(workspace) = self.workspace() {
12987 cx.spawn_in(window, async move |_, cx| {
12988 workspace
12989 .update_in(cx, |workspace, window, cx| {
12990 workspace.open_resolved_path(path, window, cx)
12991 })?
12992 .await
12993 .map(|_| TargetTaskResult::AlreadyNavigated)
12994 })
12995 } else {
12996 Task::ready(Ok(TargetTaskResult::Location(None)))
12997 }
12998 }
12999 };
13000 cx.spawn_in(window, async move |editor, cx| {
13001 let target = match target_task.await.context("target resolution task")? {
13002 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13003 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13004 TargetTaskResult::Location(Some(target)) => target,
13005 };
13006
13007 editor.update_in(cx, |editor, window, cx| {
13008 let Some(workspace) = editor.workspace() else {
13009 return Navigated::No;
13010 };
13011 let pane = workspace.read(cx).active_pane().clone();
13012
13013 let range = target.range.to_point(target.buffer.read(cx));
13014 let range = editor.range_for_match(&range);
13015 let range = collapse_multiline_range(range);
13016
13017 if !split
13018 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13019 {
13020 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13021 } else {
13022 window.defer(cx, move |window, cx| {
13023 let target_editor: Entity<Self> =
13024 workspace.update(cx, |workspace, cx| {
13025 let pane = if split {
13026 workspace.adjacent_pane(window, cx)
13027 } else {
13028 workspace.active_pane().clone()
13029 };
13030
13031 workspace.open_project_item(
13032 pane,
13033 target.buffer.clone(),
13034 true,
13035 true,
13036 window,
13037 cx,
13038 )
13039 });
13040 target_editor.update(cx, |target_editor, cx| {
13041 // When selecting a definition in a different buffer, disable the nav history
13042 // to avoid creating a history entry at the previous cursor location.
13043 pane.update(cx, |pane, _| pane.disable_history());
13044 target_editor.go_to_singleton_buffer_range(range, window, cx);
13045 pane.update(cx, |pane, _| pane.enable_history());
13046 });
13047 });
13048 }
13049 Navigated::Yes
13050 })
13051 })
13052 } else if !definitions.is_empty() {
13053 cx.spawn_in(window, async move |editor, cx| {
13054 let (title, location_tasks, workspace) = editor
13055 .update_in(cx, |editor, window, cx| {
13056 let tab_kind = match kind {
13057 Some(GotoDefinitionKind::Implementation) => "Implementations",
13058 _ => "Definitions",
13059 };
13060 let title = definitions
13061 .iter()
13062 .find_map(|definition| match definition {
13063 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13064 let buffer = origin.buffer.read(cx);
13065 format!(
13066 "{} for {}",
13067 tab_kind,
13068 buffer
13069 .text_for_range(origin.range.clone())
13070 .collect::<String>()
13071 )
13072 }),
13073 HoverLink::InlayHint(_, _) => None,
13074 HoverLink::Url(_) => None,
13075 HoverLink::File(_) => None,
13076 })
13077 .unwrap_or(tab_kind.to_string());
13078 let location_tasks = definitions
13079 .into_iter()
13080 .map(|definition| match definition {
13081 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13082 HoverLink::InlayHint(lsp_location, server_id) => editor
13083 .compute_target_location(lsp_location, server_id, window, cx),
13084 HoverLink::Url(_) => Task::ready(Ok(None)),
13085 HoverLink::File(_) => Task::ready(Ok(None)),
13086 })
13087 .collect::<Vec<_>>();
13088 (title, location_tasks, editor.workspace().clone())
13089 })
13090 .context("location tasks preparation")?;
13091
13092 let locations = future::join_all(location_tasks)
13093 .await
13094 .into_iter()
13095 .filter_map(|location| location.transpose())
13096 .collect::<Result<_>>()
13097 .context("location tasks")?;
13098
13099 let Some(workspace) = workspace else {
13100 return Ok(Navigated::No);
13101 };
13102 let opened = workspace
13103 .update_in(cx, |workspace, window, cx| {
13104 Self::open_locations_in_multibuffer(
13105 workspace,
13106 locations,
13107 title,
13108 split,
13109 MultibufferSelectionMode::First,
13110 window,
13111 cx,
13112 )
13113 })
13114 .ok();
13115
13116 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13117 })
13118 } else {
13119 Task::ready(Ok(Navigated::No))
13120 }
13121 }
13122
13123 fn compute_target_location(
13124 &self,
13125 lsp_location: lsp::Location,
13126 server_id: LanguageServerId,
13127 window: &mut Window,
13128 cx: &mut Context<Self>,
13129 ) -> Task<anyhow::Result<Option<Location>>> {
13130 let Some(project) = self.project.clone() else {
13131 return Task::ready(Ok(None));
13132 };
13133
13134 cx.spawn_in(window, async move |editor, cx| {
13135 let location_task = editor.update(cx, |_, cx| {
13136 project.update(cx, |project, cx| {
13137 let language_server_name = project
13138 .language_server_statuses(cx)
13139 .find(|(id, _)| server_id == *id)
13140 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13141 language_server_name.map(|language_server_name| {
13142 project.open_local_buffer_via_lsp(
13143 lsp_location.uri.clone(),
13144 server_id,
13145 language_server_name,
13146 cx,
13147 )
13148 })
13149 })
13150 })?;
13151 let location = match location_task {
13152 Some(task) => Some({
13153 let target_buffer_handle = task.await.context("open local buffer")?;
13154 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13155 let target_start = target_buffer
13156 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13157 let target_end = target_buffer
13158 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13159 target_buffer.anchor_after(target_start)
13160 ..target_buffer.anchor_before(target_end)
13161 })?;
13162 Location {
13163 buffer: target_buffer_handle,
13164 range,
13165 }
13166 }),
13167 None => None,
13168 };
13169 Ok(location)
13170 })
13171 }
13172
13173 pub fn find_all_references(
13174 &mut self,
13175 _: &FindAllReferences,
13176 window: &mut Window,
13177 cx: &mut Context<Self>,
13178 ) -> Option<Task<Result<Navigated>>> {
13179 let selection = self.selections.newest::<usize>(cx);
13180 let multi_buffer = self.buffer.read(cx);
13181 let head = selection.head();
13182
13183 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13184 let head_anchor = multi_buffer_snapshot.anchor_at(
13185 head,
13186 if head < selection.tail() {
13187 Bias::Right
13188 } else {
13189 Bias::Left
13190 },
13191 );
13192
13193 match self
13194 .find_all_references_task_sources
13195 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13196 {
13197 Ok(_) => {
13198 log::info!(
13199 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13200 );
13201 return None;
13202 }
13203 Err(i) => {
13204 self.find_all_references_task_sources.insert(i, head_anchor);
13205 }
13206 }
13207
13208 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13209 let workspace = self.workspace()?;
13210 let project = workspace.read(cx).project().clone();
13211 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13212 Some(cx.spawn_in(window, async move |editor, cx| {
13213 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13214 if let Ok(i) = editor
13215 .find_all_references_task_sources
13216 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13217 {
13218 editor.find_all_references_task_sources.remove(i);
13219 }
13220 });
13221
13222 let locations = references.await?;
13223 if locations.is_empty() {
13224 return anyhow::Ok(Navigated::No);
13225 }
13226
13227 workspace.update_in(cx, |workspace, window, cx| {
13228 let title = locations
13229 .first()
13230 .as_ref()
13231 .map(|location| {
13232 let buffer = location.buffer.read(cx);
13233 format!(
13234 "References to `{}`",
13235 buffer
13236 .text_for_range(location.range.clone())
13237 .collect::<String>()
13238 )
13239 })
13240 .unwrap();
13241 Self::open_locations_in_multibuffer(
13242 workspace,
13243 locations,
13244 title,
13245 false,
13246 MultibufferSelectionMode::First,
13247 window,
13248 cx,
13249 );
13250 Navigated::Yes
13251 })
13252 }))
13253 }
13254
13255 /// Opens a multibuffer with the given project locations in it
13256 pub fn open_locations_in_multibuffer(
13257 workspace: &mut Workspace,
13258 mut locations: Vec<Location>,
13259 title: String,
13260 split: bool,
13261 multibuffer_selection_mode: MultibufferSelectionMode,
13262 window: &mut Window,
13263 cx: &mut Context<Workspace>,
13264 ) {
13265 // If there are multiple definitions, open them in a multibuffer
13266 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13267 let mut locations = locations.into_iter().peekable();
13268 let mut ranges = Vec::new();
13269 let capability = workspace.project().read(cx).capability();
13270
13271 let excerpt_buffer = cx.new(|cx| {
13272 let mut multibuffer = MultiBuffer::new(capability);
13273 while let Some(location) = locations.next() {
13274 let buffer = location.buffer.read(cx);
13275 let mut ranges_for_buffer = Vec::new();
13276 let range = location.range.to_offset(buffer);
13277 ranges_for_buffer.push(range.clone());
13278
13279 while let Some(next_location) = locations.peek() {
13280 if next_location.buffer == location.buffer {
13281 ranges_for_buffer.push(next_location.range.to_offset(buffer));
13282 locations.next();
13283 } else {
13284 break;
13285 }
13286 }
13287
13288 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
13289 ranges.extend(multibuffer.push_excerpts_with_context_lines(
13290 location.buffer.clone(),
13291 ranges_for_buffer,
13292 DEFAULT_MULTIBUFFER_CONTEXT,
13293 cx,
13294 ))
13295 }
13296
13297 multibuffer.with_title(title)
13298 });
13299
13300 let editor = cx.new(|cx| {
13301 Editor::for_multibuffer(
13302 excerpt_buffer,
13303 Some(workspace.project().clone()),
13304 window,
13305 cx,
13306 )
13307 });
13308 editor.update(cx, |editor, cx| {
13309 match multibuffer_selection_mode {
13310 MultibufferSelectionMode::First => {
13311 if let Some(first_range) = ranges.first() {
13312 editor.change_selections(None, window, cx, |selections| {
13313 selections.clear_disjoint();
13314 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
13315 });
13316 }
13317 editor.highlight_background::<Self>(
13318 &ranges,
13319 |theme| theme.editor_highlighted_line_background,
13320 cx,
13321 );
13322 }
13323 MultibufferSelectionMode::All => {
13324 editor.change_selections(None, window, cx, |selections| {
13325 selections.clear_disjoint();
13326 selections.select_anchor_ranges(ranges);
13327 });
13328 }
13329 }
13330 editor.register_buffers_with_language_servers(cx);
13331 });
13332
13333 let item = Box::new(editor);
13334 let item_id = item.item_id();
13335
13336 if split {
13337 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13338 } else {
13339 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13340 let (preview_item_id, preview_item_idx) =
13341 workspace.active_pane().update(cx, |pane, _| {
13342 (pane.preview_item_id(), pane.preview_item_idx())
13343 });
13344
13345 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13346
13347 if let Some(preview_item_id) = preview_item_id {
13348 workspace.active_pane().update(cx, |pane, cx| {
13349 pane.remove_item(preview_item_id, false, false, window, cx);
13350 });
13351 }
13352 } else {
13353 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13354 }
13355 }
13356 workspace.active_pane().update(cx, |pane, cx| {
13357 pane.set_preview_item_id(Some(item_id), cx);
13358 });
13359 }
13360
13361 pub fn rename(
13362 &mut self,
13363 _: &Rename,
13364 window: &mut Window,
13365 cx: &mut Context<Self>,
13366 ) -> Option<Task<Result<()>>> {
13367 use language::ToOffset as _;
13368
13369 let provider = self.semantics_provider.clone()?;
13370 let selection = self.selections.newest_anchor().clone();
13371 let (cursor_buffer, cursor_buffer_position) = self
13372 .buffer
13373 .read(cx)
13374 .text_anchor_for_position(selection.head(), cx)?;
13375 let (tail_buffer, cursor_buffer_position_end) = self
13376 .buffer
13377 .read(cx)
13378 .text_anchor_for_position(selection.tail(), cx)?;
13379 if tail_buffer != cursor_buffer {
13380 return None;
13381 }
13382
13383 let snapshot = cursor_buffer.read(cx).snapshot();
13384 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13385 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13386 let prepare_rename = provider
13387 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13388 .unwrap_or_else(|| Task::ready(Ok(None)));
13389 drop(snapshot);
13390
13391 Some(cx.spawn_in(window, async move |this, cx| {
13392 let rename_range = if let Some(range) = prepare_rename.await? {
13393 Some(range)
13394 } else {
13395 this.update(cx, |this, cx| {
13396 let buffer = this.buffer.read(cx).snapshot(cx);
13397 let mut buffer_highlights = this
13398 .document_highlights_for_position(selection.head(), &buffer)
13399 .filter(|highlight| {
13400 highlight.start.excerpt_id == selection.head().excerpt_id
13401 && highlight.end.excerpt_id == selection.head().excerpt_id
13402 });
13403 buffer_highlights
13404 .next()
13405 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13406 })?
13407 };
13408 if let Some(rename_range) = rename_range {
13409 this.update_in(cx, |this, window, cx| {
13410 let snapshot = cursor_buffer.read(cx).snapshot();
13411 let rename_buffer_range = rename_range.to_offset(&snapshot);
13412 let cursor_offset_in_rename_range =
13413 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13414 let cursor_offset_in_rename_range_end =
13415 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13416
13417 this.take_rename(false, window, cx);
13418 let buffer = this.buffer.read(cx).read(cx);
13419 let cursor_offset = selection.head().to_offset(&buffer);
13420 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13421 let rename_end = rename_start + rename_buffer_range.len();
13422 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13423 let mut old_highlight_id = None;
13424 let old_name: Arc<str> = buffer
13425 .chunks(rename_start..rename_end, true)
13426 .map(|chunk| {
13427 if old_highlight_id.is_none() {
13428 old_highlight_id = chunk.syntax_highlight_id;
13429 }
13430 chunk.text
13431 })
13432 .collect::<String>()
13433 .into();
13434
13435 drop(buffer);
13436
13437 // Position the selection in the rename editor so that it matches the current selection.
13438 this.show_local_selections = false;
13439 let rename_editor = cx.new(|cx| {
13440 let mut editor = Editor::single_line(window, cx);
13441 editor.buffer.update(cx, |buffer, cx| {
13442 buffer.edit([(0..0, old_name.clone())], None, cx)
13443 });
13444 let rename_selection_range = match cursor_offset_in_rename_range
13445 .cmp(&cursor_offset_in_rename_range_end)
13446 {
13447 Ordering::Equal => {
13448 editor.select_all(&SelectAll, window, cx);
13449 return editor;
13450 }
13451 Ordering::Less => {
13452 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13453 }
13454 Ordering::Greater => {
13455 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13456 }
13457 };
13458 if rename_selection_range.end > old_name.len() {
13459 editor.select_all(&SelectAll, window, cx);
13460 } else {
13461 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13462 s.select_ranges([rename_selection_range]);
13463 });
13464 }
13465 editor
13466 });
13467 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13468 if e == &EditorEvent::Focused {
13469 cx.emit(EditorEvent::FocusedIn)
13470 }
13471 })
13472 .detach();
13473
13474 let write_highlights =
13475 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13476 let read_highlights =
13477 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13478 let ranges = write_highlights
13479 .iter()
13480 .flat_map(|(_, ranges)| ranges.iter())
13481 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13482 .cloned()
13483 .collect();
13484
13485 this.highlight_text::<Rename>(
13486 ranges,
13487 HighlightStyle {
13488 fade_out: Some(0.6),
13489 ..Default::default()
13490 },
13491 cx,
13492 );
13493 let rename_focus_handle = rename_editor.focus_handle(cx);
13494 window.focus(&rename_focus_handle);
13495 let block_id = this.insert_blocks(
13496 [BlockProperties {
13497 style: BlockStyle::Flex,
13498 placement: BlockPlacement::Below(range.start),
13499 height: 1,
13500 render: Arc::new({
13501 let rename_editor = rename_editor.clone();
13502 move |cx: &mut BlockContext| {
13503 let mut text_style = cx.editor_style.text.clone();
13504 if let Some(highlight_style) = old_highlight_id
13505 .and_then(|h| h.style(&cx.editor_style.syntax))
13506 {
13507 text_style = text_style.highlight(highlight_style);
13508 }
13509 div()
13510 .block_mouse_down()
13511 .pl(cx.anchor_x)
13512 .child(EditorElement::new(
13513 &rename_editor,
13514 EditorStyle {
13515 background: cx.theme().system().transparent,
13516 local_player: cx.editor_style.local_player,
13517 text: text_style,
13518 scrollbar_width: cx.editor_style.scrollbar_width,
13519 syntax: cx.editor_style.syntax.clone(),
13520 status: cx.editor_style.status.clone(),
13521 inlay_hints_style: HighlightStyle {
13522 font_weight: Some(FontWeight::BOLD),
13523 ..make_inlay_hints_style(cx.app)
13524 },
13525 inline_completion_styles: make_suggestion_styles(
13526 cx.app,
13527 ),
13528 ..EditorStyle::default()
13529 },
13530 ))
13531 .into_any_element()
13532 }
13533 }),
13534 priority: 0,
13535 }],
13536 Some(Autoscroll::fit()),
13537 cx,
13538 )[0];
13539 this.pending_rename = Some(RenameState {
13540 range,
13541 old_name,
13542 editor: rename_editor,
13543 block_id,
13544 });
13545 })?;
13546 }
13547
13548 Ok(())
13549 }))
13550 }
13551
13552 pub fn confirm_rename(
13553 &mut self,
13554 _: &ConfirmRename,
13555 window: &mut Window,
13556 cx: &mut Context<Self>,
13557 ) -> Option<Task<Result<()>>> {
13558 let rename = self.take_rename(false, window, cx)?;
13559 let workspace = self.workspace()?.downgrade();
13560 let (buffer, start) = self
13561 .buffer
13562 .read(cx)
13563 .text_anchor_for_position(rename.range.start, cx)?;
13564 let (end_buffer, _) = self
13565 .buffer
13566 .read(cx)
13567 .text_anchor_for_position(rename.range.end, cx)?;
13568 if buffer != end_buffer {
13569 return None;
13570 }
13571
13572 let old_name = rename.old_name;
13573 let new_name = rename.editor.read(cx).text(cx);
13574
13575 let rename = self.semantics_provider.as_ref()?.perform_rename(
13576 &buffer,
13577 start,
13578 new_name.clone(),
13579 cx,
13580 )?;
13581
13582 Some(cx.spawn_in(window, async move |editor, cx| {
13583 let project_transaction = rename.await?;
13584 Self::open_project_transaction(
13585 &editor,
13586 workspace,
13587 project_transaction,
13588 format!("Rename: {} → {}", old_name, new_name),
13589 cx,
13590 )
13591 .await?;
13592
13593 editor.update(cx, |editor, cx| {
13594 editor.refresh_document_highlights(cx);
13595 })?;
13596 Ok(())
13597 }))
13598 }
13599
13600 fn take_rename(
13601 &mut self,
13602 moving_cursor: bool,
13603 window: &mut Window,
13604 cx: &mut Context<Self>,
13605 ) -> Option<RenameState> {
13606 let rename = self.pending_rename.take()?;
13607 if rename.editor.focus_handle(cx).is_focused(window) {
13608 window.focus(&self.focus_handle);
13609 }
13610
13611 self.remove_blocks(
13612 [rename.block_id].into_iter().collect(),
13613 Some(Autoscroll::fit()),
13614 cx,
13615 );
13616 self.clear_highlights::<Rename>(cx);
13617 self.show_local_selections = true;
13618
13619 if moving_cursor {
13620 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13621 editor.selections.newest::<usize>(cx).head()
13622 });
13623
13624 // Update the selection to match the position of the selection inside
13625 // the rename editor.
13626 let snapshot = self.buffer.read(cx).read(cx);
13627 let rename_range = rename.range.to_offset(&snapshot);
13628 let cursor_in_editor = snapshot
13629 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13630 .min(rename_range.end);
13631 drop(snapshot);
13632
13633 self.change_selections(None, window, cx, |s| {
13634 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13635 });
13636 } else {
13637 self.refresh_document_highlights(cx);
13638 }
13639
13640 Some(rename)
13641 }
13642
13643 pub fn pending_rename(&self) -> Option<&RenameState> {
13644 self.pending_rename.as_ref()
13645 }
13646
13647 fn format(
13648 &mut self,
13649 _: &Format,
13650 window: &mut Window,
13651 cx: &mut Context<Self>,
13652 ) -> Option<Task<Result<()>>> {
13653 let project = match &self.project {
13654 Some(project) => project.clone(),
13655 None => return None,
13656 };
13657
13658 Some(self.perform_format(
13659 project,
13660 FormatTrigger::Manual,
13661 FormatTarget::Buffers,
13662 window,
13663 cx,
13664 ))
13665 }
13666
13667 fn format_selections(
13668 &mut self,
13669 _: &FormatSelections,
13670 window: &mut Window,
13671 cx: &mut Context<Self>,
13672 ) -> Option<Task<Result<()>>> {
13673 let project = match &self.project {
13674 Some(project) => project.clone(),
13675 None => return None,
13676 };
13677
13678 let ranges = self
13679 .selections
13680 .all_adjusted(cx)
13681 .into_iter()
13682 .map(|selection| selection.range())
13683 .collect_vec();
13684
13685 Some(self.perform_format(
13686 project,
13687 FormatTrigger::Manual,
13688 FormatTarget::Ranges(ranges),
13689 window,
13690 cx,
13691 ))
13692 }
13693
13694 fn perform_format(
13695 &mut self,
13696 project: Entity<Project>,
13697 trigger: FormatTrigger,
13698 target: FormatTarget,
13699 window: &mut Window,
13700 cx: &mut Context<Self>,
13701 ) -> Task<Result<()>> {
13702 let buffer = self.buffer.clone();
13703 let (buffers, target) = match target {
13704 FormatTarget::Buffers => {
13705 let mut buffers = buffer.read(cx).all_buffers();
13706 if trigger == FormatTrigger::Save {
13707 buffers.retain(|buffer| buffer.read(cx).is_dirty());
13708 }
13709 (buffers, LspFormatTarget::Buffers)
13710 }
13711 FormatTarget::Ranges(selection_ranges) => {
13712 let multi_buffer = buffer.read(cx);
13713 let snapshot = multi_buffer.read(cx);
13714 let mut buffers = HashSet::default();
13715 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13716 BTreeMap::new();
13717 for selection_range in selection_ranges {
13718 for (buffer, buffer_range, _) in
13719 snapshot.range_to_buffer_ranges(selection_range)
13720 {
13721 let buffer_id = buffer.remote_id();
13722 let start = buffer.anchor_before(buffer_range.start);
13723 let end = buffer.anchor_after(buffer_range.end);
13724 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13725 buffer_id_to_ranges
13726 .entry(buffer_id)
13727 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13728 .or_insert_with(|| vec![start..end]);
13729 }
13730 }
13731 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13732 }
13733 };
13734
13735 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13736 let format = project.update(cx, |project, cx| {
13737 project.format(buffers, target, true, trigger, cx)
13738 });
13739
13740 cx.spawn_in(window, async move |_, cx| {
13741 let transaction = futures::select_biased! {
13742 transaction = format.log_err().fuse() => transaction,
13743 () = timeout => {
13744 log::warn!("timed out waiting for formatting");
13745 None
13746 }
13747 };
13748
13749 buffer
13750 .update(cx, |buffer, cx| {
13751 if let Some(transaction) = transaction {
13752 if !buffer.is_singleton() {
13753 buffer.push_transaction(&transaction.0, cx);
13754 }
13755 }
13756 cx.notify();
13757 })
13758 .ok();
13759
13760 Ok(())
13761 })
13762 }
13763
13764 fn organize_imports(
13765 &mut self,
13766 _: &OrganizeImports,
13767 window: &mut Window,
13768 cx: &mut Context<Self>,
13769 ) -> Option<Task<Result<()>>> {
13770 let project = match &self.project {
13771 Some(project) => project.clone(),
13772 None => return None,
13773 };
13774 Some(self.perform_code_action_kind(
13775 project,
13776 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13777 window,
13778 cx,
13779 ))
13780 }
13781
13782 fn perform_code_action_kind(
13783 &mut self,
13784 project: Entity<Project>,
13785 kind: CodeActionKind,
13786 window: &mut Window,
13787 cx: &mut Context<Self>,
13788 ) -> Task<Result<()>> {
13789 let buffer = self.buffer.clone();
13790 let buffers = buffer.read(cx).all_buffers();
13791 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13792 let apply_action = project.update(cx, |project, cx| {
13793 project.apply_code_action_kind(buffers, kind, true, cx)
13794 });
13795 cx.spawn_in(window, async move |_, cx| {
13796 let transaction = futures::select_biased! {
13797 () = timeout => {
13798 log::warn!("timed out waiting for executing code action");
13799 None
13800 }
13801 transaction = apply_action.log_err().fuse() => transaction,
13802 };
13803 buffer
13804 .update(cx, |buffer, cx| {
13805 // check if we need this
13806 if let Some(transaction) = transaction {
13807 if !buffer.is_singleton() {
13808 buffer.push_transaction(&transaction.0, cx);
13809 }
13810 }
13811 cx.notify();
13812 })
13813 .ok();
13814 Ok(())
13815 })
13816 }
13817
13818 fn restart_language_server(
13819 &mut self,
13820 _: &RestartLanguageServer,
13821 _: &mut Window,
13822 cx: &mut Context<Self>,
13823 ) {
13824 if let Some(project) = self.project.clone() {
13825 self.buffer.update(cx, |multi_buffer, cx| {
13826 project.update(cx, |project, cx| {
13827 project.restart_language_servers_for_buffers(
13828 multi_buffer.all_buffers().into_iter().collect(),
13829 cx,
13830 );
13831 });
13832 })
13833 }
13834 }
13835
13836 fn cancel_language_server_work(
13837 workspace: &mut Workspace,
13838 _: &actions::CancelLanguageServerWork,
13839 _: &mut Window,
13840 cx: &mut Context<Workspace>,
13841 ) {
13842 let project = workspace.project();
13843 let buffers = workspace
13844 .active_item(cx)
13845 .and_then(|item| item.act_as::<Editor>(cx))
13846 .map_or(HashSet::default(), |editor| {
13847 editor.read(cx).buffer.read(cx).all_buffers()
13848 });
13849 project.update(cx, |project, cx| {
13850 project.cancel_language_server_work_for_buffers(buffers, cx);
13851 });
13852 }
13853
13854 fn show_character_palette(
13855 &mut self,
13856 _: &ShowCharacterPalette,
13857 window: &mut Window,
13858 _: &mut Context<Self>,
13859 ) {
13860 window.show_character_palette();
13861 }
13862
13863 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13864 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13865 let buffer = self.buffer.read(cx).snapshot(cx);
13866 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13867 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13868 let is_valid = buffer
13869 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13870 .any(|entry| {
13871 entry.diagnostic.is_primary
13872 && !entry.range.is_empty()
13873 && entry.range.start == primary_range_start
13874 && entry.diagnostic.message == active_diagnostics.primary_message
13875 });
13876
13877 if is_valid != active_diagnostics.is_valid {
13878 active_diagnostics.is_valid = is_valid;
13879 if is_valid {
13880 let mut new_styles = HashMap::default();
13881 for (block_id, diagnostic) in &active_diagnostics.blocks {
13882 new_styles.insert(
13883 *block_id,
13884 diagnostic_block_renderer(diagnostic.clone(), None, true),
13885 );
13886 }
13887 self.display_map.update(cx, |display_map, _cx| {
13888 display_map.replace_blocks(new_styles);
13889 });
13890 } else {
13891 self.dismiss_diagnostics(cx);
13892 }
13893 }
13894 }
13895 }
13896
13897 fn activate_diagnostics(
13898 &mut self,
13899 buffer_id: BufferId,
13900 group_id: usize,
13901 window: &mut Window,
13902 cx: &mut Context<Self>,
13903 ) {
13904 self.dismiss_diagnostics(cx);
13905 let snapshot = self.snapshot(window, cx);
13906 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13907 let buffer = self.buffer.read(cx).snapshot(cx);
13908
13909 let mut primary_range = None;
13910 let mut primary_message = None;
13911 let diagnostic_group = buffer
13912 .diagnostic_group(buffer_id, group_id)
13913 .filter_map(|entry| {
13914 let start = entry.range.start;
13915 let end = entry.range.end;
13916 if snapshot.is_line_folded(MultiBufferRow(start.row))
13917 && (start.row == end.row
13918 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13919 {
13920 return None;
13921 }
13922 if entry.diagnostic.is_primary {
13923 primary_range = Some(entry.range.clone());
13924 primary_message = Some(entry.diagnostic.message.clone());
13925 }
13926 Some(entry)
13927 })
13928 .collect::<Vec<_>>();
13929 let primary_range = primary_range?;
13930 let primary_message = primary_message?;
13931
13932 let blocks = display_map
13933 .insert_blocks(
13934 diagnostic_group.iter().map(|entry| {
13935 let diagnostic = entry.diagnostic.clone();
13936 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13937 BlockProperties {
13938 style: BlockStyle::Fixed,
13939 placement: BlockPlacement::Below(
13940 buffer.anchor_after(entry.range.start),
13941 ),
13942 height: message_height,
13943 render: diagnostic_block_renderer(diagnostic, None, true),
13944 priority: 0,
13945 }
13946 }),
13947 cx,
13948 )
13949 .into_iter()
13950 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13951 .collect();
13952
13953 Some(ActiveDiagnosticGroup {
13954 primary_range: buffer.anchor_before(primary_range.start)
13955 ..buffer.anchor_after(primary_range.end),
13956 primary_message,
13957 group_id,
13958 blocks,
13959 is_valid: true,
13960 })
13961 });
13962 }
13963
13964 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13965 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13966 self.display_map.update(cx, |display_map, cx| {
13967 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13968 });
13969 cx.notify();
13970 }
13971 }
13972
13973 /// Disable inline diagnostics rendering for this editor.
13974 pub fn disable_inline_diagnostics(&mut self) {
13975 self.inline_diagnostics_enabled = false;
13976 self.inline_diagnostics_update = Task::ready(());
13977 self.inline_diagnostics.clear();
13978 }
13979
13980 pub fn inline_diagnostics_enabled(&self) -> bool {
13981 self.inline_diagnostics_enabled
13982 }
13983
13984 pub fn show_inline_diagnostics(&self) -> bool {
13985 self.show_inline_diagnostics
13986 }
13987
13988 pub fn toggle_inline_diagnostics(
13989 &mut self,
13990 _: &ToggleInlineDiagnostics,
13991 window: &mut Window,
13992 cx: &mut Context<'_, Editor>,
13993 ) {
13994 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13995 self.refresh_inline_diagnostics(false, window, cx);
13996 }
13997
13998 fn refresh_inline_diagnostics(
13999 &mut self,
14000 debounce: bool,
14001 window: &mut Window,
14002 cx: &mut Context<Self>,
14003 ) {
14004 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14005 self.inline_diagnostics_update = Task::ready(());
14006 self.inline_diagnostics.clear();
14007 return;
14008 }
14009
14010 let debounce_ms = ProjectSettings::get_global(cx)
14011 .diagnostics
14012 .inline
14013 .update_debounce_ms;
14014 let debounce = if debounce && debounce_ms > 0 {
14015 Some(Duration::from_millis(debounce_ms))
14016 } else {
14017 None
14018 };
14019 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14020 if let Some(debounce) = debounce {
14021 cx.background_executor().timer(debounce).await;
14022 }
14023 let Some(snapshot) = editor
14024 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14025 .ok()
14026 else {
14027 return;
14028 };
14029
14030 let new_inline_diagnostics = cx
14031 .background_spawn(async move {
14032 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14033 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14034 let message = diagnostic_entry
14035 .diagnostic
14036 .message
14037 .split_once('\n')
14038 .map(|(line, _)| line)
14039 .map(SharedString::new)
14040 .unwrap_or_else(|| {
14041 SharedString::from(diagnostic_entry.diagnostic.message)
14042 });
14043 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14044 let (Ok(i) | Err(i)) = inline_diagnostics
14045 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14046 inline_diagnostics.insert(
14047 i,
14048 (
14049 start_anchor,
14050 InlineDiagnostic {
14051 message,
14052 group_id: diagnostic_entry.diagnostic.group_id,
14053 start: diagnostic_entry.range.start.to_point(&snapshot),
14054 is_primary: diagnostic_entry.diagnostic.is_primary,
14055 severity: diagnostic_entry.diagnostic.severity,
14056 },
14057 ),
14058 );
14059 }
14060 inline_diagnostics
14061 })
14062 .await;
14063
14064 editor
14065 .update(cx, |editor, cx| {
14066 editor.inline_diagnostics = new_inline_diagnostics;
14067 cx.notify();
14068 })
14069 .ok();
14070 });
14071 }
14072
14073 pub fn set_selections_from_remote(
14074 &mut self,
14075 selections: Vec<Selection<Anchor>>,
14076 pending_selection: Option<Selection<Anchor>>,
14077 window: &mut Window,
14078 cx: &mut Context<Self>,
14079 ) {
14080 let old_cursor_position = self.selections.newest_anchor().head();
14081 self.selections.change_with(cx, |s| {
14082 s.select_anchors(selections);
14083 if let Some(pending_selection) = pending_selection {
14084 s.set_pending(pending_selection, SelectMode::Character);
14085 } else {
14086 s.clear_pending();
14087 }
14088 });
14089 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14090 }
14091
14092 fn push_to_selection_history(&mut self) {
14093 self.selection_history.push(SelectionHistoryEntry {
14094 selections: self.selections.disjoint_anchors(),
14095 select_next_state: self.select_next_state.clone(),
14096 select_prev_state: self.select_prev_state.clone(),
14097 add_selections_state: self.add_selections_state.clone(),
14098 });
14099 }
14100
14101 pub fn transact(
14102 &mut self,
14103 window: &mut Window,
14104 cx: &mut Context<Self>,
14105 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14106 ) -> Option<TransactionId> {
14107 self.start_transaction_at(Instant::now(), window, cx);
14108 update(self, window, cx);
14109 self.end_transaction_at(Instant::now(), cx)
14110 }
14111
14112 pub fn start_transaction_at(
14113 &mut self,
14114 now: Instant,
14115 window: &mut Window,
14116 cx: &mut Context<Self>,
14117 ) {
14118 self.end_selection(window, cx);
14119 if let Some(tx_id) = self
14120 .buffer
14121 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14122 {
14123 self.selection_history
14124 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14125 cx.emit(EditorEvent::TransactionBegun {
14126 transaction_id: tx_id,
14127 })
14128 }
14129 }
14130
14131 pub fn end_transaction_at(
14132 &mut self,
14133 now: Instant,
14134 cx: &mut Context<Self>,
14135 ) -> Option<TransactionId> {
14136 if let Some(transaction_id) = self
14137 .buffer
14138 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14139 {
14140 if let Some((_, end_selections)) =
14141 self.selection_history.transaction_mut(transaction_id)
14142 {
14143 *end_selections = Some(self.selections.disjoint_anchors());
14144 } else {
14145 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14146 }
14147
14148 cx.emit(EditorEvent::Edited { transaction_id });
14149 Some(transaction_id)
14150 } else {
14151 None
14152 }
14153 }
14154
14155 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14156 if self.selection_mark_mode {
14157 self.change_selections(None, window, cx, |s| {
14158 s.move_with(|_, sel| {
14159 sel.collapse_to(sel.head(), SelectionGoal::None);
14160 });
14161 })
14162 }
14163 self.selection_mark_mode = true;
14164 cx.notify();
14165 }
14166
14167 pub fn swap_selection_ends(
14168 &mut self,
14169 _: &actions::SwapSelectionEnds,
14170 window: &mut Window,
14171 cx: &mut Context<Self>,
14172 ) {
14173 self.change_selections(None, window, cx, |s| {
14174 s.move_with(|_, sel| {
14175 if sel.start != sel.end {
14176 sel.reversed = !sel.reversed
14177 }
14178 });
14179 });
14180 self.request_autoscroll(Autoscroll::newest(), cx);
14181 cx.notify();
14182 }
14183
14184 pub fn toggle_fold(
14185 &mut self,
14186 _: &actions::ToggleFold,
14187 window: &mut Window,
14188 cx: &mut Context<Self>,
14189 ) {
14190 if self.is_singleton(cx) {
14191 let selection = self.selections.newest::<Point>(cx);
14192
14193 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14194 let range = if selection.is_empty() {
14195 let point = selection.head().to_display_point(&display_map);
14196 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14197 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14198 .to_point(&display_map);
14199 start..end
14200 } else {
14201 selection.range()
14202 };
14203 if display_map.folds_in_range(range).next().is_some() {
14204 self.unfold_lines(&Default::default(), window, cx)
14205 } else {
14206 self.fold(&Default::default(), window, cx)
14207 }
14208 } else {
14209 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14210 let buffer_ids: HashSet<_> = self
14211 .selections
14212 .disjoint_anchor_ranges()
14213 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14214 .collect();
14215
14216 let should_unfold = buffer_ids
14217 .iter()
14218 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14219
14220 for buffer_id in buffer_ids {
14221 if should_unfold {
14222 self.unfold_buffer(buffer_id, cx);
14223 } else {
14224 self.fold_buffer(buffer_id, cx);
14225 }
14226 }
14227 }
14228 }
14229
14230 pub fn toggle_fold_recursive(
14231 &mut self,
14232 _: &actions::ToggleFoldRecursive,
14233 window: &mut Window,
14234 cx: &mut Context<Self>,
14235 ) {
14236 let selection = self.selections.newest::<Point>(cx);
14237
14238 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14239 let range = if selection.is_empty() {
14240 let point = selection.head().to_display_point(&display_map);
14241 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14242 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14243 .to_point(&display_map);
14244 start..end
14245 } else {
14246 selection.range()
14247 };
14248 if display_map.folds_in_range(range).next().is_some() {
14249 self.unfold_recursive(&Default::default(), window, cx)
14250 } else {
14251 self.fold_recursive(&Default::default(), window, cx)
14252 }
14253 }
14254
14255 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
14256 if self.is_singleton(cx) {
14257 let mut to_fold = Vec::new();
14258 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14259 let selections = self.selections.all_adjusted(cx);
14260
14261 for selection in selections {
14262 let range = selection.range().sorted();
14263 let buffer_start_row = range.start.row;
14264
14265 if range.start.row != range.end.row {
14266 let mut found = false;
14267 let mut row = range.start.row;
14268 while row <= range.end.row {
14269 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
14270 {
14271 found = true;
14272 row = crease.range().end.row + 1;
14273 to_fold.push(crease);
14274 } else {
14275 row += 1
14276 }
14277 }
14278 if found {
14279 continue;
14280 }
14281 }
14282
14283 for row in (0..=range.start.row).rev() {
14284 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14285 if crease.range().end.row >= buffer_start_row {
14286 to_fold.push(crease);
14287 if row <= range.start.row {
14288 break;
14289 }
14290 }
14291 }
14292 }
14293 }
14294
14295 self.fold_creases(to_fold, true, window, cx);
14296 } else {
14297 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14298 let buffer_ids = self
14299 .selections
14300 .disjoint_anchor_ranges()
14301 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14302 .collect::<HashSet<_>>();
14303 for buffer_id in buffer_ids {
14304 self.fold_buffer(buffer_id, cx);
14305 }
14306 }
14307 }
14308
14309 fn fold_at_level(
14310 &mut self,
14311 fold_at: &FoldAtLevel,
14312 window: &mut Window,
14313 cx: &mut Context<Self>,
14314 ) {
14315 if !self.buffer.read(cx).is_singleton() {
14316 return;
14317 }
14318
14319 let fold_at_level = fold_at.0;
14320 let snapshot = self.buffer.read(cx).snapshot(cx);
14321 let mut to_fold = Vec::new();
14322 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14323
14324 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14325 while start_row < end_row {
14326 match self
14327 .snapshot(window, cx)
14328 .crease_for_buffer_row(MultiBufferRow(start_row))
14329 {
14330 Some(crease) => {
14331 let nested_start_row = crease.range().start.row + 1;
14332 let nested_end_row = crease.range().end.row;
14333
14334 if current_level < fold_at_level {
14335 stack.push((nested_start_row, nested_end_row, current_level + 1));
14336 } else if current_level == fold_at_level {
14337 to_fold.push(crease);
14338 }
14339
14340 start_row = nested_end_row + 1;
14341 }
14342 None => start_row += 1,
14343 }
14344 }
14345 }
14346
14347 self.fold_creases(to_fold, true, window, cx);
14348 }
14349
14350 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14351 if self.buffer.read(cx).is_singleton() {
14352 let mut fold_ranges = Vec::new();
14353 let snapshot = self.buffer.read(cx).snapshot(cx);
14354
14355 for row in 0..snapshot.max_row().0 {
14356 if let Some(foldable_range) = self
14357 .snapshot(window, cx)
14358 .crease_for_buffer_row(MultiBufferRow(row))
14359 {
14360 fold_ranges.push(foldable_range);
14361 }
14362 }
14363
14364 self.fold_creases(fold_ranges, true, window, cx);
14365 } else {
14366 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14367 editor
14368 .update_in(cx, |editor, _, cx| {
14369 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14370 editor.fold_buffer(buffer_id, cx);
14371 }
14372 })
14373 .ok();
14374 });
14375 }
14376 }
14377
14378 pub fn fold_function_bodies(
14379 &mut self,
14380 _: &actions::FoldFunctionBodies,
14381 window: &mut Window,
14382 cx: &mut Context<Self>,
14383 ) {
14384 let snapshot = self.buffer.read(cx).snapshot(cx);
14385
14386 let ranges = snapshot
14387 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14388 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14389 .collect::<Vec<_>>();
14390
14391 let creases = ranges
14392 .into_iter()
14393 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14394 .collect();
14395
14396 self.fold_creases(creases, true, window, cx);
14397 }
14398
14399 pub fn fold_recursive(
14400 &mut self,
14401 _: &actions::FoldRecursive,
14402 window: &mut Window,
14403 cx: &mut Context<Self>,
14404 ) {
14405 let mut to_fold = Vec::new();
14406 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14407 let selections = self.selections.all_adjusted(cx);
14408
14409 for selection in selections {
14410 let range = selection.range().sorted();
14411 let buffer_start_row = range.start.row;
14412
14413 if range.start.row != range.end.row {
14414 let mut found = false;
14415 for row in range.start.row..=range.end.row {
14416 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14417 found = true;
14418 to_fold.push(crease);
14419 }
14420 }
14421 if found {
14422 continue;
14423 }
14424 }
14425
14426 for row in (0..=range.start.row).rev() {
14427 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14428 if crease.range().end.row >= buffer_start_row {
14429 to_fold.push(crease);
14430 } else {
14431 break;
14432 }
14433 }
14434 }
14435 }
14436
14437 self.fold_creases(to_fold, true, window, cx);
14438 }
14439
14440 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14441 let buffer_row = fold_at.buffer_row;
14442 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14443
14444 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14445 let autoscroll = self
14446 .selections
14447 .all::<Point>(cx)
14448 .iter()
14449 .any(|selection| crease.range().overlaps(&selection.range()));
14450
14451 self.fold_creases(vec![crease], autoscroll, window, cx);
14452 }
14453 }
14454
14455 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14456 if self.is_singleton(cx) {
14457 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14458 let buffer = &display_map.buffer_snapshot;
14459 let selections = self.selections.all::<Point>(cx);
14460 let ranges = selections
14461 .iter()
14462 .map(|s| {
14463 let range = s.display_range(&display_map).sorted();
14464 let mut start = range.start.to_point(&display_map);
14465 let mut end = range.end.to_point(&display_map);
14466 start.column = 0;
14467 end.column = buffer.line_len(MultiBufferRow(end.row));
14468 start..end
14469 })
14470 .collect::<Vec<_>>();
14471
14472 self.unfold_ranges(&ranges, true, true, cx);
14473 } else {
14474 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14475 let buffer_ids = self
14476 .selections
14477 .disjoint_anchor_ranges()
14478 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14479 .collect::<HashSet<_>>();
14480 for buffer_id in buffer_ids {
14481 self.unfold_buffer(buffer_id, cx);
14482 }
14483 }
14484 }
14485
14486 pub fn unfold_recursive(
14487 &mut self,
14488 _: &UnfoldRecursive,
14489 _window: &mut Window,
14490 cx: &mut Context<Self>,
14491 ) {
14492 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14493 let selections = self.selections.all::<Point>(cx);
14494 let ranges = selections
14495 .iter()
14496 .map(|s| {
14497 let mut range = s.display_range(&display_map).sorted();
14498 *range.start.column_mut() = 0;
14499 *range.end.column_mut() = display_map.line_len(range.end.row());
14500 let start = range.start.to_point(&display_map);
14501 let end = range.end.to_point(&display_map);
14502 start..end
14503 })
14504 .collect::<Vec<_>>();
14505
14506 self.unfold_ranges(&ranges, true, true, cx);
14507 }
14508
14509 pub fn unfold_at(
14510 &mut self,
14511 unfold_at: &UnfoldAt,
14512 _window: &mut Window,
14513 cx: &mut Context<Self>,
14514 ) {
14515 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14516
14517 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14518 ..Point::new(
14519 unfold_at.buffer_row.0,
14520 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14521 );
14522
14523 let autoscroll = self
14524 .selections
14525 .all::<Point>(cx)
14526 .iter()
14527 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14528
14529 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14530 }
14531
14532 pub fn unfold_all(
14533 &mut self,
14534 _: &actions::UnfoldAll,
14535 _window: &mut Window,
14536 cx: &mut Context<Self>,
14537 ) {
14538 if self.buffer.read(cx).is_singleton() {
14539 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14540 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14541 } else {
14542 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14543 editor
14544 .update(cx, |editor, cx| {
14545 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14546 editor.unfold_buffer(buffer_id, cx);
14547 }
14548 })
14549 .ok();
14550 });
14551 }
14552 }
14553
14554 pub fn fold_selected_ranges(
14555 &mut self,
14556 _: &FoldSelectedRanges,
14557 window: &mut Window,
14558 cx: &mut Context<Self>,
14559 ) {
14560 let selections = self.selections.all::<Point>(cx);
14561 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14562 let line_mode = self.selections.line_mode;
14563 let ranges = selections
14564 .into_iter()
14565 .map(|s| {
14566 if line_mode {
14567 let start = Point::new(s.start.row, 0);
14568 let end = Point::new(
14569 s.end.row,
14570 display_map
14571 .buffer_snapshot
14572 .line_len(MultiBufferRow(s.end.row)),
14573 );
14574 Crease::simple(start..end, display_map.fold_placeholder.clone())
14575 } else {
14576 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14577 }
14578 })
14579 .collect::<Vec<_>>();
14580 self.fold_creases(ranges, true, window, cx);
14581 }
14582
14583 pub fn fold_ranges<T: ToOffset + Clone>(
14584 &mut self,
14585 ranges: Vec<Range<T>>,
14586 auto_scroll: bool,
14587 window: &mut Window,
14588 cx: &mut Context<Self>,
14589 ) {
14590 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14591 let ranges = ranges
14592 .into_iter()
14593 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14594 .collect::<Vec<_>>();
14595 self.fold_creases(ranges, auto_scroll, window, cx);
14596 }
14597
14598 pub fn fold_creases<T: ToOffset + Clone>(
14599 &mut self,
14600 creases: Vec<Crease<T>>,
14601 auto_scroll: bool,
14602 window: &mut Window,
14603 cx: &mut Context<Self>,
14604 ) {
14605 if creases.is_empty() {
14606 return;
14607 }
14608
14609 let mut buffers_affected = HashSet::default();
14610 let multi_buffer = self.buffer().read(cx);
14611 for crease in &creases {
14612 if let Some((_, buffer, _)) =
14613 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14614 {
14615 buffers_affected.insert(buffer.read(cx).remote_id());
14616 };
14617 }
14618
14619 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14620
14621 if auto_scroll {
14622 self.request_autoscroll(Autoscroll::fit(), cx);
14623 }
14624
14625 cx.notify();
14626
14627 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14628 // Clear diagnostics block when folding a range that contains it.
14629 let snapshot = self.snapshot(window, cx);
14630 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14631 drop(snapshot);
14632 self.active_diagnostics = Some(active_diagnostics);
14633 self.dismiss_diagnostics(cx);
14634 } else {
14635 self.active_diagnostics = Some(active_diagnostics);
14636 }
14637 }
14638
14639 self.scrollbar_marker_state.dirty = true;
14640 self.folds_did_change(cx);
14641 }
14642
14643 /// Removes any folds whose ranges intersect any of the given ranges.
14644 pub fn unfold_ranges<T: ToOffset + Clone>(
14645 &mut self,
14646 ranges: &[Range<T>],
14647 inclusive: bool,
14648 auto_scroll: bool,
14649 cx: &mut Context<Self>,
14650 ) {
14651 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14652 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14653 });
14654 self.folds_did_change(cx);
14655 }
14656
14657 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14658 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14659 return;
14660 }
14661 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14662 self.display_map.update(cx, |display_map, cx| {
14663 display_map.fold_buffers([buffer_id], cx)
14664 });
14665 cx.emit(EditorEvent::BufferFoldToggled {
14666 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14667 folded: true,
14668 });
14669 cx.notify();
14670 }
14671
14672 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14673 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14674 return;
14675 }
14676 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14677 self.display_map.update(cx, |display_map, cx| {
14678 display_map.unfold_buffers([buffer_id], cx);
14679 });
14680 cx.emit(EditorEvent::BufferFoldToggled {
14681 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14682 folded: false,
14683 });
14684 cx.notify();
14685 }
14686
14687 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14688 self.display_map.read(cx).is_buffer_folded(buffer)
14689 }
14690
14691 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14692 self.display_map.read(cx).folded_buffers()
14693 }
14694
14695 /// Removes any folds with the given ranges.
14696 pub fn remove_folds_with_type<T: ToOffset + Clone>(
14697 &mut self,
14698 ranges: &[Range<T>],
14699 type_id: TypeId,
14700 auto_scroll: bool,
14701 cx: &mut Context<Self>,
14702 ) {
14703 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14704 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14705 });
14706 self.folds_did_change(cx);
14707 }
14708
14709 fn remove_folds_with<T: ToOffset + Clone>(
14710 &mut self,
14711 ranges: &[Range<T>],
14712 auto_scroll: bool,
14713 cx: &mut Context<Self>,
14714 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14715 ) {
14716 if ranges.is_empty() {
14717 return;
14718 }
14719
14720 let mut buffers_affected = HashSet::default();
14721 let multi_buffer = self.buffer().read(cx);
14722 for range in ranges {
14723 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14724 buffers_affected.insert(buffer.read(cx).remote_id());
14725 };
14726 }
14727
14728 self.display_map.update(cx, update);
14729
14730 if auto_scroll {
14731 self.request_autoscroll(Autoscroll::fit(), cx);
14732 }
14733
14734 cx.notify();
14735 self.scrollbar_marker_state.dirty = true;
14736 self.active_indent_guides_state.dirty = true;
14737 }
14738
14739 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14740 self.display_map.read(cx).fold_placeholder.clone()
14741 }
14742
14743 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14744 self.buffer.update(cx, |buffer, cx| {
14745 buffer.set_all_diff_hunks_expanded(cx);
14746 });
14747 }
14748
14749 pub fn expand_all_diff_hunks(
14750 &mut self,
14751 _: &ExpandAllDiffHunks,
14752 _window: &mut Window,
14753 cx: &mut Context<Self>,
14754 ) {
14755 self.buffer.update(cx, |buffer, cx| {
14756 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14757 });
14758 }
14759
14760 pub fn toggle_selected_diff_hunks(
14761 &mut self,
14762 _: &ToggleSelectedDiffHunks,
14763 _window: &mut Window,
14764 cx: &mut Context<Self>,
14765 ) {
14766 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14767 self.toggle_diff_hunks_in_ranges(ranges, cx);
14768 }
14769
14770 pub fn diff_hunks_in_ranges<'a>(
14771 &'a self,
14772 ranges: &'a [Range<Anchor>],
14773 buffer: &'a MultiBufferSnapshot,
14774 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14775 ranges.iter().flat_map(move |range| {
14776 let end_excerpt_id = range.end.excerpt_id;
14777 let range = range.to_point(buffer);
14778 let mut peek_end = range.end;
14779 if range.end.row < buffer.max_row().0 {
14780 peek_end = Point::new(range.end.row + 1, 0);
14781 }
14782 buffer
14783 .diff_hunks_in_range(range.start..peek_end)
14784 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14785 })
14786 }
14787
14788 pub fn has_stageable_diff_hunks_in_ranges(
14789 &self,
14790 ranges: &[Range<Anchor>],
14791 snapshot: &MultiBufferSnapshot,
14792 ) -> bool {
14793 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14794 hunks.any(|hunk| hunk.status().has_secondary_hunk())
14795 }
14796
14797 pub fn toggle_staged_selected_diff_hunks(
14798 &mut self,
14799 _: &::git::ToggleStaged,
14800 _: &mut Window,
14801 cx: &mut Context<Self>,
14802 ) {
14803 let snapshot = self.buffer.read(cx).snapshot(cx);
14804 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14805 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14806 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14807 }
14808
14809 pub fn stage_and_next(
14810 &mut self,
14811 _: &::git::StageAndNext,
14812 window: &mut Window,
14813 cx: &mut Context<Self>,
14814 ) {
14815 self.do_stage_or_unstage_and_next(true, window, cx);
14816 }
14817
14818 pub fn unstage_and_next(
14819 &mut self,
14820 _: &::git::UnstageAndNext,
14821 window: &mut Window,
14822 cx: &mut Context<Self>,
14823 ) {
14824 self.do_stage_or_unstage_and_next(false, window, cx);
14825 }
14826
14827 pub fn stage_or_unstage_diff_hunks(
14828 &mut self,
14829 stage: bool,
14830 ranges: Vec<Range<Anchor>>,
14831 cx: &mut Context<Self>,
14832 ) {
14833 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14834 cx.spawn(async move |this, cx| {
14835 task.await?;
14836 this.update(cx, |this, cx| {
14837 let snapshot = this.buffer.read(cx).snapshot(cx);
14838 let chunk_by = this
14839 .diff_hunks_in_ranges(&ranges, &snapshot)
14840 .chunk_by(|hunk| hunk.buffer_id);
14841 for (buffer_id, hunks) in &chunk_by {
14842 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14843 }
14844 })
14845 })
14846 .detach_and_log_err(cx);
14847 }
14848
14849 fn save_buffers_for_ranges_if_needed(
14850 &mut self,
14851 ranges: &[Range<Anchor>],
14852 cx: &mut Context<'_, Editor>,
14853 ) -> Task<Result<()>> {
14854 let multibuffer = self.buffer.read(cx);
14855 let snapshot = multibuffer.read(cx);
14856 let buffer_ids: HashSet<_> = ranges
14857 .iter()
14858 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14859 .collect();
14860 drop(snapshot);
14861
14862 let mut buffers = HashSet::default();
14863 for buffer_id in buffer_ids {
14864 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14865 let buffer = buffer_entity.read(cx);
14866 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14867 {
14868 buffers.insert(buffer_entity);
14869 }
14870 }
14871 }
14872
14873 if let Some(project) = &self.project {
14874 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14875 } else {
14876 Task::ready(Ok(()))
14877 }
14878 }
14879
14880 fn do_stage_or_unstage_and_next(
14881 &mut self,
14882 stage: bool,
14883 window: &mut Window,
14884 cx: &mut Context<Self>,
14885 ) {
14886 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14887
14888 if ranges.iter().any(|range| range.start != range.end) {
14889 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14890 return;
14891 }
14892
14893 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14894 let snapshot = self.snapshot(window, cx);
14895 let position = self.selections.newest::<Point>(cx).head();
14896 let mut row = snapshot
14897 .buffer_snapshot
14898 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14899 .find(|hunk| hunk.row_range.start.0 > position.row)
14900 .map(|hunk| hunk.row_range.start);
14901
14902 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14903 // Outside of the project diff editor, wrap around to the beginning.
14904 if !all_diff_hunks_expanded {
14905 row = row.or_else(|| {
14906 snapshot
14907 .buffer_snapshot
14908 .diff_hunks_in_range(Point::zero()..position)
14909 .find(|hunk| hunk.row_range.end.0 < position.row)
14910 .map(|hunk| hunk.row_range.start)
14911 });
14912 }
14913
14914 if let Some(row) = row {
14915 let destination = Point::new(row.0, 0);
14916 let autoscroll = Autoscroll::center();
14917
14918 self.unfold_ranges(&[destination..destination], false, false, cx);
14919 self.change_selections(Some(autoscroll), window, cx, |s| {
14920 s.select_ranges([destination..destination]);
14921 });
14922 }
14923 }
14924
14925 fn do_stage_or_unstage(
14926 &self,
14927 stage: bool,
14928 buffer_id: BufferId,
14929 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14930 cx: &mut App,
14931 ) -> Option<()> {
14932 let project = self.project.as_ref()?;
14933 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14934 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14935 let buffer_snapshot = buffer.read(cx).snapshot();
14936 let file_exists = buffer_snapshot
14937 .file()
14938 .is_some_and(|file| file.disk_state().exists());
14939 diff.update(cx, |diff, cx| {
14940 diff.stage_or_unstage_hunks(
14941 stage,
14942 &hunks
14943 .map(|hunk| buffer_diff::DiffHunk {
14944 buffer_range: hunk.buffer_range,
14945 diff_base_byte_range: hunk.diff_base_byte_range,
14946 secondary_status: hunk.secondary_status,
14947 range: Point::zero()..Point::zero(), // unused
14948 })
14949 .collect::<Vec<_>>(),
14950 &buffer_snapshot,
14951 file_exists,
14952 cx,
14953 )
14954 });
14955 None
14956 }
14957
14958 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14959 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14960 self.buffer
14961 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14962 }
14963
14964 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14965 self.buffer.update(cx, |buffer, cx| {
14966 let ranges = vec![Anchor::min()..Anchor::max()];
14967 if !buffer.all_diff_hunks_expanded()
14968 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14969 {
14970 buffer.collapse_diff_hunks(ranges, cx);
14971 true
14972 } else {
14973 false
14974 }
14975 })
14976 }
14977
14978 fn toggle_diff_hunks_in_ranges(
14979 &mut self,
14980 ranges: Vec<Range<Anchor>>,
14981 cx: &mut Context<'_, Editor>,
14982 ) {
14983 self.buffer.update(cx, |buffer, cx| {
14984 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14985 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14986 })
14987 }
14988
14989 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14990 self.buffer.update(cx, |buffer, cx| {
14991 let snapshot = buffer.snapshot(cx);
14992 let excerpt_id = range.end.excerpt_id;
14993 let point_range = range.to_point(&snapshot);
14994 let expand = !buffer.single_hunk_is_expanded(range, cx);
14995 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14996 })
14997 }
14998
14999 pub(crate) fn apply_all_diff_hunks(
15000 &mut self,
15001 _: &ApplyAllDiffHunks,
15002 window: &mut Window,
15003 cx: &mut Context<Self>,
15004 ) {
15005 let buffers = self.buffer.read(cx).all_buffers();
15006 for branch_buffer in buffers {
15007 branch_buffer.update(cx, |branch_buffer, cx| {
15008 branch_buffer.merge_into_base(Vec::new(), cx);
15009 });
15010 }
15011
15012 if let Some(project) = self.project.clone() {
15013 self.save(true, project, window, cx).detach_and_log_err(cx);
15014 }
15015 }
15016
15017 pub(crate) fn apply_selected_diff_hunks(
15018 &mut self,
15019 _: &ApplyDiffHunk,
15020 window: &mut Window,
15021 cx: &mut Context<Self>,
15022 ) {
15023 let snapshot = self.snapshot(window, cx);
15024 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15025 let mut ranges_by_buffer = HashMap::default();
15026 self.transact(window, cx, |editor, _window, cx| {
15027 for hunk in hunks {
15028 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15029 ranges_by_buffer
15030 .entry(buffer.clone())
15031 .or_insert_with(Vec::new)
15032 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15033 }
15034 }
15035
15036 for (buffer, ranges) in ranges_by_buffer {
15037 buffer.update(cx, |buffer, cx| {
15038 buffer.merge_into_base(ranges, cx);
15039 });
15040 }
15041 });
15042
15043 if let Some(project) = self.project.clone() {
15044 self.save(true, project, window, cx).detach_and_log_err(cx);
15045 }
15046 }
15047
15048 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15049 if hovered != self.gutter_hovered {
15050 self.gutter_hovered = hovered;
15051 cx.notify();
15052 }
15053 }
15054
15055 pub fn insert_blocks(
15056 &mut self,
15057 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15058 autoscroll: Option<Autoscroll>,
15059 cx: &mut Context<Self>,
15060 ) -> Vec<CustomBlockId> {
15061 let blocks = self
15062 .display_map
15063 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15064 if let Some(autoscroll) = autoscroll {
15065 self.request_autoscroll(autoscroll, cx);
15066 }
15067 cx.notify();
15068 blocks
15069 }
15070
15071 pub fn resize_blocks(
15072 &mut self,
15073 heights: HashMap<CustomBlockId, u32>,
15074 autoscroll: Option<Autoscroll>,
15075 cx: &mut Context<Self>,
15076 ) {
15077 self.display_map
15078 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15079 if let Some(autoscroll) = autoscroll {
15080 self.request_autoscroll(autoscroll, cx);
15081 }
15082 cx.notify();
15083 }
15084
15085 pub fn replace_blocks(
15086 &mut self,
15087 renderers: HashMap<CustomBlockId, RenderBlock>,
15088 autoscroll: Option<Autoscroll>,
15089 cx: &mut Context<Self>,
15090 ) {
15091 self.display_map
15092 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15093 if let Some(autoscroll) = autoscroll {
15094 self.request_autoscroll(autoscroll, cx);
15095 }
15096 cx.notify();
15097 }
15098
15099 pub fn remove_blocks(
15100 &mut self,
15101 block_ids: HashSet<CustomBlockId>,
15102 autoscroll: Option<Autoscroll>,
15103 cx: &mut Context<Self>,
15104 ) {
15105 self.display_map.update(cx, |display_map, cx| {
15106 display_map.remove_blocks(block_ids, cx)
15107 });
15108 if let Some(autoscroll) = autoscroll {
15109 self.request_autoscroll(autoscroll, cx);
15110 }
15111 cx.notify();
15112 }
15113
15114 pub fn row_for_block(
15115 &self,
15116 block_id: CustomBlockId,
15117 cx: &mut Context<Self>,
15118 ) -> Option<DisplayRow> {
15119 self.display_map
15120 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15121 }
15122
15123 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15124 self.focused_block = Some(focused_block);
15125 }
15126
15127 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15128 self.focused_block.take()
15129 }
15130
15131 pub fn insert_creases(
15132 &mut self,
15133 creases: impl IntoIterator<Item = Crease<Anchor>>,
15134 cx: &mut Context<Self>,
15135 ) -> Vec<CreaseId> {
15136 self.display_map
15137 .update(cx, |map, cx| map.insert_creases(creases, cx))
15138 }
15139
15140 pub fn remove_creases(
15141 &mut self,
15142 ids: impl IntoIterator<Item = CreaseId>,
15143 cx: &mut Context<Self>,
15144 ) {
15145 self.display_map
15146 .update(cx, |map, cx| map.remove_creases(ids, cx));
15147 }
15148
15149 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15150 self.display_map
15151 .update(cx, |map, cx| map.snapshot(cx))
15152 .longest_row()
15153 }
15154
15155 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15156 self.display_map
15157 .update(cx, |map, cx| map.snapshot(cx))
15158 .max_point()
15159 }
15160
15161 pub fn text(&self, cx: &App) -> String {
15162 self.buffer.read(cx).read(cx).text()
15163 }
15164
15165 pub fn is_empty(&self, cx: &App) -> bool {
15166 self.buffer.read(cx).read(cx).is_empty()
15167 }
15168
15169 pub fn text_option(&self, cx: &App) -> Option<String> {
15170 let text = self.text(cx);
15171 let text = text.trim();
15172
15173 if text.is_empty() {
15174 return None;
15175 }
15176
15177 Some(text.to_string())
15178 }
15179
15180 pub fn set_text(
15181 &mut self,
15182 text: impl Into<Arc<str>>,
15183 window: &mut Window,
15184 cx: &mut Context<Self>,
15185 ) {
15186 self.transact(window, cx, |this, _, cx| {
15187 this.buffer
15188 .read(cx)
15189 .as_singleton()
15190 .expect("you can only call set_text on editors for singleton buffers")
15191 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15192 });
15193 }
15194
15195 pub fn display_text(&self, cx: &mut App) -> String {
15196 self.display_map
15197 .update(cx, |map, cx| map.snapshot(cx))
15198 .text()
15199 }
15200
15201 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15202 let mut wrap_guides = smallvec::smallvec![];
15203
15204 if self.show_wrap_guides == Some(false) {
15205 return wrap_guides;
15206 }
15207
15208 let settings = self.buffer.read(cx).language_settings(cx);
15209 if settings.show_wrap_guides {
15210 match self.soft_wrap_mode(cx) {
15211 SoftWrap::Column(soft_wrap) => {
15212 wrap_guides.push((soft_wrap as usize, true));
15213 }
15214 SoftWrap::Bounded(soft_wrap) => {
15215 wrap_guides.push((soft_wrap as usize, true));
15216 }
15217 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15218 }
15219 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15220 }
15221
15222 wrap_guides
15223 }
15224
15225 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15226 let settings = self.buffer.read(cx).language_settings(cx);
15227 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15228 match mode {
15229 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15230 SoftWrap::None
15231 }
15232 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15233 language_settings::SoftWrap::PreferredLineLength => {
15234 SoftWrap::Column(settings.preferred_line_length)
15235 }
15236 language_settings::SoftWrap::Bounded => {
15237 SoftWrap::Bounded(settings.preferred_line_length)
15238 }
15239 }
15240 }
15241
15242 pub fn set_soft_wrap_mode(
15243 &mut self,
15244 mode: language_settings::SoftWrap,
15245
15246 cx: &mut Context<Self>,
15247 ) {
15248 self.soft_wrap_mode_override = Some(mode);
15249 cx.notify();
15250 }
15251
15252 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
15253 self.hard_wrap = hard_wrap;
15254 cx.notify();
15255 }
15256
15257 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
15258 self.text_style_refinement = Some(style);
15259 }
15260
15261 /// called by the Element so we know what style we were most recently rendered with.
15262 pub(crate) fn set_style(
15263 &mut self,
15264 style: EditorStyle,
15265 window: &mut Window,
15266 cx: &mut Context<Self>,
15267 ) {
15268 let rem_size = window.rem_size();
15269 self.display_map.update(cx, |map, cx| {
15270 map.set_font(
15271 style.text.font(),
15272 style.text.font_size.to_pixels(rem_size),
15273 cx,
15274 )
15275 });
15276 self.style = Some(style);
15277 }
15278
15279 pub fn style(&self) -> Option<&EditorStyle> {
15280 self.style.as_ref()
15281 }
15282
15283 // Called by the element. This method is not designed to be called outside of the editor
15284 // element's layout code because it does not notify when rewrapping is computed synchronously.
15285 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
15286 self.display_map
15287 .update(cx, |map, cx| map.set_wrap_width(width, cx))
15288 }
15289
15290 pub fn set_soft_wrap(&mut self) {
15291 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
15292 }
15293
15294 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
15295 if self.soft_wrap_mode_override.is_some() {
15296 self.soft_wrap_mode_override.take();
15297 } else {
15298 let soft_wrap = match self.soft_wrap_mode(cx) {
15299 SoftWrap::GitDiff => return,
15300 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
15301 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
15302 language_settings::SoftWrap::None
15303 }
15304 };
15305 self.soft_wrap_mode_override = Some(soft_wrap);
15306 }
15307 cx.notify();
15308 }
15309
15310 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
15311 let Some(workspace) = self.workspace() else {
15312 return;
15313 };
15314 let fs = workspace.read(cx).app_state().fs.clone();
15315 let current_show = TabBarSettings::get_global(cx).show;
15316 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
15317 setting.show = Some(!current_show);
15318 });
15319 }
15320
15321 pub fn toggle_indent_guides(
15322 &mut self,
15323 _: &ToggleIndentGuides,
15324 _: &mut Window,
15325 cx: &mut Context<Self>,
15326 ) {
15327 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15328 self.buffer
15329 .read(cx)
15330 .language_settings(cx)
15331 .indent_guides
15332 .enabled
15333 });
15334 self.show_indent_guides = Some(!currently_enabled);
15335 cx.notify();
15336 }
15337
15338 fn should_show_indent_guides(&self) -> Option<bool> {
15339 self.show_indent_guides
15340 }
15341
15342 pub fn toggle_line_numbers(
15343 &mut self,
15344 _: &ToggleLineNumbers,
15345 _: &mut Window,
15346 cx: &mut Context<Self>,
15347 ) {
15348 let mut editor_settings = EditorSettings::get_global(cx).clone();
15349 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15350 EditorSettings::override_global(editor_settings, cx);
15351 }
15352
15353 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15354 if let Some(show_line_numbers) = self.show_line_numbers {
15355 return show_line_numbers;
15356 }
15357 EditorSettings::get_global(cx).gutter.line_numbers
15358 }
15359
15360 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15361 self.use_relative_line_numbers
15362 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15363 }
15364
15365 pub fn toggle_relative_line_numbers(
15366 &mut self,
15367 _: &ToggleRelativeLineNumbers,
15368 _: &mut Window,
15369 cx: &mut Context<Self>,
15370 ) {
15371 let is_relative = self.should_use_relative_line_numbers(cx);
15372 self.set_relative_line_number(Some(!is_relative), cx)
15373 }
15374
15375 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15376 self.use_relative_line_numbers = is_relative;
15377 cx.notify();
15378 }
15379
15380 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15381 self.show_gutter = show_gutter;
15382 cx.notify();
15383 }
15384
15385 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15386 self.show_scrollbars = show_scrollbars;
15387 cx.notify();
15388 }
15389
15390 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15391 self.show_line_numbers = Some(show_line_numbers);
15392 cx.notify();
15393 }
15394
15395 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15396 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15397 cx.notify();
15398 }
15399
15400 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15401 self.show_code_actions = Some(show_code_actions);
15402 cx.notify();
15403 }
15404
15405 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15406 self.show_runnables = Some(show_runnables);
15407 cx.notify();
15408 }
15409
15410 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15411 self.show_breakpoints = Some(show_breakpoints);
15412 cx.notify();
15413 }
15414
15415 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15416 if self.display_map.read(cx).masked != masked {
15417 self.display_map.update(cx, |map, _| map.masked = masked);
15418 }
15419 cx.notify()
15420 }
15421
15422 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15423 self.show_wrap_guides = Some(show_wrap_guides);
15424 cx.notify();
15425 }
15426
15427 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15428 self.show_indent_guides = Some(show_indent_guides);
15429 cx.notify();
15430 }
15431
15432 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15433 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15434 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15435 if let Some(dir) = file.abs_path(cx).parent() {
15436 return Some(dir.to_owned());
15437 }
15438 }
15439
15440 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15441 return Some(project_path.path.to_path_buf());
15442 }
15443 }
15444
15445 None
15446 }
15447
15448 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15449 self.active_excerpt(cx)?
15450 .1
15451 .read(cx)
15452 .file()
15453 .and_then(|f| f.as_local())
15454 }
15455
15456 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15457 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15458 let buffer = buffer.read(cx);
15459 if let Some(project_path) = buffer.project_path(cx) {
15460 let project = self.project.as_ref()?.read(cx);
15461 project.absolute_path(&project_path, cx)
15462 } else {
15463 buffer
15464 .file()
15465 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15466 }
15467 })
15468 }
15469
15470 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15471 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15472 let project_path = buffer.read(cx).project_path(cx)?;
15473 let project = self.project.as_ref()?.read(cx);
15474 let entry = project.entry_for_path(&project_path, cx)?;
15475 let path = entry.path.to_path_buf();
15476 Some(path)
15477 })
15478 }
15479
15480 pub fn reveal_in_finder(
15481 &mut self,
15482 _: &RevealInFileManager,
15483 _window: &mut Window,
15484 cx: &mut Context<Self>,
15485 ) {
15486 if let Some(target) = self.target_file(cx) {
15487 cx.reveal_path(&target.abs_path(cx));
15488 }
15489 }
15490
15491 pub fn copy_path(
15492 &mut self,
15493 _: &zed_actions::workspace::CopyPath,
15494 _window: &mut Window,
15495 cx: &mut Context<Self>,
15496 ) {
15497 if let Some(path) = self.target_file_abs_path(cx) {
15498 if let Some(path) = path.to_str() {
15499 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15500 }
15501 }
15502 }
15503
15504 pub fn copy_relative_path(
15505 &mut self,
15506 _: &zed_actions::workspace::CopyRelativePath,
15507 _window: &mut Window,
15508 cx: &mut Context<Self>,
15509 ) {
15510 if let Some(path) = self.target_file_path(cx) {
15511 if let Some(path) = path.to_str() {
15512 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15513 }
15514 }
15515 }
15516
15517 pub fn project_path(&self, cx: &mut Context<Self>) -> Option<ProjectPath> {
15518 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15519 buffer.read_with(cx, |buffer, cx| buffer.project_path(cx))
15520 } else {
15521 None
15522 }
15523 }
15524
15525 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15526 let _ = maybe!({
15527 let breakpoint_store = self.breakpoint_store.as_ref()?;
15528
15529 let Some((_, _, active_position)) =
15530 breakpoint_store.read(cx).active_position().cloned()
15531 else {
15532 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15533 return None;
15534 };
15535
15536 let snapshot = self
15537 .project
15538 .as_ref()?
15539 .read(cx)
15540 .buffer_for_id(active_position.buffer_id?, cx)?
15541 .read(cx)
15542 .snapshot();
15543
15544 for (id, ExcerptRange { context, .. }) in self
15545 .buffer
15546 .read(cx)
15547 .excerpts_for_buffer(active_position.buffer_id?, cx)
15548 {
15549 if context.start.cmp(&active_position, &snapshot).is_ge()
15550 || context.end.cmp(&active_position, &snapshot).is_lt()
15551 {
15552 continue;
15553 }
15554 let snapshot = self.buffer.read(cx).snapshot(cx);
15555 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15556
15557 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15558 self.go_to_line::<DebugCurrentRowHighlight>(
15559 multibuffer_anchor,
15560 Some(cx.theme().colors().editor_debugger_active_line_background),
15561 window,
15562 cx,
15563 );
15564
15565 cx.notify();
15566 }
15567
15568 Some(())
15569 });
15570 }
15571
15572 pub fn copy_file_name_without_extension(
15573 &mut self,
15574 _: &CopyFileNameWithoutExtension,
15575 _: &mut Window,
15576 cx: &mut Context<Self>,
15577 ) {
15578 if let Some(file) = self.target_file(cx) {
15579 if let Some(file_stem) = file.path().file_stem() {
15580 if let Some(name) = file_stem.to_str() {
15581 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15582 }
15583 }
15584 }
15585 }
15586
15587 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15588 if let Some(file) = self.target_file(cx) {
15589 if let Some(file_name) = file.path().file_name() {
15590 if let Some(name) = file_name.to_str() {
15591 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15592 }
15593 }
15594 }
15595 }
15596
15597 pub fn toggle_git_blame(
15598 &mut self,
15599 _: &::git::Blame,
15600 window: &mut Window,
15601 cx: &mut Context<Self>,
15602 ) {
15603 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15604
15605 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15606 self.start_git_blame(true, window, cx);
15607 }
15608
15609 cx.notify();
15610 }
15611
15612 pub fn toggle_git_blame_inline(
15613 &mut self,
15614 _: &ToggleGitBlameInline,
15615 window: &mut Window,
15616 cx: &mut Context<Self>,
15617 ) {
15618 self.toggle_git_blame_inline_internal(true, window, cx);
15619 cx.notify();
15620 }
15621
15622 pub fn git_blame_inline_enabled(&self) -> bool {
15623 self.git_blame_inline_enabled
15624 }
15625
15626 pub fn toggle_selection_menu(
15627 &mut self,
15628 _: &ToggleSelectionMenu,
15629 _: &mut Window,
15630 cx: &mut Context<Self>,
15631 ) {
15632 self.show_selection_menu = self
15633 .show_selection_menu
15634 .map(|show_selections_menu| !show_selections_menu)
15635 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15636
15637 cx.notify();
15638 }
15639
15640 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15641 self.show_selection_menu
15642 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15643 }
15644
15645 fn start_git_blame(
15646 &mut self,
15647 user_triggered: bool,
15648 window: &mut Window,
15649 cx: &mut Context<Self>,
15650 ) {
15651 if let Some(project) = self.project.as_ref() {
15652 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15653 return;
15654 };
15655
15656 if buffer.read(cx).file().is_none() {
15657 return;
15658 }
15659
15660 let focused = self.focus_handle(cx).contains_focused(window, cx);
15661
15662 let project = project.clone();
15663 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15664 self.blame_subscription =
15665 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15666 self.blame = Some(blame);
15667 }
15668 }
15669
15670 fn toggle_git_blame_inline_internal(
15671 &mut self,
15672 user_triggered: bool,
15673 window: &mut Window,
15674 cx: &mut Context<Self>,
15675 ) {
15676 if self.git_blame_inline_enabled {
15677 self.git_blame_inline_enabled = false;
15678 self.show_git_blame_inline = false;
15679 self.show_git_blame_inline_delay_task.take();
15680 } else {
15681 self.git_blame_inline_enabled = true;
15682 self.start_git_blame_inline(user_triggered, window, cx);
15683 }
15684
15685 cx.notify();
15686 }
15687
15688 fn start_git_blame_inline(
15689 &mut self,
15690 user_triggered: bool,
15691 window: &mut Window,
15692 cx: &mut Context<Self>,
15693 ) {
15694 self.start_git_blame(user_triggered, window, cx);
15695
15696 if ProjectSettings::get_global(cx)
15697 .git
15698 .inline_blame_delay()
15699 .is_some()
15700 {
15701 self.start_inline_blame_timer(window, cx);
15702 } else {
15703 self.show_git_blame_inline = true
15704 }
15705 }
15706
15707 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15708 self.blame.as_ref()
15709 }
15710
15711 pub fn show_git_blame_gutter(&self) -> bool {
15712 self.show_git_blame_gutter
15713 }
15714
15715 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15716 self.show_git_blame_gutter && self.has_blame_entries(cx)
15717 }
15718
15719 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15720 self.show_git_blame_inline
15721 && (self.focus_handle.is_focused(window)
15722 || self
15723 .git_blame_inline_tooltip
15724 .as_ref()
15725 .and_then(|t| t.upgrade())
15726 .is_some())
15727 && !self.newest_selection_head_on_empty_line(cx)
15728 && self.has_blame_entries(cx)
15729 }
15730
15731 fn has_blame_entries(&self, cx: &App) -> bool {
15732 self.blame()
15733 .map_or(false, |blame| blame.read(cx).has_generated_entries())
15734 }
15735
15736 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15737 let cursor_anchor = self.selections.newest_anchor().head();
15738
15739 let snapshot = self.buffer.read(cx).snapshot(cx);
15740 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15741
15742 snapshot.line_len(buffer_row) == 0
15743 }
15744
15745 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15746 let buffer_and_selection = maybe!({
15747 let selection = self.selections.newest::<Point>(cx);
15748 let selection_range = selection.range();
15749
15750 let multi_buffer = self.buffer().read(cx);
15751 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15752 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15753
15754 let (buffer, range, _) = if selection.reversed {
15755 buffer_ranges.first()
15756 } else {
15757 buffer_ranges.last()
15758 }?;
15759
15760 let selection = text::ToPoint::to_point(&range.start, &buffer).row
15761 ..text::ToPoint::to_point(&range.end, &buffer).row;
15762 Some((
15763 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15764 selection,
15765 ))
15766 });
15767
15768 let Some((buffer, selection)) = buffer_and_selection else {
15769 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15770 };
15771
15772 let Some(project) = self.project.as_ref() else {
15773 return Task::ready(Err(anyhow!("editor does not have project")));
15774 };
15775
15776 project.update(cx, |project, cx| {
15777 project.get_permalink_to_line(&buffer, selection, cx)
15778 })
15779 }
15780
15781 pub fn copy_permalink_to_line(
15782 &mut self,
15783 _: &CopyPermalinkToLine,
15784 window: &mut Window,
15785 cx: &mut Context<Self>,
15786 ) {
15787 let permalink_task = self.get_permalink_to_line(cx);
15788 let workspace = self.workspace();
15789
15790 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15791 Ok(permalink) => {
15792 cx.update(|_, cx| {
15793 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15794 })
15795 .ok();
15796 }
15797 Err(err) => {
15798 let message = format!("Failed to copy permalink: {err}");
15799
15800 Err::<(), anyhow::Error>(err).log_err();
15801
15802 if let Some(workspace) = workspace {
15803 workspace
15804 .update_in(cx, |workspace, _, cx| {
15805 struct CopyPermalinkToLine;
15806
15807 workspace.show_toast(
15808 Toast::new(
15809 NotificationId::unique::<CopyPermalinkToLine>(),
15810 message,
15811 ),
15812 cx,
15813 )
15814 })
15815 .ok();
15816 }
15817 }
15818 })
15819 .detach();
15820 }
15821
15822 pub fn copy_file_location(
15823 &mut self,
15824 _: &CopyFileLocation,
15825 _: &mut Window,
15826 cx: &mut Context<Self>,
15827 ) {
15828 let selection = self.selections.newest::<Point>(cx).start.row + 1;
15829 if let Some(file) = self.target_file(cx) {
15830 if let Some(path) = file.path().to_str() {
15831 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15832 }
15833 }
15834 }
15835
15836 pub fn open_permalink_to_line(
15837 &mut self,
15838 _: &OpenPermalinkToLine,
15839 window: &mut Window,
15840 cx: &mut Context<Self>,
15841 ) {
15842 let permalink_task = self.get_permalink_to_line(cx);
15843 let workspace = self.workspace();
15844
15845 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15846 Ok(permalink) => {
15847 cx.update(|_, cx| {
15848 cx.open_url(permalink.as_ref());
15849 })
15850 .ok();
15851 }
15852 Err(err) => {
15853 let message = format!("Failed to open permalink: {err}");
15854
15855 Err::<(), anyhow::Error>(err).log_err();
15856
15857 if let Some(workspace) = workspace {
15858 workspace
15859 .update(cx, |workspace, cx| {
15860 struct OpenPermalinkToLine;
15861
15862 workspace.show_toast(
15863 Toast::new(
15864 NotificationId::unique::<OpenPermalinkToLine>(),
15865 message,
15866 ),
15867 cx,
15868 )
15869 })
15870 .ok();
15871 }
15872 }
15873 })
15874 .detach();
15875 }
15876
15877 pub fn insert_uuid_v4(
15878 &mut self,
15879 _: &InsertUuidV4,
15880 window: &mut Window,
15881 cx: &mut Context<Self>,
15882 ) {
15883 self.insert_uuid(UuidVersion::V4, window, cx);
15884 }
15885
15886 pub fn insert_uuid_v7(
15887 &mut self,
15888 _: &InsertUuidV7,
15889 window: &mut Window,
15890 cx: &mut Context<Self>,
15891 ) {
15892 self.insert_uuid(UuidVersion::V7, window, cx);
15893 }
15894
15895 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15896 self.transact(window, cx, |this, window, cx| {
15897 let edits = this
15898 .selections
15899 .all::<Point>(cx)
15900 .into_iter()
15901 .map(|selection| {
15902 let uuid = match version {
15903 UuidVersion::V4 => uuid::Uuid::new_v4(),
15904 UuidVersion::V7 => uuid::Uuid::now_v7(),
15905 };
15906
15907 (selection.range(), uuid.to_string())
15908 });
15909 this.edit(edits, cx);
15910 this.refresh_inline_completion(true, false, window, cx);
15911 });
15912 }
15913
15914 pub fn open_selections_in_multibuffer(
15915 &mut self,
15916 _: &OpenSelectionsInMultibuffer,
15917 window: &mut Window,
15918 cx: &mut Context<Self>,
15919 ) {
15920 let multibuffer = self.buffer.read(cx);
15921
15922 let Some(buffer) = multibuffer.as_singleton() else {
15923 return;
15924 };
15925
15926 let Some(workspace) = self.workspace() else {
15927 return;
15928 };
15929
15930 let locations = self
15931 .selections
15932 .disjoint_anchors()
15933 .iter()
15934 .map(|range| Location {
15935 buffer: buffer.clone(),
15936 range: range.start.text_anchor..range.end.text_anchor,
15937 })
15938 .collect::<Vec<_>>();
15939
15940 let title = multibuffer.title(cx).to_string();
15941
15942 cx.spawn_in(window, async move |_, cx| {
15943 workspace.update_in(cx, |workspace, window, cx| {
15944 Self::open_locations_in_multibuffer(
15945 workspace,
15946 locations,
15947 format!("Selections for '{title}'"),
15948 false,
15949 MultibufferSelectionMode::All,
15950 window,
15951 cx,
15952 );
15953 })
15954 })
15955 .detach();
15956 }
15957
15958 /// Adds a row highlight for the given range. If a row has multiple highlights, the
15959 /// last highlight added will be used.
15960 ///
15961 /// If the range ends at the beginning of a line, then that line will not be highlighted.
15962 pub fn highlight_rows<T: 'static>(
15963 &mut self,
15964 range: Range<Anchor>,
15965 color: Hsla,
15966 should_autoscroll: bool,
15967 cx: &mut Context<Self>,
15968 ) {
15969 let snapshot = self.buffer().read(cx).snapshot(cx);
15970 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15971 let ix = row_highlights.binary_search_by(|highlight| {
15972 Ordering::Equal
15973 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15974 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15975 });
15976
15977 if let Err(mut ix) = ix {
15978 let index = post_inc(&mut self.highlight_order);
15979
15980 // If this range intersects with the preceding highlight, then merge it with
15981 // the preceding highlight. Otherwise insert a new highlight.
15982 let mut merged = false;
15983 if ix > 0 {
15984 let prev_highlight = &mut row_highlights[ix - 1];
15985 if prev_highlight
15986 .range
15987 .end
15988 .cmp(&range.start, &snapshot)
15989 .is_ge()
15990 {
15991 ix -= 1;
15992 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15993 prev_highlight.range.end = range.end;
15994 }
15995 merged = true;
15996 prev_highlight.index = index;
15997 prev_highlight.color = color;
15998 prev_highlight.should_autoscroll = should_autoscroll;
15999 }
16000 }
16001
16002 if !merged {
16003 row_highlights.insert(
16004 ix,
16005 RowHighlight {
16006 range: range.clone(),
16007 index,
16008 color,
16009 should_autoscroll,
16010 },
16011 );
16012 }
16013
16014 // If any of the following highlights intersect with this one, merge them.
16015 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16016 let highlight = &row_highlights[ix];
16017 if next_highlight
16018 .range
16019 .start
16020 .cmp(&highlight.range.end, &snapshot)
16021 .is_le()
16022 {
16023 if next_highlight
16024 .range
16025 .end
16026 .cmp(&highlight.range.end, &snapshot)
16027 .is_gt()
16028 {
16029 row_highlights[ix].range.end = next_highlight.range.end;
16030 }
16031 row_highlights.remove(ix + 1);
16032 } else {
16033 break;
16034 }
16035 }
16036 }
16037 }
16038
16039 /// Remove any highlighted row ranges of the given type that intersect the
16040 /// given ranges.
16041 pub fn remove_highlighted_rows<T: 'static>(
16042 &mut self,
16043 ranges_to_remove: Vec<Range<Anchor>>,
16044 cx: &mut Context<Self>,
16045 ) {
16046 let snapshot = self.buffer().read(cx).snapshot(cx);
16047 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16048 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16049 row_highlights.retain(|highlight| {
16050 while let Some(range_to_remove) = ranges_to_remove.peek() {
16051 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16052 Ordering::Less | Ordering::Equal => {
16053 ranges_to_remove.next();
16054 }
16055 Ordering::Greater => {
16056 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16057 Ordering::Less | Ordering::Equal => {
16058 return false;
16059 }
16060 Ordering::Greater => break,
16061 }
16062 }
16063 }
16064 }
16065
16066 true
16067 })
16068 }
16069
16070 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16071 pub fn clear_row_highlights<T: 'static>(&mut self) {
16072 self.highlighted_rows.remove(&TypeId::of::<T>());
16073 }
16074
16075 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16076 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16077 self.highlighted_rows
16078 .get(&TypeId::of::<T>())
16079 .map_or(&[] as &[_], |vec| vec.as_slice())
16080 .iter()
16081 .map(|highlight| (highlight.range.clone(), highlight.color))
16082 }
16083
16084 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16085 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16086 /// Allows to ignore certain kinds of highlights.
16087 pub fn highlighted_display_rows(
16088 &self,
16089 window: &mut Window,
16090 cx: &mut App,
16091 ) -> BTreeMap<DisplayRow, LineHighlight> {
16092 let snapshot = self.snapshot(window, cx);
16093 let mut used_highlight_orders = HashMap::default();
16094 self.highlighted_rows
16095 .iter()
16096 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16097 .fold(
16098 BTreeMap::<DisplayRow, LineHighlight>::new(),
16099 |mut unique_rows, highlight| {
16100 let start = highlight.range.start.to_display_point(&snapshot);
16101 let end = highlight.range.end.to_display_point(&snapshot);
16102 let start_row = start.row().0;
16103 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16104 && end.column() == 0
16105 {
16106 end.row().0.saturating_sub(1)
16107 } else {
16108 end.row().0
16109 };
16110 for row in start_row..=end_row {
16111 let used_index =
16112 used_highlight_orders.entry(row).or_insert(highlight.index);
16113 if highlight.index >= *used_index {
16114 *used_index = highlight.index;
16115 unique_rows.insert(DisplayRow(row), highlight.color.into());
16116 }
16117 }
16118 unique_rows
16119 },
16120 )
16121 }
16122
16123 pub fn highlighted_display_row_for_autoscroll(
16124 &self,
16125 snapshot: &DisplaySnapshot,
16126 ) -> Option<DisplayRow> {
16127 self.highlighted_rows
16128 .values()
16129 .flat_map(|highlighted_rows| highlighted_rows.iter())
16130 .filter_map(|highlight| {
16131 if highlight.should_autoscroll {
16132 Some(highlight.range.start.to_display_point(snapshot).row())
16133 } else {
16134 None
16135 }
16136 })
16137 .min()
16138 }
16139
16140 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16141 self.highlight_background::<SearchWithinRange>(
16142 ranges,
16143 |colors| colors.editor_document_highlight_read_background,
16144 cx,
16145 )
16146 }
16147
16148 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16149 self.breadcrumb_header = Some(new_header);
16150 }
16151
16152 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16153 self.clear_background_highlights::<SearchWithinRange>(cx);
16154 }
16155
16156 pub fn highlight_background<T: 'static>(
16157 &mut self,
16158 ranges: &[Range<Anchor>],
16159 color_fetcher: fn(&ThemeColors) -> Hsla,
16160 cx: &mut Context<Self>,
16161 ) {
16162 self.background_highlights
16163 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16164 self.scrollbar_marker_state.dirty = true;
16165 cx.notify();
16166 }
16167
16168 pub fn clear_background_highlights<T: 'static>(
16169 &mut self,
16170 cx: &mut Context<Self>,
16171 ) -> Option<BackgroundHighlight> {
16172 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16173 if !text_highlights.1.is_empty() {
16174 self.scrollbar_marker_state.dirty = true;
16175 cx.notify();
16176 }
16177 Some(text_highlights)
16178 }
16179
16180 pub fn highlight_gutter<T: 'static>(
16181 &mut self,
16182 ranges: &[Range<Anchor>],
16183 color_fetcher: fn(&App) -> Hsla,
16184 cx: &mut Context<Self>,
16185 ) {
16186 self.gutter_highlights
16187 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16188 cx.notify();
16189 }
16190
16191 pub fn clear_gutter_highlights<T: 'static>(
16192 &mut self,
16193 cx: &mut Context<Self>,
16194 ) -> Option<GutterHighlight> {
16195 cx.notify();
16196 self.gutter_highlights.remove(&TypeId::of::<T>())
16197 }
16198
16199 #[cfg(feature = "test-support")]
16200 pub fn all_text_background_highlights(
16201 &self,
16202 window: &mut Window,
16203 cx: &mut Context<Self>,
16204 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16205 let snapshot = self.snapshot(window, cx);
16206 let buffer = &snapshot.buffer_snapshot;
16207 let start = buffer.anchor_before(0);
16208 let end = buffer.anchor_after(buffer.len());
16209 let theme = cx.theme().colors();
16210 self.background_highlights_in_range(start..end, &snapshot, theme)
16211 }
16212
16213 #[cfg(feature = "test-support")]
16214 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
16215 let snapshot = self.buffer().read(cx).snapshot(cx);
16216
16217 let highlights = self
16218 .background_highlights
16219 .get(&TypeId::of::<items::BufferSearchHighlights>());
16220
16221 if let Some((_color, ranges)) = highlights {
16222 ranges
16223 .iter()
16224 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
16225 .collect_vec()
16226 } else {
16227 vec![]
16228 }
16229 }
16230
16231 fn document_highlights_for_position<'a>(
16232 &'a self,
16233 position: Anchor,
16234 buffer: &'a MultiBufferSnapshot,
16235 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
16236 let read_highlights = self
16237 .background_highlights
16238 .get(&TypeId::of::<DocumentHighlightRead>())
16239 .map(|h| &h.1);
16240 let write_highlights = self
16241 .background_highlights
16242 .get(&TypeId::of::<DocumentHighlightWrite>())
16243 .map(|h| &h.1);
16244 let left_position = position.bias_left(buffer);
16245 let right_position = position.bias_right(buffer);
16246 read_highlights
16247 .into_iter()
16248 .chain(write_highlights)
16249 .flat_map(move |ranges| {
16250 let start_ix = match ranges.binary_search_by(|probe| {
16251 let cmp = probe.end.cmp(&left_position, buffer);
16252 if cmp.is_ge() {
16253 Ordering::Greater
16254 } else {
16255 Ordering::Less
16256 }
16257 }) {
16258 Ok(i) | Err(i) => i,
16259 };
16260
16261 ranges[start_ix..]
16262 .iter()
16263 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
16264 })
16265 }
16266
16267 pub fn has_background_highlights<T: 'static>(&self) -> bool {
16268 self.background_highlights
16269 .get(&TypeId::of::<T>())
16270 .map_or(false, |(_, highlights)| !highlights.is_empty())
16271 }
16272
16273 pub fn background_highlights_in_range(
16274 &self,
16275 search_range: Range<Anchor>,
16276 display_snapshot: &DisplaySnapshot,
16277 theme: &ThemeColors,
16278 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16279 let mut results = Vec::new();
16280 for (color_fetcher, ranges) in self.background_highlights.values() {
16281 let color = color_fetcher(theme);
16282 let start_ix = match ranges.binary_search_by(|probe| {
16283 let cmp = probe
16284 .end
16285 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16286 if cmp.is_gt() {
16287 Ordering::Greater
16288 } else {
16289 Ordering::Less
16290 }
16291 }) {
16292 Ok(i) | Err(i) => i,
16293 };
16294 for range in &ranges[start_ix..] {
16295 if range
16296 .start
16297 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16298 .is_ge()
16299 {
16300 break;
16301 }
16302
16303 let start = range.start.to_display_point(display_snapshot);
16304 let end = range.end.to_display_point(display_snapshot);
16305 results.push((start..end, color))
16306 }
16307 }
16308 results
16309 }
16310
16311 pub fn background_highlight_row_ranges<T: 'static>(
16312 &self,
16313 search_range: Range<Anchor>,
16314 display_snapshot: &DisplaySnapshot,
16315 count: usize,
16316 ) -> Vec<RangeInclusive<DisplayPoint>> {
16317 let mut results = Vec::new();
16318 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
16319 return vec![];
16320 };
16321
16322 let start_ix = match ranges.binary_search_by(|probe| {
16323 let cmp = probe
16324 .end
16325 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16326 if cmp.is_gt() {
16327 Ordering::Greater
16328 } else {
16329 Ordering::Less
16330 }
16331 }) {
16332 Ok(i) | Err(i) => i,
16333 };
16334 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16335 if let (Some(start_display), Some(end_display)) = (start, end) {
16336 results.push(
16337 start_display.to_display_point(display_snapshot)
16338 ..=end_display.to_display_point(display_snapshot),
16339 );
16340 }
16341 };
16342 let mut start_row: Option<Point> = None;
16343 let mut end_row: Option<Point> = None;
16344 if ranges.len() > count {
16345 return Vec::new();
16346 }
16347 for range in &ranges[start_ix..] {
16348 if range
16349 .start
16350 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16351 .is_ge()
16352 {
16353 break;
16354 }
16355 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16356 if let Some(current_row) = &end_row {
16357 if end.row == current_row.row {
16358 continue;
16359 }
16360 }
16361 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16362 if start_row.is_none() {
16363 assert_eq!(end_row, None);
16364 start_row = Some(start);
16365 end_row = Some(end);
16366 continue;
16367 }
16368 if let Some(current_end) = end_row.as_mut() {
16369 if start.row > current_end.row + 1 {
16370 push_region(start_row, end_row);
16371 start_row = Some(start);
16372 end_row = Some(end);
16373 } else {
16374 // Merge two hunks.
16375 *current_end = end;
16376 }
16377 } else {
16378 unreachable!();
16379 }
16380 }
16381 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16382 push_region(start_row, end_row);
16383 results
16384 }
16385
16386 pub fn gutter_highlights_in_range(
16387 &self,
16388 search_range: Range<Anchor>,
16389 display_snapshot: &DisplaySnapshot,
16390 cx: &App,
16391 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16392 let mut results = Vec::new();
16393 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16394 let color = color_fetcher(cx);
16395 let start_ix = match ranges.binary_search_by(|probe| {
16396 let cmp = probe
16397 .end
16398 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16399 if cmp.is_gt() {
16400 Ordering::Greater
16401 } else {
16402 Ordering::Less
16403 }
16404 }) {
16405 Ok(i) | Err(i) => i,
16406 };
16407 for range in &ranges[start_ix..] {
16408 if range
16409 .start
16410 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16411 .is_ge()
16412 {
16413 break;
16414 }
16415
16416 let start = range.start.to_display_point(display_snapshot);
16417 let end = range.end.to_display_point(display_snapshot);
16418 results.push((start..end, color))
16419 }
16420 }
16421 results
16422 }
16423
16424 /// Get the text ranges corresponding to the redaction query
16425 pub fn redacted_ranges(
16426 &self,
16427 search_range: Range<Anchor>,
16428 display_snapshot: &DisplaySnapshot,
16429 cx: &App,
16430 ) -> Vec<Range<DisplayPoint>> {
16431 display_snapshot
16432 .buffer_snapshot
16433 .redacted_ranges(search_range, |file| {
16434 if let Some(file) = file {
16435 file.is_private()
16436 && EditorSettings::get(
16437 Some(SettingsLocation {
16438 worktree_id: file.worktree_id(cx),
16439 path: file.path().as_ref(),
16440 }),
16441 cx,
16442 )
16443 .redact_private_values
16444 } else {
16445 false
16446 }
16447 })
16448 .map(|range| {
16449 range.start.to_display_point(display_snapshot)
16450 ..range.end.to_display_point(display_snapshot)
16451 })
16452 .collect()
16453 }
16454
16455 pub fn highlight_text<T: 'static>(
16456 &mut self,
16457 ranges: Vec<Range<Anchor>>,
16458 style: HighlightStyle,
16459 cx: &mut Context<Self>,
16460 ) {
16461 self.display_map.update(cx, |map, _| {
16462 map.highlight_text(TypeId::of::<T>(), ranges, style)
16463 });
16464 cx.notify();
16465 }
16466
16467 pub(crate) fn highlight_inlays<T: 'static>(
16468 &mut self,
16469 highlights: Vec<InlayHighlight>,
16470 style: HighlightStyle,
16471 cx: &mut Context<Self>,
16472 ) {
16473 self.display_map.update(cx, |map, _| {
16474 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16475 });
16476 cx.notify();
16477 }
16478
16479 pub fn text_highlights<'a, T: 'static>(
16480 &'a self,
16481 cx: &'a App,
16482 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16483 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16484 }
16485
16486 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16487 let cleared = self
16488 .display_map
16489 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16490 if cleared {
16491 cx.notify();
16492 }
16493 }
16494
16495 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16496 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16497 && self.focus_handle.is_focused(window)
16498 }
16499
16500 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16501 self.show_cursor_when_unfocused = is_enabled;
16502 cx.notify();
16503 }
16504
16505 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16506 cx.notify();
16507 }
16508
16509 fn on_buffer_event(
16510 &mut self,
16511 multibuffer: &Entity<MultiBuffer>,
16512 event: &multi_buffer::Event,
16513 window: &mut Window,
16514 cx: &mut Context<Self>,
16515 ) {
16516 match event {
16517 multi_buffer::Event::Edited {
16518 singleton_buffer_edited,
16519 edited_buffer: buffer_edited,
16520 } => {
16521 self.scrollbar_marker_state.dirty = true;
16522 self.active_indent_guides_state.dirty = true;
16523 self.refresh_active_diagnostics(cx);
16524 self.refresh_code_actions(window, cx);
16525 if self.has_active_inline_completion() {
16526 self.update_visible_inline_completion(window, cx);
16527 }
16528 if let Some(buffer) = buffer_edited {
16529 let buffer_id = buffer.read(cx).remote_id();
16530 if !self.registered_buffers.contains_key(&buffer_id) {
16531 if let Some(project) = self.project.as_ref() {
16532 project.update(cx, |project, cx| {
16533 self.registered_buffers.insert(
16534 buffer_id,
16535 project.register_buffer_with_language_servers(&buffer, cx),
16536 );
16537 })
16538 }
16539 }
16540 }
16541 cx.emit(EditorEvent::BufferEdited);
16542 cx.emit(SearchEvent::MatchesInvalidated);
16543 if *singleton_buffer_edited {
16544 if let Some(project) = &self.project {
16545 #[allow(clippy::mutable_key_type)]
16546 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16547 multibuffer
16548 .all_buffers()
16549 .into_iter()
16550 .filter_map(|buffer| {
16551 buffer.update(cx, |buffer, cx| {
16552 let language = buffer.language()?;
16553 let should_discard = project.update(cx, |project, cx| {
16554 project.is_local()
16555 && !project.has_language_servers_for(buffer, cx)
16556 });
16557 should_discard.not().then_some(language.clone())
16558 })
16559 })
16560 .collect::<HashSet<_>>()
16561 });
16562 if !languages_affected.is_empty() {
16563 self.refresh_inlay_hints(
16564 InlayHintRefreshReason::BufferEdited(languages_affected),
16565 cx,
16566 );
16567 }
16568 }
16569 }
16570
16571 let Some(project) = &self.project else { return };
16572 let (telemetry, is_via_ssh) = {
16573 let project = project.read(cx);
16574 let telemetry = project.client().telemetry().clone();
16575 let is_via_ssh = project.is_via_ssh();
16576 (telemetry, is_via_ssh)
16577 };
16578 refresh_linked_ranges(self, window, cx);
16579 telemetry.log_edit_event("editor", is_via_ssh);
16580 }
16581 multi_buffer::Event::ExcerptsAdded {
16582 buffer,
16583 predecessor,
16584 excerpts,
16585 } => {
16586 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16587 let buffer_id = buffer.read(cx).remote_id();
16588 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16589 if let Some(project) = &self.project {
16590 get_uncommitted_diff_for_buffer(
16591 project,
16592 [buffer.clone()],
16593 self.buffer.clone(),
16594 cx,
16595 )
16596 .detach();
16597 }
16598 }
16599 cx.emit(EditorEvent::ExcerptsAdded {
16600 buffer: buffer.clone(),
16601 predecessor: *predecessor,
16602 excerpts: excerpts.clone(),
16603 });
16604 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16605 }
16606 multi_buffer::Event::ExcerptsRemoved { ids } => {
16607 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16608 let buffer = self.buffer.read(cx);
16609 self.registered_buffers
16610 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16611 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16612 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16613 }
16614 multi_buffer::Event::ExcerptsEdited {
16615 excerpt_ids,
16616 buffer_ids,
16617 } => {
16618 self.display_map.update(cx, |map, cx| {
16619 map.unfold_buffers(buffer_ids.iter().copied(), cx)
16620 });
16621 cx.emit(EditorEvent::ExcerptsEdited {
16622 ids: excerpt_ids.clone(),
16623 })
16624 }
16625 multi_buffer::Event::ExcerptsExpanded { ids } => {
16626 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16627 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16628 }
16629 multi_buffer::Event::Reparsed(buffer_id) => {
16630 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16631 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16632
16633 cx.emit(EditorEvent::Reparsed(*buffer_id));
16634 }
16635 multi_buffer::Event::DiffHunksToggled => {
16636 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16637 }
16638 multi_buffer::Event::LanguageChanged(buffer_id) => {
16639 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16640 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16641 cx.emit(EditorEvent::Reparsed(*buffer_id));
16642 cx.notify();
16643 }
16644 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16645 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16646 multi_buffer::Event::FileHandleChanged
16647 | multi_buffer::Event::Reloaded
16648 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16649 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16650 multi_buffer::Event::DiagnosticsUpdated => {
16651 self.refresh_active_diagnostics(cx);
16652 self.refresh_inline_diagnostics(true, window, cx);
16653 self.scrollbar_marker_state.dirty = true;
16654 cx.notify();
16655 }
16656 _ => {}
16657 };
16658 }
16659
16660 fn on_display_map_changed(
16661 &mut self,
16662 _: Entity<DisplayMap>,
16663 _: &mut Window,
16664 cx: &mut Context<Self>,
16665 ) {
16666 cx.notify();
16667 }
16668
16669 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16670 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16671 self.update_edit_prediction_settings(cx);
16672 self.refresh_inline_completion(true, false, window, cx);
16673 self.refresh_inlay_hints(
16674 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16675 self.selections.newest_anchor().head(),
16676 &self.buffer.read(cx).snapshot(cx),
16677 cx,
16678 )),
16679 cx,
16680 );
16681
16682 let old_cursor_shape = self.cursor_shape;
16683
16684 {
16685 let editor_settings = EditorSettings::get_global(cx);
16686 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16687 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16688 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16689 self.hide_mouse_while_typing = editor_settings.hide_mouse_while_typing.unwrap_or(true);
16690
16691 if !self.hide_mouse_while_typing {
16692 self.mouse_cursor_hidden = false;
16693 }
16694 }
16695
16696 if old_cursor_shape != self.cursor_shape {
16697 cx.emit(EditorEvent::CursorShapeChanged);
16698 }
16699
16700 let project_settings = ProjectSettings::get_global(cx);
16701 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16702
16703 if self.mode == EditorMode::Full {
16704 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16705 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16706 if self.show_inline_diagnostics != show_inline_diagnostics {
16707 self.show_inline_diagnostics = show_inline_diagnostics;
16708 self.refresh_inline_diagnostics(false, window, cx);
16709 }
16710
16711 if self.git_blame_inline_enabled != inline_blame_enabled {
16712 self.toggle_git_blame_inline_internal(false, window, cx);
16713 }
16714 }
16715
16716 cx.notify();
16717 }
16718
16719 pub fn set_searchable(&mut self, searchable: bool) {
16720 self.searchable = searchable;
16721 }
16722
16723 pub fn searchable(&self) -> bool {
16724 self.searchable
16725 }
16726
16727 fn open_proposed_changes_editor(
16728 &mut self,
16729 _: &OpenProposedChangesEditor,
16730 window: &mut Window,
16731 cx: &mut Context<Self>,
16732 ) {
16733 let Some(workspace) = self.workspace() else {
16734 cx.propagate();
16735 return;
16736 };
16737
16738 let selections = self.selections.all::<usize>(cx);
16739 let multi_buffer = self.buffer.read(cx);
16740 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16741 let mut new_selections_by_buffer = HashMap::default();
16742 for selection in selections {
16743 for (buffer, range, _) in
16744 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16745 {
16746 let mut range = range.to_point(buffer);
16747 range.start.column = 0;
16748 range.end.column = buffer.line_len(range.end.row);
16749 new_selections_by_buffer
16750 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16751 .or_insert(Vec::new())
16752 .push(range)
16753 }
16754 }
16755
16756 let proposed_changes_buffers = new_selections_by_buffer
16757 .into_iter()
16758 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16759 .collect::<Vec<_>>();
16760 let proposed_changes_editor = cx.new(|cx| {
16761 ProposedChangesEditor::new(
16762 "Proposed changes",
16763 proposed_changes_buffers,
16764 self.project.clone(),
16765 window,
16766 cx,
16767 )
16768 });
16769
16770 window.defer(cx, move |window, cx| {
16771 workspace.update(cx, |workspace, cx| {
16772 workspace.active_pane().update(cx, |pane, cx| {
16773 pane.add_item(
16774 Box::new(proposed_changes_editor),
16775 true,
16776 true,
16777 None,
16778 window,
16779 cx,
16780 );
16781 });
16782 });
16783 });
16784 }
16785
16786 pub fn open_excerpts_in_split(
16787 &mut self,
16788 _: &OpenExcerptsSplit,
16789 window: &mut Window,
16790 cx: &mut Context<Self>,
16791 ) {
16792 self.open_excerpts_common(None, true, window, cx)
16793 }
16794
16795 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16796 self.open_excerpts_common(None, false, window, cx)
16797 }
16798
16799 fn open_excerpts_common(
16800 &mut self,
16801 jump_data: Option<JumpData>,
16802 split: bool,
16803 window: &mut Window,
16804 cx: &mut Context<Self>,
16805 ) {
16806 let Some(workspace) = self.workspace() else {
16807 cx.propagate();
16808 return;
16809 };
16810
16811 if self.buffer.read(cx).is_singleton() {
16812 cx.propagate();
16813 return;
16814 }
16815
16816 let mut new_selections_by_buffer = HashMap::default();
16817 match &jump_data {
16818 Some(JumpData::MultiBufferPoint {
16819 excerpt_id,
16820 position,
16821 anchor,
16822 line_offset_from_top,
16823 }) => {
16824 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16825 if let Some(buffer) = multi_buffer_snapshot
16826 .buffer_id_for_excerpt(*excerpt_id)
16827 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16828 {
16829 let buffer_snapshot = buffer.read(cx).snapshot();
16830 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16831 language::ToPoint::to_point(anchor, &buffer_snapshot)
16832 } else {
16833 buffer_snapshot.clip_point(*position, Bias::Left)
16834 };
16835 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16836 new_selections_by_buffer.insert(
16837 buffer,
16838 (
16839 vec![jump_to_offset..jump_to_offset],
16840 Some(*line_offset_from_top),
16841 ),
16842 );
16843 }
16844 }
16845 Some(JumpData::MultiBufferRow {
16846 row,
16847 line_offset_from_top,
16848 }) => {
16849 let point = MultiBufferPoint::new(row.0, 0);
16850 if let Some((buffer, buffer_point, _)) =
16851 self.buffer.read(cx).point_to_buffer_point(point, cx)
16852 {
16853 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16854 new_selections_by_buffer
16855 .entry(buffer)
16856 .or_insert((Vec::new(), Some(*line_offset_from_top)))
16857 .0
16858 .push(buffer_offset..buffer_offset)
16859 }
16860 }
16861 None => {
16862 let selections = self.selections.all::<usize>(cx);
16863 let multi_buffer = self.buffer.read(cx);
16864 for selection in selections {
16865 for (snapshot, range, _, anchor) in multi_buffer
16866 .snapshot(cx)
16867 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16868 {
16869 if let Some(anchor) = anchor {
16870 // selection is in a deleted hunk
16871 let Some(buffer_id) = anchor.buffer_id else {
16872 continue;
16873 };
16874 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16875 continue;
16876 };
16877 let offset = text::ToOffset::to_offset(
16878 &anchor.text_anchor,
16879 &buffer_handle.read(cx).snapshot(),
16880 );
16881 let range = offset..offset;
16882 new_selections_by_buffer
16883 .entry(buffer_handle)
16884 .or_insert((Vec::new(), None))
16885 .0
16886 .push(range)
16887 } else {
16888 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16889 else {
16890 continue;
16891 };
16892 new_selections_by_buffer
16893 .entry(buffer_handle)
16894 .or_insert((Vec::new(), None))
16895 .0
16896 .push(range)
16897 }
16898 }
16899 }
16900 }
16901 }
16902
16903 if new_selections_by_buffer.is_empty() {
16904 return;
16905 }
16906
16907 // We defer the pane interaction because we ourselves are a workspace item
16908 // and activating a new item causes the pane to call a method on us reentrantly,
16909 // which panics if we're on the stack.
16910 window.defer(cx, move |window, cx| {
16911 workspace.update(cx, |workspace, cx| {
16912 let pane = if split {
16913 workspace.adjacent_pane(window, cx)
16914 } else {
16915 workspace.active_pane().clone()
16916 };
16917
16918 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16919 let editor = buffer
16920 .read(cx)
16921 .file()
16922 .is_none()
16923 .then(|| {
16924 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16925 // so `workspace.open_project_item` will never find them, always opening a new editor.
16926 // Instead, we try to activate the existing editor in the pane first.
16927 let (editor, pane_item_index) =
16928 pane.read(cx).items().enumerate().find_map(|(i, item)| {
16929 let editor = item.downcast::<Editor>()?;
16930 let singleton_buffer =
16931 editor.read(cx).buffer().read(cx).as_singleton()?;
16932 if singleton_buffer == buffer {
16933 Some((editor, i))
16934 } else {
16935 None
16936 }
16937 })?;
16938 pane.update(cx, |pane, cx| {
16939 pane.activate_item(pane_item_index, true, true, window, cx)
16940 });
16941 Some(editor)
16942 })
16943 .flatten()
16944 .unwrap_or_else(|| {
16945 workspace.open_project_item::<Self>(
16946 pane.clone(),
16947 buffer,
16948 true,
16949 true,
16950 window,
16951 cx,
16952 )
16953 });
16954
16955 editor.update(cx, |editor, cx| {
16956 let autoscroll = match scroll_offset {
16957 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16958 None => Autoscroll::newest(),
16959 };
16960 let nav_history = editor.nav_history.take();
16961 editor.change_selections(Some(autoscroll), window, cx, |s| {
16962 s.select_ranges(ranges);
16963 });
16964 editor.nav_history = nav_history;
16965 });
16966 }
16967 })
16968 });
16969 }
16970
16971 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16972 let snapshot = self.buffer.read(cx).read(cx);
16973 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16974 Some(
16975 ranges
16976 .iter()
16977 .map(move |range| {
16978 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16979 })
16980 .collect(),
16981 )
16982 }
16983
16984 fn selection_replacement_ranges(
16985 &self,
16986 range: Range<OffsetUtf16>,
16987 cx: &mut App,
16988 ) -> Vec<Range<OffsetUtf16>> {
16989 let selections = self.selections.all::<OffsetUtf16>(cx);
16990 let newest_selection = selections
16991 .iter()
16992 .max_by_key(|selection| selection.id)
16993 .unwrap();
16994 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16995 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16996 let snapshot = self.buffer.read(cx).read(cx);
16997 selections
16998 .into_iter()
16999 .map(|mut selection| {
17000 selection.start.0 =
17001 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17002 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17003 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17004 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17005 })
17006 .collect()
17007 }
17008
17009 fn report_editor_event(
17010 &self,
17011 event_type: &'static str,
17012 file_extension: Option<String>,
17013 cx: &App,
17014 ) {
17015 if cfg!(any(test, feature = "test-support")) {
17016 return;
17017 }
17018
17019 let Some(project) = &self.project else { return };
17020
17021 // If None, we are in a file without an extension
17022 let file = self
17023 .buffer
17024 .read(cx)
17025 .as_singleton()
17026 .and_then(|b| b.read(cx).file());
17027 let file_extension = file_extension.or(file
17028 .as_ref()
17029 .and_then(|file| Path::new(file.file_name(cx)).extension())
17030 .and_then(|e| e.to_str())
17031 .map(|a| a.to_string()));
17032
17033 let vim_mode = cx
17034 .global::<SettingsStore>()
17035 .raw_user_settings()
17036 .get("vim_mode")
17037 == Some(&serde_json::Value::Bool(true));
17038
17039 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17040 let copilot_enabled = edit_predictions_provider
17041 == language::language_settings::EditPredictionProvider::Copilot;
17042 let copilot_enabled_for_language = self
17043 .buffer
17044 .read(cx)
17045 .language_settings(cx)
17046 .show_edit_predictions;
17047
17048 let project = project.read(cx);
17049 telemetry::event!(
17050 event_type,
17051 file_extension,
17052 vim_mode,
17053 copilot_enabled,
17054 copilot_enabled_for_language,
17055 edit_predictions_provider,
17056 is_via_ssh = project.is_via_ssh(),
17057 );
17058 }
17059
17060 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17061 /// with each line being an array of {text, highlight} objects.
17062 fn copy_highlight_json(
17063 &mut self,
17064 _: &CopyHighlightJson,
17065 window: &mut Window,
17066 cx: &mut Context<Self>,
17067 ) {
17068 #[derive(Serialize)]
17069 struct Chunk<'a> {
17070 text: String,
17071 highlight: Option<&'a str>,
17072 }
17073
17074 let snapshot = self.buffer.read(cx).snapshot(cx);
17075 let range = self
17076 .selected_text_range(false, window, cx)
17077 .and_then(|selection| {
17078 if selection.range.is_empty() {
17079 None
17080 } else {
17081 Some(selection.range)
17082 }
17083 })
17084 .unwrap_or_else(|| 0..snapshot.len());
17085
17086 let chunks = snapshot.chunks(range, true);
17087 let mut lines = Vec::new();
17088 let mut line: VecDeque<Chunk> = VecDeque::new();
17089
17090 let Some(style) = self.style.as_ref() else {
17091 return;
17092 };
17093
17094 for chunk in chunks {
17095 let highlight = chunk
17096 .syntax_highlight_id
17097 .and_then(|id| id.name(&style.syntax));
17098 let mut chunk_lines = chunk.text.split('\n').peekable();
17099 while let Some(text) = chunk_lines.next() {
17100 let mut merged_with_last_token = false;
17101 if let Some(last_token) = line.back_mut() {
17102 if last_token.highlight == highlight {
17103 last_token.text.push_str(text);
17104 merged_with_last_token = true;
17105 }
17106 }
17107
17108 if !merged_with_last_token {
17109 line.push_back(Chunk {
17110 text: text.into(),
17111 highlight,
17112 });
17113 }
17114
17115 if chunk_lines.peek().is_some() {
17116 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17117 line.pop_front();
17118 }
17119 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17120 line.pop_back();
17121 }
17122
17123 lines.push(mem::take(&mut line));
17124 }
17125 }
17126 }
17127
17128 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17129 return;
17130 };
17131 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17132 }
17133
17134 pub fn open_context_menu(
17135 &mut self,
17136 _: &OpenContextMenu,
17137 window: &mut Window,
17138 cx: &mut Context<Self>,
17139 ) {
17140 self.request_autoscroll(Autoscroll::newest(), cx);
17141 let position = self.selections.newest_display(cx).start;
17142 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17143 }
17144
17145 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17146 &self.inlay_hint_cache
17147 }
17148
17149 pub fn replay_insert_event(
17150 &mut self,
17151 text: &str,
17152 relative_utf16_range: Option<Range<isize>>,
17153 window: &mut Window,
17154 cx: &mut Context<Self>,
17155 ) {
17156 if !self.input_enabled {
17157 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17158 return;
17159 }
17160 if let Some(relative_utf16_range) = relative_utf16_range {
17161 let selections = self.selections.all::<OffsetUtf16>(cx);
17162 self.change_selections(None, window, cx, |s| {
17163 let new_ranges = selections.into_iter().map(|range| {
17164 let start = OffsetUtf16(
17165 range
17166 .head()
17167 .0
17168 .saturating_add_signed(relative_utf16_range.start),
17169 );
17170 let end = OffsetUtf16(
17171 range
17172 .head()
17173 .0
17174 .saturating_add_signed(relative_utf16_range.end),
17175 );
17176 start..end
17177 });
17178 s.select_ranges(new_ranges);
17179 });
17180 }
17181
17182 self.handle_input(text, window, cx);
17183 }
17184
17185 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
17186 let Some(provider) = self.semantics_provider.as_ref() else {
17187 return false;
17188 };
17189
17190 let mut supports = false;
17191 self.buffer().update(cx, |this, cx| {
17192 this.for_each_buffer(|buffer| {
17193 supports |= provider.supports_inlay_hints(buffer, cx);
17194 });
17195 });
17196
17197 supports
17198 }
17199
17200 pub fn is_focused(&self, window: &Window) -> bool {
17201 self.focus_handle.is_focused(window)
17202 }
17203
17204 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17205 cx.emit(EditorEvent::Focused);
17206
17207 if let Some(descendant) = self
17208 .last_focused_descendant
17209 .take()
17210 .and_then(|descendant| descendant.upgrade())
17211 {
17212 window.focus(&descendant);
17213 } else {
17214 if let Some(blame) = self.blame.as_ref() {
17215 blame.update(cx, GitBlame::focus)
17216 }
17217
17218 self.blink_manager.update(cx, BlinkManager::enable);
17219 self.show_cursor_names(window, cx);
17220 self.buffer.update(cx, |buffer, cx| {
17221 buffer.finalize_last_transaction(cx);
17222 if self.leader_peer_id.is_none() {
17223 buffer.set_active_selections(
17224 &self.selections.disjoint_anchors(),
17225 self.selections.line_mode,
17226 self.cursor_shape,
17227 cx,
17228 );
17229 }
17230 });
17231 }
17232 }
17233
17234 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
17235 cx.emit(EditorEvent::FocusedIn)
17236 }
17237
17238 fn handle_focus_out(
17239 &mut self,
17240 event: FocusOutEvent,
17241 _window: &mut Window,
17242 cx: &mut Context<Self>,
17243 ) {
17244 if event.blurred != self.focus_handle {
17245 self.last_focused_descendant = Some(event.blurred);
17246 }
17247 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
17248 }
17249
17250 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17251 self.blink_manager.update(cx, BlinkManager::disable);
17252 self.buffer
17253 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
17254
17255 if let Some(blame) = self.blame.as_ref() {
17256 blame.update(cx, GitBlame::blur)
17257 }
17258 if !self.hover_state.focused(window, cx) {
17259 hide_hover(self, cx);
17260 }
17261 if !self
17262 .context_menu
17263 .borrow()
17264 .as_ref()
17265 .is_some_and(|context_menu| context_menu.focused(window, cx))
17266 {
17267 self.hide_context_menu(window, cx);
17268 }
17269 self.discard_inline_completion(false, cx);
17270 cx.emit(EditorEvent::Blurred);
17271 cx.notify();
17272 }
17273
17274 pub fn register_action<A: Action>(
17275 &mut self,
17276 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
17277 ) -> Subscription {
17278 let id = self.next_editor_action_id.post_inc();
17279 let listener = Arc::new(listener);
17280 self.editor_actions.borrow_mut().insert(
17281 id,
17282 Box::new(move |window, _| {
17283 let listener = listener.clone();
17284 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
17285 let action = action.downcast_ref().unwrap();
17286 if phase == DispatchPhase::Bubble {
17287 listener(action, window, cx)
17288 }
17289 })
17290 }),
17291 );
17292
17293 let editor_actions = self.editor_actions.clone();
17294 Subscription::new(move || {
17295 editor_actions.borrow_mut().remove(&id);
17296 })
17297 }
17298
17299 pub fn file_header_size(&self) -> u32 {
17300 FILE_HEADER_HEIGHT
17301 }
17302
17303 pub fn restore(
17304 &mut self,
17305 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
17306 window: &mut Window,
17307 cx: &mut Context<Self>,
17308 ) {
17309 let workspace = self.workspace();
17310 let project = self.project.as_ref();
17311 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
17312 let mut tasks = Vec::new();
17313 for (buffer_id, changes) in revert_changes {
17314 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
17315 buffer.update(cx, |buffer, cx| {
17316 buffer.edit(
17317 changes
17318 .into_iter()
17319 .map(|(range, text)| (range, text.to_string())),
17320 None,
17321 cx,
17322 );
17323 });
17324
17325 if let Some(project) =
17326 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
17327 {
17328 project.update(cx, |project, cx| {
17329 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
17330 })
17331 }
17332 }
17333 }
17334 tasks
17335 });
17336 cx.spawn_in(window, async move |_, cx| {
17337 for (buffer, task) in save_tasks {
17338 let result = task.await;
17339 if result.is_err() {
17340 let Some(path) = buffer
17341 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17342 .ok()
17343 else {
17344 continue;
17345 };
17346 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17347 let Some(task) = cx
17348 .update_window_entity(&workspace, |workspace, window, cx| {
17349 workspace
17350 .open_path_preview(path, None, false, false, false, window, cx)
17351 })
17352 .ok()
17353 else {
17354 continue;
17355 };
17356 task.await.log_err();
17357 }
17358 }
17359 }
17360 })
17361 .detach();
17362 self.change_selections(None, window, cx, |selections| selections.refresh());
17363 }
17364
17365 pub fn to_pixel_point(
17366 &self,
17367 source: multi_buffer::Anchor,
17368 editor_snapshot: &EditorSnapshot,
17369 window: &mut Window,
17370 ) -> Option<gpui::Point<Pixels>> {
17371 let source_point = source.to_display_point(editor_snapshot);
17372 self.display_to_pixel_point(source_point, editor_snapshot, window)
17373 }
17374
17375 pub fn display_to_pixel_point(
17376 &self,
17377 source: DisplayPoint,
17378 editor_snapshot: &EditorSnapshot,
17379 window: &mut Window,
17380 ) -> Option<gpui::Point<Pixels>> {
17381 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17382 let text_layout_details = self.text_layout_details(window);
17383 let scroll_top = text_layout_details
17384 .scroll_anchor
17385 .scroll_position(editor_snapshot)
17386 .y;
17387
17388 if source.row().as_f32() < scroll_top.floor() {
17389 return None;
17390 }
17391 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17392 let source_y = line_height * (source.row().as_f32() - scroll_top);
17393 Some(gpui::Point::new(source_x, source_y))
17394 }
17395
17396 pub fn has_visible_completions_menu(&self) -> bool {
17397 !self.edit_prediction_preview_is_active()
17398 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17399 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17400 })
17401 }
17402
17403 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17404 self.addons
17405 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17406 }
17407
17408 pub fn unregister_addon<T: Addon>(&mut self) {
17409 self.addons.remove(&std::any::TypeId::of::<T>());
17410 }
17411
17412 pub fn addon<T: Addon>(&self) -> Option<&T> {
17413 let type_id = std::any::TypeId::of::<T>();
17414 self.addons
17415 .get(&type_id)
17416 .and_then(|item| item.to_any().downcast_ref::<T>())
17417 }
17418
17419 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17420 let text_layout_details = self.text_layout_details(window);
17421 let style = &text_layout_details.editor_style;
17422 let font_id = window.text_system().resolve_font(&style.text.font());
17423 let font_size = style.text.font_size.to_pixels(window.rem_size());
17424 let line_height = style.text.line_height_in_pixels(window.rem_size());
17425 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17426
17427 gpui::Size::new(em_width, line_height)
17428 }
17429
17430 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17431 self.load_diff_task.clone()
17432 }
17433
17434 fn read_metadata_from_db(
17435 &mut self,
17436 item_id: u64,
17437 workspace_id: WorkspaceId,
17438 window: &mut Window,
17439 cx: &mut Context<Editor>,
17440 ) {
17441 if self.is_singleton(cx)
17442 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
17443 {
17444 let buffer_snapshot = OnceCell::new();
17445
17446 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
17447 if !selections.is_empty() {
17448 let snapshot =
17449 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17450 self.change_selections(None, window, cx, |s| {
17451 s.select_ranges(selections.into_iter().map(|(start, end)| {
17452 snapshot.clip_offset(start, Bias::Left)
17453 ..snapshot.clip_offset(end, Bias::Right)
17454 }));
17455 });
17456 }
17457 };
17458
17459 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
17460 if !folds.is_empty() {
17461 let snapshot =
17462 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
17463 self.fold_ranges(
17464 folds
17465 .into_iter()
17466 .map(|(start, end)| {
17467 snapshot.clip_offset(start, Bias::Left)
17468 ..snapshot.clip_offset(end, Bias::Right)
17469 })
17470 .collect(),
17471 false,
17472 window,
17473 cx,
17474 );
17475 }
17476 }
17477 }
17478
17479 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
17480 }
17481}
17482
17483fn insert_extra_newline_brackets(
17484 buffer: &MultiBufferSnapshot,
17485 range: Range<usize>,
17486 language: &language::LanguageScope,
17487) -> bool {
17488 let leading_whitespace_len = buffer
17489 .reversed_chars_at(range.start)
17490 .take_while(|c| c.is_whitespace() && *c != '\n')
17491 .map(|c| c.len_utf8())
17492 .sum::<usize>();
17493 let trailing_whitespace_len = buffer
17494 .chars_at(range.end)
17495 .take_while(|c| c.is_whitespace() && *c != '\n')
17496 .map(|c| c.len_utf8())
17497 .sum::<usize>();
17498 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17499
17500 language.brackets().any(|(pair, enabled)| {
17501 let pair_start = pair.start.trim_end();
17502 let pair_end = pair.end.trim_start();
17503
17504 enabled
17505 && pair.newline
17506 && buffer.contains_str_at(range.end, pair_end)
17507 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17508 })
17509}
17510
17511fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17512 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17513 [(buffer, range, _)] => (*buffer, range.clone()),
17514 _ => return false,
17515 };
17516 let pair = {
17517 let mut result: Option<BracketMatch> = None;
17518
17519 for pair in buffer
17520 .all_bracket_ranges(range.clone())
17521 .filter(move |pair| {
17522 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17523 })
17524 {
17525 let len = pair.close_range.end - pair.open_range.start;
17526
17527 if let Some(existing) = &result {
17528 let existing_len = existing.close_range.end - existing.open_range.start;
17529 if len > existing_len {
17530 continue;
17531 }
17532 }
17533
17534 result = Some(pair);
17535 }
17536
17537 result
17538 };
17539 let Some(pair) = pair else {
17540 return false;
17541 };
17542 pair.newline_only
17543 && buffer
17544 .chars_for_range(pair.open_range.end..range.start)
17545 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17546 .all(|c| c.is_whitespace() && c != '\n')
17547}
17548
17549fn get_uncommitted_diff_for_buffer(
17550 project: &Entity<Project>,
17551 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17552 buffer: Entity<MultiBuffer>,
17553 cx: &mut App,
17554) -> Task<()> {
17555 let mut tasks = Vec::new();
17556 project.update(cx, |project, cx| {
17557 for buffer in buffers {
17558 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17559 }
17560 });
17561 cx.spawn(async move |cx| {
17562 let diffs = future::join_all(tasks).await;
17563 buffer
17564 .update(cx, |buffer, cx| {
17565 for diff in diffs.into_iter().flatten() {
17566 buffer.add_diff(diff, cx);
17567 }
17568 })
17569 .ok();
17570 })
17571}
17572
17573fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17574 let tab_size = tab_size.get() as usize;
17575 let mut width = offset;
17576
17577 for ch in text.chars() {
17578 width += if ch == '\t' {
17579 tab_size - (width % tab_size)
17580 } else {
17581 1
17582 };
17583 }
17584
17585 width - offset
17586}
17587
17588#[cfg(test)]
17589mod tests {
17590 use super::*;
17591
17592 #[test]
17593 fn test_string_size_with_expanded_tabs() {
17594 let nz = |val| NonZeroU32::new(val).unwrap();
17595 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17596 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17597 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17598 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17599 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17600 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17601 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17602 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17603 }
17604}
17605
17606/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17607struct WordBreakingTokenizer<'a> {
17608 input: &'a str,
17609}
17610
17611impl<'a> WordBreakingTokenizer<'a> {
17612 fn new(input: &'a str) -> Self {
17613 Self { input }
17614 }
17615}
17616
17617fn is_char_ideographic(ch: char) -> bool {
17618 use unicode_script::Script::*;
17619 use unicode_script::UnicodeScript;
17620 matches!(ch.script(), Han | Tangut | Yi)
17621}
17622
17623fn is_grapheme_ideographic(text: &str) -> bool {
17624 text.chars().any(is_char_ideographic)
17625}
17626
17627fn is_grapheme_whitespace(text: &str) -> bool {
17628 text.chars().any(|x| x.is_whitespace())
17629}
17630
17631fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17632 text.chars().next().map_or(false, |ch| {
17633 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17634 })
17635}
17636
17637#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17638enum WordBreakToken<'a> {
17639 Word { token: &'a str, grapheme_len: usize },
17640 InlineWhitespace { token: &'a str, grapheme_len: usize },
17641 Newline,
17642}
17643
17644impl<'a> Iterator for WordBreakingTokenizer<'a> {
17645 /// Yields a span, the count of graphemes in the token, and whether it was
17646 /// whitespace. Note that it also breaks at word boundaries.
17647 type Item = WordBreakToken<'a>;
17648
17649 fn next(&mut self) -> Option<Self::Item> {
17650 use unicode_segmentation::UnicodeSegmentation;
17651 if self.input.is_empty() {
17652 return None;
17653 }
17654
17655 let mut iter = self.input.graphemes(true).peekable();
17656 let mut offset = 0;
17657 let mut grapheme_len = 0;
17658 if let Some(first_grapheme) = iter.next() {
17659 let is_newline = first_grapheme == "\n";
17660 let is_whitespace = is_grapheme_whitespace(first_grapheme);
17661 offset += first_grapheme.len();
17662 grapheme_len += 1;
17663 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17664 if let Some(grapheme) = iter.peek().copied() {
17665 if should_stay_with_preceding_ideograph(grapheme) {
17666 offset += grapheme.len();
17667 grapheme_len += 1;
17668 }
17669 }
17670 } else {
17671 let mut words = self.input[offset..].split_word_bound_indices().peekable();
17672 let mut next_word_bound = words.peek().copied();
17673 if next_word_bound.map_or(false, |(i, _)| i == 0) {
17674 next_word_bound = words.next();
17675 }
17676 while let Some(grapheme) = iter.peek().copied() {
17677 if next_word_bound.map_or(false, |(i, _)| i == offset) {
17678 break;
17679 };
17680 if is_grapheme_whitespace(grapheme) != is_whitespace
17681 || (grapheme == "\n") != is_newline
17682 {
17683 break;
17684 };
17685 offset += grapheme.len();
17686 grapheme_len += 1;
17687 iter.next();
17688 }
17689 }
17690 let token = &self.input[..offset];
17691 self.input = &self.input[offset..];
17692 if token == "\n" {
17693 Some(WordBreakToken::Newline)
17694 } else if is_whitespace {
17695 Some(WordBreakToken::InlineWhitespace {
17696 token,
17697 grapheme_len,
17698 })
17699 } else {
17700 Some(WordBreakToken::Word {
17701 token,
17702 grapheme_len,
17703 })
17704 }
17705 } else {
17706 None
17707 }
17708 }
17709}
17710
17711#[test]
17712fn test_word_breaking_tokenizer() {
17713 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17714 ("", &[]),
17715 (" ", &[whitespace(" ", 2)]),
17716 ("Ʒ", &[word("Ʒ", 1)]),
17717 ("Ǽ", &[word("Ǽ", 1)]),
17718 ("⋑", &[word("⋑", 1)]),
17719 ("⋑⋑", &[word("⋑⋑", 2)]),
17720 (
17721 "原理,进而",
17722 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
17723 ),
17724 (
17725 "hello world",
17726 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17727 ),
17728 (
17729 "hello, world",
17730 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17731 ),
17732 (
17733 " hello world",
17734 &[
17735 whitespace(" ", 2),
17736 word("hello", 5),
17737 whitespace(" ", 1),
17738 word("world", 5),
17739 ],
17740 ),
17741 (
17742 "这是什么 \n 钢笔",
17743 &[
17744 word("这", 1),
17745 word("是", 1),
17746 word("什", 1),
17747 word("么", 1),
17748 whitespace(" ", 1),
17749 newline(),
17750 whitespace(" ", 1),
17751 word("钢", 1),
17752 word("笔", 1),
17753 ],
17754 ),
17755 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
17756 ];
17757
17758 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17759 WordBreakToken::Word {
17760 token,
17761 grapheme_len,
17762 }
17763 }
17764
17765 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17766 WordBreakToken::InlineWhitespace {
17767 token,
17768 grapheme_len,
17769 }
17770 }
17771
17772 fn newline() -> WordBreakToken<'static> {
17773 WordBreakToken::Newline
17774 }
17775
17776 for (input, result) in tests {
17777 assert_eq!(
17778 WordBreakingTokenizer::new(input)
17779 .collect::<Vec<_>>()
17780 .as_slice(),
17781 *result,
17782 );
17783 }
17784}
17785
17786fn wrap_with_prefix(
17787 line_prefix: String,
17788 unwrapped_text: String,
17789 wrap_column: usize,
17790 tab_size: NonZeroU32,
17791 preserve_existing_whitespace: bool,
17792) -> String {
17793 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17794 let mut wrapped_text = String::new();
17795 let mut current_line = line_prefix.clone();
17796
17797 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17798 let mut current_line_len = line_prefix_len;
17799 let mut in_whitespace = false;
17800 for token in tokenizer {
17801 let have_preceding_whitespace = in_whitespace;
17802 match token {
17803 WordBreakToken::Word {
17804 token,
17805 grapheme_len,
17806 } => {
17807 in_whitespace = false;
17808 if current_line_len + grapheme_len > wrap_column
17809 && current_line_len != line_prefix_len
17810 {
17811 wrapped_text.push_str(current_line.trim_end());
17812 wrapped_text.push('\n');
17813 current_line.truncate(line_prefix.len());
17814 current_line_len = line_prefix_len;
17815 }
17816 current_line.push_str(token);
17817 current_line_len += grapheme_len;
17818 }
17819 WordBreakToken::InlineWhitespace {
17820 mut token,
17821 mut grapheme_len,
17822 } => {
17823 in_whitespace = true;
17824 if have_preceding_whitespace && !preserve_existing_whitespace {
17825 continue;
17826 }
17827 if !preserve_existing_whitespace {
17828 token = " ";
17829 grapheme_len = 1;
17830 }
17831 if current_line_len + grapheme_len > wrap_column {
17832 wrapped_text.push_str(current_line.trim_end());
17833 wrapped_text.push('\n');
17834 current_line.truncate(line_prefix.len());
17835 current_line_len = line_prefix_len;
17836 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17837 current_line.push_str(token);
17838 current_line_len += grapheme_len;
17839 }
17840 }
17841 WordBreakToken::Newline => {
17842 in_whitespace = true;
17843 if preserve_existing_whitespace {
17844 wrapped_text.push_str(current_line.trim_end());
17845 wrapped_text.push('\n');
17846 current_line.truncate(line_prefix.len());
17847 current_line_len = line_prefix_len;
17848 } else if have_preceding_whitespace {
17849 continue;
17850 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17851 {
17852 wrapped_text.push_str(current_line.trim_end());
17853 wrapped_text.push('\n');
17854 current_line.truncate(line_prefix.len());
17855 current_line_len = line_prefix_len;
17856 } else if current_line_len != line_prefix_len {
17857 current_line.push(' ');
17858 current_line_len += 1;
17859 }
17860 }
17861 }
17862 }
17863
17864 if !current_line.is_empty() {
17865 wrapped_text.push_str(¤t_line);
17866 }
17867 wrapped_text
17868}
17869
17870#[test]
17871fn test_wrap_with_prefix() {
17872 assert_eq!(
17873 wrap_with_prefix(
17874 "# ".to_string(),
17875 "abcdefg".to_string(),
17876 4,
17877 NonZeroU32::new(4).unwrap(),
17878 false,
17879 ),
17880 "# abcdefg"
17881 );
17882 assert_eq!(
17883 wrap_with_prefix(
17884 "".to_string(),
17885 "\thello world".to_string(),
17886 8,
17887 NonZeroU32::new(4).unwrap(),
17888 false,
17889 ),
17890 "hello\nworld"
17891 );
17892 assert_eq!(
17893 wrap_with_prefix(
17894 "// ".to_string(),
17895 "xx \nyy zz aa bb cc".to_string(),
17896 12,
17897 NonZeroU32::new(4).unwrap(),
17898 false,
17899 ),
17900 "// xx yy zz\n// aa bb cc"
17901 );
17902 assert_eq!(
17903 wrap_with_prefix(
17904 String::new(),
17905 "这是什么 \n 钢笔".to_string(),
17906 3,
17907 NonZeroU32::new(4).unwrap(),
17908 false,
17909 ),
17910 "这是什\n么 钢\n笔"
17911 );
17912}
17913
17914pub trait CollaborationHub {
17915 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17916 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17917 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17918}
17919
17920impl CollaborationHub for Entity<Project> {
17921 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17922 self.read(cx).collaborators()
17923 }
17924
17925 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17926 self.read(cx).user_store().read(cx).participant_indices()
17927 }
17928
17929 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17930 let this = self.read(cx);
17931 let user_ids = this.collaborators().values().map(|c| c.user_id);
17932 this.user_store().read_with(cx, |user_store, cx| {
17933 user_store.participant_names(user_ids, cx)
17934 })
17935 }
17936}
17937
17938pub trait SemanticsProvider {
17939 fn hover(
17940 &self,
17941 buffer: &Entity<Buffer>,
17942 position: text::Anchor,
17943 cx: &mut App,
17944 ) -> Option<Task<Vec<project::Hover>>>;
17945
17946 fn inlay_hints(
17947 &self,
17948 buffer_handle: Entity<Buffer>,
17949 range: Range<text::Anchor>,
17950 cx: &mut App,
17951 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17952
17953 fn resolve_inlay_hint(
17954 &self,
17955 hint: InlayHint,
17956 buffer_handle: Entity<Buffer>,
17957 server_id: LanguageServerId,
17958 cx: &mut App,
17959 ) -> Option<Task<anyhow::Result<InlayHint>>>;
17960
17961 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17962
17963 fn document_highlights(
17964 &self,
17965 buffer: &Entity<Buffer>,
17966 position: text::Anchor,
17967 cx: &mut App,
17968 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17969
17970 fn definitions(
17971 &self,
17972 buffer: &Entity<Buffer>,
17973 position: text::Anchor,
17974 kind: GotoDefinitionKind,
17975 cx: &mut App,
17976 ) -> Option<Task<Result<Vec<LocationLink>>>>;
17977
17978 fn range_for_rename(
17979 &self,
17980 buffer: &Entity<Buffer>,
17981 position: text::Anchor,
17982 cx: &mut App,
17983 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17984
17985 fn perform_rename(
17986 &self,
17987 buffer: &Entity<Buffer>,
17988 position: text::Anchor,
17989 new_name: String,
17990 cx: &mut App,
17991 ) -> Option<Task<Result<ProjectTransaction>>>;
17992}
17993
17994pub trait CompletionProvider {
17995 fn completions(
17996 &self,
17997 excerpt_id: ExcerptId,
17998 buffer: &Entity<Buffer>,
17999 buffer_position: text::Anchor,
18000 trigger: CompletionContext,
18001 window: &mut Window,
18002 cx: &mut Context<Editor>,
18003 ) -> Task<Result<Option<Vec<Completion>>>>;
18004
18005 fn resolve_completions(
18006 &self,
18007 buffer: Entity<Buffer>,
18008 completion_indices: Vec<usize>,
18009 completions: Rc<RefCell<Box<[Completion]>>>,
18010 cx: &mut Context<Editor>,
18011 ) -> Task<Result<bool>>;
18012
18013 fn apply_additional_edits_for_completion(
18014 &self,
18015 _buffer: Entity<Buffer>,
18016 _completions: Rc<RefCell<Box<[Completion]>>>,
18017 _completion_index: usize,
18018 _push_to_history: bool,
18019 _cx: &mut Context<Editor>,
18020 ) -> Task<Result<Option<language::Transaction>>> {
18021 Task::ready(Ok(None))
18022 }
18023
18024 fn is_completion_trigger(
18025 &self,
18026 buffer: &Entity<Buffer>,
18027 position: language::Anchor,
18028 text: &str,
18029 trigger_in_words: bool,
18030 cx: &mut Context<Editor>,
18031 ) -> bool;
18032
18033 fn sort_completions(&self) -> bool {
18034 true
18035 }
18036}
18037
18038pub trait CodeActionProvider {
18039 fn id(&self) -> Arc<str>;
18040
18041 fn code_actions(
18042 &self,
18043 buffer: &Entity<Buffer>,
18044 range: Range<text::Anchor>,
18045 window: &mut Window,
18046 cx: &mut App,
18047 ) -> Task<Result<Vec<CodeAction>>>;
18048
18049 fn apply_code_action(
18050 &self,
18051 buffer_handle: Entity<Buffer>,
18052 action: CodeAction,
18053 excerpt_id: ExcerptId,
18054 push_to_history: bool,
18055 window: &mut Window,
18056 cx: &mut App,
18057 ) -> Task<Result<ProjectTransaction>>;
18058}
18059
18060impl CodeActionProvider for Entity<Project> {
18061 fn id(&self) -> Arc<str> {
18062 "project".into()
18063 }
18064
18065 fn code_actions(
18066 &self,
18067 buffer: &Entity<Buffer>,
18068 range: Range<text::Anchor>,
18069 _window: &mut Window,
18070 cx: &mut App,
18071 ) -> Task<Result<Vec<CodeAction>>> {
18072 self.update(cx, |project, cx| {
18073 let code_lens = project.code_lens(buffer, range.clone(), cx);
18074 let code_actions = project.code_actions(buffer, range, None, cx);
18075 cx.background_spawn(async move {
18076 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18077 Ok(code_lens
18078 .context("code lens fetch")?
18079 .into_iter()
18080 .chain(code_actions.context("code action fetch")?)
18081 .collect())
18082 })
18083 })
18084 }
18085
18086 fn apply_code_action(
18087 &self,
18088 buffer_handle: Entity<Buffer>,
18089 action: CodeAction,
18090 _excerpt_id: ExcerptId,
18091 push_to_history: bool,
18092 _window: &mut Window,
18093 cx: &mut App,
18094 ) -> Task<Result<ProjectTransaction>> {
18095 self.update(cx, |project, cx| {
18096 project.apply_code_action(buffer_handle, action, push_to_history, cx)
18097 })
18098 }
18099}
18100
18101fn snippet_completions(
18102 project: &Project,
18103 buffer: &Entity<Buffer>,
18104 buffer_position: text::Anchor,
18105 cx: &mut App,
18106) -> Task<Result<Vec<Completion>>> {
18107 let language = buffer.read(cx).language_at(buffer_position);
18108 let language_name = language.as_ref().map(|language| language.lsp_id());
18109 let snippet_store = project.snippets().read(cx);
18110 let snippets = snippet_store.snippets_for(language_name, cx);
18111
18112 if snippets.is_empty() {
18113 return Task::ready(Ok(vec![]));
18114 }
18115 let snapshot = buffer.read(cx).text_snapshot();
18116 let chars: String = snapshot
18117 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
18118 .collect();
18119
18120 let scope = language.map(|language| language.default_scope());
18121 let executor = cx.background_executor().clone();
18122
18123 cx.background_spawn(async move {
18124 let classifier = CharClassifier::new(scope).for_completion(true);
18125 let mut last_word = chars
18126 .chars()
18127 .take_while(|c| classifier.is_word(*c))
18128 .collect::<String>();
18129 last_word = last_word.chars().rev().collect();
18130
18131 if last_word.is_empty() {
18132 return Ok(vec![]);
18133 }
18134
18135 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
18136 let to_lsp = |point: &text::Anchor| {
18137 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
18138 point_to_lsp(end)
18139 };
18140 let lsp_end = to_lsp(&buffer_position);
18141
18142 let candidates = snippets
18143 .iter()
18144 .enumerate()
18145 .flat_map(|(ix, snippet)| {
18146 snippet
18147 .prefix
18148 .iter()
18149 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
18150 })
18151 .collect::<Vec<StringMatchCandidate>>();
18152
18153 let mut matches = fuzzy::match_strings(
18154 &candidates,
18155 &last_word,
18156 last_word.chars().any(|c| c.is_uppercase()),
18157 100,
18158 &Default::default(),
18159 executor,
18160 )
18161 .await;
18162
18163 // Remove all candidates where the query's start does not match the start of any word in the candidate
18164 if let Some(query_start) = last_word.chars().next() {
18165 matches.retain(|string_match| {
18166 split_words(&string_match.string).any(|word| {
18167 // Check that the first codepoint of the word as lowercase matches the first
18168 // codepoint of the query as lowercase
18169 word.chars()
18170 .flat_map(|codepoint| codepoint.to_lowercase())
18171 .zip(query_start.to_lowercase())
18172 .all(|(word_cp, query_cp)| word_cp == query_cp)
18173 })
18174 });
18175 }
18176
18177 let matched_strings = matches
18178 .into_iter()
18179 .map(|m| m.string)
18180 .collect::<HashSet<_>>();
18181
18182 let result: Vec<Completion> = snippets
18183 .into_iter()
18184 .filter_map(|snippet| {
18185 let matching_prefix = snippet
18186 .prefix
18187 .iter()
18188 .find(|prefix| matched_strings.contains(*prefix))?;
18189 let start = as_offset - last_word.len();
18190 let start = snapshot.anchor_before(start);
18191 let range = start..buffer_position;
18192 let lsp_start = to_lsp(&start);
18193 let lsp_range = lsp::Range {
18194 start: lsp_start,
18195 end: lsp_end,
18196 };
18197 Some(Completion {
18198 old_range: range,
18199 new_text: snippet.body.clone(),
18200 source: CompletionSource::Lsp {
18201 server_id: LanguageServerId(usize::MAX),
18202 resolved: true,
18203 lsp_completion: Box::new(lsp::CompletionItem {
18204 label: snippet.prefix.first().unwrap().clone(),
18205 kind: Some(CompletionItemKind::SNIPPET),
18206 label_details: snippet.description.as_ref().map(|description| {
18207 lsp::CompletionItemLabelDetails {
18208 detail: Some(description.clone()),
18209 description: None,
18210 }
18211 }),
18212 insert_text_format: Some(InsertTextFormat::SNIPPET),
18213 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
18214 lsp::InsertReplaceEdit {
18215 new_text: snippet.body.clone(),
18216 insert: lsp_range,
18217 replace: lsp_range,
18218 },
18219 )),
18220 filter_text: Some(snippet.body.clone()),
18221 sort_text: Some(char::MAX.to_string()),
18222 ..lsp::CompletionItem::default()
18223 }),
18224 lsp_defaults: None,
18225 },
18226 label: CodeLabel {
18227 text: matching_prefix.clone(),
18228 runs: Vec::new(),
18229 filter_range: 0..matching_prefix.len(),
18230 },
18231 icon_path: None,
18232 documentation: snippet
18233 .description
18234 .clone()
18235 .map(|description| CompletionDocumentation::SingleLine(description.into())),
18236 confirm: None,
18237 })
18238 })
18239 .collect();
18240
18241 Ok(result)
18242 })
18243}
18244
18245impl CompletionProvider for Entity<Project> {
18246 fn completions(
18247 &self,
18248 _excerpt_id: ExcerptId,
18249 buffer: &Entity<Buffer>,
18250 buffer_position: text::Anchor,
18251 options: CompletionContext,
18252 _window: &mut Window,
18253 cx: &mut Context<Editor>,
18254 ) -> Task<Result<Option<Vec<Completion>>>> {
18255 self.update(cx, |project, cx| {
18256 let snippets = snippet_completions(project, buffer, buffer_position, cx);
18257 let project_completions = project.completions(buffer, buffer_position, options, cx);
18258 cx.background_spawn(async move {
18259 let snippets_completions = snippets.await?;
18260 match project_completions.await? {
18261 Some(mut completions) => {
18262 completions.extend(snippets_completions);
18263 Ok(Some(completions))
18264 }
18265 None => {
18266 if snippets_completions.is_empty() {
18267 Ok(None)
18268 } else {
18269 Ok(Some(snippets_completions))
18270 }
18271 }
18272 }
18273 })
18274 })
18275 }
18276
18277 fn resolve_completions(
18278 &self,
18279 buffer: Entity<Buffer>,
18280 completion_indices: Vec<usize>,
18281 completions: Rc<RefCell<Box<[Completion]>>>,
18282 cx: &mut Context<Editor>,
18283 ) -> Task<Result<bool>> {
18284 self.update(cx, |project, cx| {
18285 project.lsp_store().update(cx, |lsp_store, cx| {
18286 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
18287 })
18288 })
18289 }
18290
18291 fn apply_additional_edits_for_completion(
18292 &self,
18293 buffer: Entity<Buffer>,
18294 completions: Rc<RefCell<Box<[Completion]>>>,
18295 completion_index: usize,
18296 push_to_history: bool,
18297 cx: &mut Context<Editor>,
18298 ) -> Task<Result<Option<language::Transaction>>> {
18299 self.update(cx, |project, cx| {
18300 project.lsp_store().update(cx, |lsp_store, cx| {
18301 lsp_store.apply_additional_edits_for_completion(
18302 buffer,
18303 completions,
18304 completion_index,
18305 push_to_history,
18306 cx,
18307 )
18308 })
18309 })
18310 }
18311
18312 fn is_completion_trigger(
18313 &self,
18314 buffer: &Entity<Buffer>,
18315 position: language::Anchor,
18316 text: &str,
18317 trigger_in_words: bool,
18318 cx: &mut Context<Editor>,
18319 ) -> bool {
18320 let mut chars = text.chars();
18321 let char = if let Some(char) = chars.next() {
18322 char
18323 } else {
18324 return false;
18325 };
18326 if chars.next().is_some() {
18327 return false;
18328 }
18329
18330 let buffer = buffer.read(cx);
18331 let snapshot = buffer.snapshot();
18332 if !snapshot.settings_at(position, cx).show_completions_on_input {
18333 return false;
18334 }
18335 let classifier = snapshot.char_classifier_at(position).for_completion(true);
18336 if trigger_in_words && classifier.is_word(char) {
18337 return true;
18338 }
18339
18340 buffer.completion_triggers().contains(text)
18341 }
18342}
18343
18344impl SemanticsProvider for Entity<Project> {
18345 fn hover(
18346 &self,
18347 buffer: &Entity<Buffer>,
18348 position: text::Anchor,
18349 cx: &mut App,
18350 ) -> Option<Task<Vec<project::Hover>>> {
18351 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
18352 }
18353
18354 fn document_highlights(
18355 &self,
18356 buffer: &Entity<Buffer>,
18357 position: text::Anchor,
18358 cx: &mut App,
18359 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18360 Some(self.update(cx, |project, cx| {
18361 project.document_highlights(buffer, position, cx)
18362 }))
18363 }
18364
18365 fn definitions(
18366 &self,
18367 buffer: &Entity<Buffer>,
18368 position: text::Anchor,
18369 kind: GotoDefinitionKind,
18370 cx: &mut App,
18371 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18372 Some(self.update(cx, |project, cx| match kind {
18373 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18374 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18375 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18376 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18377 }))
18378 }
18379
18380 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18381 // TODO: make this work for remote projects
18382 self.update(cx, |this, cx| {
18383 buffer.update(cx, |buffer, cx| {
18384 this.any_language_server_supports_inlay_hints(buffer, cx)
18385 })
18386 })
18387 }
18388
18389 fn inlay_hints(
18390 &self,
18391 buffer_handle: Entity<Buffer>,
18392 range: Range<text::Anchor>,
18393 cx: &mut App,
18394 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18395 Some(self.update(cx, |project, cx| {
18396 project.inlay_hints(buffer_handle, range, cx)
18397 }))
18398 }
18399
18400 fn resolve_inlay_hint(
18401 &self,
18402 hint: InlayHint,
18403 buffer_handle: Entity<Buffer>,
18404 server_id: LanguageServerId,
18405 cx: &mut App,
18406 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18407 Some(self.update(cx, |project, cx| {
18408 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18409 }))
18410 }
18411
18412 fn range_for_rename(
18413 &self,
18414 buffer: &Entity<Buffer>,
18415 position: text::Anchor,
18416 cx: &mut App,
18417 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18418 Some(self.update(cx, |project, cx| {
18419 let buffer = buffer.clone();
18420 let task = project.prepare_rename(buffer.clone(), position, cx);
18421 cx.spawn(async move |_, cx| {
18422 Ok(match task.await? {
18423 PrepareRenameResponse::Success(range) => Some(range),
18424 PrepareRenameResponse::InvalidPosition => None,
18425 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18426 // Fallback on using TreeSitter info to determine identifier range
18427 buffer.update(cx, |buffer, _| {
18428 let snapshot = buffer.snapshot();
18429 let (range, kind) = snapshot.surrounding_word(position);
18430 if kind != Some(CharKind::Word) {
18431 return None;
18432 }
18433 Some(
18434 snapshot.anchor_before(range.start)
18435 ..snapshot.anchor_after(range.end),
18436 )
18437 })?
18438 }
18439 })
18440 })
18441 }))
18442 }
18443
18444 fn perform_rename(
18445 &self,
18446 buffer: &Entity<Buffer>,
18447 position: text::Anchor,
18448 new_name: String,
18449 cx: &mut App,
18450 ) -> Option<Task<Result<ProjectTransaction>>> {
18451 Some(self.update(cx, |project, cx| {
18452 project.perform_rename(buffer.clone(), position, new_name, cx)
18453 }))
18454 }
18455}
18456
18457fn inlay_hint_settings(
18458 location: Anchor,
18459 snapshot: &MultiBufferSnapshot,
18460 cx: &mut Context<Editor>,
18461) -> InlayHintSettings {
18462 let file = snapshot.file_at(location);
18463 let language = snapshot.language_at(location).map(|l| l.name());
18464 language_settings(language, file, cx).inlay_hints
18465}
18466
18467fn consume_contiguous_rows(
18468 contiguous_row_selections: &mut Vec<Selection<Point>>,
18469 selection: &Selection<Point>,
18470 display_map: &DisplaySnapshot,
18471 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18472) -> (MultiBufferRow, MultiBufferRow) {
18473 contiguous_row_selections.push(selection.clone());
18474 let start_row = MultiBufferRow(selection.start.row);
18475 let mut end_row = ending_row(selection, display_map);
18476
18477 while let Some(next_selection) = selections.peek() {
18478 if next_selection.start.row <= end_row.0 {
18479 end_row = ending_row(next_selection, display_map);
18480 contiguous_row_selections.push(selections.next().unwrap().clone());
18481 } else {
18482 break;
18483 }
18484 }
18485 (start_row, end_row)
18486}
18487
18488fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18489 if next_selection.end.column > 0 || next_selection.is_empty() {
18490 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18491 } else {
18492 MultiBufferRow(next_selection.end.row)
18493 }
18494}
18495
18496impl EditorSnapshot {
18497 pub fn remote_selections_in_range<'a>(
18498 &'a self,
18499 range: &'a Range<Anchor>,
18500 collaboration_hub: &dyn CollaborationHub,
18501 cx: &'a App,
18502 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18503 let participant_names = collaboration_hub.user_names(cx);
18504 let participant_indices = collaboration_hub.user_participant_indices(cx);
18505 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18506 let collaborators_by_replica_id = collaborators_by_peer_id
18507 .iter()
18508 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18509 .collect::<HashMap<_, _>>();
18510 self.buffer_snapshot
18511 .selections_in_range(range, false)
18512 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18513 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18514 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18515 let user_name = participant_names.get(&collaborator.user_id).cloned();
18516 Some(RemoteSelection {
18517 replica_id,
18518 selection,
18519 cursor_shape,
18520 line_mode,
18521 participant_index,
18522 peer_id: collaborator.peer_id,
18523 user_name,
18524 })
18525 })
18526 }
18527
18528 pub fn hunks_for_ranges(
18529 &self,
18530 ranges: impl IntoIterator<Item = Range<Point>>,
18531 ) -> Vec<MultiBufferDiffHunk> {
18532 let mut hunks = Vec::new();
18533 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18534 HashMap::default();
18535 for query_range in ranges {
18536 let query_rows =
18537 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18538 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18539 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18540 ) {
18541 // Include deleted hunks that are adjacent to the query range, because
18542 // otherwise they would be missed.
18543 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18544 if hunk.status().is_deleted() {
18545 intersects_range |= hunk.row_range.start == query_rows.end;
18546 intersects_range |= hunk.row_range.end == query_rows.start;
18547 }
18548 if intersects_range {
18549 if !processed_buffer_rows
18550 .entry(hunk.buffer_id)
18551 .or_default()
18552 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18553 {
18554 continue;
18555 }
18556 hunks.push(hunk);
18557 }
18558 }
18559 }
18560
18561 hunks
18562 }
18563
18564 fn display_diff_hunks_for_rows<'a>(
18565 &'a self,
18566 display_rows: Range<DisplayRow>,
18567 folded_buffers: &'a HashSet<BufferId>,
18568 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18569 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18570 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18571
18572 self.buffer_snapshot
18573 .diff_hunks_in_range(buffer_start..buffer_end)
18574 .filter_map(|hunk| {
18575 if folded_buffers.contains(&hunk.buffer_id) {
18576 return None;
18577 }
18578
18579 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18580 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18581
18582 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18583 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18584
18585 let display_hunk = if hunk_display_start.column() != 0 {
18586 DisplayDiffHunk::Folded {
18587 display_row: hunk_display_start.row(),
18588 }
18589 } else {
18590 let mut end_row = hunk_display_end.row();
18591 if hunk_display_end.column() > 0 {
18592 end_row.0 += 1;
18593 }
18594 let is_created_file = hunk.is_created_file();
18595 DisplayDiffHunk::Unfolded {
18596 status: hunk.status(),
18597 diff_base_byte_range: hunk.diff_base_byte_range,
18598 display_row_range: hunk_display_start.row()..end_row,
18599 multi_buffer_range: Anchor::range_in_buffer(
18600 hunk.excerpt_id,
18601 hunk.buffer_id,
18602 hunk.buffer_range,
18603 ),
18604 is_created_file,
18605 }
18606 };
18607
18608 Some(display_hunk)
18609 })
18610 }
18611
18612 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18613 self.display_snapshot.buffer_snapshot.language_at(position)
18614 }
18615
18616 pub fn is_focused(&self) -> bool {
18617 self.is_focused
18618 }
18619
18620 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18621 self.placeholder_text.as_ref()
18622 }
18623
18624 pub fn scroll_position(&self) -> gpui::Point<f32> {
18625 self.scroll_anchor.scroll_position(&self.display_snapshot)
18626 }
18627
18628 fn gutter_dimensions(
18629 &self,
18630 font_id: FontId,
18631 font_size: Pixels,
18632 max_line_number_width: Pixels,
18633 cx: &App,
18634 ) -> Option<GutterDimensions> {
18635 if !self.show_gutter {
18636 return None;
18637 }
18638
18639 let descent = cx.text_system().descent(font_id, font_size);
18640 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18641 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18642
18643 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18644 matches!(
18645 ProjectSettings::get_global(cx).git.git_gutter,
18646 Some(GitGutterSetting::TrackedFiles)
18647 )
18648 });
18649 let gutter_settings = EditorSettings::get_global(cx).gutter;
18650 let show_line_numbers = self
18651 .show_line_numbers
18652 .unwrap_or(gutter_settings.line_numbers);
18653 let line_gutter_width = if show_line_numbers {
18654 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18655 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18656 max_line_number_width.max(min_width_for_number_on_gutter)
18657 } else {
18658 0.0.into()
18659 };
18660
18661 let show_code_actions = self
18662 .show_code_actions
18663 .unwrap_or(gutter_settings.code_actions);
18664
18665 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18666 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18667
18668 let git_blame_entries_width =
18669 self.git_blame_gutter_max_author_length
18670 .map(|max_author_length| {
18671 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18672
18673 /// The number of characters to dedicate to gaps and margins.
18674 const SPACING_WIDTH: usize = 4;
18675
18676 let max_char_count = max_author_length
18677 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18678 + ::git::SHORT_SHA_LENGTH
18679 + MAX_RELATIVE_TIMESTAMP.len()
18680 + SPACING_WIDTH;
18681
18682 em_advance * max_char_count
18683 });
18684
18685 let is_singleton = self.buffer_snapshot.is_singleton();
18686
18687 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18688 left_padding += if !is_singleton {
18689 em_width * 4.0
18690 } else if show_code_actions || show_runnables || show_breakpoints {
18691 em_width * 3.0
18692 } else if show_git_gutter && show_line_numbers {
18693 em_width * 2.0
18694 } else if show_git_gutter || show_line_numbers {
18695 em_width
18696 } else {
18697 px(0.)
18698 };
18699
18700 let shows_folds = is_singleton && gutter_settings.folds;
18701
18702 let right_padding = if shows_folds && show_line_numbers {
18703 em_width * 4.0
18704 } else if shows_folds || (!is_singleton && show_line_numbers) {
18705 em_width * 3.0
18706 } else if show_line_numbers {
18707 em_width
18708 } else {
18709 px(0.)
18710 };
18711
18712 Some(GutterDimensions {
18713 left_padding,
18714 right_padding,
18715 width: line_gutter_width + left_padding + right_padding,
18716 margin: -descent,
18717 git_blame_entries_width,
18718 })
18719 }
18720
18721 pub fn render_crease_toggle(
18722 &self,
18723 buffer_row: MultiBufferRow,
18724 row_contains_cursor: bool,
18725 editor: Entity<Editor>,
18726 window: &mut Window,
18727 cx: &mut App,
18728 ) -> Option<AnyElement> {
18729 let folded = self.is_line_folded(buffer_row);
18730 let mut is_foldable = false;
18731
18732 if let Some(crease) = self
18733 .crease_snapshot
18734 .query_row(buffer_row, &self.buffer_snapshot)
18735 {
18736 is_foldable = true;
18737 match crease {
18738 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18739 if let Some(render_toggle) = render_toggle {
18740 let toggle_callback =
18741 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18742 if folded {
18743 editor.update(cx, |editor, cx| {
18744 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18745 });
18746 } else {
18747 editor.update(cx, |editor, cx| {
18748 editor.unfold_at(
18749 &crate::UnfoldAt { buffer_row },
18750 window,
18751 cx,
18752 )
18753 });
18754 }
18755 });
18756 return Some((render_toggle)(
18757 buffer_row,
18758 folded,
18759 toggle_callback,
18760 window,
18761 cx,
18762 ));
18763 }
18764 }
18765 }
18766 }
18767
18768 is_foldable |= self.starts_indent(buffer_row);
18769
18770 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18771 Some(
18772 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18773 .toggle_state(folded)
18774 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18775 if folded {
18776 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18777 } else {
18778 this.fold_at(&FoldAt { buffer_row }, window, cx);
18779 }
18780 }))
18781 .into_any_element(),
18782 )
18783 } else {
18784 None
18785 }
18786 }
18787
18788 pub fn render_crease_trailer(
18789 &self,
18790 buffer_row: MultiBufferRow,
18791 window: &mut Window,
18792 cx: &mut App,
18793 ) -> Option<AnyElement> {
18794 let folded = self.is_line_folded(buffer_row);
18795 if let Crease::Inline { render_trailer, .. } = self
18796 .crease_snapshot
18797 .query_row(buffer_row, &self.buffer_snapshot)?
18798 {
18799 let render_trailer = render_trailer.as_ref()?;
18800 Some(render_trailer(buffer_row, folded, window, cx))
18801 } else {
18802 None
18803 }
18804 }
18805}
18806
18807impl Deref for EditorSnapshot {
18808 type Target = DisplaySnapshot;
18809
18810 fn deref(&self) -> &Self::Target {
18811 &self.display_snapshot
18812 }
18813}
18814
18815#[derive(Clone, Debug, PartialEq, Eq)]
18816pub enum EditorEvent {
18817 InputIgnored {
18818 text: Arc<str>,
18819 },
18820 InputHandled {
18821 utf16_range_to_replace: Option<Range<isize>>,
18822 text: Arc<str>,
18823 },
18824 ExcerptsAdded {
18825 buffer: Entity<Buffer>,
18826 predecessor: ExcerptId,
18827 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18828 },
18829 ExcerptsRemoved {
18830 ids: Vec<ExcerptId>,
18831 },
18832 BufferFoldToggled {
18833 ids: Vec<ExcerptId>,
18834 folded: bool,
18835 },
18836 ExcerptsEdited {
18837 ids: Vec<ExcerptId>,
18838 },
18839 ExcerptsExpanded {
18840 ids: Vec<ExcerptId>,
18841 },
18842 BufferEdited,
18843 Edited {
18844 transaction_id: clock::Lamport,
18845 },
18846 Reparsed(BufferId),
18847 Focused,
18848 FocusedIn,
18849 Blurred,
18850 DirtyChanged,
18851 Saved,
18852 TitleChanged,
18853 DiffBaseChanged,
18854 SelectionsChanged {
18855 local: bool,
18856 },
18857 ScrollPositionChanged {
18858 local: bool,
18859 autoscroll: bool,
18860 },
18861 Closed,
18862 TransactionUndone {
18863 transaction_id: clock::Lamport,
18864 },
18865 TransactionBegun {
18866 transaction_id: clock::Lamport,
18867 },
18868 Reloaded,
18869 CursorShapeChanged,
18870 PushedToNavHistory {
18871 anchor: Anchor,
18872 is_deactivate: bool,
18873 },
18874}
18875
18876impl EventEmitter<EditorEvent> for Editor {}
18877
18878impl Focusable for Editor {
18879 fn focus_handle(&self, _cx: &App) -> FocusHandle {
18880 self.focus_handle.clone()
18881 }
18882}
18883
18884impl Render for Editor {
18885 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18886 let settings = ThemeSettings::get_global(cx);
18887
18888 let mut text_style = match self.mode {
18889 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18890 color: cx.theme().colors().editor_foreground,
18891 font_family: settings.ui_font.family.clone(),
18892 font_features: settings.ui_font.features.clone(),
18893 font_fallbacks: settings.ui_font.fallbacks.clone(),
18894 font_size: rems(0.875).into(),
18895 font_weight: settings.ui_font.weight,
18896 line_height: relative(settings.buffer_line_height.value()),
18897 ..Default::default()
18898 },
18899 EditorMode::Full => TextStyle {
18900 color: cx.theme().colors().editor_foreground,
18901 font_family: settings.buffer_font.family.clone(),
18902 font_features: settings.buffer_font.features.clone(),
18903 font_fallbacks: settings.buffer_font.fallbacks.clone(),
18904 font_size: settings.buffer_font_size(cx).into(),
18905 font_weight: settings.buffer_font.weight,
18906 line_height: relative(settings.buffer_line_height.value()),
18907 ..Default::default()
18908 },
18909 };
18910 if let Some(text_style_refinement) = &self.text_style_refinement {
18911 text_style.refine(text_style_refinement)
18912 }
18913
18914 let background = match self.mode {
18915 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18916 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18917 EditorMode::Full => cx.theme().colors().editor_background,
18918 };
18919
18920 EditorElement::new(
18921 &cx.entity(),
18922 EditorStyle {
18923 background,
18924 local_player: cx.theme().players().local(),
18925 text: text_style,
18926 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18927 syntax: cx.theme().syntax().clone(),
18928 status: cx.theme().status().clone(),
18929 inlay_hints_style: make_inlay_hints_style(cx),
18930 inline_completion_styles: make_suggestion_styles(cx),
18931 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18932 },
18933 )
18934 }
18935}
18936
18937impl EntityInputHandler for Editor {
18938 fn text_for_range(
18939 &mut self,
18940 range_utf16: Range<usize>,
18941 adjusted_range: &mut Option<Range<usize>>,
18942 _: &mut Window,
18943 cx: &mut Context<Self>,
18944 ) -> Option<String> {
18945 let snapshot = self.buffer.read(cx).read(cx);
18946 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18947 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18948 if (start.0..end.0) != range_utf16 {
18949 adjusted_range.replace(start.0..end.0);
18950 }
18951 Some(snapshot.text_for_range(start..end).collect())
18952 }
18953
18954 fn selected_text_range(
18955 &mut self,
18956 ignore_disabled_input: bool,
18957 _: &mut Window,
18958 cx: &mut Context<Self>,
18959 ) -> Option<UTF16Selection> {
18960 // Prevent the IME menu from appearing when holding down an alphabetic key
18961 // while input is disabled.
18962 if !ignore_disabled_input && !self.input_enabled {
18963 return None;
18964 }
18965
18966 let selection = self.selections.newest::<OffsetUtf16>(cx);
18967 let range = selection.range();
18968
18969 Some(UTF16Selection {
18970 range: range.start.0..range.end.0,
18971 reversed: selection.reversed,
18972 })
18973 }
18974
18975 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18976 let snapshot = self.buffer.read(cx).read(cx);
18977 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18978 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18979 }
18980
18981 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18982 self.clear_highlights::<InputComposition>(cx);
18983 self.ime_transaction.take();
18984 }
18985
18986 fn replace_text_in_range(
18987 &mut self,
18988 range_utf16: Option<Range<usize>>,
18989 text: &str,
18990 window: &mut Window,
18991 cx: &mut Context<Self>,
18992 ) {
18993 if !self.input_enabled {
18994 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18995 return;
18996 }
18997
18998 self.transact(window, cx, |this, window, cx| {
18999 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19000 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19001 Some(this.selection_replacement_ranges(range_utf16, cx))
19002 } else {
19003 this.marked_text_ranges(cx)
19004 };
19005
19006 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19007 let newest_selection_id = this.selections.newest_anchor().id;
19008 this.selections
19009 .all::<OffsetUtf16>(cx)
19010 .iter()
19011 .zip(ranges_to_replace.iter())
19012 .find_map(|(selection, range)| {
19013 if selection.id == newest_selection_id {
19014 Some(
19015 (range.start.0 as isize - selection.head().0 as isize)
19016 ..(range.end.0 as isize - selection.head().0 as isize),
19017 )
19018 } else {
19019 None
19020 }
19021 })
19022 });
19023
19024 cx.emit(EditorEvent::InputHandled {
19025 utf16_range_to_replace: range_to_replace,
19026 text: text.into(),
19027 });
19028
19029 if let Some(new_selected_ranges) = new_selected_ranges {
19030 this.change_selections(None, window, cx, |selections| {
19031 selections.select_ranges(new_selected_ranges)
19032 });
19033 this.backspace(&Default::default(), window, cx);
19034 }
19035
19036 this.handle_input(text, window, cx);
19037 });
19038
19039 if let Some(transaction) = self.ime_transaction {
19040 self.buffer.update(cx, |buffer, cx| {
19041 buffer.group_until_transaction(transaction, cx);
19042 });
19043 }
19044
19045 self.unmark_text(window, cx);
19046 }
19047
19048 fn replace_and_mark_text_in_range(
19049 &mut self,
19050 range_utf16: Option<Range<usize>>,
19051 text: &str,
19052 new_selected_range_utf16: Option<Range<usize>>,
19053 window: &mut Window,
19054 cx: &mut Context<Self>,
19055 ) {
19056 if !self.input_enabled {
19057 return;
19058 }
19059
19060 let transaction = self.transact(window, cx, |this, window, cx| {
19061 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19062 let snapshot = this.buffer.read(cx).read(cx);
19063 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19064 for marked_range in &mut marked_ranges {
19065 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19066 marked_range.start.0 += relative_range_utf16.start;
19067 marked_range.start =
19068 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19069 marked_range.end =
19070 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19071 }
19072 }
19073 Some(marked_ranges)
19074 } else if let Some(range_utf16) = range_utf16 {
19075 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19076 Some(this.selection_replacement_ranges(range_utf16, cx))
19077 } else {
19078 None
19079 };
19080
19081 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
19082 let newest_selection_id = this.selections.newest_anchor().id;
19083 this.selections
19084 .all::<OffsetUtf16>(cx)
19085 .iter()
19086 .zip(ranges_to_replace.iter())
19087 .find_map(|(selection, range)| {
19088 if selection.id == newest_selection_id {
19089 Some(
19090 (range.start.0 as isize - selection.head().0 as isize)
19091 ..(range.end.0 as isize - selection.head().0 as isize),
19092 )
19093 } else {
19094 None
19095 }
19096 })
19097 });
19098
19099 cx.emit(EditorEvent::InputHandled {
19100 utf16_range_to_replace: range_to_replace,
19101 text: text.into(),
19102 });
19103
19104 if let Some(ranges) = ranges_to_replace {
19105 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
19106 }
19107
19108 let marked_ranges = {
19109 let snapshot = this.buffer.read(cx).read(cx);
19110 this.selections
19111 .disjoint_anchors()
19112 .iter()
19113 .map(|selection| {
19114 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
19115 })
19116 .collect::<Vec<_>>()
19117 };
19118
19119 if text.is_empty() {
19120 this.unmark_text(window, cx);
19121 } else {
19122 this.highlight_text::<InputComposition>(
19123 marked_ranges.clone(),
19124 HighlightStyle {
19125 underline: Some(UnderlineStyle {
19126 thickness: px(1.),
19127 color: None,
19128 wavy: false,
19129 }),
19130 ..Default::default()
19131 },
19132 cx,
19133 );
19134 }
19135
19136 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
19137 let use_autoclose = this.use_autoclose;
19138 let use_auto_surround = this.use_auto_surround;
19139 this.set_use_autoclose(false);
19140 this.set_use_auto_surround(false);
19141 this.handle_input(text, window, cx);
19142 this.set_use_autoclose(use_autoclose);
19143 this.set_use_auto_surround(use_auto_surround);
19144
19145 if let Some(new_selected_range) = new_selected_range_utf16 {
19146 let snapshot = this.buffer.read(cx).read(cx);
19147 let new_selected_ranges = marked_ranges
19148 .into_iter()
19149 .map(|marked_range| {
19150 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
19151 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
19152 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
19153 snapshot.clip_offset_utf16(new_start, Bias::Left)
19154 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
19155 })
19156 .collect::<Vec<_>>();
19157
19158 drop(snapshot);
19159 this.change_selections(None, window, cx, |selections| {
19160 selections.select_ranges(new_selected_ranges)
19161 });
19162 }
19163 });
19164
19165 self.ime_transaction = self.ime_transaction.or(transaction);
19166 if let Some(transaction) = self.ime_transaction {
19167 self.buffer.update(cx, |buffer, cx| {
19168 buffer.group_until_transaction(transaction, cx);
19169 });
19170 }
19171
19172 if self.text_highlights::<InputComposition>(cx).is_none() {
19173 self.ime_transaction.take();
19174 }
19175 }
19176
19177 fn bounds_for_range(
19178 &mut self,
19179 range_utf16: Range<usize>,
19180 element_bounds: gpui::Bounds<Pixels>,
19181 window: &mut Window,
19182 cx: &mut Context<Self>,
19183 ) -> Option<gpui::Bounds<Pixels>> {
19184 let text_layout_details = self.text_layout_details(window);
19185 let gpui::Size {
19186 width: em_width,
19187 height: line_height,
19188 } = self.character_size(window);
19189
19190 let snapshot = self.snapshot(window, cx);
19191 let scroll_position = snapshot.scroll_position();
19192 let scroll_left = scroll_position.x * em_width;
19193
19194 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
19195 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
19196 + self.gutter_dimensions.width
19197 + self.gutter_dimensions.margin;
19198 let y = line_height * (start.row().as_f32() - scroll_position.y);
19199
19200 Some(Bounds {
19201 origin: element_bounds.origin + point(x, y),
19202 size: size(em_width, line_height),
19203 })
19204 }
19205
19206 fn character_index_for_point(
19207 &mut self,
19208 point: gpui::Point<Pixels>,
19209 _window: &mut Window,
19210 _cx: &mut Context<Self>,
19211 ) -> Option<usize> {
19212 let position_map = self.last_position_map.as_ref()?;
19213 if !position_map.text_hitbox.contains(&point) {
19214 return None;
19215 }
19216 let display_point = position_map.point_for_position(point).previous_valid;
19217 let anchor = position_map
19218 .snapshot
19219 .display_point_to_anchor(display_point, Bias::Left);
19220 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
19221 Some(utf16_offset.0)
19222 }
19223}
19224
19225trait SelectionExt {
19226 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
19227 fn spanned_rows(
19228 &self,
19229 include_end_if_at_line_start: bool,
19230 map: &DisplaySnapshot,
19231 ) -> Range<MultiBufferRow>;
19232}
19233
19234impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
19235 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
19236 let start = self
19237 .start
19238 .to_point(&map.buffer_snapshot)
19239 .to_display_point(map);
19240 let end = self
19241 .end
19242 .to_point(&map.buffer_snapshot)
19243 .to_display_point(map);
19244 if self.reversed {
19245 end..start
19246 } else {
19247 start..end
19248 }
19249 }
19250
19251 fn spanned_rows(
19252 &self,
19253 include_end_if_at_line_start: bool,
19254 map: &DisplaySnapshot,
19255 ) -> Range<MultiBufferRow> {
19256 let start = self.start.to_point(&map.buffer_snapshot);
19257 let mut end = self.end.to_point(&map.buffer_snapshot);
19258 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
19259 end.row -= 1;
19260 }
19261
19262 let buffer_start = map.prev_line_boundary(start).0;
19263 let buffer_end = map.next_line_boundary(end).0;
19264 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
19265 }
19266}
19267
19268impl<T: InvalidationRegion> InvalidationStack<T> {
19269 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
19270 where
19271 S: Clone + ToOffset,
19272 {
19273 while let Some(region) = self.last() {
19274 let all_selections_inside_invalidation_ranges =
19275 if selections.len() == region.ranges().len() {
19276 selections
19277 .iter()
19278 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
19279 .all(|(selection, invalidation_range)| {
19280 let head = selection.head().to_offset(buffer);
19281 invalidation_range.start <= head && invalidation_range.end >= head
19282 })
19283 } else {
19284 false
19285 };
19286
19287 if all_selections_inside_invalidation_ranges {
19288 break;
19289 } else {
19290 self.pop();
19291 }
19292 }
19293 }
19294}
19295
19296impl<T> Default for InvalidationStack<T> {
19297 fn default() -> Self {
19298 Self(Default::default())
19299 }
19300}
19301
19302impl<T> Deref for InvalidationStack<T> {
19303 type Target = Vec<T>;
19304
19305 fn deref(&self) -> &Self::Target {
19306 &self.0
19307 }
19308}
19309
19310impl<T> DerefMut for InvalidationStack<T> {
19311 fn deref_mut(&mut self) -> &mut Self::Target {
19312 &mut self.0
19313 }
19314}
19315
19316impl InvalidationRegion for SnippetState {
19317 fn ranges(&self) -> &[Range<Anchor>] {
19318 &self.ranges[self.active_index]
19319 }
19320}
19321
19322pub fn diagnostic_block_renderer(
19323 diagnostic: Diagnostic,
19324 max_message_rows: Option<u8>,
19325 allow_closing: bool,
19326) -> RenderBlock {
19327 let (text_without_backticks, code_ranges) =
19328 highlight_diagnostic_message(&diagnostic, max_message_rows);
19329
19330 Arc::new(move |cx: &mut BlockContext| {
19331 let group_id: SharedString = cx.block_id.to_string().into();
19332
19333 let mut text_style = cx.window.text_style().clone();
19334 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
19335 let theme_settings = ThemeSettings::get_global(cx);
19336 text_style.font_family = theme_settings.buffer_font.family.clone();
19337 text_style.font_style = theme_settings.buffer_font.style;
19338 text_style.font_features = theme_settings.buffer_font.features.clone();
19339 text_style.font_weight = theme_settings.buffer_font.weight;
19340
19341 let multi_line_diagnostic = diagnostic.message.contains('\n');
19342
19343 let buttons = |diagnostic: &Diagnostic| {
19344 if multi_line_diagnostic {
19345 v_flex()
19346 } else {
19347 h_flex()
19348 }
19349 .when(allow_closing, |div| {
19350 div.children(diagnostic.is_primary.then(|| {
19351 IconButton::new("close-block", IconName::XCircle)
19352 .icon_color(Color::Muted)
19353 .size(ButtonSize::Compact)
19354 .style(ButtonStyle::Transparent)
19355 .visible_on_hover(group_id.clone())
19356 .on_click(move |_click, window, cx| {
19357 window.dispatch_action(Box::new(Cancel), cx)
19358 })
19359 .tooltip(|window, cx| {
19360 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19361 })
19362 }))
19363 })
19364 .child(
19365 IconButton::new("copy-block", IconName::Copy)
19366 .icon_color(Color::Muted)
19367 .size(ButtonSize::Compact)
19368 .style(ButtonStyle::Transparent)
19369 .visible_on_hover(group_id.clone())
19370 .on_click({
19371 let message = diagnostic.message.clone();
19372 move |_click, _, cx| {
19373 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19374 }
19375 })
19376 .tooltip(Tooltip::text("Copy diagnostic message")),
19377 )
19378 };
19379
19380 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19381 AvailableSpace::min_size(),
19382 cx.window,
19383 cx.app,
19384 );
19385
19386 h_flex()
19387 .id(cx.block_id)
19388 .group(group_id.clone())
19389 .relative()
19390 .size_full()
19391 .block_mouse_down()
19392 .pl(cx.gutter_dimensions.width)
19393 .w(cx.max_width - cx.gutter_dimensions.full_width())
19394 .child(
19395 div()
19396 .flex()
19397 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19398 .flex_shrink(),
19399 )
19400 .child(buttons(&diagnostic))
19401 .child(div().flex().flex_shrink_0().child(
19402 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19403 &text_style,
19404 code_ranges.iter().map(|range| {
19405 (
19406 range.clone(),
19407 HighlightStyle {
19408 font_weight: Some(FontWeight::BOLD),
19409 ..Default::default()
19410 },
19411 )
19412 }),
19413 ),
19414 ))
19415 .into_any_element()
19416 })
19417}
19418
19419fn inline_completion_edit_text(
19420 current_snapshot: &BufferSnapshot,
19421 edits: &[(Range<Anchor>, String)],
19422 edit_preview: &EditPreview,
19423 include_deletions: bool,
19424 cx: &App,
19425) -> HighlightedText {
19426 let edits = edits
19427 .iter()
19428 .map(|(anchor, text)| {
19429 (
19430 anchor.start.text_anchor..anchor.end.text_anchor,
19431 text.clone(),
19432 )
19433 })
19434 .collect::<Vec<_>>();
19435
19436 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19437}
19438
19439pub fn highlight_diagnostic_message(
19440 diagnostic: &Diagnostic,
19441 mut max_message_rows: Option<u8>,
19442) -> (SharedString, Vec<Range<usize>>) {
19443 let mut text_without_backticks = String::new();
19444 let mut code_ranges = Vec::new();
19445
19446 if let Some(source) = &diagnostic.source {
19447 text_without_backticks.push_str(source);
19448 code_ranges.push(0..source.len());
19449 text_without_backticks.push_str(": ");
19450 }
19451
19452 let mut prev_offset = 0;
19453 let mut in_code_block = false;
19454 let has_row_limit = max_message_rows.is_some();
19455 let mut newline_indices = diagnostic
19456 .message
19457 .match_indices('\n')
19458 .filter(|_| has_row_limit)
19459 .map(|(ix, _)| ix)
19460 .fuse()
19461 .peekable();
19462
19463 for (quote_ix, _) in diagnostic
19464 .message
19465 .match_indices('`')
19466 .chain([(diagnostic.message.len(), "")])
19467 {
19468 let mut first_newline_ix = None;
19469 let mut last_newline_ix = None;
19470 while let Some(newline_ix) = newline_indices.peek() {
19471 if *newline_ix < quote_ix {
19472 if first_newline_ix.is_none() {
19473 first_newline_ix = Some(*newline_ix);
19474 }
19475 last_newline_ix = Some(*newline_ix);
19476
19477 if let Some(rows_left) = &mut max_message_rows {
19478 if *rows_left == 0 {
19479 break;
19480 } else {
19481 *rows_left -= 1;
19482 }
19483 }
19484 let _ = newline_indices.next();
19485 } else {
19486 break;
19487 }
19488 }
19489 let prev_len = text_without_backticks.len();
19490 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19491 text_without_backticks.push_str(new_text);
19492 if in_code_block {
19493 code_ranges.push(prev_len..text_without_backticks.len());
19494 }
19495 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19496 in_code_block = !in_code_block;
19497 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19498 text_without_backticks.push_str("...");
19499 break;
19500 }
19501 }
19502
19503 (text_without_backticks.into(), code_ranges)
19504}
19505
19506fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19507 match severity {
19508 DiagnosticSeverity::ERROR => colors.error,
19509 DiagnosticSeverity::WARNING => colors.warning,
19510 DiagnosticSeverity::INFORMATION => colors.info,
19511 DiagnosticSeverity::HINT => colors.info,
19512 _ => colors.ignored,
19513 }
19514}
19515
19516pub fn styled_runs_for_code_label<'a>(
19517 label: &'a CodeLabel,
19518 syntax_theme: &'a theme::SyntaxTheme,
19519) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19520 let fade_out = HighlightStyle {
19521 fade_out: Some(0.35),
19522 ..Default::default()
19523 };
19524
19525 let mut prev_end = label.filter_range.end;
19526 label
19527 .runs
19528 .iter()
19529 .enumerate()
19530 .flat_map(move |(ix, (range, highlight_id))| {
19531 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19532 style
19533 } else {
19534 return Default::default();
19535 };
19536 let mut muted_style = style;
19537 muted_style.highlight(fade_out);
19538
19539 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19540 if range.start >= label.filter_range.end {
19541 if range.start > prev_end {
19542 runs.push((prev_end..range.start, fade_out));
19543 }
19544 runs.push((range.clone(), muted_style));
19545 } else if range.end <= label.filter_range.end {
19546 runs.push((range.clone(), style));
19547 } else {
19548 runs.push((range.start..label.filter_range.end, style));
19549 runs.push((label.filter_range.end..range.end, muted_style));
19550 }
19551 prev_end = cmp::max(prev_end, range.end);
19552
19553 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19554 runs.push((prev_end..label.text.len(), fade_out));
19555 }
19556
19557 runs
19558 })
19559}
19560
19561pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19562 let mut prev_index = 0;
19563 let mut prev_codepoint: Option<char> = None;
19564 text.char_indices()
19565 .chain([(text.len(), '\0')])
19566 .filter_map(move |(index, codepoint)| {
19567 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19568 let is_boundary = index == text.len()
19569 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19570 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19571 if is_boundary {
19572 let chunk = &text[prev_index..index];
19573 prev_index = index;
19574 Some(chunk)
19575 } else {
19576 None
19577 }
19578 })
19579}
19580
19581pub trait RangeToAnchorExt: Sized {
19582 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19583
19584 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19585 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19586 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19587 }
19588}
19589
19590impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19591 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19592 let start_offset = self.start.to_offset(snapshot);
19593 let end_offset = self.end.to_offset(snapshot);
19594 if start_offset == end_offset {
19595 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19596 } else {
19597 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19598 }
19599 }
19600}
19601
19602pub trait RowExt {
19603 fn as_f32(&self) -> f32;
19604
19605 fn next_row(&self) -> Self;
19606
19607 fn previous_row(&self) -> Self;
19608
19609 fn minus(&self, other: Self) -> u32;
19610}
19611
19612impl RowExt for DisplayRow {
19613 fn as_f32(&self) -> f32 {
19614 self.0 as f32
19615 }
19616
19617 fn next_row(&self) -> Self {
19618 Self(self.0 + 1)
19619 }
19620
19621 fn previous_row(&self) -> Self {
19622 Self(self.0.saturating_sub(1))
19623 }
19624
19625 fn minus(&self, other: Self) -> u32 {
19626 self.0 - other.0
19627 }
19628}
19629
19630impl RowExt for MultiBufferRow {
19631 fn as_f32(&self) -> f32 {
19632 self.0 as f32
19633 }
19634
19635 fn next_row(&self) -> Self {
19636 Self(self.0 + 1)
19637 }
19638
19639 fn previous_row(&self) -> Self {
19640 Self(self.0.saturating_sub(1))
19641 }
19642
19643 fn minus(&self, other: Self) -> u32 {
19644 self.0 - other.0
19645 }
19646}
19647
19648trait RowRangeExt {
19649 type Row;
19650
19651 fn len(&self) -> usize;
19652
19653 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19654}
19655
19656impl RowRangeExt for Range<MultiBufferRow> {
19657 type Row = MultiBufferRow;
19658
19659 fn len(&self) -> usize {
19660 (self.end.0 - self.start.0) as usize
19661 }
19662
19663 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19664 (self.start.0..self.end.0).map(MultiBufferRow)
19665 }
19666}
19667
19668impl RowRangeExt for Range<DisplayRow> {
19669 type Row = DisplayRow;
19670
19671 fn len(&self) -> usize {
19672 (self.end.0 - self.start.0) as usize
19673 }
19674
19675 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19676 (self.start.0..self.end.0).map(DisplayRow)
19677 }
19678}
19679
19680/// If select range has more than one line, we
19681/// just point the cursor to range.start.
19682fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19683 if range.start.row == range.end.row {
19684 range
19685 } else {
19686 range.start..range.start
19687 }
19688}
19689pub struct KillRing(ClipboardItem);
19690impl Global for KillRing {}
19691
19692const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19693
19694struct BreakpointPromptEditor {
19695 pub(crate) prompt: Entity<Editor>,
19696 editor: WeakEntity<Editor>,
19697 breakpoint_anchor: Anchor,
19698 breakpoint: Breakpoint,
19699 block_ids: HashSet<CustomBlockId>,
19700 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19701 _subscriptions: Vec<Subscription>,
19702}
19703
19704impl BreakpointPromptEditor {
19705 const MAX_LINES: u8 = 4;
19706
19707 fn new(
19708 editor: WeakEntity<Editor>,
19709 breakpoint_anchor: Anchor,
19710 breakpoint: Breakpoint,
19711 window: &mut Window,
19712 cx: &mut Context<Self>,
19713 ) -> Self {
19714 let buffer = cx.new(|cx| {
19715 Buffer::local(
19716 breakpoint
19717 .kind
19718 .log_message()
19719 .map(|msg| msg.to_string())
19720 .unwrap_or_default(),
19721 cx,
19722 )
19723 });
19724 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19725
19726 let prompt = cx.new(|cx| {
19727 let mut prompt = Editor::new(
19728 EditorMode::AutoHeight {
19729 max_lines: Self::MAX_LINES as usize,
19730 },
19731 buffer,
19732 None,
19733 window,
19734 cx,
19735 );
19736 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19737 prompt.set_show_cursor_when_unfocused(false, cx);
19738 prompt.set_placeholder_text(
19739 "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19740 cx,
19741 );
19742
19743 prompt
19744 });
19745
19746 Self {
19747 prompt,
19748 editor,
19749 breakpoint_anchor,
19750 breakpoint,
19751 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19752 block_ids: Default::default(),
19753 _subscriptions: vec![],
19754 }
19755 }
19756
19757 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19758 self.block_ids.extend(block_ids)
19759 }
19760
19761 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19762 if let Some(editor) = self.editor.upgrade() {
19763 let log_message = self
19764 .prompt
19765 .read(cx)
19766 .buffer
19767 .read(cx)
19768 .as_singleton()
19769 .expect("A multi buffer in breakpoint prompt isn't possible")
19770 .read(cx)
19771 .as_rope()
19772 .to_string();
19773
19774 editor.update(cx, |editor, cx| {
19775 editor.edit_breakpoint_at_anchor(
19776 self.breakpoint_anchor,
19777 self.breakpoint.clone(),
19778 BreakpointEditAction::EditLogMessage(log_message.into()),
19779 cx,
19780 );
19781
19782 editor.remove_blocks(self.block_ids.clone(), None, cx);
19783 cx.focus_self(window);
19784 });
19785 }
19786 }
19787
19788 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19789 self.editor
19790 .update(cx, |editor, cx| {
19791 editor.remove_blocks(self.block_ids.clone(), None, cx);
19792 window.focus(&editor.focus_handle);
19793 })
19794 .log_err();
19795 }
19796
19797 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19798 let settings = ThemeSettings::get_global(cx);
19799 let text_style = TextStyle {
19800 color: if self.prompt.read(cx).read_only(cx) {
19801 cx.theme().colors().text_disabled
19802 } else {
19803 cx.theme().colors().text
19804 },
19805 font_family: settings.buffer_font.family.clone(),
19806 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19807 font_size: settings.buffer_font_size(cx).into(),
19808 font_weight: settings.buffer_font.weight,
19809 line_height: relative(settings.buffer_line_height.value()),
19810 ..Default::default()
19811 };
19812 EditorElement::new(
19813 &self.prompt,
19814 EditorStyle {
19815 background: cx.theme().colors().editor_background,
19816 local_player: cx.theme().players().local(),
19817 text: text_style,
19818 ..Default::default()
19819 },
19820 )
19821 }
19822}
19823
19824impl Render for BreakpointPromptEditor {
19825 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19826 let gutter_dimensions = *self.gutter_dimensions.lock();
19827 h_flex()
19828 .key_context("Editor")
19829 .bg(cx.theme().colors().editor_background)
19830 .border_y_1()
19831 .border_color(cx.theme().status().info_border)
19832 .size_full()
19833 .py(window.line_height() / 2.5)
19834 .on_action(cx.listener(Self::confirm))
19835 .on_action(cx.listener(Self::cancel))
19836 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19837 .child(div().flex_1().child(self.render_prompt_editor(cx)))
19838 }
19839}
19840
19841impl Focusable for BreakpointPromptEditor {
19842 fn focus_handle(&self, cx: &App) -> FocusHandle {
19843 self.prompt.focus_handle(cx)
19844 }
19845}
19846
19847fn all_edits_insertions_or_deletions(
19848 edits: &Vec<(Range<Anchor>, String)>,
19849 snapshot: &MultiBufferSnapshot,
19850) -> bool {
19851 let mut all_insertions = true;
19852 let mut all_deletions = true;
19853
19854 for (range, new_text) in edits.iter() {
19855 let range_is_empty = range.to_offset(&snapshot).is_empty();
19856 let text_is_empty = new_text.is_empty();
19857
19858 if range_is_empty != text_is_empty {
19859 if range_is_empty {
19860 all_deletions = false;
19861 } else {
19862 all_insertions = false;
19863 }
19864 } else {
19865 return false;
19866 }
19867
19868 if !all_insertions && !all_deletions {
19869 return false;
19870 }
19871 }
19872 all_insertions || all_deletions
19873}
19874
19875struct MissingEditPredictionKeybindingTooltip;
19876
19877impl Render for MissingEditPredictionKeybindingTooltip {
19878 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
19879 ui::tooltip_container(window, cx, |container, _, cx| {
19880 container
19881 .flex_shrink_0()
19882 .max_w_80()
19883 .min_h(rems_from_px(124.))
19884 .justify_between()
19885 .child(
19886 v_flex()
19887 .flex_1()
19888 .text_ui_sm(cx)
19889 .child(Label::new("Conflict with Accept Keybinding"))
19890 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19891 )
19892 .child(
19893 h_flex()
19894 .pb_1()
19895 .gap_1()
19896 .items_end()
19897 .w_full()
19898 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19899 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19900 }))
19901 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19902 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19903 })),
19904 )
19905 })
19906 }
19907}
19908
19909#[derive(Debug, Clone, Copy, PartialEq)]
19910pub struct LineHighlight {
19911 pub background: Background,
19912 pub border: Option<gpui::Hsla>,
19913}
19914
19915impl From<Hsla> for LineHighlight {
19916 fn from(hsla: Hsla) -> Self {
19917 Self {
19918 background: hsla.into(),
19919 border: None,
19920 }
19921 }
19922}
19923
19924impl From<Background> for LineHighlight {
19925 fn from(background: Background) -> Self {
19926 Self {
19927 background,
19928 border: None,
19929 }
19930 }
19931}