1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blink_manager;
17mod clangd_ext;
18mod code_context_menus;
19pub mod commit_tooltip;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod jsx_tag_auto_close;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51pub(crate) use actions::*;
52pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use buffer_diff::DiffHunkStatus;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::{layout_line, AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use feature_flags::{Debugger, FeatureFlagAppExt};
72use futures::{
73 future::{self, join, Shared},
74 FutureExt,
75};
76use fuzzy::StringMatchCandidate;
77
78use ::git::Restore;
79use code_context_menus::{
80 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
81 CompletionsMenu, ContextMenuOrigin,
82};
83use git::blame::GitBlame;
84use gpui::{
85 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
86 AnimationExt, AnyElement, App, AppContext, AsyncWindowContext, AvailableSpace, Background,
87 Bounds, ClickEvent, ClipboardEntry, ClipboardItem, Context, DispatchPhase, Edges, Entity,
88 EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight,
89 Global, HighlightStyle, Hsla, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad,
90 ParentElement, Pixels, Render, SharedString, Size, Stateful, Styled, StyledText, Subscription,
91 Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
92 WeakEntity, WeakFocusHandle, Window,
93};
94use highlight_matching_bracket::refresh_matching_bracket_highlights;
95use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
96use hover_popover::{hide_hover, HoverState};
97use indent_guides::ActiveIndentGuidesState;
98use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
99pub use inline_completion::Direction;
100use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
101pub use items::MAX_TAB_TITLE_LEN;
102use itertools::Itertools;
103use language::{
104 language_settings::{
105 self, all_language_settings, language_settings, InlayHintSettings, RewrapBehavior,
106 WordsCompletionMode,
107 },
108 point_from_lsp, text_diff_with_options, AutoindentMode, BracketMatch, BracketPair, Buffer,
109 Capability, CharKind, CodeLabel, CursorShape, Diagnostic, DiffOptions, EditPredictionsMode,
110 EditPreview, HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point,
111 Selection, SelectionGoal, TextObject, TransactionId, TreeSitterOptions, WordsQuery,
112};
113use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
114use linked_editing_ranges::refresh_linked_ranges;
115use mouse_context_menu::MouseContextMenu;
116use persistence::DB;
117use project::{
118 debugger::breakpoint_store::{BreakpointEditAction, BreakpointStore, BreakpointStoreEvent},
119 ProjectPath,
120};
121
122pub use proposed_changes_editor::{
123 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
124};
125use smallvec::smallvec;
126use std::iter::Peekable;
127use task::{ResolvedTask, TaskTemplate, TaskVariables};
128
129pub use lsp::CompletionContext;
130use lsp::{
131 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
132 InsertTextFormat, LanguageServerId, LanguageServerName,
133};
134
135use language::BufferSnapshot;
136use movement::TextLayoutDetails;
137pub use multi_buffer::{
138 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
139 ToOffset, ToPoint,
140};
141use multi_buffer::{
142 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
143 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
144};
145use parking_lot::Mutex;
146use project::{
147 debugger::breakpoint_store::{Breakpoint, BreakpointKind},
148 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
149 project_settings::{GitGutterSetting, ProjectSettings},
150 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
151 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
152 TaskSourceKind,
153};
154use rand::prelude::*;
155use rpc::{proto::*, ErrorExt};
156use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
157use selections_collection::{
158 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
159};
160use serde::{Deserialize, Serialize};
161use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
162use smallvec::SmallVec;
163use snippet::Snippet;
164use std::sync::Arc;
165use std::{
166 any::TypeId,
167 borrow::Cow,
168 cell::RefCell,
169 cmp::{self, Ordering, Reverse},
170 mem,
171 num::NonZeroU32,
172 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
173 path::{Path, PathBuf},
174 rc::Rc,
175 time::{Duration, Instant},
176};
177pub use sum_tree::Bias;
178use sum_tree::TreeMap;
179use text::{BufferId, OffsetUtf16, Rope};
180use theme::{
181 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
182 ThemeColors, ThemeSettings,
183};
184use ui::{
185 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
186 Tooltip,
187};
188use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
189use workspace::{
190 item::{ItemHandle, PreviewTabsSettings},
191 ItemId, RestoreOnStartupBehavior,
192};
193use workspace::{
194 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
195 WorkspaceSettings,
196};
197use workspace::{
198 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
199};
200use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
201
202use crate::hover_links::{find_url, find_url_from_range};
203use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
204
205pub const FILE_HEADER_HEIGHT: u32 = 2;
206pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
207pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
208const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
209const MAX_LINE_LEN: usize = 1024;
210const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
211const MAX_SELECTION_HISTORY_LEN: usize = 1024;
212pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
213#[doc(hidden)]
214pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
215
216pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
217pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
218pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
219
220pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
221pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
222pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
223
224const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
225 alt: true,
226 shift: true,
227 control: false,
228 platform: false,
229 function: false,
230};
231
232#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
233pub enum InlayId {
234 InlineCompletion(usize),
235 Hint(usize),
236}
237
238impl InlayId {
239 fn id(&self) -> usize {
240 match self {
241 Self::InlineCompletion(id) => *id,
242 Self::Hint(id) => *id,
243 }
244 }
245}
246
247pub enum DebugCurrentRowHighlight {}
248enum DocumentHighlightRead {}
249enum DocumentHighlightWrite {}
250enum InputComposition {}
251enum SelectedTextHighlight {}
252
253#[derive(Debug, Copy, Clone, PartialEq, Eq)]
254pub enum Navigated {
255 Yes,
256 No,
257}
258
259impl Navigated {
260 pub fn from_bool(yes: bool) -> Navigated {
261 if yes {
262 Navigated::Yes
263 } else {
264 Navigated::No
265 }
266 }
267}
268
269#[derive(Debug, Clone, PartialEq, Eq)]
270enum DisplayDiffHunk {
271 Folded {
272 display_row: DisplayRow,
273 },
274 Unfolded {
275 is_created_file: bool,
276 diff_base_byte_range: Range<usize>,
277 display_row_range: Range<DisplayRow>,
278 multi_buffer_range: Range<Anchor>,
279 status: DiffHunkStatus,
280 },
281}
282
283pub fn init_settings(cx: &mut App) {
284 EditorSettings::register(cx);
285}
286
287pub fn init(cx: &mut App) {
288 init_settings(cx);
289
290 workspace::register_project_item::<Editor>(cx);
291 workspace::FollowableViewRegistry::register::<Editor>(cx);
292 workspace::register_serializable_item::<Editor>(cx);
293
294 cx.observe_new(
295 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
296 workspace.register_action(Editor::new_file);
297 workspace.register_action(Editor::new_file_vertical);
298 workspace.register_action(Editor::new_file_horizontal);
299 workspace.register_action(Editor::cancel_language_server_work);
300 },
301 )
302 .detach();
303
304 cx.on_action(move |_: &workspace::NewFile, cx| {
305 let app_state = workspace::AppState::global(cx);
306 if let Some(app_state) = app_state.upgrade() {
307 workspace::open_new(
308 Default::default(),
309 app_state,
310 cx,
311 |workspace, window, cx| {
312 Editor::new_file(workspace, &Default::default(), window, cx)
313 },
314 )
315 .detach();
316 }
317 });
318 cx.on_action(move |_: &workspace::NewWindow, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(
322 Default::default(),
323 app_state,
324 cx,
325 |workspace, window, cx| {
326 cx.activate(true);
327 Editor::new_file(workspace, &Default::default(), window, cx)
328 },
329 )
330 .detach();
331 }
332 });
333}
334
335pub struct SearchWithinRange;
336
337trait InvalidationRegion {
338 fn ranges(&self) -> &[Range<Anchor>];
339}
340
341#[derive(Clone, Debug, PartialEq)]
342pub enum SelectPhase {
343 Begin {
344 position: DisplayPoint,
345 add: bool,
346 click_count: usize,
347 },
348 BeginColumnar {
349 position: DisplayPoint,
350 reset: bool,
351 goal_column: u32,
352 },
353 Extend {
354 position: DisplayPoint,
355 click_count: usize,
356 },
357 Update {
358 position: DisplayPoint,
359 goal_column: u32,
360 scroll_delta: gpui::Point<f32>,
361 },
362 End,
363}
364
365#[derive(Clone, Debug)]
366pub enum SelectMode {
367 Character,
368 Word(Range<Anchor>),
369 Line(Range<Anchor>),
370 All,
371}
372
373#[derive(Copy, Clone, PartialEq, Eq, Debug)]
374pub enum EditorMode {
375 SingleLine { auto_width: bool },
376 AutoHeight { max_lines: usize },
377 Full,
378}
379
380#[derive(Copy, Clone, Debug)]
381pub enum SoftWrap {
382 /// Prefer not to wrap at all.
383 ///
384 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
385 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
386 GitDiff,
387 /// Prefer a single line generally, unless an overly long line is encountered.
388 None,
389 /// Soft wrap lines that exceed the editor width.
390 EditorWidth,
391 /// Soft wrap lines at the preferred line length.
392 Column(u32),
393 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
394 Bounded(u32),
395}
396
397#[derive(Clone)]
398pub struct EditorStyle {
399 pub background: Hsla,
400 pub local_player: PlayerColor,
401 pub text: TextStyle,
402 pub scrollbar_width: Pixels,
403 pub syntax: Arc<SyntaxTheme>,
404 pub status: StatusColors,
405 pub inlay_hints_style: HighlightStyle,
406 pub inline_completion_styles: InlineCompletionStyles,
407 pub unnecessary_code_fade: f32,
408}
409
410impl Default for EditorStyle {
411 fn default() -> Self {
412 Self {
413 background: Hsla::default(),
414 local_player: PlayerColor::default(),
415 text: TextStyle::default(),
416 scrollbar_width: Pixels::default(),
417 syntax: Default::default(),
418 // HACK: Status colors don't have a real default.
419 // We should look into removing the status colors from the editor
420 // style and retrieve them directly from the theme.
421 status: StatusColors::dark(),
422 inlay_hints_style: HighlightStyle::default(),
423 inline_completion_styles: InlineCompletionStyles {
424 insertion: HighlightStyle::default(),
425 whitespace: HighlightStyle::default(),
426 },
427 unnecessary_code_fade: Default::default(),
428 }
429 }
430}
431
432pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
433 let show_background = language_settings::language_settings(None, None, cx)
434 .inlay_hints
435 .show_background;
436
437 HighlightStyle {
438 color: Some(cx.theme().status().hint),
439 background_color: show_background.then(|| cx.theme().status().hint_background),
440 ..HighlightStyle::default()
441 }
442}
443
444pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
445 InlineCompletionStyles {
446 insertion: HighlightStyle {
447 color: Some(cx.theme().status().predictive),
448 ..HighlightStyle::default()
449 },
450 whitespace: HighlightStyle {
451 background_color: Some(cx.theme().status().created_background),
452 ..HighlightStyle::default()
453 },
454 }
455}
456
457type CompletionId = usize;
458
459pub(crate) enum EditDisplayMode {
460 TabAccept,
461 DiffPopover,
462 Inline,
463}
464
465enum InlineCompletion {
466 Edit {
467 edits: Vec<(Range<Anchor>, String)>,
468 edit_preview: Option<EditPreview>,
469 display_mode: EditDisplayMode,
470 snapshot: BufferSnapshot,
471 },
472 Move {
473 target: Anchor,
474 snapshot: BufferSnapshot,
475 },
476}
477
478struct InlineCompletionState {
479 inlay_ids: Vec<InlayId>,
480 completion: InlineCompletion,
481 completion_id: Option<SharedString>,
482 invalidation_range: Range<Anchor>,
483}
484
485enum EditPredictionSettings {
486 Disabled,
487 Enabled {
488 show_in_menu: bool,
489 preview_requires_modifier: bool,
490 },
491}
492
493enum InlineCompletionHighlight {}
494
495#[derive(Debug, Clone)]
496struct InlineDiagnostic {
497 message: SharedString,
498 group_id: usize,
499 is_primary: bool,
500 start: Point,
501 severity: DiagnosticSeverity,
502}
503
504pub enum MenuInlineCompletionsPolicy {
505 Never,
506 ByProvider,
507}
508
509pub enum EditPredictionPreview {
510 /// Modifier is not pressed
511 Inactive { released_too_fast: bool },
512 /// Modifier pressed
513 Active {
514 since: Instant,
515 previous_scroll_position: Option<ScrollAnchor>,
516 },
517}
518
519impl EditPredictionPreview {
520 pub fn released_too_fast(&self) -> bool {
521 match self {
522 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
523 EditPredictionPreview::Active { .. } => false,
524 }
525 }
526
527 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
528 if let EditPredictionPreview::Active {
529 previous_scroll_position,
530 ..
531 } = self
532 {
533 *previous_scroll_position = scroll_position;
534 }
535 }
536}
537
538#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
539struct EditorActionId(usize);
540
541impl EditorActionId {
542 pub fn post_inc(&mut self) -> Self {
543 let answer = self.0;
544
545 *self = Self(answer + 1);
546
547 Self(answer)
548 }
549}
550
551// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
552// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
553
554type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
555type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
556
557#[derive(Default)]
558struct ScrollbarMarkerState {
559 scrollbar_size: Size<Pixels>,
560 dirty: bool,
561 markers: Arc<[PaintQuad]>,
562 pending_refresh: Option<Task<Result<()>>>,
563}
564
565impl ScrollbarMarkerState {
566 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
567 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
568 }
569}
570
571#[derive(Clone, Debug)]
572struct RunnableTasks {
573 templates: Vec<(TaskSourceKind, TaskTemplate)>,
574 offset: multi_buffer::Anchor,
575 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
576 column: u32,
577 // Values of all named captures, including those starting with '_'
578 extra_variables: HashMap<String, String>,
579 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
580 context_range: Range<BufferOffset>,
581}
582
583impl RunnableTasks {
584 fn resolve<'a>(
585 &'a self,
586 cx: &'a task::TaskContext,
587 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
588 self.templates.iter().filter_map(|(kind, template)| {
589 template
590 .resolve_task(&kind.to_id_base(), cx)
591 .map(|task| (kind.clone(), task))
592 })
593 }
594}
595
596#[derive(Clone)]
597struct ResolvedTasks {
598 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
599 position: Anchor,
600}
601
602#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
603struct BufferOffset(usize);
604
605// Addons allow storing per-editor state in other crates (e.g. Vim)
606pub trait Addon: 'static {
607 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
608
609 fn render_buffer_header_controls(
610 &self,
611 _: &ExcerptInfo,
612 _: &Window,
613 _: &App,
614 ) -> Option<AnyElement> {
615 None
616 }
617
618 fn to_any(&self) -> &dyn std::any::Any;
619}
620
621/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
622///
623/// See the [module level documentation](self) for more information.
624pub struct Editor {
625 focus_handle: FocusHandle,
626 last_focused_descendant: Option<WeakFocusHandle>,
627 /// The text buffer being edited
628 buffer: Entity<MultiBuffer>,
629 /// Map of how text in the buffer should be displayed.
630 /// Handles soft wraps, folds, fake inlay text insertions, etc.
631 pub display_map: Entity<DisplayMap>,
632 pub selections: SelectionsCollection,
633 pub scroll_manager: ScrollManager,
634 /// When inline assist editors are linked, they all render cursors because
635 /// typing enters text into each of them, even the ones that aren't focused.
636 pub(crate) show_cursor_when_unfocused: bool,
637 columnar_selection_tail: Option<Anchor>,
638 add_selections_state: Option<AddSelectionsState>,
639 select_next_state: Option<SelectNextState>,
640 select_prev_state: Option<SelectNextState>,
641 selection_history: SelectionHistory,
642 autoclose_regions: Vec<AutocloseRegion>,
643 snippet_stack: InvalidationStack<SnippetState>,
644 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
645 ime_transaction: Option<TransactionId>,
646 active_diagnostics: Option<ActiveDiagnosticGroup>,
647 show_inline_diagnostics: bool,
648 inline_diagnostics_update: Task<()>,
649 inline_diagnostics_enabled: bool,
650 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
651 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
652 hard_wrap: Option<usize>,
653
654 // TODO: make this a access method
655 pub project: Option<Entity<Project>>,
656 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
657 completion_provider: Option<Box<dyn CompletionProvider>>,
658 collaboration_hub: Option<Box<dyn CollaborationHub>>,
659 blink_manager: Entity<BlinkManager>,
660 show_cursor_names: bool,
661 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
662 pub show_local_selections: bool,
663 mode: EditorMode,
664 show_breadcrumbs: bool,
665 show_gutter: bool,
666 show_scrollbars: bool,
667 show_line_numbers: Option<bool>,
668 use_relative_line_numbers: Option<bool>,
669 show_git_diff_gutter: Option<bool>,
670 show_code_actions: Option<bool>,
671 show_runnables: Option<bool>,
672 show_breakpoints: Option<bool>,
673 show_wrap_guides: Option<bool>,
674 show_indent_guides: Option<bool>,
675 placeholder_text: Option<Arc<str>>,
676 highlight_order: usize,
677 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
678 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
679 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
680 scrollbar_marker_state: ScrollbarMarkerState,
681 active_indent_guides_state: ActiveIndentGuidesState,
682 nav_history: Option<ItemNavHistory>,
683 context_menu: RefCell<Option<CodeContextMenu>>,
684 mouse_context_menu: Option<MouseContextMenu>,
685 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
686 signature_help_state: SignatureHelpState,
687 auto_signature_help: Option<bool>,
688 find_all_references_task_sources: Vec<Anchor>,
689 next_completion_id: CompletionId,
690 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
691 code_actions_task: Option<Task<Result<()>>>,
692 selection_highlight_task: Option<Task<()>>,
693 document_highlights_task: Option<Task<()>>,
694 linked_editing_range_task: Option<Task<Option<()>>>,
695 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
696 pending_rename: Option<RenameState>,
697 searchable: bool,
698 cursor_shape: CursorShape,
699 current_line_highlight: Option<CurrentLineHighlight>,
700 collapse_matches: bool,
701 autoindent_mode: Option<AutoindentMode>,
702 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
703 input_enabled: bool,
704 use_modal_editing: bool,
705 read_only: bool,
706 leader_peer_id: Option<PeerId>,
707 remote_id: Option<ViewId>,
708 hover_state: HoverState,
709 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
710 gutter_hovered: bool,
711 hovered_link_state: Option<HoveredLinkState>,
712 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
713 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
714 active_inline_completion: Option<InlineCompletionState>,
715 /// Used to prevent flickering as the user types while the menu is open
716 stale_inline_completion_in_menu: Option<InlineCompletionState>,
717 edit_prediction_settings: EditPredictionSettings,
718 inline_completions_hidden_for_vim_mode: bool,
719 show_inline_completions_override: Option<bool>,
720 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
721 edit_prediction_preview: EditPredictionPreview,
722 edit_prediction_indent_conflict: bool,
723 edit_prediction_requires_modifier_in_indent_conflict: bool,
724 inlay_hint_cache: InlayHintCache,
725 next_inlay_id: usize,
726 _subscriptions: Vec<Subscription>,
727 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
728 gutter_dimensions: GutterDimensions,
729 style: Option<EditorStyle>,
730 text_style_refinement: Option<TextStyleRefinement>,
731 next_editor_action_id: EditorActionId,
732 editor_actions:
733 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
734 use_autoclose: bool,
735 use_auto_surround: bool,
736 auto_replace_emoji_shortcode: bool,
737 jsx_tag_auto_close_enabled_in_any_buffer: bool,
738 show_git_blame_gutter: bool,
739 show_git_blame_inline: bool,
740 show_git_blame_inline_delay_task: Option<Task<()>>,
741 git_blame_inline_tooltip: Option<WeakEntity<crate::commit_tooltip::CommitTooltip>>,
742 git_blame_inline_enabled: bool,
743 serialize_dirty_buffers: bool,
744 show_selection_menu: Option<bool>,
745 blame: Option<Entity<GitBlame>>,
746 blame_subscription: Option<Subscription>,
747 custom_context_menu: Option<
748 Box<
749 dyn 'static
750 + Fn(
751 &mut Self,
752 DisplayPoint,
753 &mut Window,
754 &mut Context<Self>,
755 ) -> Option<Entity<ui::ContextMenu>>,
756 >,
757 >,
758 last_bounds: Option<Bounds<Pixels>>,
759 last_position_map: Option<Rc<PositionMap>>,
760 expect_bounds_change: Option<Bounds<Pixels>>,
761 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
762 tasks_update_task: Option<Task<()>>,
763 pub breakpoint_store: Option<Entity<BreakpointStore>>,
764 /// Allow's a user to create a breakpoint by selecting this indicator
765 /// It should be None while a user is not hovering over the gutter
766 /// Otherwise it represents the point that the breakpoint will be shown
767 pub gutter_breakpoint_indicator: Option<DisplayPoint>,
768 in_project_search: bool,
769 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
770 breadcrumb_header: Option<String>,
771 focused_block: Option<FocusedBlock>,
772 next_scroll_position: NextScrollCursorCenterTopBottom,
773 addons: HashMap<TypeId, Box<dyn Addon>>,
774 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
775 load_diff_task: Option<Shared<Task<()>>>,
776 selection_mark_mode: bool,
777 toggle_fold_multiple_buffers: Task<()>,
778 _scroll_cursor_center_top_bottom_task: Task<()>,
779 serialize_selections: Task<()>,
780}
781
782#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
783enum NextScrollCursorCenterTopBottom {
784 #[default]
785 Center,
786 Top,
787 Bottom,
788}
789
790impl NextScrollCursorCenterTopBottom {
791 fn next(&self) -> Self {
792 match self {
793 Self::Center => Self::Top,
794 Self::Top => Self::Bottom,
795 Self::Bottom => Self::Center,
796 }
797 }
798}
799
800#[derive(Clone)]
801pub struct EditorSnapshot {
802 pub mode: EditorMode,
803 show_gutter: bool,
804 show_line_numbers: Option<bool>,
805 show_git_diff_gutter: Option<bool>,
806 show_code_actions: Option<bool>,
807 show_runnables: Option<bool>,
808 show_breakpoints: Option<bool>,
809 git_blame_gutter_max_author_length: Option<usize>,
810 pub display_snapshot: DisplaySnapshot,
811 pub placeholder_text: Option<Arc<str>>,
812 is_focused: bool,
813 scroll_anchor: ScrollAnchor,
814 ongoing_scroll: OngoingScroll,
815 current_line_highlight: CurrentLineHighlight,
816 gutter_hovered: bool,
817}
818
819const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
820
821#[derive(Default, Debug, Clone, Copy)]
822pub struct GutterDimensions {
823 pub left_padding: Pixels,
824 pub right_padding: Pixels,
825 pub width: Pixels,
826 pub margin: Pixels,
827 pub git_blame_entries_width: Option<Pixels>,
828}
829
830impl GutterDimensions {
831 /// The full width of the space taken up by the gutter.
832 pub fn full_width(&self) -> Pixels {
833 self.margin + self.width
834 }
835
836 /// The width of the space reserved for the fold indicators,
837 /// use alongside 'justify_end' and `gutter_width` to
838 /// right align content with the line numbers
839 pub fn fold_area_width(&self) -> Pixels {
840 self.margin + self.right_padding
841 }
842}
843
844#[derive(Debug)]
845pub struct RemoteSelection {
846 pub replica_id: ReplicaId,
847 pub selection: Selection<Anchor>,
848 pub cursor_shape: CursorShape,
849 pub peer_id: PeerId,
850 pub line_mode: bool,
851 pub participant_index: Option<ParticipantIndex>,
852 pub user_name: Option<SharedString>,
853}
854
855#[derive(Clone, Debug)]
856struct SelectionHistoryEntry {
857 selections: Arc<[Selection<Anchor>]>,
858 select_next_state: Option<SelectNextState>,
859 select_prev_state: Option<SelectNextState>,
860 add_selections_state: Option<AddSelectionsState>,
861}
862
863enum SelectionHistoryMode {
864 Normal,
865 Undoing,
866 Redoing,
867}
868
869#[derive(Clone, PartialEq, Eq, Hash)]
870struct HoveredCursor {
871 replica_id: u16,
872 selection_id: usize,
873}
874
875impl Default for SelectionHistoryMode {
876 fn default() -> Self {
877 Self::Normal
878 }
879}
880
881#[derive(Default)]
882struct SelectionHistory {
883 #[allow(clippy::type_complexity)]
884 selections_by_transaction:
885 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
886 mode: SelectionHistoryMode,
887 undo_stack: VecDeque<SelectionHistoryEntry>,
888 redo_stack: VecDeque<SelectionHistoryEntry>,
889}
890
891impl SelectionHistory {
892 fn insert_transaction(
893 &mut self,
894 transaction_id: TransactionId,
895 selections: Arc<[Selection<Anchor>]>,
896 ) {
897 self.selections_by_transaction
898 .insert(transaction_id, (selections, None));
899 }
900
901 #[allow(clippy::type_complexity)]
902 fn transaction(
903 &self,
904 transaction_id: TransactionId,
905 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
906 self.selections_by_transaction.get(&transaction_id)
907 }
908
909 #[allow(clippy::type_complexity)]
910 fn transaction_mut(
911 &mut self,
912 transaction_id: TransactionId,
913 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
914 self.selections_by_transaction.get_mut(&transaction_id)
915 }
916
917 fn push(&mut self, entry: SelectionHistoryEntry) {
918 if !entry.selections.is_empty() {
919 match self.mode {
920 SelectionHistoryMode::Normal => {
921 self.push_undo(entry);
922 self.redo_stack.clear();
923 }
924 SelectionHistoryMode::Undoing => self.push_redo(entry),
925 SelectionHistoryMode::Redoing => self.push_undo(entry),
926 }
927 }
928 }
929
930 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
931 if self
932 .undo_stack
933 .back()
934 .map_or(true, |e| e.selections != entry.selections)
935 {
936 self.undo_stack.push_back(entry);
937 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
938 self.undo_stack.pop_front();
939 }
940 }
941 }
942
943 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
944 if self
945 .redo_stack
946 .back()
947 .map_or(true, |e| e.selections != entry.selections)
948 {
949 self.redo_stack.push_back(entry);
950 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
951 self.redo_stack.pop_front();
952 }
953 }
954 }
955}
956
957struct RowHighlight {
958 index: usize,
959 range: Range<Anchor>,
960 color: Hsla,
961 should_autoscroll: bool,
962}
963
964#[derive(Clone, Debug)]
965struct AddSelectionsState {
966 above: bool,
967 stack: Vec<usize>,
968}
969
970#[derive(Clone)]
971struct SelectNextState {
972 query: AhoCorasick,
973 wordwise: bool,
974 done: bool,
975}
976
977impl std::fmt::Debug for SelectNextState {
978 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
979 f.debug_struct(std::any::type_name::<Self>())
980 .field("wordwise", &self.wordwise)
981 .field("done", &self.done)
982 .finish()
983 }
984}
985
986#[derive(Debug)]
987struct AutocloseRegion {
988 selection_id: usize,
989 range: Range<Anchor>,
990 pair: BracketPair,
991}
992
993#[derive(Debug)]
994struct SnippetState {
995 ranges: Vec<Vec<Range<Anchor>>>,
996 active_index: usize,
997 choices: Vec<Option<Vec<String>>>,
998}
999
1000#[doc(hidden)]
1001pub struct RenameState {
1002 pub range: Range<Anchor>,
1003 pub old_name: Arc<str>,
1004 pub editor: Entity<Editor>,
1005 block_id: CustomBlockId,
1006}
1007
1008struct InvalidationStack<T>(Vec<T>);
1009
1010struct RegisteredInlineCompletionProvider {
1011 provider: Arc<dyn InlineCompletionProviderHandle>,
1012 _subscription: Subscription,
1013}
1014
1015#[derive(Debug, PartialEq, Eq)]
1016struct ActiveDiagnosticGroup {
1017 primary_range: Range<Anchor>,
1018 primary_message: String,
1019 group_id: usize,
1020 blocks: HashMap<CustomBlockId, Diagnostic>,
1021 is_valid: bool,
1022}
1023
1024#[derive(Serialize, Deserialize, Clone, Debug)]
1025pub struct ClipboardSelection {
1026 /// The number of bytes in this selection.
1027 pub len: usize,
1028 /// Whether this was a full-line selection.
1029 pub is_entire_line: bool,
1030 /// The indentation of the first line when this content was originally copied.
1031 pub first_line_indent: u32,
1032}
1033
1034#[derive(Debug)]
1035pub(crate) struct NavigationData {
1036 cursor_anchor: Anchor,
1037 cursor_position: Point,
1038 scroll_anchor: ScrollAnchor,
1039 scroll_top_row: u32,
1040}
1041
1042#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1043pub enum GotoDefinitionKind {
1044 Symbol,
1045 Declaration,
1046 Type,
1047 Implementation,
1048}
1049
1050#[derive(Debug, Clone)]
1051enum InlayHintRefreshReason {
1052 ModifiersChanged(bool),
1053 Toggle(bool),
1054 SettingsChange(InlayHintSettings),
1055 NewLinesShown,
1056 BufferEdited(HashSet<Arc<Language>>),
1057 RefreshRequested,
1058 ExcerptsRemoved(Vec<ExcerptId>),
1059}
1060
1061impl InlayHintRefreshReason {
1062 fn description(&self) -> &'static str {
1063 match self {
1064 Self::ModifiersChanged(_) => "modifiers changed",
1065 Self::Toggle(_) => "toggle",
1066 Self::SettingsChange(_) => "settings change",
1067 Self::NewLinesShown => "new lines shown",
1068 Self::BufferEdited(_) => "buffer edited",
1069 Self::RefreshRequested => "refresh requested",
1070 Self::ExcerptsRemoved(_) => "excerpts removed",
1071 }
1072 }
1073}
1074
1075pub enum FormatTarget {
1076 Buffers,
1077 Ranges(Vec<Range<MultiBufferPoint>>),
1078}
1079
1080pub(crate) struct FocusedBlock {
1081 id: BlockId,
1082 focus_handle: WeakFocusHandle,
1083}
1084
1085#[derive(Clone)]
1086enum JumpData {
1087 MultiBufferRow {
1088 row: MultiBufferRow,
1089 line_offset_from_top: u32,
1090 },
1091 MultiBufferPoint {
1092 excerpt_id: ExcerptId,
1093 position: Point,
1094 anchor: text::Anchor,
1095 line_offset_from_top: u32,
1096 },
1097}
1098
1099pub enum MultibufferSelectionMode {
1100 First,
1101 All,
1102}
1103
1104#[derive(Clone, Copy, Debug, Default)]
1105pub struct RewrapOptions {
1106 pub override_language_settings: bool,
1107 pub preserve_existing_whitespace: bool,
1108}
1109
1110impl Editor {
1111 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1112 let buffer = cx.new(|cx| Buffer::local("", cx));
1113 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1114 Self::new(
1115 EditorMode::SingleLine { auto_width: false },
1116 buffer,
1117 None,
1118 window,
1119 cx,
1120 )
1121 }
1122
1123 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1124 let buffer = cx.new(|cx| Buffer::local("", cx));
1125 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1126 Self::new(EditorMode::Full, buffer, None, window, cx)
1127 }
1128
1129 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1130 let buffer = cx.new(|cx| Buffer::local("", cx));
1131 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1132 Self::new(
1133 EditorMode::SingleLine { auto_width: true },
1134 buffer,
1135 None,
1136 window,
1137 cx,
1138 )
1139 }
1140
1141 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1142 let buffer = cx.new(|cx| Buffer::local("", cx));
1143 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1144 Self::new(
1145 EditorMode::AutoHeight { max_lines },
1146 buffer,
1147 None,
1148 window,
1149 cx,
1150 )
1151 }
1152
1153 pub fn for_buffer(
1154 buffer: Entity<Buffer>,
1155 project: Option<Entity<Project>>,
1156 window: &mut Window,
1157 cx: &mut Context<Self>,
1158 ) -> Self {
1159 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1160 Self::new(EditorMode::Full, buffer, project, window, cx)
1161 }
1162
1163 pub fn for_multibuffer(
1164 buffer: Entity<MultiBuffer>,
1165 project: Option<Entity<Project>>,
1166 window: &mut Window,
1167 cx: &mut Context<Self>,
1168 ) -> Self {
1169 Self::new(EditorMode::Full, buffer, project, window, cx)
1170 }
1171
1172 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1173 let mut clone = Self::new(
1174 self.mode,
1175 self.buffer.clone(),
1176 self.project.clone(),
1177 window,
1178 cx,
1179 );
1180 self.display_map.update(cx, |display_map, cx| {
1181 let snapshot = display_map.snapshot(cx);
1182 clone.display_map.update(cx, |display_map, cx| {
1183 display_map.set_state(&snapshot, cx);
1184 });
1185 });
1186 clone.selections.clone_state(&self.selections);
1187 clone.scroll_manager.clone_state(&self.scroll_manager);
1188 clone.searchable = self.searchable;
1189 clone
1190 }
1191
1192 pub fn new(
1193 mode: EditorMode,
1194 buffer: Entity<MultiBuffer>,
1195 project: Option<Entity<Project>>,
1196 window: &mut Window,
1197 cx: &mut Context<Self>,
1198 ) -> Self {
1199 let style = window.text_style();
1200 let font_size = style.font_size.to_pixels(window.rem_size());
1201 let editor = cx.entity().downgrade();
1202 let fold_placeholder = FoldPlaceholder {
1203 constrain_width: true,
1204 render: Arc::new(move |fold_id, fold_range, cx| {
1205 let editor = editor.clone();
1206 div()
1207 .id(fold_id)
1208 .bg(cx.theme().colors().ghost_element_background)
1209 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1210 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1211 .rounded_xs()
1212 .size_full()
1213 .cursor_pointer()
1214 .child("⋯")
1215 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1216 .on_click(move |_, _window, cx| {
1217 editor
1218 .update(cx, |editor, cx| {
1219 editor.unfold_ranges(
1220 &[fold_range.start..fold_range.end],
1221 true,
1222 false,
1223 cx,
1224 );
1225 cx.stop_propagation();
1226 })
1227 .ok();
1228 })
1229 .into_any()
1230 }),
1231 merge_adjacent: true,
1232 ..Default::default()
1233 };
1234 let display_map = cx.new(|cx| {
1235 DisplayMap::new(
1236 buffer.clone(),
1237 style.font(),
1238 font_size,
1239 None,
1240 FILE_HEADER_HEIGHT,
1241 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1242 fold_placeholder,
1243 cx,
1244 )
1245 });
1246
1247 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1248
1249 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1250
1251 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1252 .then(|| language_settings::SoftWrap::None);
1253
1254 let mut project_subscriptions = Vec::new();
1255 if mode == EditorMode::Full {
1256 if let Some(project) = project.as_ref() {
1257 project_subscriptions.push(cx.subscribe_in(
1258 project,
1259 window,
1260 |editor, _, event, window, cx| match event {
1261 project::Event::RefreshCodeLens => {
1262 // we always query lens with actions, without storing them, always refreshing them
1263 }
1264 project::Event::RefreshInlayHints => {
1265 editor
1266 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1267 }
1268 project::Event::SnippetEdit(id, snippet_edits) => {
1269 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1270 let focus_handle = editor.focus_handle(cx);
1271 if focus_handle.is_focused(window) {
1272 let snapshot = buffer.read(cx).snapshot();
1273 for (range, snippet) in snippet_edits {
1274 let editor_range =
1275 language::range_from_lsp(*range).to_offset(&snapshot);
1276 editor
1277 .insert_snippet(
1278 &[editor_range],
1279 snippet.clone(),
1280 window,
1281 cx,
1282 )
1283 .ok();
1284 }
1285 }
1286 }
1287 }
1288 _ => {}
1289 },
1290 ));
1291 if let Some(task_inventory) = project
1292 .read(cx)
1293 .task_store()
1294 .read(cx)
1295 .task_inventory()
1296 .cloned()
1297 {
1298 project_subscriptions.push(cx.observe_in(
1299 &task_inventory,
1300 window,
1301 |editor, _, window, cx| {
1302 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1303 },
1304 ));
1305 };
1306
1307 project_subscriptions.push(cx.subscribe_in(
1308 &project.read(cx).breakpoint_store(),
1309 window,
1310 |editor, _, event, window, cx| match event {
1311 BreakpointStoreEvent::ActiveDebugLineChanged => {
1312 editor.go_to_active_debug_line(window, cx);
1313 }
1314 _ => {}
1315 },
1316 ));
1317 }
1318 }
1319
1320 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1321
1322 let inlay_hint_settings =
1323 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1324 let focus_handle = cx.focus_handle();
1325 cx.on_focus(&focus_handle, window, Self::handle_focus)
1326 .detach();
1327 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1328 .detach();
1329 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1330 .detach();
1331 cx.on_blur(&focus_handle, window, Self::handle_blur)
1332 .detach();
1333
1334 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1335 Some(false)
1336 } else {
1337 None
1338 };
1339
1340 let breakpoint_store = match (mode, project.as_ref()) {
1341 (EditorMode::Full, Some(project)) => Some(project.read(cx).breakpoint_store()),
1342 _ => None,
1343 };
1344
1345 let mut code_action_providers = Vec::new();
1346 let mut load_uncommitted_diff = None;
1347 if let Some(project) = project.clone() {
1348 load_uncommitted_diff = Some(
1349 get_uncommitted_diff_for_buffer(
1350 &project,
1351 buffer.read(cx).all_buffers(),
1352 buffer.clone(),
1353 cx,
1354 )
1355 .shared(),
1356 );
1357 code_action_providers.push(Rc::new(project) as Rc<_>);
1358 }
1359
1360 let mut this = Self {
1361 focus_handle,
1362 show_cursor_when_unfocused: false,
1363 last_focused_descendant: None,
1364 buffer: buffer.clone(),
1365 display_map: display_map.clone(),
1366 selections,
1367 scroll_manager: ScrollManager::new(cx),
1368 columnar_selection_tail: None,
1369 add_selections_state: None,
1370 select_next_state: None,
1371 select_prev_state: None,
1372 selection_history: Default::default(),
1373 autoclose_regions: Default::default(),
1374 snippet_stack: Default::default(),
1375 select_larger_syntax_node_stack: Vec::new(),
1376 ime_transaction: Default::default(),
1377 active_diagnostics: None,
1378 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1379 inline_diagnostics_update: Task::ready(()),
1380 inline_diagnostics: Vec::new(),
1381 soft_wrap_mode_override,
1382 hard_wrap: None,
1383 completion_provider: project.clone().map(|project| Box::new(project) as _),
1384 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1385 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1386 project,
1387 blink_manager: blink_manager.clone(),
1388 show_local_selections: true,
1389 show_scrollbars: true,
1390 mode,
1391 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1392 show_gutter: mode == EditorMode::Full,
1393 show_line_numbers: None,
1394 use_relative_line_numbers: None,
1395 show_git_diff_gutter: None,
1396 show_code_actions: None,
1397 show_runnables: None,
1398 show_breakpoints: None,
1399 show_wrap_guides: None,
1400 show_indent_guides,
1401 placeholder_text: None,
1402 highlight_order: 0,
1403 highlighted_rows: HashMap::default(),
1404 background_highlights: Default::default(),
1405 gutter_highlights: TreeMap::default(),
1406 scrollbar_marker_state: ScrollbarMarkerState::default(),
1407 active_indent_guides_state: ActiveIndentGuidesState::default(),
1408 nav_history: None,
1409 context_menu: RefCell::new(None),
1410 mouse_context_menu: None,
1411 completion_tasks: Default::default(),
1412 signature_help_state: SignatureHelpState::default(),
1413 auto_signature_help: None,
1414 find_all_references_task_sources: Vec::new(),
1415 next_completion_id: 0,
1416 next_inlay_id: 0,
1417 code_action_providers,
1418 available_code_actions: Default::default(),
1419 code_actions_task: Default::default(),
1420 selection_highlight_task: Default::default(),
1421 document_highlights_task: Default::default(),
1422 linked_editing_range_task: Default::default(),
1423 pending_rename: Default::default(),
1424 searchable: true,
1425 cursor_shape: EditorSettings::get_global(cx)
1426 .cursor_shape
1427 .unwrap_or_default(),
1428 current_line_highlight: None,
1429 autoindent_mode: Some(AutoindentMode::EachLine),
1430 collapse_matches: false,
1431 workspace: None,
1432 input_enabled: true,
1433 use_modal_editing: mode == EditorMode::Full,
1434 read_only: false,
1435 use_autoclose: true,
1436 use_auto_surround: true,
1437 auto_replace_emoji_shortcode: false,
1438 jsx_tag_auto_close_enabled_in_any_buffer: false,
1439 leader_peer_id: None,
1440 remote_id: None,
1441 hover_state: Default::default(),
1442 pending_mouse_down: None,
1443 hovered_link_state: Default::default(),
1444 edit_prediction_provider: None,
1445 active_inline_completion: None,
1446 stale_inline_completion_in_menu: None,
1447 edit_prediction_preview: EditPredictionPreview::Inactive {
1448 released_too_fast: false,
1449 },
1450 inline_diagnostics_enabled: mode == EditorMode::Full,
1451 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1452
1453 gutter_hovered: false,
1454 pixel_position_of_newest_cursor: None,
1455 last_bounds: None,
1456 last_position_map: None,
1457 expect_bounds_change: None,
1458 gutter_dimensions: GutterDimensions::default(),
1459 style: None,
1460 show_cursor_names: false,
1461 hovered_cursors: Default::default(),
1462 next_editor_action_id: EditorActionId::default(),
1463 editor_actions: Rc::default(),
1464 inline_completions_hidden_for_vim_mode: false,
1465 show_inline_completions_override: None,
1466 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1467 edit_prediction_settings: EditPredictionSettings::Disabled,
1468 edit_prediction_indent_conflict: false,
1469 edit_prediction_requires_modifier_in_indent_conflict: true,
1470 custom_context_menu: None,
1471 show_git_blame_gutter: false,
1472 show_git_blame_inline: false,
1473 show_selection_menu: None,
1474 show_git_blame_inline_delay_task: None,
1475 git_blame_inline_tooltip: None,
1476 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1477 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1478 .session
1479 .restore_unsaved_buffers,
1480 blame: None,
1481 blame_subscription: None,
1482 tasks: Default::default(),
1483
1484 breakpoint_store,
1485 gutter_breakpoint_indicator: None,
1486 _subscriptions: vec![
1487 cx.observe(&buffer, Self::on_buffer_changed),
1488 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1489 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1490 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1491 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1492 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1493 cx.observe_window_activation(window, |editor, window, cx| {
1494 let active = window.is_window_active();
1495 editor.blink_manager.update(cx, |blink_manager, cx| {
1496 if active {
1497 blink_manager.enable(cx);
1498 } else {
1499 blink_manager.disable(cx);
1500 }
1501 });
1502 }),
1503 ],
1504 tasks_update_task: None,
1505 linked_edit_ranges: Default::default(),
1506 in_project_search: false,
1507 previous_search_ranges: None,
1508 breadcrumb_header: None,
1509 focused_block: None,
1510 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1511 addons: HashMap::default(),
1512 registered_buffers: HashMap::default(),
1513 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1514 selection_mark_mode: false,
1515 toggle_fold_multiple_buffers: Task::ready(()),
1516 serialize_selections: Task::ready(()),
1517 text_style_refinement: None,
1518 load_diff_task: load_uncommitted_diff,
1519 };
1520 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1521 this._subscriptions
1522 .push(cx.observe(breakpoints, |_, _, cx| {
1523 cx.notify();
1524 }));
1525 }
1526 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1527 this._subscriptions.extend(project_subscriptions);
1528
1529 this.end_selection(window, cx);
1530 this.scroll_manager.show_scrollbar(window, cx);
1531 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1532
1533 if mode == EditorMode::Full {
1534 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1535 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1536
1537 if this.git_blame_inline_enabled {
1538 this.git_blame_inline_enabled = true;
1539 this.start_git_blame_inline(false, window, cx);
1540 }
1541
1542 this.go_to_active_debug_line(window, cx);
1543
1544 if let Some(buffer) = buffer.read(cx).as_singleton() {
1545 if let Some(project) = this.project.as_ref() {
1546 let handle = project.update(cx, |project, cx| {
1547 project.register_buffer_with_language_servers(&buffer, cx)
1548 });
1549 this.registered_buffers
1550 .insert(buffer.read(cx).remote_id(), handle);
1551 }
1552 }
1553 }
1554
1555 this.report_editor_event("Editor Opened", None, cx);
1556 this
1557 }
1558
1559 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1560 self.mouse_context_menu
1561 .as_ref()
1562 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1563 }
1564
1565 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1566 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1567 }
1568
1569 fn key_context_internal(
1570 &self,
1571 has_active_edit_prediction: bool,
1572 window: &Window,
1573 cx: &App,
1574 ) -> KeyContext {
1575 let mut key_context = KeyContext::new_with_defaults();
1576 key_context.add("Editor");
1577 let mode = match self.mode {
1578 EditorMode::SingleLine { .. } => "single_line",
1579 EditorMode::AutoHeight { .. } => "auto_height",
1580 EditorMode::Full => "full",
1581 };
1582
1583 if EditorSettings::jupyter_enabled(cx) {
1584 key_context.add("jupyter");
1585 }
1586
1587 key_context.set("mode", mode);
1588 if self.pending_rename.is_some() {
1589 key_context.add("renaming");
1590 }
1591
1592 match self.context_menu.borrow().as_ref() {
1593 Some(CodeContextMenu::Completions(_)) => {
1594 key_context.add("menu");
1595 key_context.add("showing_completions");
1596 }
1597 Some(CodeContextMenu::CodeActions(_)) => {
1598 key_context.add("menu");
1599 key_context.add("showing_code_actions")
1600 }
1601 None => {}
1602 }
1603
1604 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1605 if !self.focus_handle(cx).contains_focused(window, cx)
1606 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1607 {
1608 for addon in self.addons.values() {
1609 addon.extend_key_context(&mut key_context, cx)
1610 }
1611 }
1612
1613 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1614 if let Some(extension) = singleton_buffer
1615 .read(cx)
1616 .file()
1617 .and_then(|file| file.path().extension()?.to_str())
1618 {
1619 key_context.set("extension", extension.to_string());
1620 }
1621 } else {
1622 key_context.add("multibuffer");
1623 }
1624
1625 if has_active_edit_prediction {
1626 if self.edit_prediction_in_conflict() {
1627 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1628 } else {
1629 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1630 key_context.add("copilot_suggestion");
1631 }
1632 }
1633
1634 if self.selection_mark_mode {
1635 key_context.add("selection_mode");
1636 }
1637
1638 key_context
1639 }
1640
1641 pub fn edit_prediction_in_conflict(&self) -> bool {
1642 if !self.show_edit_predictions_in_menu() {
1643 return false;
1644 }
1645
1646 let showing_completions = self
1647 .context_menu
1648 .borrow()
1649 .as_ref()
1650 .map_or(false, |context| {
1651 matches!(context, CodeContextMenu::Completions(_))
1652 });
1653
1654 showing_completions
1655 || self.edit_prediction_requires_modifier()
1656 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1657 // bindings to insert tab characters.
1658 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1659 }
1660
1661 pub fn accept_edit_prediction_keybind(
1662 &self,
1663 window: &Window,
1664 cx: &App,
1665 ) -> AcceptEditPredictionBinding {
1666 let key_context = self.key_context_internal(true, window, cx);
1667 let in_conflict = self.edit_prediction_in_conflict();
1668
1669 AcceptEditPredictionBinding(
1670 window
1671 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1672 .into_iter()
1673 .filter(|binding| {
1674 !in_conflict
1675 || binding
1676 .keystrokes()
1677 .first()
1678 .map_or(false, |keystroke| keystroke.modifiers.modified())
1679 })
1680 .rev()
1681 .min_by_key(|binding| {
1682 binding
1683 .keystrokes()
1684 .first()
1685 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1686 }),
1687 )
1688 }
1689
1690 pub fn new_file(
1691 workspace: &mut Workspace,
1692 _: &workspace::NewFile,
1693 window: &mut Window,
1694 cx: &mut Context<Workspace>,
1695 ) {
1696 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1697 "Failed to create buffer",
1698 window,
1699 cx,
1700 |e, _, _| match e.error_code() {
1701 ErrorCode::RemoteUpgradeRequired => Some(format!(
1702 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1703 e.error_tag("required").unwrap_or("the latest version")
1704 )),
1705 _ => None,
1706 },
1707 );
1708 }
1709
1710 pub fn new_in_workspace(
1711 workspace: &mut Workspace,
1712 window: &mut Window,
1713 cx: &mut Context<Workspace>,
1714 ) -> Task<Result<Entity<Editor>>> {
1715 let project = workspace.project().clone();
1716 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1717
1718 cx.spawn_in(window, async move |workspace, cx| {
1719 let buffer = create.await?;
1720 workspace.update_in(cx, |workspace, window, cx| {
1721 let editor =
1722 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1723 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1724 editor
1725 })
1726 })
1727 }
1728
1729 fn new_file_vertical(
1730 workspace: &mut Workspace,
1731 _: &workspace::NewFileSplitVertical,
1732 window: &mut Window,
1733 cx: &mut Context<Workspace>,
1734 ) {
1735 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1736 }
1737
1738 fn new_file_horizontal(
1739 workspace: &mut Workspace,
1740 _: &workspace::NewFileSplitHorizontal,
1741 window: &mut Window,
1742 cx: &mut Context<Workspace>,
1743 ) {
1744 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1745 }
1746
1747 fn new_file_in_direction(
1748 workspace: &mut Workspace,
1749 direction: SplitDirection,
1750 window: &mut Window,
1751 cx: &mut Context<Workspace>,
1752 ) {
1753 let project = workspace.project().clone();
1754 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1755
1756 cx.spawn_in(window, async move |workspace, cx| {
1757 let buffer = create.await?;
1758 workspace.update_in(cx, move |workspace, window, cx| {
1759 workspace.split_item(
1760 direction,
1761 Box::new(
1762 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1763 ),
1764 window,
1765 cx,
1766 )
1767 })?;
1768 anyhow::Ok(())
1769 })
1770 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1771 match e.error_code() {
1772 ErrorCode::RemoteUpgradeRequired => Some(format!(
1773 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1774 e.error_tag("required").unwrap_or("the latest version")
1775 )),
1776 _ => None,
1777 }
1778 });
1779 }
1780
1781 pub fn leader_peer_id(&self) -> Option<PeerId> {
1782 self.leader_peer_id
1783 }
1784
1785 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1786 &self.buffer
1787 }
1788
1789 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1790 self.workspace.as_ref()?.0.upgrade()
1791 }
1792
1793 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1794 self.buffer().read(cx).title(cx)
1795 }
1796
1797 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1798 let git_blame_gutter_max_author_length = self
1799 .render_git_blame_gutter(cx)
1800 .then(|| {
1801 if let Some(blame) = self.blame.as_ref() {
1802 let max_author_length =
1803 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1804 Some(max_author_length)
1805 } else {
1806 None
1807 }
1808 })
1809 .flatten();
1810
1811 EditorSnapshot {
1812 mode: self.mode,
1813 show_gutter: self.show_gutter,
1814 show_line_numbers: self.show_line_numbers,
1815 show_git_diff_gutter: self.show_git_diff_gutter,
1816 show_code_actions: self.show_code_actions,
1817 show_runnables: self.show_runnables,
1818 show_breakpoints: self.show_breakpoints,
1819 git_blame_gutter_max_author_length,
1820 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1821 scroll_anchor: self.scroll_manager.anchor(),
1822 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1823 placeholder_text: self.placeholder_text.clone(),
1824 is_focused: self.focus_handle.is_focused(window),
1825 current_line_highlight: self
1826 .current_line_highlight
1827 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1828 gutter_hovered: self.gutter_hovered,
1829 }
1830 }
1831
1832 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1833 self.buffer.read(cx).language_at(point, cx)
1834 }
1835
1836 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1837 self.buffer.read(cx).read(cx).file_at(point).cloned()
1838 }
1839
1840 pub fn active_excerpt(
1841 &self,
1842 cx: &App,
1843 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1844 self.buffer
1845 .read(cx)
1846 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1847 }
1848
1849 pub fn mode(&self) -> EditorMode {
1850 self.mode
1851 }
1852
1853 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1854 self.collaboration_hub.as_deref()
1855 }
1856
1857 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1858 self.collaboration_hub = Some(hub);
1859 }
1860
1861 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1862 self.in_project_search = in_project_search;
1863 }
1864
1865 pub fn set_custom_context_menu(
1866 &mut self,
1867 f: impl 'static
1868 + Fn(
1869 &mut Self,
1870 DisplayPoint,
1871 &mut Window,
1872 &mut Context<Self>,
1873 ) -> Option<Entity<ui::ContextMenu>>,
1874 ) {
1875 self.custom_context_menu = Some(Box::new(f))
1876 }
1877
1878 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1879 self.completion_provider = provider;
1880 }
1881
1882 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1883 self.semantics_provider.clone()
1884 }
1885
1886 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1887 self.semantics_provider = provider;
1888 }
1889
1890 pub fn set_edit_prediction_provider<T>(
1891 &mut self,
1892 provider: Option<Entity<T>>,
1893 window: &mut Window,
1894 cx: &mut Context<Self>,
1895 ) where
1896 T: EditPredictionProvider,
1897 {
1898 self.edit_prediction_provider =
1899 provider.map(|provider| RegisteredInlineCompletionProvider {
1900 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1901 if this.focus_handle.is_focused(window) {
1902 this.update_visible_inline_completion(window, cx);
1903 }
1904 }),
1905 provider: Arc::new(provider),
1906 });
1907 self.update_edit_prediction_settings(cx);
1908 self.refresh_inline_completion(false, false, window, cx);
1909 }
1910
1911 pub fn placeholder_text(&self) -> Option<&str> {
1912 self.placeholder_text.as_deref()
1913 }
1914
1915 pub fn set_placeholder_text(
1916 &mut self,
1917 placeholder_text: impl Into<Arc<str>>,
1918 cx: &mut Context<Self>,
1919 ) {
1920 let placeholder_text = Some(placeholder_text.into());
1921 if self.placeholder_text != placeholder_text {
1922 self.placeholder_text = placeholder_text;
1923 cx.notify();
1924 }
1925 }
1926
1927 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1928 self.cursor_shape = cursor_shape;
1929
1930 // Disrupt blink for immediate user feedback that the cursor shape has changed
1931 self.blink_manager.update(cx, BlinkManager::show_cursor);
1932
1933 cx.notify();
1934 }
1935
1936 pub fn set_current_line_highlight(
1937 &mut self,
1938 current_line_highlight: Option<CurrentLineHighlight>,
1939 ) {
1940 self.current_line_highlight = current_line_highlight;
1941 }
1942
1943 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1944 self.collapse_matches = collapse_matches;
1945 }
1946
1947 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1948 let buffers = self.buffer.read(cx).all_buffers();
1949 let Some(project) = self.project.as_ref() else {
1950 return;
1951 };
1952 project.update(cx, |project, cx| {
1953 for buffer in buffers {
1954 self.registered_buffers
1955 .entry(buffer.read(cx).remote_id())
1956 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
1957 }
1958 })
1959 }
1960
1961 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1962 if self.collapse_matches {
1963 return range.start..range.start;
1964 }
1965 range.clone()
1966 }
1967
1968 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1969 if self.display_map.read(cx).clip_at_line_ends != clip {
1970 self.display_map
1971 .update(cx, |map, _| map.clip_at_line_ends = clip);
1972 }
1973 }
1974
1975 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1976 self.input_enabled = input_enabled;
1977 }
1978
1979 pub fn set_inline_completions_hidden_for_vim_mode(
1980 &mut self,
1981 hidden: bool,
1982 window: &mut Window,
1983 cx: &mut Context<Self>,
1984 ) {
1985 if hidden != self.inline_completions_hidden_for_vim_mode {
1986 self.inline_completions_hidden_for_vim_mode = hidden;
1987 if hidden {
1988 self.update_visible_inline_completion(window, cx);
1989 } else {
1990 self.refresh_inline_completion(true, false, window, cx);
1991 }
1992 }
1993 }
1994
1995 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1996 self.menu_inline_completions_policy = value;
1997 }
1998
1999 pub fn set_autoindent(&mut self, autoindent: bool) {
2000 if autoindent {
2001 self.autoindent_mode = Some(AutoindentMode::EachLine);
2002 } else {
2003 self.autoindent_mode = None;
2004 }
2005 }
2006
2007 pub fn read_only(&self, cx: &App) -> bool {
2008 self.read_only || self.buffer.read(cx).read_only()
2009 }
2010
2011 pub fn set_read_only(&mut self, read_only: bool) {
2012 self.read_only = read_only;
2013 }
2014
2015 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2016 self.use_autoclose = autoclose;
2017 }
2018
2019 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2020 self.use_auto_surround = auto_surround;
2021 }
2022
2023 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2024 self.auto_replace_emoji_shortcode = auto_replace;
2025 }
2026
2027 pub fn toggle_edit_predictions(
2028 &mut self,
2029 _: &ToggleEditPrediction,
2030 window: &mut Window,
2031 cx: &mut Context<Self>,
2032 ) {
2033 if self.show_inline_completions_override.is_some() {
2034 self.set_show_edit_predictions(None, window, cx);
2035 } else {
2036 let show_edit_predictions = !self.edit_predictions_enabled();
2037 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2038 }
2039 }
2040
2041 pub fn set_show_edit_predictions(
2042 &mut self,
2043 show_edit_predictions: Option<bool>,
2044 window: &mut Window,
2045 cx: &mut Context<Self>,
2046 ) {
2047 self.show_inline_completions_override = show_edit_predictions;
2048 self.update_edit_prediction_settings(cx);
2049
2050 if let Some(false) = show_edit_predictions {
2051 self.discard_inline_completion(false, cx);
2052 } else {
2053 self.refresh_inline_completion(false, true, window, cx);
2054 }
2055 }
2056
2057 fn inline_completions_disabled_in_scope(
2058 &self,
2059 buffer: &Entity<Buffer>,
2060 buffer_position: language::Anchor,
2061 cx: &App,
2062 ) -> bool {
2063 let snapshot = buffer.read(cx).snapshot();
2064 let settings = snapshot.settings_at(buffer_position, cx);
2065
2066 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2067 return false;
2068 };
2069
2070 scope.override_name().map_or(false, |scope_name| {
2071 settings
2072 .edit_predictions_disabled_in
2073 .iter()
2074 .any(|s| s == scope_name)
2075 })
2076 }
2077
2078 pub fn set_use_modal_editing(&mut self, to: bool) {
2079 self.use_modal_editing = to;
2080 }
2081
2082 pub fn use_modal_editing(&self) -> bool {
2083 self.use_modal_editing
2084 }
2085
2086 fn selections_did_change(
2087 &mut self,
2088 local: bool,
2089 old_cursor_position: &Anchor,
2090 show_completions: bool,
2091 window: &mut Window,
2092 cx: &mut Context<Self>,
2093 ) {
2094 window.invalidate_character_coordinates();
2095
2096 // Copy selections to primary selection buffer
2097 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2098 if local {
2099 let selections = self.selections.all::<usize>(cx);
2100 let buffer_handle = self.buffer.read(cx).read(cx);
2101
2102 let mut text = String::new();
2103 for (index, selection) in selections.iter().enumerate() {
2104 let text_for_selection = buffer_handle
2105 .text_for_range(selection.start..selection.end)
2106 .collect::<String>();
2107
2108 text.push_str(&text_for_selection);
2109 if index != selections.len() - 1 {
2110 text.push('\n');
2111 }
2112 }
2113
2114 if !text.is_empty() {
2115 cx.write_to_primary(ClipboardItem::new_string(text));
2116 }
2117 }
2118
2119 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2120 self.buffer.update(cx, |buffer, cx| {
2121 buffer.set_active_selections(
2122 &self.selections.disjoint_anchors(),
2123 self.selections.line_mode,
2124 self.cursor_shape,
2125 cx,
2126 )
2127 });
2128 }
2129 let display_map = self
2130 .display_map
2131 .update(cx, |display_map, cx| display_map.snapshot(cx));
2132 let buffer = &display_map.buffer_snapshot;
2133 self.add_selections_state = None;
2134 self.select_next_state = None;
2135 self.select_prev_state = None;
2136 self.select_larger_syntax_node_stack.clear();
2137 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2138 self.snippet_stack
2139 .invalidate(&self.selections.disjoint_anchors(), buffer);
2140 self.take_rename(false, window, cx);
2141
2142 let new_cursor_position = self.selections.newest_anchor().head();
2143
2144 self.push_to_nav_history(
2145 *old_cursor_position,
2146 Some(new_cursor_position.to_point(buffer)),
2147 cx,
2148 );
2149
2150 if local {
2151 let new_cursor_position = self.selections.newest_anchor().head();
2152 let mut context_menu = self.context_menu.borrow_mut();
2153 let completion_menu = match context_menu.as_ref() {
2154 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2155 _ => {
2156 *context_menu = None;
2157 None
2158 }
2159 };
2160 if let Some(buffer_id) = new_cursor_position.buffer_id {
2161 if !self.registered_buffers.contains_key(&buffer_id) {
2162 if let Some(project) = self.project.as_ref() {
2163 project.update(cx, |project, cx| {
2164 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2165 return;
2166 };
2167 self.registered_buffers.insert(
2168 buffer_id,
2169 project.register_buffer_with_language_servers(&buffer, cx),
2170 );
2171 })
2172 }
2173 }
2174 }
2175
2176 if let Some(completion_menu) = completion_menu {
2177 let cursor_position = new_cursor_position.to_offset(buffer);
2178 let (word_range, kind) =
2179 buffer.surrounding_word(completion_menu.initial_position, true);
2180 if kind == Some(CharKind::Word)
2181 && word_range.to_inclusive().contains(&cursor_position)
2182 {
2183 let mut completion_menu = completion_menu.clone();
2184 drop(context_menu);
2185
2186 let query = Self::completion_query(buffer, cursor_position);
2187 cx.spawn(async move |this, cx| {
2188 completion_menu
2189 .filter(query.as_deref(), cx.background_executor().clone())
2190 .await;
2191
2192 this.update(cx, |this, cx| {
2193 let mut context_menu = this.context_menu.borrow_mut();
2194 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2195 else {
2196 return;
2197 };
2198
2199 if menu.id > completion_menu.id {
2200 return;
2201 }
2202
2203 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2204 drop(context_menu);
2205 cx.notify();
2206 })
2207 })
2208 .detach();
2209
2210 if show_completions {
2211 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2212 }
2213 } else {
2214 drop(context_menu);
2215 self.hide_context_menu(window, cx);
2216 }
2217 } else {
2218 drop(context_menu);
2219 }
2220
2221 hide_hover(self, cx);
2222
2223 if old_cursor_position.to_display_point(&display_map).row()
2224 != new_cursor_position.to_display_point(&display_map).row()
2225 {
2226 self.available_code_actions.take();
2227 }
2228 self.refresh_code_actions(window, cx);
2229 self.refresh_document_highlights(cx);
2230 self.refresh_selected_text_highlights(window, cx);
2231 refresh_matching_bracket_highlights(self, window, cx);
2232 self.update_visible_inline_completion(window, cx);
2233 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2234 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2235 if self.git_blame_inline_enabled {
2236 self.start_inline_blame_timer(window, cx);
2237 }
2238 }
2239
2240 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2241 cx.emit(EditorEvent::SelectionsChanged { local });
2242
2243 let selections = &self.selections.disjoint;
2244 if selections.len() == 1 {
2245 cx.emit(SearchEvent::ActiveMatchChanged)
2246 }
2247 if local
2248 && self.is_singleton(cx)
2249 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
2250 {
2251 if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
2252 let background_executor = cx.background_executor().clone();
2253 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2254 let snapshot = self.buffer().read(cx).snapshot(cx);
2255 let selections = selections.clone();
2256 self.serialize_selections = cx.background_spawn(async move {
2257 background_executor.timer(Duration::from_millis(100)).await;
2258 let selections = selections
2259 .iter()
2260 .map(|selection| {
2261 (
2262 selection.start.to_offset(&snapshot),
2263 selection.end.to_offset(&snapshot),
2264 )
2265 })
2266 .collect();
2267 DB.save_editor_selections(editor_id, workspace_id, selections)
2268 .await
2269 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2270 .log_err();
2271 });
2272 }
2273 }
2274
2275 cx.notify();
2276 }
2277
2278 pub fn sync_selections(
2279 &mut self,
2280 other: Entity<Editor>,
2281 cx: &mut Context<Self>,
2282 ) -> gpui::Subscription {
2283 let other_selections = other.read(cx).selections.disjoint.to_vec();
2284 self.selections.change_with(cx, |selections| {
2285 selections.select_anchors(other_selections);
2286 });
2287
2288 let other_subscription =
2289 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2290 EditorEvent::SelectionsChanged { local: true } => {
2291 let other_selections = other.read(cx).selections.disjoint.to_vec();
2292 if other_selections.is_empty() {
2293 return;
2294 }
2295 this.selections.change_with(cx, |selections| {
2296 selections.select_anchors(other_selections);
2297 });
2298 }
2299 _ => {}
2300 });
2301
2302 let this_subscription =
2303 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2304 EditorEvent::SelectionsChanged { local: true } => {
2305 let these_selections = this.selections.disjoint.to_vec();
2306 if these_selections.is_empty() {
2307 return;
2308 }
2309 other.update(cx, |other_editor, cx| {
2310 other_editor.selections.change_with(cx, |selections| {
2311 selections.select_anchors(these_selections);
2312 })
2313 });
2314 }
2315 _ => {}
2316 });
2317
2318 Subscription::join(other_subscription, this_subscription)
2319 }
2320
2321 pub fn change_selections<R>(
2322 &mut self,
2323 autoscroll: Option<Autoscroll>,
2324 window: &mut Window,
2325 cx: &mut Context<Self>,
2326 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2327 ) -> R {
2328 self.change_selections_inner(autoscroll, true, window, cx, change)
2329 }
2330
2331 fn change_selections_inner<R>(
2332 &mut self,
2333 autoscroll: Option<Autoscroll>,
2334 request_completions: bool,
2335 window: &mut Window,
2336 cx: &mut Context<Self>,
2337 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2338 ) -> R {
2339 let old_cursor_position = self.selections.newest_anchor().head();
2340 self.push_to_selection_history();
2341
2342 let (changed, result) = self.selections.change_with(cx, change);
2343
2344 if changed {
2345 if let Some(autoscroll) = autoscroll {
2346 self.request_autoscroll(autoscroll, cx);
2347 }
2348 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2349
2350 if self.should_open_signature_help_automatically(
2351 &old_cursor_position,
2352 self.signature_help_state.backspace_pressed(),
2353 cx,
2354 ) {
2355 self.show_signature_help(&ShowSignatureHelp, window, cx);
2356 }
2357 self.signature_help_state.set_backspace_pressed(false);
2358 }
2359
2360 result
2361 }
2362
2363 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2364 where
2365 I: IntoIterator<Item = (Range<S>, T)>,
2366 S: ToOffset,
2367 T: Into<Arc<str>>,
2368 {
2369 if self.read_only(cx) {
2370 return;
2371 }
2372
2373 self.buffer
2374 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2375 }
2376
2377 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2378 where
2379 I: IntoIterator<Item = (Range<S>, T)>,
2380 S: ToOffset,
2381 T: Into<Arc<str>>,
2382 {
2383 if self.read_only(cx) {
2384 return;
2385 }
2386
2387 self.buffer.update(cx, |buffer, cx| {
2388 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2389 });
2390 }
2391
2392 pub fn edit_with_block_indent<I, S, T>(
2393 &mut self,
2394 edits: I,
2395 original_indent_columns: Vec<Option<u32>>,
2396 cx: &mut Context<Self>,
2397 ) where
2398 I: IntoIterator<Item = (Range<S>, T)>,
2399 S: ToOffset,
2400 T: Into<Arc<str>>,
2401 {
2402 if self.read_only(cx) {
2403 return;
2404 }
2405
2406 self.buffer.update(cx, |buffer, cx| {
2407 buffer.edit(
2408 edits,
2409 Some(AutoindentMode::Block {
2410 original_indent_columns,
2411 }),
2412 cx,
2413 )
2414 });
2415 }
2416
2417 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2418 self.hide_context_menu(window, cx);
2419
2420 match phase {
2421 SelectPhase::Begin {
2422 position,
2423 add,
2424 click_count,
2425 } => self.begin_selection(position, add, click_count, window, cx),
2426 SelectPhase::BeginColumnar {
2427 position,
2428 goal_column,
2429 reset,
2430 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2431 SelectPhase::Extend {
2432 position,
2433 click_count,
2434 } => self.extend_selection(position, click_count, window, cx),
2435 SelectPhase::Update {
2436 position,
2437 goal_column,
2438 scroll_delta,
2439 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2440 SelectPhase::End => self.end_selection(window, cx),
2441 }
2442 }
2443
2444 fn extend_selection(
2445 &mut self,
2446 position: DisplayPoint,
2447 click_count: usize,
2448 window: &mut Window,
2449 cx: &mut Context<Self>,
2450 ) {
2451 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2452 let tail = self.selections.newest::<usize>(cx).tail();
2453 self.begin_selection(position, false, click_count, window, cx);
2454
2455 let position = position.to_offset(&display_map, Bias::Left);
2456 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2457
2458 let mut pending_selection = self
2459 .selections
2460 .pending_anchor()
2461 .expect("extend_selection not called with pending selection");
2462 if position >= tail {
2463 pending_selection.start = tail_anchor;
2464 } else {
2465 pending_selection.end = tail_anchor;
2466 pending_selection.reversed = true;
2467 }
2468
2469 let mut pending_mode = self.selections.pending_mode().unwrap();
2470 match &mut pending_mode {
2471 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2472 _ => {}
2473 }
2474
2475 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2476 s.set_pending(pending_selection, pending_mode)
2477 });
2478 }
2479
2480 fn begin_selection(
2481 &mut self,
2482 position: DisplayPoint,
2483 add: bool,
2484 click_count: usize,
2485 window: &mut Window,
2486 cx: &mut Context<Self>,
2487 ) {
2488 if !self.focus_handle.is_focused(window) {
2489 self.last_focused_descendant = None;
2490 window.focus(&self.focus_handle);
2491 }
2492
2493 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2494 let buffer = &display_map.buffer_snapshot;
2495 let newest_selection = self.selections.newest_anchor().clone();
2496 let position = display_map.clip_point(position, Bias::Left);
2497
2498 let start;
2499 let end;
2500 let mode;
2501 let mut auto_scroll;
2502 match click_count {
2503 1 => {
2504 start = buffer.anchor_before(position.to_point(&display_map));
2505 end = start;
2506 mode = SelectMode::Character;
2507 auto_scroll = true;
2508 }
2509 2 => {
2510 let range = movement::surrounding_word(&display_map, position);
2511 start = buffer.anchor_before(range.start.to_point(&display_map));
2512 end = buffer.anchor_before(range.end.to_point(&display_map));
2513 mode = SelectMode::Word(start..end);
2514 auto_scroll = true;
2515 }
2516 3 => {
2517 let position = display_map
2518 .clip_point(position, Bias::Left)
2519 .to_point(&display_map);
2520 let line_start = display_map.prev_line_boundary(position).0;
2521 let next_line_start = buffer.clip_point(
2522 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2523 Bias::Left,
2524 );
2525 start = buffer.anchor_before(line_start);
2526 end = buffer.anchor_before(next_line_start);
2527 mode = SelectMode::Line(start..end);
2528 auto_scroll = true;
2529 }
2530 _ => {
2531 start = buffer.anchor_before(0);
2532 end = buffer.anchor_before(buffer.len());
2533 mode = SelectMode::All;
2534 auto_scroll = false;
2535 }
2536 }
2537 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2538
2539 let point_to_delete: Option<usize> = {
2540 let selected_points: Vec<Selection<Point>> =
2541 self.selections.disjoint_in_range(start..end, cx);
2542
2543 if !add || click_count > 1 {
2544 None
2545 } else if !selected_points.is_empty() {
2546 Some(selected_points[0].id)
2547 } else {
2548 let clicked_point_already_selected =
2549 self.selections.disjoint.iter().find(|selection| {
2550 selection.start.to_point(buffer) == start.to_point(buffer)
2551 || selection.end.to_point(buffer) == end.to_point(buffer)
2552 });
2553
2554 clicked_point_already_selected.map(|selection| selection.id)
2555 }
2556 };
2557
2558 let selections_count = self.selections.count();
2559
2560 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2561 if let Some(point_to_delete) = point_to_delete {
2562 s.delete(point_to_delete);
2563
2564 if selections_count == 1 {
2565 s.set_pending_anchor_range(start..end, mode);
2566 }
2567 } else {
2568 if !add {
2569 s.clear_disjoint();
2570 } else if click_count > 1 {
2571 s.delete(newest_selection.id)
2572 }
2573
2574 s.set_pending_anchor_range(start..end, mode);
2575 }
2576 });
2577 }
2578
2579 fn begin_columnar_selection(
2580 &mut self,
2581 position: DisplayPoint,
2582 goal_column: u32,
2583 reset: bool,
2584 window: &mut Window,
2585 cx: &mut Context<Self>,
2586 ) {
2587 if !self.focus_handle.is_focused(window) {
2588 self.last_focused_descendant = None;
2589 window.focus(&self.focus_handle);
2590 }
2591
2592 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2593
2594 if reset {
2595 let pointer_position = display_map
2596 .buffer_snapshot
2597 .anchor_before(position.to_point(&display_map));
2598
2599 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2600 s.clear_disjoint();
2601 s.set_pending_anchor_range(
2602 pointer_position..pointer_position,
2603 SelectMode::Character,
2604 );
2605 });
2606 }
2607
2608 let tail = self.selections.newest::<Point>(cx).tail();
2609 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2610
2611 if !reset {
2612 self.select_columns(
2613 tail.to_display_point(&display_map),
2614 position,
2615 goal_column,
2616 &display_map,
2617 window,
2618 cx,
2619 );
2620 }
2621 }
2622
2623 fn update_selection(
2624 &mut self,
2625 position: DisplayPoint,
2626 goal_column: u32,
2627 scroll_delta: gpui::Point<f32>,
2628 window: &mut Window,
2629 cx: &mut Context<Self>,
2630 ) {
2631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2632
2633 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2634 let tail = tail.to_display_point(&display_map);
2635 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2636 } else if let Some(mut pending) = self.selections.pending_anchor() {
2637 let buffer = self.buffer.read(cx).snapshot(cx);
2638 let head;
2639 let tail;
2640 let mode = self.selections.pending_mode().unwrap();
2641 match &mode {
2642 SelectMode::Character => {
2643 head = position.to_point(&display_map);
2644 tail = pending.tail().to_point(&buffer);
2645 }
2646 SelectMode::Word(original_range) => {
2647 let original_display_range = original_range.start.to_display_point(&display_map)
2648 ..original_range.end.to_display_point(&display_map);
2649 let original_buffer_range = original_display_range.start.to_point(&display_map)
2650 ..original_display_range.end.to_point(&display_map);
2651 if movement::is_inside_word(&display_map, position)
2652 || original_display_range.contains(&position)
2653 {
2654 let word_range = movement::surrounding_word(&display_map, position);
2655 if word_range.start < original_display_range.start {
2656 head = word_range.start.to_point(&display_map);
2657 } else {
2658 head = word_range.end.to_point(&display_map);
2659 }
2660 } else {
2661 head = position.to_point(&display_map);
2662 }
2663
2664 if head <= original_buffer_range.start {
2665 tail = original_buffer_range.end;
2666 } else {
2667 tail = original_buffer_range.start;
2668 }
2669 }
2670 SelectMode::Line(original_range) => {
2671 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2672
2673 let position = display_map
2674 .clip_point(position, Bias::Left)
2675 .to_point(&display_map);
2676 let line_start = display_map.prev_line_boundary(position).0;
2677 let next_line_start = buffer.clip_point(
2678 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2679 Bias::Left,
2680 );
2681
2682 if line_start < original_range.start {
2683 head = line_start
2684 } else {
2685 head = next_line_start
2686 }
2687
2688 if head <= original_range.start {
2689 tail = original_range.end;
2690 } else {
2691 tail = original_range.start;
2692 }
2693 }
2694 SelectMode::All => {
2695 return;
2696 }
2697 };
2698
2699 if head < tail {
2700 pending.start = buffer.anchor_before(head);
2701 pending.end = buffer.anchor_before(tail);
2702 pending.reversed = true;
2703 } else {
2704 pending.start = buffer.anchor_before(tail);
2705 pending.end = buffer.anchor_before(head);
2706 pending.reversed = false;
2707 }
2708
2709 self.change_selections(None, window, cx, |s| {
2710 s.set_pending(pending, mode);
2711 });
2712 } else {
2713 log::error!("update_selection dispatched with no pending selection");
2714 return;
2715 }
2716
2717 self.apply_scroll_delta(scroll_delta, window, cx);
2718 cx.notify();
2719 }
2720
2721 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2722 self.columnar_selection_tail.take();
2723 if self.selections.pending_anchor().is_some() {
2724 let selections = self.selections.all::<usize>(cx);
2725 self.change_selections(None, window, cx, |s| {
2726 s.select(selections);
2727 s.clear_pending();
2728 });
2729 }
2730 }
2731
2732 fn select_columns(
2733 &mut self,
2734 tail: DisplayPoint,
2735 head: DisplayPoint,
2736 goal_column: u32,
2737 display_map: &DisplaySnapshot,
2738 window: &mut Window,
2739 cx: &mut Context<Self>,
2740 ) {
2741 let start_row = cmp::min(tail.row(), head.row());
2742 let end_row = cmp::max(tail.row(), head.row());
2743 let start_column = cmp::min(tail.column(), goal_column);
2744 let end_column = cmp::max(tail.column(), goal_column);
2745 let reversed = start_column < tail.column();
2746
2747 let selection_ranges = (start_row.0..=end_row.0)
2748 .map(DisplayRow)
2749 .filter_map(|row| {
2750 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2751 let start = display_map
2752 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2753 .to_point(display_map);
2754 let end = display_map
2755 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2756 .to_point(display_map);
2757 if reversed {
2758 Some(end..start)
2759 } else {
2760 Some(start..end)
2761 }
2762 } else {
2763 None
2764 }
2765 })
2766 .collect::<Vec<_>>();
2767
2768 self.change_selections(None, window, cx, |s| {
2769 s.select_ranges(selection_ranges);
2770 });
2771 cx.notify();
2772 }
2773
2774 pub fn has_pending_nonempty_selection(&self) -> bool {
2775 let pending_nonempty_selection = match self.selections.pending_anchor() {
2776 Some(Selection { start, end, .. }) => start != end,
2777 None => false,
2778 };
2779
2780 pending_nonempty_selection
2781 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2782 }
2783
2784 pub fn has_pending_selection(&self) -> bool {
2785 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2786 }
2787
2788 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2789 self.selection_mark_mode = false;
2790
2791 if self.clear_expanded_diff_hunks(cx) {
2792 cx.notify();
2793 return;
2794 }
2795 if self.dismiss_menus_and_popups(true, window, cx) {
2796 return;
2797 }
2798
2799 if self.mode == EditorMode::Full
2800 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2801 {
2802 return;
2803 }
2804
2805 cx.propagate();
2806 }
2807
2808 pub fn dismiss_menus_and_popups(
2809 &mut self,
2810 is_user_requested: bool,
2811 window: &mut Window,
2812 cx: &mut Context<Self>,
2813 ) -> bool {
2814 if self.take_rename(false, window, cx).is_some() {
2815 return true;
2816 }
2817
2818 if hide_hover(self, cx) {
2819 return true;
2820 }
2821
2822 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2823 return true;
2824 }
2825
2826 if self.hide_context_menu(window, cx).is_some() {
2827 return true;
2828 }
2829
2830 if self.mouse_context_menu.take().is_some() {
2831 return true;
2832 }
2833
2834 if is_user_requested && self.discard_inline_completion(true, cx) {
2835 return true;
2836 }
2837
2838 if self.snippet_stack.pop().is_some() {
2839 return true;
2840 }
2841
2842 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2843 self.dismiss_diagnostics(cx);
2844 return true;
2845 }
2846
2847 false
2848 }
2849
2850 fn linked_editing_ranges_for(
2851 &self,
2852 selection: Range<text::Anchor>,
2853 cx: &App,
2854 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2855 if self.linked_edit_ranges.is_empty() {
2856 return None;
2857 }
2858 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2859 selection.end.buffer_id.and_then(|end_buffer_id| {
2860 if selection.start.buffer_id != Some(end_buffer_id) {
2861 return None;
2862 }
2863 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2864 let snapshot = buffer.read(cx).snapshot();
2865 self.linked_edit_ranges
2866 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2867 .map(|ranges| (ranges, snapshot, buffer))
2868 })?;
2869 use text::ToOffset as TO;
2870 // find offset from the start of current range to current cursor position
2871 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2872
2873 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2874 let start_difference = start_offset - start_byte_offset;
2875 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2876 let end_difference = end_offset - start_byte_offset;
2877 // Current range has associated linked ranges.
2878 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2879 for range in linked_ranges.iter() {
2880 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2881 let end_offset = start_offset + end_difference;
2882 let start_offset = start_offset + start_difference;
2883 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2884 continue;
2885 }
2886 if self.selections.disjoint_anchor_ranges().any(|s| {
2887 if s.start.buffer_id != selection.start.buffer_id
2888 || s.end.buffer_id != selection.end.buffer_id
2889 {
2890 return false;
2891 }
2892 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2893 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2894 }) {
2895 continue;
2896 }
2897 let start = buffer_snapshot.anchor_after(start_offset);
2898 let end = buffer_snapshot.anchor_after(end_offset);
2899 linked_edits
2900 .entry(buffer.clone())
2901 .or_default()
2902 .push(start..end);
2903 }
2904 Some(linked_edits)
2905 }
2906
2907 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2908 let text: Arc<str> = text.into();
2909
2910 if self.read_only(cx) {
2911 return;
2912 }
2913
2914 let selections = self.selections.all_adjusted(cx);
2915 let mut bracket_inserted = false;
2916 let mut edits = Vec::new();
2917 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2918 let mut new_selections = Vec::with_capacity(selections.len());
2919 let mut new_autoclose_regions = Vec::new();
2920 let snapshot = self.buffer.read(cx).read(cx);
2921
2922 for (selection, autoclose_region) in
2923 self.selections_with_autoclose_regions(selections, &snapshot)
2924 {
2925 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2926 // Determine if the inserted text matches the opening or closing
2927 // bracket of any of this language's bracket pairs.
2928 let mut bracket_pair = None;
2929 let mut is_bracket_pair_start = false;
2930 let mut is_bracket_pair_end = false;
2931 if !text.is_empty() {
2932 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2933 // and they are removing the character that triggered IME popup.
2934 for (pair, enabled) in scope.brackets() {
2935 if !pair.close && !pair.surround {
2936 continue;
2937 }
2938
2939 if enabled && pair.start.ends_with(text.as_ref()) {
2940 let prefix_len = pair.start.len() - text.len();
2941 let preceding_text_matches_prefix = prefix_len == 0
2942 || (selection.start.column >= (prefix_len as u32)
2943 && snapshot.contains_str_at(
2944 Point::new(
2945 selection.start.row,
2946 selection.start.column - (prefix_len as u32),
2947 ),
2948 &pair.start[..prefix_len],
2949 ));
2950 if preceding_text_matches_prefix {
2951 bracket_pair = Some(pair.clone());
2952 is_bracket_pair_start = true;
2953 break;
2954 }
2955 }
2956 if pair.end.as_str() == text.as_ref() {
2957 bracket_pair = Some(pair.clone());
2958 is_bracket_pair_end = true;
2959 break;
2960 }
2961 }
2962 }
2963
2964 if let Some(bracket_pair) = bracket_pair {
2965 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
2966 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2967 let auto_surround =
2968 self.use_auto_surround && snapshot_settings.use_auto_surround;
2969 if selection.is_empty() {
2970 if is_bracket_pair_start {
2971 // If the inserted text is a suffix of an opening bracket and the
2972 // selection is preceded by the rest of the opening bracket, then
2973 // insert the closing bracket.
2974 let following_text_allows_autoclose = snapshot
2975 .chars_at(selection.start)
2976 .next()
2977 .map_or(true, |c| scope.should_autoclose_before(c));
2978
2979 let preceding_text_allows_autoclose = selection.start.column == 0
2980 || snapshot.reversed_chars_at(selection.start).next().map_or(
2981 true,
2982 |c| {
2983 bracket_pair.start != bracket_pair.end
2984 || !snapshot
2985 .char_classifier_at(selection.start)
2986 .is_word(c)
2987 },
2988 );
2989
2990 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2991 && bracket_pair.start.len() == 1
2992 {
2993 let target = bracket_pair.start.chars().next().unwrap();
2994 let current_line_count = snapshot
2995 .reversed_chars_at(selection.start)
2996 .take_while(|&c| c != '\n')
2997 .filter(|&c| c == target)
2998 .count();
2999 current_line_count % 2 == 1
3000 } else {
3001 false
3002 };
3003
3004 if autoclose
3005 && bracket_pair.close
3006 && following_text_allows_autoclose
3007 && preceding_text_allows_autoclose
3008 && !is_closing_quote
3009 {
3010 let anchor = snapshot.anchor_before(selection.end);
3011 new_selections.push((selection.map(|_| anchor), text.len()));
3012 new_autoclose_regions.push((
3013 anchor,
3014 text.len(),
3015 selection.id,
3016 bracket_pair.clone(),
3017 ));
3018 edits.push((
3019 selection.range(),
3020 format!("{}{}", text, bracket_pair.end).into(),
3021 ));
3022 bracket_inserted = true;
3023 continue;
3024 }
3025 }
3026
3027 if let Some(region) = autoclose_region {
3028 // If the selection is followed by an auto-inserted closing bracket,
3029 // then don't insert that closing bracket again; just move the selection
3030 // past the closing bracket.
3031 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3032 && text.as_ref() == region.pair.end.as_str();
3033 if should_skip {
3034 let anchor = snapshot.anchor_after(selection.end);
3035 new_selections
3036 .push((selection.map(|_| anchor), region.pair.end.len()));
3037 continue;
3038 }
3039 }
3040
3041 let always_treat_brackets_as_autoclosed = snapshot
3042 .language_settings_at(selection.start, cx)
3043 .always_treat_brackets_as_autoclosed;
3044 if always_treat_brackets_as_autoclosed
3045 && is_bracket_pair_end
3046 && snapshot.contains_str_at(selection.end, text.as_ref())
3047 {
3048 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3049 // and the inserted text is a closing bracket and the selection is followed
3050 // by the closing bracket then move the selection past the closing bracket.
3051 let anchor = snapshot.anchor_after(selection.end);
3052 new_selections.push((selection.map(|_| anchor), text.len()));
3053 continue;
3054 }
3055 }
3056 // If an opening bracket is 1 character long and is typed while
3057 // text is selected, then surround that text with the bracket pair.
3058 else if auto_surround
3059 && bracket_pair.surround
3060 && is_bracket_pair_start
3061 && bracket_pair.start.chars().count() == 1
3062 {
3063 edits.push((selection.start..selection.start, text.clone()));
3064 edits.push((
3065 selection.end..selection.end,
3066 bracket_pair.end.as_str().into(),
3067 ));
3068 bracket_inserted = true;
3069 new_selections.push((
3070 Selection {
3071 id: selection.id,
3072 start: snapshot.anchor_after(selection.start),
3073 end: snapshot.anchor_before(selection.end),
3074 reversed: selection.reversed,
3075 goal: selection.goal,
3076 },
3077 0,
3078 ));
3079 continue;
3080 }
3081 }
3082 }
3083
3084 if self.auto_replace_emoji_shortcode
3085 && selection.is_empty()
3086 && text.as_ref().ends_with(':')
3087 {
3088 if let Some(possible_emoji_short_code) =
3089 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3090 {
3091 if !possible_emoji_short_code.is_empty() {
3092 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3093 let emoji_shortcode_start = Point::new(
3094 selection.start.row,
3095 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3096 );
3097
3098 // Remove shortcode from buffer
3099 edits.push((
3100 emoji_shortcode_start..selection.start,
3101 "".to_string().into(),
3102 ));
3103 new_selections.push((
3104 Selection {
3105 id: selection.id,
3106 start: snapshot.anchor_after(emoji_shortcode_start),
3107 end: snapshot.anchor_before(selection.start),
3108 reversed: selection.reversed,
3109 goal: selection.goal,
3110 },
3111 0,
3112 ));
3113
3114 // Insert emoji
3115 let selection_start_anchor = snapshot.anchor_after(selection.start);
3116 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3117 edits.push((selection.start..selection.end, emoji.to_string().into()));
3118
3119 continue;
3120 }
3121 }
3122 }
3123 }
3124
3125 // If not handling any auto-close operation, then just replace the selected
3126 // text with the given input and move the selection to the end of the
3127 // newly inserted text.
3128 let anchor = snapshot.anchor_after(selection.end);
3129 if !self.linked_edit_ranges.is_empty() {
3130 let start_anchor = snapshot.anchor_before(selection.start);
3131
3132 let is_word_char = text.chars().next().map_or(true, |char| {
3133 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3134 classifier.is_word(char)
3135 });
3136
3137 if is_word_char {
3138 if let Some(ranges) = self
3139 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3140 {
3141 for (buffer, edits) in ranges {
3142 linked_edits
3143 .entry(buffer.clone())
3144 .or_default()
3145 .extend(edits.into_iter().map(|range| (range, text.clone())));
3146 }
3147 }
3148 }
3149 }
3150
3151 new_selections.push((selection.map(|_| anchor), 0));
3152 edits.push((selection.start..selection.end, text.clone()));
3153 }
3154
3155 drop(snapshot);
3156
3157 self.transact(window, cx, |this, window, cx| {
3158 let initial_buffer_versions =
3159 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3160
3161 this.buffer.update(cx, |buffer, cx| {
3162 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3163 });
3164 for (buffer, edits) in linked_edits {
3165 buffer.update(cx, |buffer, cx| {
3166 let snapshot = buffer.snapshot();
3167 let edits = edits
3168 .into_iter()
3169 .map(|(range, text)| {
3170 use text::ToPoint as TP;
3171 let end_point = TP::to_point(&range.end, &snapshot);
3172 let start_point = TP::to_point(&range.start, &snapshot);
3173 (start_point..end_point, text)
3174 })
3175 .sorted_by_key(|(range, _)| range.start)
3176 .collect::<Vec<_>>();
3177 buffer.edit(edits, None, cx);
3178 })
3179 }
3180 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3181 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3182 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3183 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3184 .zip(new_selection_deltas)
3185 .map(|(selection, delta)| Selection {
3186 id: selection.id,
3187 start: selection.start + delta,
3188 end: selection.end + delta,
3189 reversed: selection.reversed,
3190 goal: SelectionGoal::None,
3191 })
3192 .collect::<Vec<_>>();
3193
3194 let mut i = 0;
3195 for (position, delta, selection_id, pair) in new_autoclose_regions {
3196 let position = position.to_offset(&map.buffer_snapshot) + delta;
3197 let start = map.buffer_snapshot.anchor_before(position);
3198 let end = map.buffer_snapshot.anchor_after(position);
3199 while let Some(existing_state) = this.autoclose_regions.get(i) {
3200 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3201 Ordering::Less => i += 1,
3202 Ordering::Greater => break,
3203 Ordering::Equal => {
3204 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3205 Ordering::Less => i += 1,
3206 Ordering::Equal => break,
3207 Ordering::Greater => break,
3208 }
3209 }
3210 }
3211 }
3212 this.autoclose_regions.insert(
3213 i,
3214 AutocloseRegion {
3215 selection_id,
3216 range: start..end,
3217 pair,
3218 },
3219 );
3220 }
3221
3222 let had_active_inline_completion = this.has_active_inline_completion();
3223 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3224 s.select(new_selections)
3225 });
3226
3227 if !bracket_inserted {
3228 if let Some(on_type_format_task) =
3229 this.trigger_on_type_formatting(text.to_string(), window, cx)
3230 {
3231 on_type_format_task.detach_and_log_err(cx);
3232 }
3233 }
3234
3235 let editor_settings = EditorSettings::get_global(cx);
3236 if bracket_inserted
3237 && (editor_settings.auto_signature_help
3238 || editor_settings.show_signature_help_after_edits)
3239 {
3240 this.show_signature_help(&ShowSignatureHelp, window, cx);
3241 }
3242
3243 let trigger_in_words =
3244 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3245 if this.hard_wrap.is_some() {
3246 let latest: Range<Point> = this.selections.newest(cx).range();
3247 if latest.is_empty()
3248 && this
3249 .buffer()
3250 .read(cx)
3251 .snapshot(cx)
3252 .line_len(MultiBufferRow(latest.start.row))
3253 == latest.start.column
3254 {
3255 this.rewrap_impl(
3256 RewrapOptions {
3257 override_language_settings: true,
3258 preserve_existing_whitespace: true,
3259 },
3260 cx,
3261 )
3262 }
3263 }
3264 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3265 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3266 this.refresh_inline_completion(true, false, window, cx);
3267 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3268 });
3269 }
3270
3271 fn find_possible_emoji_shortcode_at_position(
3272 snapshot: &MultiBufferSnapshot,
3273 position: Point,
3274 ) -> Option<String> {
3275 let mut chars = Vec::new();
3276 let mut found_colon = false;
3277 for char in snapshot.reversed_chars_at(position).take(100) {
3278 // Found a possible emoji shortcode in the middle of the buffer
3279 if found_colon {
3280 if char.is_whitespace() {
3281 chars.reverse();
3282 return Some(chars.iter().collect());
3283 }
3284 // If the previous character is not a whitespace, we are in the middle of a word
3285 // and we only want to complete the shortcode if the word is made up of other emojis
3286 let mut containing_word = String::new();
3287 for ch in snapshot
3288 .reversed_chars_at(position)
3289 .skip(chars.len() + 1)
3290 .take(100)
3291 {
3292 if ch.is_whitespace() {
3293 break;
3294 }
3295 containing_word.push(ch);
3296 }
3297 let containing_word = containing_word.chars().rev().collect::<String>();
3298 if util::word_consists_of_emojis(containing_word.as_str()) {
3299 chars.reverse();
3300 return Some(chars.iter().collect());
3301 }
3302 }
3303
3304 if char.is_whitespace() || !char.is_ascii() {
3305 return None;
3306 }
3307 if char == ':' {
3308 found_colon = true;
3309 } else {
3310 chars.push(char);
3311 }
3312 }
3313 // Found a possible emoji shortcode at the beginning of the buffer
3314 chars.reverse();
3315 Some(chars.iter().collect())
3316 }
3317
3318 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3319 self.transact(window, cx, |this, window, cx| {
3320 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3321 let selections = this.selections.all::<usize>(cx);
3322 let multi_buffer = this.buffer.read(cx);
3323 let buffer = multi_buffer.snapshot(cx);
3324 selections
3325 .iter()
3326 .map(|selection| {
3327 let start_point = selection.start.to_point(&buffer);
3328 let mut indent =
3329 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3330 indent.len = cmp::min(indent.len, start_point.column);
3331 let start = selection.start;
3332 let end = selection.end;
3333 let selection_is_empty = start == end;
3334 let language_scope = buffer.language_scope_at(start);
3335 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3336 &language_scope
3337 {
3338 let insert_extra_newline =
3339 insert_extra_newline_brackets(&buffer, start..end, language)
3340 || insert_extra_newline_tree_sitter(&buffer, start..end);
3341
3342 // Comment extension on newline is allowed only for cursor selections
3343 let comment_delimiter = maybe!({
3344 if !selection_is_empty {
3345 return None;
3346 }
3347
3348 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3349 return None;
3350 }
3351
3352 let delimiters = language.line_comment_prefixes();
3353 let max_len_of_delimiter =
3354 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3355 let (snapshot, range) =
3356 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3357
3358 let mut index_of_first_non_whitespace = 0;
3359 let comment_candidate = snapshot
3360 .chars_for_range(range)
3361 .skip_while(|c| {
3362 let should_skip = c.is_whitespace();
3363 if should_skip {
3364 index_of_first_non_whitespace += 1;
3365 }
3366 should_skip
3367 })
3368 .take(max_len_of_delimiter)
3369 .collect::<String>();
3370 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3371 comment_candidate.starts_with(comment_prefix.as_ref())
3372 })?;
3373 let cursor_is_placed_after_comment_marker =
3374 index_of_first_non_whitespace + comment_prefix.len()
3375 <= start_point.column as usize;
3376 if cursor_is_placed_after_comment_marker {
3377 Some(comment_prefix.clone())
3378 } else {
3379 None
3380 }
3381 });
3382 (comment_delimiter, insert_extra_newline)
3383 } else {
3384 (None, false)
3385 };
3386
3387 let capacity_for_delimiter = comment_delimiter
3388 .as_deref()
3389 .map(str::len)
3390 .unwrap_or_default();
3391 let mut new_text =
3392 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3393 new_text.push('\n');
3394 new_text.extend(indent.chars());
3395 if let Some(delimiter) = &comment_delimiter {
3396 new_text.push_str(delimiter);
3397 }
3398 if insert_extra_newline {
3399 new_text = new_text.repeat(2);
3400 }
3401
3402 let anchor = buffer.anchor_after(end);
3403 let new_selection = selection.map(|_| anchor);
3404 (
3405 (start..end, new_text),
3406 (insert_extra_newline, new_selection),
3407 )
3408 })
3409 .unzip()
3410 };
3411
3412 this.edit_with_autoindent(edits, cx);
3413 let buffer = this.buffer.read(cx).snapshot(cx);
3414 let new_selections = selection_fixup_info
3415 .into_iter()
3416 .map(|(extra_newline_inserted, new_selection)| {
3417 let mut cursor = new_selection.end.to_point(&buffer);
3418 if extra_newline_inserted {
3419 cursor.row -= 1;
3420 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3421 }
3422 new_selection.map(|_| cursor)
3423 })
3424 .collect();
3425
3426 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3427 s.select(new_selections)
3428 });
3429 this.refresh_inline_completion(true, false, window, cx);
3430 });
3431 }
3432
3433 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3434 let buffer = self.buffer.read(cx);
3435 let snapshot = buffer.snapshot(cx);
3436
3437 let mut edits = Vec::new();
3438 let mut rows = Vec::new();
3439
3440 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3441 let cursor = selection.head();
3442 let row = cursor.row;
3443
3444 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3445
3446 let newline = "\n".to_string();
3447 edits.push((start_of_line..start_of_line, newline));
3448
3449 rows.push(row + rows_inserted as u32);
3450 }
3451
3452 self.transact(window, cx, |editor, window, cx| {
3453 editor.edit(edits, cx);
3454
3455 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3456 let mut index = 0;
3457 s.move_cursors_with(|map, _, _| {
3458 let row = rows[index];
3459 index += 1;
3460
3461 let point = Point::new(row, 0);
3462 let boundary = map.next_line_boundary(point).1;
3463 let clipped = map.clip_point(boundary, Bias::Left);
3464
3465 (clipped, SelectionGoal::None)
3466 });
3467 });
3468
3469 let mut indent_edits = Vec::new();
3470 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3471 for row in rows {
3472 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3473 for (row, indent) in indents {
3474 if indent.len == 0 {
3475 continue;
3476 }
3477
3478 let text = match indent.kind {
3479 IndentKind::Space => " ".repeat(indent.len as usize),
3480 IndentKind::Tab => "\t".repeat(indent.len as usize),
3481 };
3482 let point = Point::new(row.0, 0);
3483 indent_edits.push((point..point, text));
3484 }
3485 }
3486 editor.edit(indent_edits, cx);
3487 });
3488 }
3489
3490 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3491 let buffer = self.buffer.read(cx);
3492 let snapshot = buffer.snapshot(cx);
3493
3494 let mut edits = Vec::new();
3495 let mut rows = Vec::new();
3496 let mut rows_inserted = 0;
3497
3498 for selection in self.selections.all_adjusted(cx) {
3499 let cursor = selection.head();
3500 let row = cursor.row;
3501
3502 let point = Point::new(row + 1, 0);
3503 let start_of_line = snapshot.clip_point(point, Bias::Left);
3504
3505 let newline = "\n".to_string();
3506 edits.push((start_of_line..start_of_line, newline));
3507
3508 rows_inserted += 1;
3509 rows.push(row + rows_inserted);
3510 }
3511
3512 self.transact(window, cx, |editor, window, cx| {
3513 editor.edit(edits, cx);
3514
3515 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3516 let mut index = 0;
3517 s.move_cursors_with(|map, _, _| {
3518 let row = rows[index];
3519 index += 1;
3520
3521 let point = Point::new(row, 0);
3522 let boundary = map.next_line_boundary(point).1;
3523 let clipped = map.clip_point(boundary, Bias::Left);
3524
3525 (clipped, SelectionGoal::None)
3526 });
3527 });
3528
3529 let mut indent_edits = Vec::new();
3530 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3531 for row in rows {
3532 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3533 for (row, indent) in indents {
3534 if indent.len == 0 {
3535 continue;
3536 }
3537
3538 let text = match indent.kind {
3539 IndentKind::Space => " ".repeat(indent.len as usize),
3540 IndentKind::Tab => "\t".repeat(indent.len as usize),
3541 };
3542 let point = Point::new(row.0, 0);
3543 indent_edits.push((point..point, text));
3544 }
3545 }
3546 editor.edit(indent_edits, cx);
3547 });
3548 }
3549
3550 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3551 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3552 original_indent_columns: Vec::new(),
3553 });
3554 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3555 }
3556
3557 fn insert_with_autoindent_mode(
3558 &mut self,
3559 text: &str,
3560 autoindent_mode: Option<AutoindentMode>,
3561 window: &mut Window,
3562 cx: &mut Context<Self>,
3563 ) {
3564 if self.read_only(cx) {
3565 return;
3566 }
3567
3568 let text: Arc<str> = text.into();
3569 self.transact(window, cx, |this, window, cx| {
3570 let old_selections = this.selections.all_adjusted(cx);
3571 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3572 let anchors = {
3573 let snapshot = buffer.read(cx);
3574 old_selections
3575 .iter()
3576 .map(|s| {
3577 let anchor = snapshot.anchor_after(s.head());
3578 s.map(|_| anchor)
3579 })
3580 .collect::<Vec<_>>()
3581 };
3582 buffer.edit(
3583 old_selections
3584 .iter()
3585 .map(|s| (s.start..s.end, text.clone())),
3586 autoindent_mode,
3587 cx,
3588 );
3589 anchors
3590 });
3591
3592 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3593 s.select_anchors(selection_anchors);
3594 });
3595
3596 cx.notify();
3597 });
3598 }
3599
3600 fn trigger_completion_on_input(
3601 &mut self,
3602 text: &str,
3603 trigger_in_words: bool,
3604 window: &mut Window,
3605 cx: &mut Context<Self>,
3606 ) {
3607 let ignore_completion_provider = self
3608 .context_menu
3609 .borrow()
3610 .as_ref()
3611 .map(|menu| match menu {
3612 CodeContextMenu::Completions(completions_menu) => {
3613 completions_menu.ignore_completion_provider
3614 }
3615 CodeContextMenu::CodeActions(_) => false,
3616 })
3617 .unwrap_or(false);
3618
3619 if ignore_completion_provider {
3620 self.show_word_completions(&ShowWordCompletions, window, cx);
3621 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3622 self.show_completions(
3623 &ShowCompletions {
3624 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3625 },
3626 window,
3627 cx,
3628 );
3629 } else {
3630 self.hide_context_menu(window, cx);
3631 }
3632 }
3633
3634 fn is_completion_trigger(
3635 &self,
3636 text: &str,
3637 trigger_in_words: bool,
3638 cx: &mut Context<Self>,
3639 ) -> bool {
3640 let position = self.selections.newest_anchor().head();
3641 let multibuffer = self.buffer.read(cx);
3642 let Some(buffer) = position
3643 .buffer_id
3644 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3645 else {
3646 return false;
3647 };
3648
3649 if let Some(completion_provider) = &self.completion_provider {
3650 completion_provider.is_completion_trigger(
3651 &buffer,
3652 position.text_anchor,
3653 text,
3654 trigger_in_words,
3655 cx,
3656 )
3657 } else {
3658 false
3659 }
3660 }
3661
3662 /// If any empty selections is touching the start of its innermost containing autoclose
3663 /// region, expand it to select the brackets.
3664 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3665 let selections = self.selections.all::<usize>(cx);
3666 let buffer = self.buffer.read(cx).read(cx);
3667 let new_selections = self
3668 .selections_with_autoclose_regions(selections, &buffer)
3669 .map(|(mut selection, region)| {
3670 if !selection.is_empty() {
3671 return selection;
3672 }
3673
3674 if let Some(region) = region {
3675 let mut range = region.range.to_offset(&buffer);
3676 if selection.start == range.start && range.start >= region.pair.start.len() {
3677 range.start -= region.pair.start.len();
3678 if buffer.contains_str_at(range.start, ®ion.pair.start)
3679 && buffer.contains_str_at(range.end, ®ion.pair.end)
3680 {
3681 range.end += region.pair.end.len();
3682 selection.start = range.start;
3683 selection.end = range.end;
3684
3685 return selection;
3686 }
3687 }
3688 }
3689
3690 let always_treat_brackets_as_autoclosed = buffer
3691 .language_settings_at(selection.start, cx)
3692 .always_treat_brackets_as_autoclosed;
3693
3694 if !always_treat_brackets_as_autoclosed {
3695 return selection;
3696 }
3697
3698 if let Some(scope) = buffer.language_scope_at(selection.start) {
3699 for (pair, enabled) in scope.brackets() {
3700 if !enabled || !pair.close {
3701 continue;
3702 }
3703
3704 if buffer.contains_str_at(selection.start, &pair.end) {
3705 let pair_start_len = pair.start.len();
3706 if buffer.contains_str_at(
3707 selection.start.saturating_sub(pair_start_len),
3708 &pair.start,
3709 ) {
3710 selection.start -= pair_start_len;
3711 selection.end += pair.end.len();
3712
3713 return selection;
3714 }
3715 }
3716 }
3717 }
3718
3719 selection
3720 })
3721 .collect();
3722
3723 drop(buffer);
3724 self.change_selections(None, window, cx, |selections| {
3725 selections.select(new_selections)
3726 });
3727 }
3728
3729 /// Iterate the given selections, and for each one, find the smallest surrounding
3730 /// autoclose region. This uses the ordering of the selections and the autoclose
3731 /// regions to avoid repeated comparisons.
3732 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3733 &'a self,
3734 selections: impl IntoIterator<Item = Selection<D>>,
3735 buffer: &'a MultiBufferSnapshot,
3736 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3737 let mut i = 0;
3738 let mut regions = self.autoclose_regions.as_slice();
3739 selections.into_iter().map(move |selection| {
3740 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3741
3742 let mut enclosing = None;
3743 while let Some(pair_state) = regions.get(i) {
3744 if pair_state.range.end.to_offset(buffer) < range.start {
3745 regions = ®ions[i + 1..];
3746 i = 0;
3747 } else if pair_state.range.start.to_offset(buffer) > range.end {
3748 break;
3749 } else {
3750 if pair_state.selection_id == selection.id {
3751 enclosing = Some(pair_state);
3752 }
3753 i += 1;
3754 }
3755 }
3756
3757 (selection, enclosing)
3758 })
3759 }
3760
3761 /// Remove any autoclose regions that no longer contain their selection.
3762 fn invalidate_autoclose_regions(
3763 &mut self,
3764 mut selections: &[Selection<Anchor>],
3765 buffer: &MultiBufferSnapshot,
3766 ) {
3767 self.autoclose_regions.retain(|state| {
3768 let mut i = 0;
3769 while let Some(selection) = selections.get(i) {
3770 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3771 selections = &selections[1..];
3772 continue;
3773 }
3774 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3775 break;
3776 }
3777 if selection.id == state.selection_id {
3778 return true;
3779 } else {
3780 i += 1;
3781 }
3782 }
3783 false
3784 });
3785 }
3786
3787 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3788 let offset = position.to_offset(buffer);
3789 let (word_range, kind) = buffer.surrounding_word(offset, true);
3790 if offset > word_range.start && kind == Some(CharKind::Word) {
3791 Some(
3792 buffer
3793 .text_for_range(word_range.start..offset)
3794 .collect::<String>(),
3795 )
3796 } else {
3797 None
3798 }
3799 }
3800
3801 pub fn toggle_inlay_hints(
3802 &mut self,
3803 _: &ToggleInlayHints,
3804 _: &mut Window,
3805 cx: &mut Context<Self>,
3806 ) {
3807 self.refresh_inlay_hints(
3808 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
3809 cx,
3810 );
3811 }
3812
3813 pub fn inlay_hints_enabled(&self) -> bool {
3814 self.inlay_hint_cache.enabled
3815 }
3816
3817 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3818 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3819 return;
3820 }
3821
3822 let reason_description = reason.description();
3823 let ignore_debounce = matches!(
3824 reason,
3825 InlayHintRefreshReason::SettingsChange(_)
3826 | InlayHintRefreshReason::Toggle(_)
3827 | InlayHintRefreshReason::ExcerptsRemoved(_)
3828 | InlayHintRefreshReason::ModifiersChanged(_)
3829 );
3830 let (invalidate_cache, required_languages) = match reason {
3831 InlayHintRefreshReason::ModifiersChanged(enabled) => {
3832 match self.inlay_hint_cache.modifiers_override(enabled) {
3833 Some(enabled) => {
3834 if enabled {
3835 (InvalidationStrategy::RefreshRequested, None)
3836 } else {
3837 self.splice_inlays(
3838 &self
3839 .visible_inlay_hints(cx)
3840 .iter()
3841 .map(|inlay| inlay.id)
3842 .collect::<Vec<InlayId>>(),
3843 Vec::new(),
3844 cx,
3845 );
3846 return;
3847 }
3848 }
3849 None => return,
3850 }
3851 }
3852 InlayHintRefreshReason::Toggle(enabled) => {
3853 if self.inlay_hint_cache.toggle(enabled) {
3854 if enabled {
3855 (InvalidationStrategy::RefreshRequested, None)
3856 } else {
3857 self.splice_inlays(
3858 &self
3859 .visible_inlay_hints(cx)
3860 .iter()
3861 .map(|inlay| inlay.id)
3862 .collect::<Vec<InlayId>>(),
3863 Vec::new(),
3864 cx,
3865 );
3866 return;
3867 }
3868 } else {
3869 return;
3870 }
3871 }
3872 InlayHintRefreshReason::SettingsChange(new_settings) => {
3873 match self.inlay_hint_cache.update_settings(
3874 &self.buffer,
3875 new_settings,
3876 self.visible_inlay_hints(cx),
3877 cx,
3878 ) {
3879 ControlFlow::Break(Some(InlaySplice {
3880 to_remove,
3881 to_insert,
3882 })) => {
3883 self.splice_inlays(&to_remove, to_insert, cx);
3884 return;
3885 }
3886 ControlFlow::Break(None) => return,
3887 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3888 }
3889 }
3890 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3891 if let Some(InlaySplice {
3892 to_remove,
3893 to_insert,
3894 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3895 {
3896 self.splice_inlays(&to_remove, to_insert, cx);
3897 }
3898 return;
3899 }
3900 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3901 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3902 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3903 }
3904 InlayHintRefreshReason::RefreshRequested => {
3905 (InvalidationStrategy::RefreshRequested, None)
3906 }
3907 };
3908
3909 if let Some(InlaySplice {
3910 to_remove,
3911 to_insert,
3912 }) = self.inlay_hint_cache.spawn_hint_refresh(
3913 reason_description,
3914 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3915 invalidate_cache,
3916 ignore_debounce,
3917 cx,
3918 ) {
3919 self.splice_inlays(&to_remove, to_insert, cx);
3920 }
3921 }
3922
3923 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3924 self.display_map
3925 .read(cx)
3926 .current_inlays()
3927 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3928 .cloned()
3929 .collect()
3930 }
3931
3932 pub fn excerpts_for_inlay_hints_query(
3933 &self,
3934 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3935 cx: &mut Context<Editor>,
3936 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3937 let Some(project) = self.project.as_ref() else {
3938 return HashMap::default();
3939 };
3940 let project = project.read(cx);
3941 let multi_buffer = self.buffer().read(cx);
3942 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3943 let multi_buffer_visible_start = self
3944 .scroll_manager
3945 .anchor()
3946 .anchor
3947 .to_point(&multi_buffer_snapshot);
3948 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3949 multi_buffer_visible_start
3950 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3951 Bias::Left,
3952 );
3953 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3954 multi_buffer_snapshot
3955 .range_to_buffer_ranges(multi_buffer_visible_range)
3956 .into_iter()
3957 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3958 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3959 let buffer_file = project::File::from_dyn(buffer.file())?;
3960 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3961 let worktree_entry = buffer_worktree
3962 .read(cx)
3963 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3964 if worktree_entry.is_ignored {
3965 return None;
3966 }
3967
3968 let language = buffer.language()?;
3969 if let Some(restrict_to_languages) = restrict_to_languages {
3970 if !restrict_to_languages.contains(language) {
3971 return None;
3972 }
3973 }
3974 Some((
3975 excerpt_id,
3976 (
3977 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3978 buffer.version().clone(),
3979 excerpt_visible_range,
3980 ),
3981 ))
3982 })
3983 .collect()
3984 }
3985
3986 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3987 TextLayoutDetails {
3988 text_system: window.text_system().clone(),
3989 editor_style: self.style.clone().unwrap(),
3990 rem_size: window.rem_size(),
3991 scroll_anchor: self.scroll_manager.anchor(),
3992 visible_rows: self.visible_line_count(),
3993 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3994 }
3995 }
3996
3997 pub fn splice_inlays(
3998 &self,
3999 to_remove: &[InlayId],
4000 to_insert: Vec<Inlay>,
4001 cx: &mut Context<Self>,
4002 ) {
4003 self.display_map.update(cx, |display_map, cx| {
4004 display_map.splice_inlays(to_remove, to_insert, cx)
4005 });
4006 cx.notify();
4007 }
4008
4009 fn trigger_on_type_formatting(
4010 &self,
4011 input: String,
4012 window: &mut Window,
4013 cx: &mut Context<Self>,
4014 ) -> Option<Task<Result<()>>> {
4015 if input.len() != 1 {
4016 return None;
4017 }
4018
4019 let project = self.project.as_ref()?;
4020 let position = self.selections.newest_anchor().head();
4021 let (buffer, buffer_position) = self
4022 .buffer
4023 .read(cx)
4024 .text_anchor_for_position(position, cx)?;
4025
4026 let settings = language_settings::language_settings(
4027 buffer
4028 .read(cx)
4029 .language_at(buffer_position)
4030 .map(|l| l.name()),
4031 buffer.read(cx).file(),
4032 cx,
4033 );
4034 if !settings.use_on_type_format {
4035 return None;
4036 }
4037
4038 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4039 // hence we do LSP request & edit on host side only — add formats to host's history.
4040 let push_to_lsp_host_history = true;
4041 // If this is not the host, append its history with new edits.
4042 let push_to_client_history = project.read(cx).is_via_collab();
4043
4044 let on_type_formatting = project.update(cx, |project, cx| {
4045 project.on_type_format(
4046 buffer.clone(),
4047 buffer_position,
4048 input,
4049 push_to_lsp_host_history,
4050 cx,
4051 )
4052 });
4053 Some(cx.spawn_in(window, async move |editor, cx| {
4054 if let Some(transaction) = on_type_formatting.await? {
4055 if push_to_client_history {
4056 buffer
4057 .update(cx, |buffer, _| {
4058 buffer.push_transaction(transaction, Instant::now());
4059 })
4060 .ok();
4061 }
4062 editor.update(cx, |editor, cx| {
4063 editor.refresh_document_highlights(cx);
4064 })?;
4065 }
4066 Ok(())
4067 }))
4068 }
4069
4070 pub fn show_word_completions(
4071 &mut self,
4072 _: &ShowWordCompletions,
4073 window: &mut Window,
4074 cx: &mut Context<Self>,
4075 ) {
4076 self.open_completions_menu(true, None, window, cx);
4077 }
4078
4079 pub fn show_completions(
4080 &mut self,
4081 options: &ShowCompletions,
4082 window: &mut Window,
4083 cx: &mut Context<Self>,
4084 ) {
4085 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4086 }
4087
4088 fn open_completions_menu(
4089 &mut self,
4090 ignore_completion_provider: bool,
4091 trigger: Option<&str>,
4092 window: &mut Window,
4093 cx: &mut Context<Self>,
4094 ) {
4095 if self.pending_rename.is_some() {
4096 return;
4097 }
4098 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4099 return;
4100 }
4101
4102 let position = self.selections.newest_anchor().head();
4103 if position.diff_base_anchor.is_some() {
4104 return;
4105 }
4106 let (buffer, buffer_position) =
4107 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4108 output
4109 } else {
4110 return;
4111 };
4112 let buffer_snapshot = buffer.read(cx).snapshot();
4113 let show_completion_documentation = buffer_snapshot
4114 .settings_at(buffer_position, cx)
4115 .show_completion_documentation;
4116
4117 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4118
4119 let trigger_kind = match trigger {
4120 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4121 CompletionTriggerKind::TRIGGER_CHARACTER
4122 }
4123 _ => CompletionTriggerKind::INVOKED,
4124 };
4125 let completion_context = CompletionContext {
4126 trigger_character: trigger.and_then(|trigger| {
4127 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4128 Some(String::from(trigger))
4129 } else {
4130 None
4131 }
4132 }),
4133 trigger_kind,
4134 };
4135
4136 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4137 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4138 let word_to_exclude = buffer_snapshot
4139 .text_for_range(old_range.clone())
4140 .collect::<String>();
4141 (
4142 buffer_snapshot.anchor_before(old_range.start)
4143 ..buffer_snapshot.anchor_after(old_range.end),
4144 Some(word_to_exclude),
4145 )
4146 } else {
4147 (buffer_position..buffer_position, None)
4148 };
4149
4150 let completion_settings = language_settings(
4151 buffer_snapshot
4152 .language_at(buffer_position)
4153 .map(|language| language.name()),
4154 buffer_snapshot.file(),
4155 cx,
4156 )
4157 .completions;
4158
4159 // The document can be large, so stay in reasonable bounds when searching for words,
4160 // otherwise completion pop-up might be slow to appear.
4161 const WORD_LOOKUP_ROWS: u32 = 5_000;
4162 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4163 let min_word_search = buffer_snapshot.clip_point(
4164 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4165 Bias::Left,
4166 );
4167 let max_word_search = buffer_snapshot.clip_point(
4168 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4169 Bias::Right,
4170 );
4171 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4172 ..buffer_snapshot.point_to_offset(max_word_search);
4173
4174 let provider = self
4175 .completion_provider
4176 .as_ref()
4177 .filter(|_| !ignore_completion_provider);
4178 let skip_digits = query
4179 .as_ref()
4180 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4181
4182 let (mut words, provided_completions) = match provider {
4183 Some(provider) => {
4184 let completions =
4185 provider.completions(&buffer, buffer_position, completion_context, window, cx);
4186
4187 let words = match completion_settings.words {
4188 WordsCompletionMode::Disabled => Task::ready(HashMap::default()),
4189 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4190 .background_spawn(async move {
4191 buffer_snapshot.words_in_range(WordsQuery {
4192 fuzzy_contents: None,
4193 range: word_search_range,
4194 skip_digits,
4195 })
4196 }),
4197 };
4198
4199 (words, completions)
4200 }
4201 None => (
4202 cx.background_spawn(async move {
4203 buffer_snapshot.words_in_range(WordsQuery {
4204 fuzzy_contents: None,
4205 range: word_search_range,
4206 skip_digits,
4207 })
4208 }),
4209 Task::ready(Ok(None)),
4210 ),
4211 };
4212
4213 let sort_completions = provider
4214 .as_ref()
4215 .map_or(true, |provider| provider.sort_completions());
4216
4217 let id = post_inc(&mut self.next_completion_id);
4218 let task = cx.spawn_in(window, async move |editor, cx| {
4219 async move {
4220 editor.update(cx, |this, _| {
4221 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4222 })?;
4223
4224 let mut completions = Vec::new();
4225 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4226 completions.extend(provided_completions);
4227 if completion_settings.words == WordsCompletionMode::Fallback {
4228 words = Task::ready(HashMap::default());
4229 }
4230 }
4231
4232 let mut words = words.await;
4233 if let Some(word_to_exclude) = &word_to_exclude {
4234 words.remove(word_to_exclude);
4235 }
4236 for lsp_completion in &completions {
4237 words.remove(&lsp_completion.new_text);
4238 }
4239 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4240 old_range: old_range.clone(),
4241 new_text: word.clone(),
4242 label: CodeLabel::plain(word, None),
4243 documentation: None,
4244 source: CompletionSource::BufferWord {
4245 word_range,
4246 resolved: false,
4247 },
4248 confirm: None,
4249 }));
4250
4251 let menu = if completions.is_empty() {
4252 None
4253 } else {
4254 let mut menu = CompletionsMenu::new(
4255 id,
4256 sort_completions,
4257 show_completion_documentation,
4258 ignore_completion_provider,
4259 position,
4260 buffer.clone(),
4261 completions.into(),
4262 );
4263
4264 menu.filter(query.as_deref(), cx.background_executor().clone())
4265 .await;
4266
4267 menu.visible().then_some(menu)
4268 };
4269
4270 editor.update_in(cx, |editor, window, cx| {
4271 match editor.context_menu.borrow().as_ref() {
4272 None => {}
4273 Some(CodeContextMenu::Completions(prev_menu)) => {
4274 if prev_menu.id > id {
4275 return;
4276 }
4277 }
4278 _ => return,
4279 }
4280
4281 if editor.focus_handle.is_focused(window) && menu.is_some() {
4282 let mut menu = menu.unwrap();
4283 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4284
4285 *editor.context_menu.borrow_mut() =
4286 Some(CodeContextMenu::Completions(menu));
4287
4288 if editor.show_edit_predictions_in_menu() {
4289 editor.update_visible_inline_completion(window, cx);
4290 } else {
4291 editor.discard_inline_completion(false, cx);
4292 }
4293
4294 cx.notify();
4295 } else if editor.completion_tasks.len() <= 1 {
4296 // If there are no more completion tasks and the last menu was
4297 // empty, we should hide it.
4298 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4299 // If it was already hidden and we don't show inline
4300 // completions in the menu, we should also show the
4301 // inline-completion when available.
4302 if was_hidden && editor.show_edit_predictions_in_menu() {
4303 editor.update_visible_inline_completion(window, cx);
4304 }
4305 }
4306 })?;
4307
4308 anyhow::Ok(())
4309 }
4310 .log_err()
4311 .await
4312 });
4313
4314 self.completion_tasks.push((id, task));
4315 }
4316
4317 pub fn confirm_completion(
4318 &mut self,
4319 action: &ConfirmCompletion,
4320 window: &mut Window,
4321 cx: &mut Context<Self>,
4322 ) -> Option<Task<Result<()>>> {
4323 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4324 }
4325
4326 pub fn compose_completion(
4327 &mut self,
4328 action: &ComposeCompletion,
4329 window: &mut Window,
4330 cx: &mut Context<Self>,
4331 ) -> Option<Task<Result<()>>> {
4332 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4333 }
4334
4335 fn do_completion(
4336 &mut self,
4337 item_ix: Option<usize>,
4338 intent: CompletionIntent,
4339 window: &mut Window,
4340 cx: &mut Context<Editor>,
4341 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4342 use language::ToOffset as _;
4343
4344 let completions_menu =
4345 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
4346 menu
4347 } else {
4348 return None;
4349 };
4350
4351 let entries = completions_menu.entries.borrow();
4352 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4353 if self.show_edit_predictions_in_menu() {
4354 self.discard_inline_completion(true, cx);
4355 }
4356 let candidate_id = mat.candidate_id;
4357 drop(entries);
4358
4359 let buffer_handle = completions_menu.buffer;
4360 let completion = completions_menu
4361 .completions
4362 .borrow()
4363 .get(candidate_id)?
4364 .clone();
4365 cx.stop_propagation();
4366
4367 let snippet;
4368 let text;
4369
4370 if completion.is_snippet() {
4371 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4372 text = snippet.as_ref().unwrap().text.clone();
4373 } else {
4374 snippet = None;
4375 text = completion.new_text.clone();
4376 };
4377 let selections = self.selections.all::<usize>(cx);
4378 let buffer = buffer_handle.read(cx);
4379 let old_range = completion.old_range.to_offset(buffer);
4380 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4381
4382 let newest_selection = self.selections.newest_anchor();
4383 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4384 return None;
4385 }
4386
4387 let lookbehind = newest_selection
4388 .start
4389 .text_anchor
4390 .to_offset(buffer)
4391 .saturating_sub(old_range.start);
4392 let lookahead = old_range
4393 .end
4394 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4395 let mut common_prefix_len = old_text
4396 .bytes()
4397 .zip(text.bytes())
4398 .take_while(|(a, b)| a == b)
4399 .count();
4400
4401 let snapshot = self.buffer.read(cx).snapshot(cx);
4402 let mut range_to_replace: Option<Range<isize>> = None;
4403 let mut ranges = Vec::new();
4404 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4405 for selection in &selections {
4406 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4407 let start = selection.start.saturating_sub(lookbehind);
4408 let end = selection.end + lookahead;
4409 if selection.id == newest_selection.id {
4410 range_to_replace = Some(
4411 ((start + common_prefix_len) as isize - selection.start as isize)
4412 ..(end as isize - selection.start as isize),
4413 );
4414 }
4415 ranges.push(start + common_prefix_len..end);
4416 } else {
4417 common_prefix_len = 0;
4418 ranges.clear();
4419 ranges.extend(selections.iter().map(|s| {
4420 if s.id == newest_selection.id {
4421 range_to_replace = Some(
4422 old_range.start.to_offset_utf16(&snapshot).0 as isize
4423 - selection.start as isize
4424 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4425 - selection.start as isize,
4426 );
4427 old_range.clone()
4428 } else {
4429 s.start..s.end
4430 }
4431 }));
4432 break;
4433 }
4434 if !self.linked_edit_ranges.is_empty() {
4435 let start_anchor = snapshot.anchor_before(selection.head());
4436 let end_anchor = snapshot.anchor_after(selection.tail());
4437 if let Some(ranges) = self
4438 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4439 {
4440 for (buffer, edits) in ranges {
4441 linked_edits.entry(buffer.clone()).or_default().extend(
4442 edits
4443 .into_iter()
4444 .map(|range| (range, text[common_prefix_len..].to_owned())),
4445 );
4446 }
4447 }
4448 }
4449 }
4450 let text = &text[common_prefix_len..];
4451
4452 cx.emit(EditorEvent::InputHandled {
4453 utf16_range_to_replace: range_to_replace,
4454 text: text.into(),
4455 });
4456
4457 self.transact(window, cx, |this, window, cx| {
4458 if let Some(mut snippet) = snippet {
4459 snippet.text = text.to_string();
4460 for tabstop in snippet
4461 .tabstops
4462 .iter_mut()
4463 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4464 {
4465 tabstop.start -= common_prefix_len as isize;
4466 tabstop.end -= common_prefix_len as isize;
4467 }
4468
4469 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4470 } else {
4471 this.buffer.update(cx, |buffer, cx| {
4472 buffer.edit(
4473 ranges.iter().map(|range| (range.clone(), text)),
4474 this.autoindent_mode.clone(),
4475 cx,
4476 );
4477 });
4478 }
4479 for (buffer, edits) in linked_edits {
4480 buffer.update(cx, |buffer, cx| {
4481 let snapshot = buffer.snapshot();
4482 let edits = edits
4483 .into_iter()
4484 .map(|(range, text)| {
4485 use text::ToPoint as TP;
4486 let end_point = TP::to_point(&range.end, &snapshot);
4487 let start_point = TP::to_point(&range.start, &snapshot);
4488 (start_point..end_point, text)
4489 })
4490 .sorted_by_key(|(range, _)| range.start)
4491 .collect::<Vec<_>>();
4492 buffer.edit(edits, None, cx);
4493 })
4494 }
4495
4496 this.refresh_inline_completion(true, false, window, cx);
4497 });
4498
4499 let show_new_completions_on_confirm = completion
4500 .confirm
4501 .as_ref()
4502 .map_or(false, |confirm| confirm(intent, window, cx));
4503 if show_new_completions_on_confirm {
4504 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4505 }
4506
4507 let provider = self.completion_provider.as_ref()?;
4508 drop(completion);
4509 let apply_edits = provider.apply_additional_edits_for_completion(
4510 buffer_handle,
4511 completions_menu.completions.clone(),
4512 candidate_id,
4513 true,
4514 cx,
4515 );
4516
4517 let editor_settings = EditorSettings::get_global(cx);
4518 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4519 // After the code completion is finished, users often want to know what signatures are needed.
4520 // so we should automatically call signature_help
4521 self.show_signature_help(&ShowSignatureHelp, window, cx);
4522 }
4523
4524 Some(cx.foreground_executor().spawn(async move {
4525 apply_edits.await?;
4526 Ok(())
4527 }))
4528 }
4529
4530 pub fn toggle_code_actions(
4531 &mut self,
4532 action: &ToggleCodeActions,
4533 window: &mut Window,
4534 cx: &mut Context<Self>,
4535 ) {
4536 let mut context_menu = self.context_menu.borrow_mut();
4537 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4538 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4539 // Toggle if we're selecting the same one
4540 *context_menu = None;
4541 cx.notify();
4542 return;
4543 } else {
4544 // Otherwise, clear it and start a new one
4545 *context_menu = None;
4546 cx.notify();
4547 }
4548 }
4549 drop(context_menu);
4550 let snapshot = self.snapshot(window, cx);
4551 let deployed_from_indicator = action.deployed_from_indicator;
4552 let mut task = self.code_actions_task.take();
4553 let action = action.clone();
4554 cx.spawn_in(window, async move |editor, cx| {
4555 while let Some(prev_task) = task {
4556 prev_task.await.log_err();
4557 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4558 }
4559
4560 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4561 if editor.focus_handle.is_focused(window) {
4562 let multibuffer_point = action
4563 .deployed_from_indicator
4564 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4565 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4566 let (buffer, buffer_row) = snapshot
4567 .buffer_snapshot
4568 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4569 .and_then(|(buffer_snapshot, range)| {
4570 editor
4571 .buffer
4572 .read(cx)
4573 .buffer(buffer_snapshot.remote_id())
4574 .map(|buffer| (buffer, range.start.row))
4575 })?;
4576 let (_, code_actions) = editor
4577 .available_code_actions
4578 .clone()
4579 .and_then(|(location, code_actions)| {
4580 let snapshot = location.buffer.read(cx).snapshot();
4581 let point_range = location.range.to_point(&snapshot);
4582 let point_range = point_range.start.row..=point_range.end.row;
4583 if point_range.contains(&buffer_row) {
4584 Some((location, code_actions))
4585 } else {
4586 None
4587 }
4588 })
4589 .unzip();
4590 let buffer_id = buffer.read(cx).remote_id();
4591 let tasks = editor
4592 .tasks
4593 .get(&(buffer_id, buffer_row))
4594 .map(|t| Arc::new(t.to_owned()));
4595 if tasks.is_none() && code_actions.is_none() {
4596 return None;
4597 }
4598
4599 editor.completion_tasks.clear();
4600 editor.discard_inline_completion(false, cx);
4601 let task_context =
4602 tasks
4603 .as_ref()
4604 .zip(editor.project.clone())
4605 .map(|(tasks, project)| {
4606 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4607 });
4608
4609 Some(cx.spawn_in(window, async move |editor, cx| {
4610 let task_context = match task_context {
4611 Some(task_context) => task_context.await,
4612 None => None,
4613 };
4614 let resolved_tasks =
4615 tasks.zip(task_context).map(|(tasks, task_context)| {
4616 Rc::new(ResolvedTasks {
4617 templates: tasks.resolve(&task_context).collect(),
4618 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4619 multibuffer_point.row,
4620 tasks.column,
4621 )),
4622 })
4623 });
4624 let spawn_straight_away = resolved_tasks
4625 .as_ref()
4626 .map_or(false, |tasks| tasks.templates.len() == 1)
4627 && code_actions
4628 .as_ref()
4629 .map_or(true, |actions| actions.is_empty());
4630 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
4631 *editor.context_menu.borrow_mut() =
4632 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4633 buffer,
4634 actions: CodeActionContents {
4635 tasks: resolved_tasks,
4636 actions: code_actions,
4637 },
4638 selected_item: Default::default(),
4639 scroll_handle: UniformListScrollHandle::default(),
4640 deployed_from_indicator,
4641 }));
4642 if spawn_straight_away {
4643 if let Some(task) = editor.confirm_code_action(
4644 &ConfirmCodeAction { item_ix: Some(0) },
4645 window,
4646 cx,
4647 ) {
4648 cx.notify();
4649 return task;
4650 }
4651 }
4652 cx.notify();
4653 Task::ready(Ok(()))
4654 }) {
4655 task.await
4656 } else {
4657 Ok(())
4658 }
4659 }))
4660 } else {
4661 Some(Task::ready(Ok(())))
4662 }
4663 })?;
4664 if let Some(task) = spawned_test_task {
4665 task.await?;
4666 }
4667
4668 Ok::<_, anyhow::Error>(())
4669 })
4670 .detach_and_log_err(cx);
4671 }
4672
4673 pub fn confirm_code_action(
4674 &mut self,
4675 action: &ConfirmCodeAction,
4676 window: &mut Window,
4677 cx: &mut Context<Self>,
4678 ) -> Option<Task<Result<()>>> {
4679 let actions_menu =
4680 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4681 menu
4682 } else {
4683 return None;
4684 };
4685 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4686 let action = actions_menu.actions.get(action_ix)?;
4687 let title = action.label();
4688 let buffer = actions_menu.buffer;
4689 let workspace = self.workspace()?;
4690
4691 match action {
4692 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4693 workspace.update(cx, |workspace, cx| {
4694 workspace::tasks::schedule_resolved_task(
4695 workspace,
4696 task_source_kind,
4697 resolved_task,
4698 false,
4699 cx,
4700 );
4701
4702 Some(Task::ready(Ok(())))
4703 })
4704 }
4705 CodeActionsItem::CodeAction {
4706 excerpt_id,
4707 action,
4708 provider,
4709 } => {
4710 let apply_code_action =
4711 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4712 let workspace = workspace.downgrade();
4713 Some(cx.spawn_in(window, async move |editor, cx| {
4714 let project_transaction = apply_code_action.await?;
4715 Self::open_project_transaction(
4716 &editor,
4717 workspace,
4718 project_transaction,
4719 title,
4720 cx,
4721 )
4722 .await
4723 }))
4724 }
4725 }
4726 }
4727
4728 pub async fn open_project_transaction(
4729 this: &WeakEntity<Editor>,
4730 workspace: WeakEntity<Workspace>,
4731 transaction: ProjectTransaction,
4732 title: String,
4733 cx: &mut AsyncWindowContext,
4734 ) -> Result<()> {
4735 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4736 cx.update(|_, cx| {
4737 entries.sort_unstable_by_key(|(buffer, _)| {
4738 buffer.read(cx).file().map(|f| f.path().clone())
4739 });
4740 })?;
4741
4742 // If the project transaction's edits are all contained within this editor, then
4743 // avoid opening a new editor to display them.
4744
4745 if let Some((buffer, transaction)) = entries.first() {
4746 if entries.len() == 1 {
4747 let excerpt = this.update(cx, |editor, cx| {
4748 editor
4749 .buffer()
4750 .read(cx)
4751 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4752 })?;
4753 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4754 if excerpted_buffer == *buffer {
4755 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
4756 let excerpt_range = excerpt_range.to_offset(buffer);
4757 buffer
4758 .edited_ranges_for_transaction::<usize>(transaction)
4759 .all(|range| {
4760 excerpt_range.start <= range.start
4761 && excerpt_range.end >= range.end
4762 })
4763 })?;
4764
4765 if all_edits_within_excerpt {
4766 return Ok(());
4767 }
4768 }
4769 }
4770 }
4771 } else {
4772 return Ok(());
4773 }
4774
4775 let mut ranges_to_highlight = Vec::new();
4776 let excerpt_buffer = cx.new(|cx| {
4777 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4778 for (buffer_handle, transaction) in &entries {
4779 let buffer = buffer_handle.read(cx);
4780 ranges_to_highlight.extend(
4781 multibuffer.push_excerpts_with_context_lines(
4782 buffer_handle.clone(),
4783 buffer
4784 .edited_ranges_for_transaction::<usize>(transaction)
4785 .collect(),
4786 DEFAULT_MULTIBUFFER_CONTEXT,
4787 cx,
4788 ),
4789 );
4790 }
4791 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4792 multibuffer
4793 })?;
4794
4795 workspace.update_in(cx, |workspace, window, cx| {
4796 let project = workspace.project().clone();
4797 let editor =
4798 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
4799 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4800 editor.update(cx, |editor, cx| {
4801 editor.highlight_background::<Self>(
4802 &ranges_to_highlight,
4803 |theme| theme.editor_highlighted_line_background,
4804 cx,
4805 );
4806 });
4807 })?;
4808
4809 Ok(())
4810 }
4811
4812 pub fn clear_code_action_providers(&mut self) {
4813 self.code_action_providers.clear();
4814 self.available_code_actions.take();
4815 }
4816
4817 pub fn add_code_action_provider(
4818 &mut self,
4819 provider: Rc<dyn CodeActionProvider>,
4820 window: &mut Window,
4821 cx: &mut Context<Self>,
4822 ) {
4823 if self
4824 .code_action_providers
4825 .iter()
4826 .any(|existing_provider| existing_provider.id() == provider.id())
4827 {
4828 return;
4829 }
4830
4831 self.code_action_providers.push(provider);
4832 self.refresh_code_actions(window, cx);
4833 }
4834
4835 pub fn remove_code_action_provider(
4836 &mut self,
4837 id: Arc<str>,
4838 window: &mut Window,
4839 cx: &mut Context<Self>,
4840 ) {
4841 self.code_action_providers
4842 .retain(|provider| provider.id() != id);
4843 self.refresh_code_actions(window, cx);
4844 }
4845
4846 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4847 let buffer = self.buffer.read(cx);
4848 let newest_selection = self.selections.newest_anchor().clone();
4849 if newest_selection.head().diff_base_anchor.is_some() {
4850 return None;
4851 }
4852 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4853 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4854 if start_buffer != end_buffer {
4855 return None;
4856 }
4857
4858 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
4859 cx.background_executor()
4860 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4861 .await;
4862
4863 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
4864 let providers = this.code_action_providers.clone();
4865 let tasks = this
4866 .code_action_providers
4867 .iter()
4868 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4869 .collect::<Vec<_>>();
4870 (providers, tasks)
4871 })?;
4872
4873 let mut actions = Vec::new();
4874 for (provider, provider_actions) in
4875 providers.into_iter().zip(future::join_all(tasks).await)
4876 {
4877 if let Some(provider_actions) = provider_actions.log_err() {
4878 actions.extend(provider_actions.into_iter().map(|action| {
4879 AvailableCodeAction {
4880 excerpt_id: newest_selection.start.excerpt_id,
4881 action,
4882 provider: provider.clone(),
4883 }
4884 }));
4885 }
4886 }
4887
4888 this.update(cx, |this, cx| {
4889 this.available_code_actions = if actions.is_empty() {
4890 None
4891 } else {
4892 Some((
4893 Location {
4894 buffer: start_buffer,
4895 range: start..end,
4896 },
4897 actions.into(),
4898 ))
4899 };
4900 cx.notify();
4901 })
4902 }));
4903 None
4904 }
4905
4906 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4907 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4908 self.show_git_blame_inline = false;
4909
4910 self.show_git_blame_inline_delay_task =
4911 Some(cx.spawn_in(window, async move |this, cx| {
4912 cx.background_executor().timer(delay).await;
4913
4914 this.update(cx, |this, cx| {
4915 this.show_git_blame_inline = true;
4916 cx.notify();
4917 })
4918 .log_err();
4919 }));
4920 }
4921 }
4922
4923 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4924 if self.pending_rename.is_some() {
4925 return None;
4926 }
4927
4928 let provider = self.semantics_provider.clone()?;
4929 let buffer = self.buffer.read(cx);
4930 let newest_selection = self.selections.newest_anchor().clone();
4931 let cursor_position = newest_selection.head();
4932 let (cursor_buffer, cursor_buffer_position) =
4933 buffer.text_anchor_for_position(cursor_position, cx)?;
4934 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4935 if cursor_buffer != tail_buffer {
4936 return None;
4937 }
4938 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4939 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
4940 cx.background_executor()
4941 .timer(Duration::from_millis(debounce))
4942 .await;
4943
4944 let highlights = if let Some(highlights) = cx
4945 .update(|cx| {
4946 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4947 })
4948 .ok()
4949 .flatten()
4950 {
4951 highlights.await.log_err()
4952 } else {
4953 None
4954 };
4955
4956 if let Some(highlights) = highlights {
4957 this.update(cx, |this, cx| {
4958 if this.pending_rename.is_some() {
4959 return;
4960 }
4961
4962 let buffer_id = cursor_position.buffer_id;
4963 let buffer = this.buffer.read(cx);
4964 if !buffer
4965 .text_anchor_for_position(cursor_position, cx)
4966 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4967 {
4968 return;
4969 }
4970
4971 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4972 let mut write_ranges = Vec::new();
4973 let mut read_ranges = Vec::new();
4974 for highlight in highlights {
4975 for (excerpt_id, excerpt_range) in
4976 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4977 {
4978 let start = highlight
4979 .range
4980 .start
4981 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4982 let end = highlight
4983 .range
4984 .end
4985 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4986 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4987 continue;
4988 }
4989
4990 let range = Anchor {
4991 buffer_id,
4992 excerpt_id,
4993 text_anchor: start,
4994 diff_base_anchor: None,
4995 }..Anchor {
4996 buffer_id,
4997 excerpt_id,
4998 text_anchor: end,
4999 diff_base_anchor: None,
5000 };
5001 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5002 write_ranges.push(range);
5003 } else {
5004 read_ranges.push(range);
5005 }
5006 }
5007 }
5008
5009 this.highlight_background::<DocumentHighlightRead>(
5010 &read_ranges,
5011 |theme| theme.editor_document_highlight_read_background,
5012 cx,
5013 );
5014 this.highlight_background::<DocumentHighlightWrite>(
5015 &write_ranges,
5016 |theme| theme.editor_document_highlight_write_background,
5017 cx,
5018 );
5019 cx.notify();
5020 })
5021 .log_err();
5022 }
5023 }));
5024 None
5025 }
5026
5027 pub fn refresh_selected_text_highlights(
5028 &mut self,
5029 window: &mut Window,
5030 cx: &mut Context<Editor>,
5031 ) {
5032 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5033 return;
5034 }
5035 self.selection_highlight_task.take();
5036 if !EditorSettings::get_global(cx).selection_highlight {
5037 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5038 return;
5039 }
5040 if self.selections.count() != 1 || self.selections.line_mode {
5041 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5042 return;
5043 }
5044 let selection = self.selections.newest::<Point>(cx);
5045 if selection.is_empty() || selection.start.row != selection.end.row {
5046 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5047 return;
5048 }
5049 let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
5050 self.selection_highlight_task = Some(cx.spawn_in(window, async move |editor, cx| {
5051 cx.background_executor()
5052 .timer(Duration::from_millis(debounce))
5053 .await;
5054 let Some(Some(matches_task)) = editor
5055 .update_in(cx, |editor, _, cx| {
5056 if editor.selections.count() != 1 || editor.selections.line_mode {
5057 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5058 return None;
5059 }
5060 let selection = editor.selections.newest::<Point>(cx);
5061 if selection.is_empty() || selection.start.row != selection.end.row {
5062 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5063 return None;
5064 }
5065 let buffer = editor.buffer().read(cx).snapshot(cx);
5066 let query = buffer.text_for_range(selection.range()).collect::<String>();
5067 if query.trim().is_empty() {
5068 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5069 return None;
5070 }
5071 Some(cx.background_spawn(async move {
5072 let mut ranges = Vec::new();
5073 let selection_anchors = selection.range().to_anchors(&buffer);
5074 for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
5075 for (search_buffer, search_range, excerpt_id) in
5076 buffer.range_to_buffer_ranges(range)
5077 {
5078 ranges.extend(
5079 project::search::SearchQuery::text(
5080 query.clone(),
5081 false,
5082 false,
5083 false,
5084 Default::default(),
5085 Default::default(),
5086 None,
5087 )
5088 .unwrap()
5089 .search(search_buffer, Some(search_range.clone()))
5090 .await
5091 .into_iter()
5092 .filter_map(
5093 |match_range| {
5094 let start = search_buffer.anchor_after(
5095 search_range.start + match_range.start,
5096 );
5097 let end = search_buffer.anchor_before(
5098 search_range.start + match_range.end,
5099 );
5100 let range = Anchor::range_in_buffer(
5101 excerpt_id,
5102 search_buffer.remote_id(),
5103 start..end,
5104 );
5105 (range != selection_anchors).then_some(range)
5106 },
5107 ),
5108 );
5109 }
5110 }
5111 ranges
5112 }))
5113 })
5114 .log_err()
5115 else {
5116 return;
5117 };
5118 let matches = matches_task.await;
5119 editor
5120 .update_in(cx, |editor, _, cx| {
5121 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5122 if !matches.is_empty() {
5123 editor.highlight_background::<SelectedTextHighlight>(
5124 &matches,
5125 |theme| theme.editor_document_highlight_bracket_background,
5126 cx,
5127 )
5128 }
5129 })
5130 .log_err();
5131 }));
5132 }
5133
5134 pub fn refresh_inline_completion(
5135 &mut self,
5136 debounce: bool,
5137 user_requested: bool,
5138 window: &mut Window,
5139 cx: &mut Context<Self>,
5140 ) -> Option<()> {
5141 let provider = self.edit_prediction_provider()?;
5142 let cursor = self.selections.newest_anchor().head();
5143 let (buffer, cursor_buffer_position) =
5144 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5145
5146 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5147 self.discard_inline_completion(false, cx);
5148 return None;
5149 }
5150
5151 if !user_requested
5152 && (!self.should_show_edit_predictions()
5153 || !self.is_focused(window)
5154 || buffer.read(cx).is_empty())
5155 {
5156 self.discard_inline_completion(false, cx);
5157 return None;
5158 }
5159
5160 self.update_visible_inline_completion(window, cx);
5161 provider.refresh(
5162 self.project.clone(),
5163 buffer,
5164 cursor_buffer_position,
5165 debounce,
5166 cx,
5167 );
5168 Some(())
5169 }
5170
5171 fn show_edit_predictions_in_menu(&self) -> bool {
5172 match self.edit_prediction_settings {
5173 EditPredictionSettings::Disabled => false,
5174 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5175 }
5176 }
5177
5178 pub fn edit_predictions_enabled(&self) -> bool {
5179 match self.edit_prediction_settings {
5180 EditPredictionSettings::Disabled => false,
5181 EditPredictionSettings::Enabled { .. } => true,
5182 }
5183 }
5184
5185 fn edit_prediction_requires_modifier(&self) -> bool {
5186 match self.edit_prediction_settings {
5187 EditPredictionSettings::Disabled => false,
5188 EditPredictionSettings::Enabled {
5189 preview_requires_modifier,
5190 ..
5191 } => preview_requires_modifier,
5192 }
5193 }
5194
5195 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5196 if self.edit_prediction_provider.is_none() {
5197 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5198 } else {
5199 let selection = self.selections.newest_anchor();
5200 let cursor = selection.head();
5201
5202 if let Some((buffer, cursor_buffer_position)) =
5203 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5204 {
5205 self.edit_prediction_settings =
5206 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5207 }
5208 }
5209 }
5210
5211 fn edit_prediction_settings_at_position(
5212 &self,
5213 buffer: &Entity<Buffer>,
5214 buffer_position: language::Anchor,
5215 cx: &App,
5216 ) -> EditPredictionSettings {
5217 if self.mode != EditorMode::Full
5218 || !self.show_inline_completions_override.unwrap_or(true)
5219 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5220 {
5221 return EditPredictionSettings::Disabled;
5222 }
5223
5224 let buffer = buffer.read(cx);
5225
5226 let file = buffer.file();
5227
5228 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5229 return EditPredictionSettings::Disabled;
5230 };
5231
5232 let by_provider = matches!(
5233 self.menu_inline_completions_policy,
5234 MenuInlineCompletionsPolicy::ByProvider
5235 );
5236
5237 let show_in_menu = by_provider
5238 && self
5239 .edit_prediction_provider
5240 .as_ref()
5241 .map_or(false, |provider| {
5242 provider.provider.show_completions_in_menu()
5243 });
5244
5245 let preview_requires_modifier =
5246 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5247
5248 EditPredictionSettings::Enabled {
5249 show_in_menu,
5250 preview_requires_modifier,
5251 }
5252 }
5253
5254 fn should_show_edit_predictions(&self) -> bool {
5255 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5256 }
5257
5258 pub fn edit_prediction_preview_is_active(&self) -> bool {
5259 matches!(
5260 self.edit_prediction_preview,
5261 EditPredictionPreview::Active { .. }
5262 )
5263 }
5264
5265 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5266 let cursor = self.selections.newest_anchor().head();
5267 if let Some((buffer, cursor_position)) =
5268 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5269 {
5270 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5271 } else {
5272 false
5273 }
5274 }
5275
5276 fn edit_predictions_enabled_in_buffer(
5277 &self,
5278 buffer: &Entity<Buffer>,
5279 buffer_position: language::Anchor,
5280 cx: &App,
5281 ) -> bool {
5282 maybe!({
5283 if self.read_only(cx) {
5284 return Some(false);
5285 }
5286 let provider = self.edit_prediction_provider()?;
5287 if !provider.is_enabled(&buffer, buffer_position, cx) {
5288 return Some(false);
5289 }
5290 let buffer = buffer.read(cx);
5291 let Some(file) = buffer.file() else {
5292 return Some(true);
5293 };
5294 let settings = all_language_settings(Some(file), cx);
5295 Some(settings.edit_predictions_enabled_for_file(file, cx))
5296 })
5297 .unwrap_or(false)
5298 }
5299
5300 fn cycle_inline_completion(
5301 &mut self,
5302 direction: Direction,
5303 window: &mut Window,
5304 cx: &mut Context<Self>,
5305 ) -> Option<()> {
5306 let provider = self.edit_prediction_provider()?;
5307 let cursor = self.selections.newest_anchor().head();
5308 let (buffer, cursor_buffer_position) =
5309 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5310 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5311 return None;
5312 }
5313
5314 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5315 self.update_visible_inline_completion(window, cx);
5316
5317 Some(())
5318 }
5319
5320 pub fn show_inline_completion(
5321 &mut self,
5322 _: &ShowEditPrediction,
5323 window: &mut Window,
5324 cx: &mut Context<Self>,
5325 ) {
5326 if !self.has_active_inline_completion() {
5327 self.refresh_inline_completion(false, true, window, cx);
5328 return;
5329 }
5330
5331 self.update_visible_inline_completion(window, cx);
5332 }
5333
5334 pub fn display_cursor_names(
5335 &mut self,
5336 _: &DisplayCursorNames,
5337 window: &mut Window,
5338 cx: &mut Context<Self>,
5339 ) {
5340 self.show_cursor_names(window, cx);
5341 }
5342
5343 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5344 self.show_cursor_names = true;
5345 cx.notify();
5346 cx.spawn_in(window, async move |this, cx| {
5347 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5348 this.update(cx, |this, cx| {
5349 this.show_cursor_names = false;
5350 cx.notify()
5351 })
5352 .ok()
5353 })
5354 .detach();
5355 }
5356
5357 pub fn next_edit_prediction(
5358 &mut self,
5359 _: &NextEditPrediction,
5360 window: &mut Window,
5361 cx: &mut Context<Self>,
5362 ) {
5363 if self.has_active_inline_completion() {
5364 self.cycle_inline_completion(Direction::Next, window, cx);
5365 } else {
5366 let is_copilot_disabled = self
5367 .refresh_inline_completion(false, true, window, cx)
5368 .is_none();
5369 if is_copilot_disabled {
5370 cx.propagate();
5371 }
5372 }
5373 }
5374
5375 pub fn previous_edit_prediction(
5376 &mut self,
5377 _: &PreviousEditPrediction,
5378 window: &mut Window,
5379 cx: &mut Context<Self>,
5380 ) {
5381 if self.has_active_inline_completion() {
5382 self.cycle_inline_completion(Direction::Prev, window, cx);
5383 } else {
5384 let is_copilot_disabled = self
5385 .refresh_inline_completion(false, true, window, cx)
5386 .is_none();
5387 if is_copilot_disabled {
5388 cx.propagate();
5389 }
5390 }
5391 }
5392
5393 pub fn accept_edit_prediction(
5394 &mut self,
5395 _: &AcceptEditPrediction,
5396 window: &mut Window,
5397 cx: &mut Context<Self>,
5398 ) {
5399 if self.show_edit_predictions_in_menu() {
5400 self.hide_context_menu(window, cx);
5401 }
5402
5403 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5404 return;
5405 };
5406
5407 self.report_inline_completion_event(
5408 active_inline_completion.completion_id.clone(),
5409 true,
5410 cx,
5411 );
5412
5413 match &active_inline_completion.completion {
5414 InlineCompletion::Move { target, .. } => {
5415 let target = *target;
5416
5417 if let Some(position_map) = &self.last_position_map {
5418 if position_map
5419 .visible_row_range
5420 .contains(&target.to_display_point(&position_map.snapshot).row())
5421 || !self.edit_prediction_requires_modifier()
5422 {
5423 self.unfold_ranges(&[target..target], true, false, cx);
5424 // Note that this is also done in vim's handler of the Tab action.
5425 self.change_selections(
5426 Some(Autoscroll::newest()),
5427 window,
5428 cx,
5429 |selections| {
5430 selections.select_anchor_ranges([target..target]);
5431 },
5432 );
5433 self.clear_row_highlights::<EditPredictionPreview>();
5434
5435 self.edit_prediction_preview
5436 .set_previous_scroll_position(None);
5437 } else {
5438 self.edit_prediction_preview
5439 .set_previous_scroll_position(Some(
5440 position_map.snapshot.scroll_anchor,
5441 ));
5442
5443 self.highlight_rows::<EditPredictionPreview>(
5444 target..target,
5445 cx.theme().colors().editor_highlighted_line_background,
5446 true,
5447 cx,
5448 );
5449 self.request_autoscroll(Autoscroll::fit(), cx);
5450 }
5451 }
5452 }
5453 InlineCompletion::Edit { edits, .. } => {
5454 if let Some(provider) = self.edit_prediction_provider() {
5455 provider.accept(cx);
5456 }
5457
5458 let snapshot = self.buffer.read(cx).snapshot(cx);
5459 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5460
5461 self.buffer.update(cx, |buffer, cx| {
5462 buffer.edit(edits.iter().cloned(), None, cx)
5463 });
5464
5465 self.change_selections(None, window, cx, |s| {
5466 s.select_anchor_ranges([last_edit_end..last_edit_end])
5467 });
5468
5469 self.update_visible_inline_completion(window, cx);
5470 if self.active_inline_completion.is_none() {
5471 self.refresh_inline_completion(true, true, window, cx);
5472 }
5473
5474 cx.notify();
5475 }
5476 }
5477
5478 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5479 }
5480
5481 pub fn accept_partial_inline_completion(
5482 &mut self,
5483 _: &AcceptPartialEditPrediction,
5484 window: &mut Window,
5485 cx: &mut Context<Self>,
5486 ) {
5487 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5488 return;
5489 };
5490 if self.selections.count() != 1 {
5491 return;
5492 }
5493
5494 self.report_inline_completion_event(
5495 active_inline_completion.completion_id.clone(),
5496 true,
5497 cx,
5498 );
5499
5500 match &active_inline_completion.completion {
5501 InlineCompletion::Move { target, .. } => {
5502 let target = *target;
5503 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
5504 selections.select_anchor_ranges([target..target]);
5505 });
5506 }
5507 InlineCompletion::Edit { edits, .. } => {
5508 // Find an insertion that starts at the cursor position.
5509 let snapshot = self.buffer.read(cx).snapshot(cx);
5510 let cursor_offset = self.selections.newest::<usize>(cx).head();
5511 let insertion = edits.iter().find_map(|(range, text)| {
5512 let range = range.to_offset(&snapshot);
5513 if range.is_empty() && range.start == cursor_offset {
5514 Some(text)
5515 } else {
5516 None
5517 }
5518 });
5519
5520 if let Some(text) = insertion {
5521 let mut partial_completion = text
5522 .chars()
5523 .by_ref()
5524 .take_while(|c| c.is_alphabetic())
5525 .collect::<String>();
5526 if partial_completion.is_empty() {
5527 partial_completion = text
5528 .chars()
5529 .by_ref()
5530 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5531 .collect::<String>();
5532 }
5533
5534 cx.emit(EditorEvent::InputHandled {
5535 utf16_range_to_replace: None,
5536 text: partial_completion.clone().into(),
5537 });
5538
5539 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
5540
5541 self.refresh_inline_completion(true, true, window, cx);
5542 cx.notify();
5543 } else {
5544 self.accept_edit_prediction(&Default::default(), window, cx);
5545 }
5546 }
5547 }
5548 }
5549
5550 fn discard_inline_completion(
5551 &mut self,
5552 should_report_inline_completion_event: bool,
5553 cx: &mut Context<Self>,
5554 ) -> bool {
5555 if should_report_inline_completion_event {
5556 let completion_id = self
5557 .active_inline_completion
5558 .as_ref()
5559 .and_then(|active_completion| active_completion.completion_id.clone());
5560
5561 self.report_inline_completion_event(completion_id, false, cx);
5562 }
5563
5564 if let Some(provider) = self.edit_prediction_provider() {
5565 provider.discard(cx);
5566 }
5567
5568 self.take_active_inline_completion(cx)
5569 }
5570
5571 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
5572 let Some(provider) = self.edit_prediction_provider() else {
5573 return;
5574 };
5575
5576 let Some((_, buffer, _)) = self
5577 .buffer
5578 .read(cx)
5579 .excerpt_containing(self.selections.newest_anchor().head(), cx)
5580 else {
5581 return;
5582 };
5583
5584 let extension = buffer
5585 .read(cx)
5586 .file()
5587 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
5588
5589 let event_type = match accepted {
5590 true => "Edit Prediction Accepted",
5591 false => "Edit Prediction Discarded",
5592 };
5593 telemetry::event!(
5594 event_type,
5595 provider = provider.name(),
5596 prediction_id = id,
5597 suggestion_accepted = accepted,
5598 file_extension = extension,
5599 );
5600 }
5601
5602 pub fn has_active_inline_completion(&self) -> bool {
5603 self.active_inline_completion.is_some()
5604 }
5605
5606 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
5607 let Some(active_inline_completion) = self.active_inline_completion.take() else {
5608 return false;
5609 };
5610
5611 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
5612 self.clear_highlights::<InlineCompletionHighlight>(cx);
5613 self.stale_inline_completion_in_menu = Some(active_inline_completion);
5614 true
5615 }
5616
5617 /// Returns true when we're displaying the edit prediction popover below the cursor
5618 /// like we are not previewing and the LSP autocomplete menu is visible
5619 /// or we are in `when_holding_modifier` mode.
5620 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
5621 if self.edit_prediction_preview_is_active()
5622 || !self.show_edit_predictions_in_menu()
5623 || !self.edit_predictions_enabled()
5624 {
5625 return false;
5626 }
5627
5628 if self.has_visible_completions_menu() {
5629 return true;
5630 }
5631
5632 has_completion && self.edit_prediction_requires_modifier()
5633 }
5634
5635 fn handle_modifiers_changed(
5636 &mut self,
5637 modifiers: Modifiers,
5638 position_map: &PositionMap,
5639 window: &mut Window,
5640 cx: &mut Context<Self>,
5641 ) {
5642 if self.show_edit_predictions_in_menu() {
5643 self.update_edit_prediction_preview(&modifiers, window, cx);
5644 }
5645
5646 self.update_selection_mode(&modifiers, position_map, window, cx);
5647
5648 let mouse_position = window.mouse_position();
5649 if !position_map.text_hitbox.is_hovered(window) {
5650 return;
5651 }
5652
5653 self.update_hovered_link(
5654 position_map.point_for_position(mouse_position),
5655 &position_map.snapshot,
5656 modifiers,
5657 window,
5658 cx,
5659 )
5660 }
5661
5662 fn update_selection_mode(
5663 &mut self,
5664 modifiers: &Modifiers,
5665 position_map: &PositionMap,
5666 window: &mut Window,
5667 cx: &mut Context<Self>,
5668 ) {
5669 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
5670 return;
5671 }
5672
5673 let mouse_position = window.mouse_position();
5674 let point_for_position = position_map.point_for_position(mouse_position);
5675 let position = point_for_position.previous_valid;
5676
5677 self.select(
5678 SelectPhase::BeginColumnar {
5679 position,
5680 reset: false,
5681 goal_column: point_for_position.exact_unclipped.column(),
5682 },
5683 window,
5684 cx,
5685 );
5686 }
5687
5688 fn update_edit_prediction_preview(
5689 &mut self,
5690 modifiers: &Modifiers,
5691 window: &mut Window,
5692 cx: &mut Context<Self>,
5693 ) {
5694 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
5695 let Some(accept_keystroke) = accept_keybind.keystroke() else {
5696 return;
5697 };
5698
5699 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
5700 if matches!(
5701 self.edit_prediction_preview,
5702 EditPredictionPreview::Inactive { .. }
5703 ) {
5704 self.edit_prediction_preview = EditPredictionPreview::Active {
5705 previous_scroll_position: None,
5706 since: Instant::now(),
5707 };
5708
5709 self.update_visible_inline_completion(window, cx);
5710 cx.notify();
5711 }
5712 } else if let EditPredictionPreview::Active {
5713 previous_scroll_position,
5714 since,
5715 } = self.edit_prediction_preview
5716 {
5717 if let (Some(previous_scroll_position), Some(position_map)) =
5718 (previous_scroll_position, self.last_position_map.as_ref())
5719 {
5720 self.set_scroll_position(
5721 previous_scroll_position
5722 .scroll_position(&position_map.snapshot.display_snapshot),
5723 window,
5724 cx,
5725 );
5726 }
5727
5728 self.edit_prediction_preview = EditPredictionPreview::Inactive {
5729 released_too_fast: since.elapsed() < Duration::from_millis(200),
5730 };
5731 self.clear_row_highlights::<EditPredictionPreview>();
5732 self.update_visible_inline_completion(window, cx);
5733 cx.notify();
5734 }
5735 }
5736
5737 fn update_visible_inline_completion(
5738 &mut self,
5739 _window: &mut Window,
5740 cx: &mut Context<Self>,
5741 ) -> Option<()> {
5742 let selection = self.selections.newest_anchor();
5743 let cursor = selection.head();
5744 let multibuffer = self.buffer.read(cx).snapshot(cx);
5745 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5746 let excerpt_id = cursor.excerpt_id;
5747
5748 let show_in_menu = self.show_edit_predictions_in_menu();
5749 let completions_menu_has_precedence = !show_in_menu
5750 && (self.context_menu.borrow().is_some()
5751 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5752
5753 if completions_menu_has_precedence
5754 || !offset_selection.is_empty()
5755 || self
5756 .active_inline_completion
5757 .as_ref()
5758 .map_or(false, |completion| {
5759 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5760 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5761 !invalidation_range.contains(&offset_selection.head())
5762 })
5763 {
5764 self.discard_inline_completion(false, cx);
5765 return None;
5766 }
5767
5768 self.take_active_inline_completion(cx);
5769 let Some(provider) = self.edit_prediction_provider() else {
5770 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5771 return None;
5772 };
5773
5774 let (buffer, cursor_buffer_position) =
5775 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5776
5777 self.edit_prediction_settings =
5778 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5779
5780 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
5781
5782 if self.edit_prediction_indent_conflict {
5783 let cursor_point = cursor.to_point(&multibuffer);
5784
5785 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
5786
5787 if let Some((_, indent)) = indents.iter().next() {
5788 if indent.len == cursor_point.column {
5789 self.edit_prediction_indent_conflict = false;
5790 }
5791 }
5792 }
5793
5794 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5795 let edits = inline_completion
5796 .edits
5797 .into_iter()
5798 .flat_map(|(range, new_text)| {
5799 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5800 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5801 Some((start..end, new_text))
5802 })
5803 .collect::<Vec<_>>();
5804 if edits.is_empty() {
5805 return None;
5806 }
5807
5808 let first_edit_start = edits.first().unwrap().0.start;
5809 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5810 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5811
5812 let last_edit_end = edits.last().unwrap().0.end;
5813 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5814 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5815
5816 let cursor_row = cursor.to_point(&multibuffer).row;
5817
5818 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5819
5820 let mut inlay_ids = Vec::new();
5821 let invalidation_row_range;
5822 let move_invalidation_row_range = if cursor_row < edit_start_row {
5823 Some(cursor_row..edit_end_row)
5824 } else if cursor_row > edit_end_row {
5825 Some(edit_start_row..cursor_row)
5826 } else {
5827 None
5828 };
5829 let is_move =
5830 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
5831 let completion = if is_move {
5832 invalidation_row_range =
5833 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
5834 let target = first_edit_start;
5835 InlineCompletion::Move { target, snapshot }
5836 } else {
5837 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
5838 && !self.inline_completions_hidden_for_vim_mode;
5839
5840 if show_completions_in_buffer {
5841 if edits
5842 .iter()
5843 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5844 {
5845 let mut inlays = Vec::new();
5846 for (range, new_text) in &edits {
5847 let inlay = Inlay::inline_completion(
5848 post_inc(&mut self.next_inlay_id),
5849 range.start,
5850 new_text.as_str(),
5851 );
5852 inlay_ids.push(inlay.id);
5853 inlays.push(inlay);
5854 }
5855
5856 self.splice_inlays(&[], inlays, cx);
5857 } else {
5858 let background_color = cx.theme().status().deleted_background;
5859 self.highlight_text::<InlineCompletionHighlight>(
5860 edits.iter().map(|(range, _)| range.clone()).collect(),
5861 HighlightStyle {
5862 background_color: Some(background_color),
5863 ..Default::default()
5864 },
5865 cx,
5866 );
5867 }
5868 }
5869
5870 invalidation_row_range = edit_start_row..edit_end_row;
5871
5872 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5873 if provider.show_tab_accept_marker() {
5874 EditDisplayMode::TabAccept
5875 } else {
5876 EditDisplayMode::Inline
5877 }
5878 } else {
5879 EditDisplayMode::DiffPopover
5880 };
5881
5882 InlineCompletion::Edit {
5883 edits,
5884 edit_preview: inline_completion.edit_preview,
5885 display_mode,
5886 snapshot,
5887 }
5888 };
5889
5890 let invalidation_range = multibuffer
5891 .anchor_before(Point::new(invalidation_row_range.start, 0))
5892 ..multibuffer.anchor_after(Point::new(
5893 invalidation_row_range.end,
5894 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5895 ));
5896
5897 self.stale_inline_completion_in_menu = None;
5898 self.active_inline_completion = Some(InlineCompletionState {
5899 inlay_ids,
5900 completion,
5901 completion_id: inline_completion.id,
5902 invalidation_range,
5903 });
5904
5905 cx.notify();
5906
5907 Some(())
5908 }
5909
5910 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5911 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
5912 }
5913
5914 fn render_code_actions_indicator(
5915 &self,
5916 _style: &EditorStyle,
5917 row: DisplayRow,
5918 is_active: bool,
5919 breakpoint: Option<&(Anchor, Breakpoint)>,
5920 cx: &mut Context<Self>,
5921 ) -> Option<IconButton> {
5922 let color = Color::Muted;
5923
5924 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
5925 let bp_kind = Arc::new(
5926 breakpoint
5927 .map(|(_, bp)| bp.kind.clone())
5928 .unwrap_or(BreakpointKind::Standard),
5929 );
5930
5931 if self.available_code_actions.is_some() {
5932 Some(
5933 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5934 .shape(ui::IconButtonShape::Square)
5935 .icon_size(IconSize::XSmall)
5936 .icon_color(color)
5937 .toggle_state(is_active)
5938 .tooltip({
5939 let focus_handle = self.focus_handle.clone();
5940 move |window, cx| {
5941 Tooltip::for_action_in(
5942 "Toggle Code Actions",
5943 &ToggleCodeActions {
5944 deployed_from_indicator: None,
5945 },
5946 &focus_handle,
5947 window,
5948 cx,
5949 )
5950 }
5951 })
5952 .on_click(cx.listener(move |editor, _e, window, cx| {
5953 window.focus(&editor.focus_handle(cx));
5954 editor.toggle_code_actions(
5955 &ToggleCodeActions {
5956 deployed_from_indicator: Some(row),
5957 },
5958 window,
5959 cx,
5960 );
5961 }))
5962 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
5963 editor.set_breakpoint_context_menu(
5964 row,
5965 position,
5966 bp_kind.clone(),
5967 event.down.position,
5968 window,
5969 cx,
5970 );
5971 })),
5972 )
5973 } else {
5974 None
5975 }
5976 }
5977
5978 fn clear_tasks(&mut self) {
5979 self.tasks.clear()
5980 }
5981
5982 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5983 if self.tasks.insert(key, value).is_some() {
5984 // This case should hopefully be rare, but just in case...
5985 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5986 }
5987 }
5988
5989 /// Get all display points of breakpoints that will be rendered within editor
5990 ///
5991 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
5992 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
5993 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
5994 fn active_breakpoints(
5995 &mut self,
5996 range: Range<DisplayRow>,
5997 window: &mut Window,
5998 cx: &mut Context<Self>,
5999 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6000 let mut breakpoint_display_points = HashMap::default();
6001
6002 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6003 return breakpoint_display_points;
6004 };
6005
6006 let snapshot = self.snapshot(window, cx);
6007
6008 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6009 let Some(project) = self.project.as_ref() else {
6010 return breakpoint_display_points;
6011 };
6012
6013 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
6014 let buffer_snapshot = buffer.read(cx).snapshot();
6015
6016 for breakpoint in
6017 breakpoint_store
6018 .read(cx)
6019 .breakpoints(&buffer, None, buffer_snapshot.clone(), cx)
6020 {
6021 let point = buffer_snapshot.summary_for_anchor::<Point>(&breakpoint.0);
6022 let anchor = multi_buffer_snapshot.anchor_before(point);
6023 breakpoint_display_points.insert(
6024 snapshot
6025 .point_to_display_point(
6026 MultiBufferPoint {
6027 row: point.row,
6028 column: point.column,
6029 },
6030 Bias::Left,
6031 )
6032 .row(),
6033 (anchor, breakpoint.1.clone()),
6034 );
6035 }
6036
6037 return breakpoint_display_points;
6038 }
6039
6040 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6041 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6042 for excerpt_boundary in multi_buffer_snapshot.excerpt_boundaries_in_range(range) {
6043 let info = excerpt_boundary.next;
6044
6045 let Some(excerpt_ranges) = multi_buffer_snapshot.range_for_excerpt(info.id) else {
6046 continue;
6047 };
6048
6049 let Some(buffer) =
6050 project.read_with(cx, |this, cx| this.buffer_for_id(info.buffer_id, cx))
6051 else {
6052 continue;
6053 };
6054
6055 let breakpoints = breakpoint_store.read(cx).breakpoints(
6056 &buffer,
6057 Some(info.range.context.start..info.range.context.end),
6058 info.buffer.clone(),
6059 cx,
6060 );
6061
6062 // To translate a breakpoint's position within a singular buffer to a multi buffer
6063 // position we need to know it's excerpt starting location, it's position within
6064 // the singular buffer, and if that position is within the excerpt's range.
6065 let excerpt_head = excerpt_ranges
6066 .start
6067 .to_display_point(&snapshot.display_snapshot);
6068
6069 let buffer_start = info
6070 .buffer
6071 .summary_for_anchor::<Point>(&info.range.context.start);
6072
6073 for (anchor, breakpoint) in breakpoints {
6074 let as_row = info.buffer.summary_for_anchor::<Point>(&anchor).row;
6075 let delta = as_row - buffer_start.row;
6076
6077 let position = excerpt_head + DisplayPoint::new(DisplayRow(delta), 0);
6078
6079 let anchor = snapshot.display_point_to_anchor(position, Bias::Left);
6080
6081 breakpoint_display_points.insert(position.row(), (anchor, breakpoint.clone()));
6082 }
6083 }
6084
6085 breakpoint_display_points
6086 }
6087
6088 fn breakpoint_context_menu(
6089 &self,
6090 anchor: Anchor,
6091 kind: Arc<BreakpointKind>,
6092 window: &mut Window,
6093 cx: &mut Context<Self>,
6094 ) -> Entity<ui::ContextMenu> {
6095 let weak_editor = cx.weak_entity();
6096 let focus_handle = self.focus_handle(cx);
6097
6098 let second_entry_msg = if kind.log_message().is_some() {
6099 "Edit Log Breakpoint"
6100 } else {
6101 "Add Log Breakpoint"
6102 };
6103
6104 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6105 menu.on_blur_subscription(Subscription::new(|| {}))
6106 .context(focus_handle)
6107 .entry("Toggle Breakpoint", None, {
6108 let weak_editor = weak_editor.clone();
6109 move |_window, cx| {
6110 weak_editor
6111 .update(cx, |this, cx| {
6112 this.edit_breakpoint_at_anchor(
6113 anchor,
6114 BreakpointKind::Standard,
6115 BreakpointEditAction::Toggle,
6116 cx,
6117 );
6118 })
6119 .log_err();
6120 }
6121 })
6122 .entry(second_entry_msg, None, move |window, cx| {
6123 weak_editor
6124 .update(cx, |this, cx| {
6125 this.add_edit_breakpoint_block(anchor, kind.as_ref(), window, cx);
6126 })
6127 .log_err();
6128 })
6129 })
6130 }
6131
6132 fn render_breakpoint(
6133 &self,
6134 position: Anchor,
6135 row: DisplayRow,
6136 kind: &BreakpointKind,
6137 cx: &mut Context<Self>,
6138 ) -> IconButton {
6139 let color = if self
6140 .gutter_breakpoint_indicator
6141 .is_some_and(|gutter_bp| gutter_bp.row() == row)
6142 {
6143 Color::Hint
6144 } else {
6145 Color::Debugger
6146 };
6147
6148 let icon = match &kind {
6149 BreakpointKind::Standard => ui::IconName::DebugBreakpoint,
6150 BreakpointKind::Log(_) => ui::IconName::DebugLogBreakpoint,
6151 };
6152 let arc_kind = Arc::new(kind.clone());
6153 let arc_kind2 = arc_kind.clone();
6154
6155 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6156 .icon_size(IconSize::XSmall)
6157 .size(ui::ButtonSize::None)
6158 .icon_color(color)
6159 .style(ButtonStyle::Transparent)
6160 .on_click(cx.listener(move |editor, _e, window, cx| {
6161 window.focus(&editor.focus_handle(cx));
6162 editor.edit_breakpoint_at_anchor(
6163 position,
6164 arc_kind.as_ref().clone(),
6165 BreakpointEditAction::Toggle,
6166 cx,
6167 );
6168 }))
6169 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6170 editor.set_breakpoint_context_menu(
6171 row,
6172 Some(position),
6173 arc_kind2.clone(),
6174 event.down.position,
6175 window,
6176 cx,
6177 );
6178 }))
6179 }
6180
6181 fn build_tasks_context(
6182 project: &Entity<Project>,
6183 buffer: &Entity<Buffer>,
6184 buffer_row: u32,
6185 tasks: &Arc<RunnableTasks>,
6186 cx: &mut Context<Self>,
6187 ) -> Task<Option<task::TaskContext>> {
6188 let position = Point::new(buffer_row, tasks.column);
6189 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6190 let location = Location {
6191 buffer: buffer.clone(),
6192 range: range_start..range_start,
6193 };
6194 // Fill in the environmental variables from the tree-sitter captures
6195 let mut captured_task_variables = TaskVariables::default();
6196 for (capture_name, value) in tasks.extra_variables.clone() {
6197 captured_task_variables.insert(
6198 task::VariableName::Custom(capture_name.into()),
6199 value.clone(),
6200 );
6201 }
6202 project.update(cx, |project, cx| {
6203 project.task_store().update(cx, |task_store, cx| {
6204 task_store.task_context_for_location(captured_task_variables, location, cx)
6205 })
6206 })
6207 }
6208
6209 pub fn spawn_nearest_task(
6210 &mut self,
6211 action: &SpawnNearestTask,
6212 window: &mut Window,
6213 cx: &mut Context<Self>,
6214 ) {
6215 let Some((workspace, _)) = self.workspace.clone() else {
6216 return;
6217 };
6218 let Some(project) = self.project.clone() else {
6219 return;
6220 };
6221
6222 // Try to find a closest, enclosing node using tree-sitter that has a
6223 // task
6224 let Some((buffer, buffer_row, tasks)) = self
6225 .find_enclosing_node_task(cx)
6226 // Or find the task that's closest in row-distance.
6227 .or_else(|| self.find_closest_task(cx))
6228 else {
6229 return;
6230 };
6231
6232 let reveal_strategy = action.reveal;
6233 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6234 cx.spawn_in(window, async move |_, cx| {
6235 let context = task_context.await?;
6236 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6237
6238 let resolved = resolved_task.resolved.as_mut()?;
6239 resolved.reveal = reveal_strategy;
6240
6241 workspace
6242 .update(cx, |workspace, cx| {
6243 workspace::tasks::schedule_resolved_task(
6244 workspace,
6245 task_source_kind,
6246 resolved_task,
6247 false,
6248 cx,
6249 );
6250 })
6251 .ok()
6252 })
6253 .detach();
6254 }
6255
6256 fn find_closest_task(
6257 &mut self,
6258 cx: &mut Context<Self>,
6259 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6260 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6261
6262 let ((buffer_id, row), tasks) = self
6263 .tasks
6264 .iter()
6265 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6266
6267 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6268 let tasks = Arc::new(tasks.to_owned());
6269 Some((buffer, *row, tasks))
6270 }
6271
6272 fn find_enclosing_node_task(
6273 &mut self,
6274 cx: &mut Context<Self>,
6275 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6276 let snapshot = self.buffer.read(cx).snapshot(cx);
6277 let offset = self.selections.newest::<usize>(cx).head();
6278 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6279 let buffer_id = excerpt.buffer().remote_id();
6280
6281 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6282 let mut cursor = layer.node().walk();
6283
6284 while cursor.goto_first_child_for_byte(offset).is_some() {
6285 if cursor.node().end_byte() == offset {
6286 cursor.goto_next_sibling();
6287 }
6288 }
6289
6290 // Ascend to the smallest ancestor that contains the range and has a task.
6291 loop {
6292 let node = cursor.node();
6293 let node_range = node.byte_range();
6294 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6295
6296 // Check if this node contains our offset
6297 if node_range.start <= offset && node_range.end >= offset {
6298 // If it contains offset, check for task
6299 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6300 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6301 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6302 }
6303 }
6304
6305 if !cursor.goto_parent() {
6306 break;
6307 }
6308 }
6309 None
6310 }
6311
6312 fn render_run_indicator(
6313 &self,
6314 _style: &EditorStyle,
6315 is_active: bool,
6316 row: DisplayRow,
6317 breakpoint: Option<(Anchor, Breakpoint)>,
6318 cx: &mut Context<Self>,
6319 ) -> IconButton {
6320 let color = Color::Muted;
6321
6322 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6323 let bp_kind = Arc::new(
6324 breakpoint
6325 .map(|(_, bp)| bp.kind)
6326 .unwrap_or(BreakpointKind::Standard),
6327 );
6328
6329 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6330 .shape(ui::IconButtonShape::Square)
6331 .icon_size(IconSize::XSmall)
6332 .icon_color(color)
6333 .toggle_state(is_active)
6334 .on_click(cx.listener(move |editor, _e, window, cx| {
6335 window.focus(&editor.focus_handle(cx));
6336 editor.toggle_code_actions(
6337 &ToggleCodeActions {
6338 deployed_from_indicator: Some(row),
6339 },
6340 window,
6341 cx,
6342 );
6343 }))
6344 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6345 editor.set_breakpoint_context_menu(
6346 row,
6347 position,
6348 bp_kind.clone(),
6349 event.down.position,
6350 window,
6351 cx,
6352 );
6353 }))
6354 }
6355
6356 pub fn context_menu_visible(&self) -> bool {
6357 !self.edit_prediction_preview_is_active()
6358 && self
6359 .context_menu
6360 .borrow()
6361 .as_ref()
6362 .map_or(false, |menu| menu.visible())
6363 }
6364
6365 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6366 self.context_menu
6367 .borrow()
6368 .as_ref()
6369 .map(|menu| menu.origin())
6370 }
6371
6372 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6373 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6374
6375 fn render_edit_prediction_popover(
6376 &mut self,
6377 text_bounds: &Bounds<Pixels>,
6378 content_origin: gpui::Point<Pixels>,
6379 editor_snapshot: &EditorSnapshot,
6380 visible_row_range: Range<DisplayRow>,
6381 scroll_top: f32,
6382 scroll_bottom: f32,
6383 line_layouts: &[LineWithInvisibles],
6384 line_height: Pixels,
6385 scroll_pixel_position: gpui::Point<Pixels>,
6386 newest_selection_head: Option<DisplayPoint>,
6387 editor_width: Pixels,
6388 style: &EditorStyle,
6389 window: &mut Window,
6390 cx: &mut App,
6391 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6392 let active_inline_completion = self.active_inline_completion.as_ref()?;
6393
6394 if self.edit_prediction_visible_in_cursor_popover(true) {
6395 return None;
6396 }
6397
6398 match &active_inline_completion.completion {
6399 InlineCompletion::Move { target, .. } => {
6400 let target_display_point = target.to_display_point(editor_snapshot);
6401
6402 if self.edit_prediction_requires_modifier() {
6403 if !self.edit_prediction_preview_is_active() {
6404 return None;
6405 }
6406
6407 self.render_edit_prediction_modifier_jump_popover(
6408 text_bounds,
6409 content_origin,
6410 visible_row_range,
6411 line_layouts,
6412 line_height,
6413 scroll_pixel_position,
6414 newest_selection_head,
6415 target_display_point,
6416 window,
6417 cx,
6418 )
6419 } else {
6420 self.render_edit_prediction_eager_jump_popover(
6421 text_bounds,
6422 content_origin,
6423 editor_snapshot,
6424 visible_row_range,
6425 scroll_top,
6426 scroll_bottom,
6427 line_height,
6428 scroll_pixel_position,
6429 target_display_point,
6430 editor_width,
6431 window,
6432 cx,
6433 )
6434 }
6435 }
6436 InlineCompletion::Edit {
6437 display_mode: EditDisplayMode::Inline,
6438 ..
6439 } => None,
6440 InlineCompletion::Edit {
6441 display_mode: EditDisplayMode::TabAccept,
6442 edits,
6443 ..
6444 } => {
6445 let range = &edits.first()?.0;
6446 let target_display_point = range.end.to_display_point(editor_snapshot);
6447
6448 self.render_edit_prediction_end_of_line_popover(
6449 "Accept",
6450 editor_snapshot,
6451 visible_row_range,
6452 target_display_point,
6453 line_height,
6454 scroll_pixel_position,
6455 content_origin,
6456 editor_width,
6457 window,
6458 cx,
6459 )
6460 }
6461 InlineCompletion::Edit {
6462 edits,
6463 edit_preview,
6464 display_mode: EditDisplayMode::DiffPopover,
6465 snapshot,
6466 } => self.render_edit_prediction_diff_popover(
6467 text_bounds,
6468 content_origin,
6469 editor_snapshot,
6470 visible_row_range,
6471 line_layouts,
6472 line_height,
6473 scroll_pixel_position,
6474 newest_selection_head,
6475 editor_width,
6476 style,
6477 edits,
6478 edit_preview,
6479 snapshot,
6480 window,
6481 cx,
6482 ),
6483 }
6484 }
6485
6486 fn render_edit_prediction_modifier_jump_popover(
6487 &mut self,
6488 text_bounds: &Bounds<Pixels>,
6489 content_origin: gpui::Point<Pixels>,
6490 visible_row_range: Range<DisplayRow>,
6491 line_layouts: &[LineWithInvisibles],
6492 line_height: Pixels,
6493 scroll_pixel_position: gpui::Point<Pixels>,
6494 newest_selection_head: Option<DisplayPoint>,
6495 target_display_point: DisplayPoint,
6496 window: &mut Window,
6497 cx: &mut App,
6498 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6499 let scrolled_content_origin =
6500 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6501
6502 const SCROLL_PADDING_Y: Pixels = px(12.);
6503
6504 if target_display_point.row() < visible_row_range.start {
6505 return self.render_edit_prediction_scroll_popover(
6506 |_| SCROLL_PADDING_Y,
6507 IconName::ArrowUp,
6508 visible_row_range,
6509 line_layouts,
6510 newest_selection_head,
6511 scrolled_content_origin,
6512 window,
6513 cx,
6514 );
6515 } else if target_display_point.row() >= visible_row_range.end {
6516 return self.render_edit_prediction_scroll_popover(
6517 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6518 IconName::ArrowDown,
6519 visible_row_range,
6520 line_layouts,
6521 newest_selection_head,
6522 scrolled_content_origin,
6523 window,
6524 cx,
6525 );
6526 }
6527
6528 const POLE_WIDTH: Pixels = px(2.);
6529
6530 let line_layout =
6531 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6532 let target_column = target_display_point.column() as usize;
6533
6534 let target_x = line_layout.x_for_index(target_column);
6535 let target_y =
6536 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6537
6538 let flag_on_right = target_x < text_bounds.size.width / 2.;
6539
6540 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6541 border_color.l += 0.001;
6542
6543 let mut element = v_flex()
6544 .items_end()
6545 .when(flag_on_right, |el| el.items_start())
6546 .child(if flag_on_right {
6547 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6548 .rounded_bl(px(0.))
6549 .rounded_tl(px(0.))
6550 .border_l_2()
6551 .border_color(border_color)
6552 } else {
6553 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6554 .rounded_br(px(0.))
6555 .rounded_tr(px(0.))
6556 .border_r_2()
6557 .border_color(border_color)
6558 })
6559 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6560 .into_any();
6561
6562 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6563
6564 let mut origin = scrolled_content_origin + point(target_x, target_y)
6565 - point(
6566 if flag_on_right {
6567 POLE_WIDTH
6568 } else {
6569 size.width - POLE_WIDTH
6570 },
6571 size.height - line_height,
6572 );
6573
6574 origin.x = origin.x.max(content_origin.x);
6575
6576 element.prepaint_at(origin, window, cx);
6577
6578 Some((element, origin))
6579 }
6580
6581 fn render_edit_prediction_scroll_popover(
6582 &mut self,
6583 to_y: impl Fn(Size<Pixels>) -> Pixels,
6584 scroll_icon: IconName,
6585 visible_row_range: Range<DisplayRow>,
6586 line_layouts: &[LineWithInvisibles],
6587 newest_selection_head: Option<DisplayPoint>,
6588 scrolled_content_origin: gpui::Point<Pixels>,
6589 window: &mut Window,
6590 cx: &mut App,
6591 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6592 let mut element = self
6593 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6594 .into_any();
6595
6596 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6597
6598 let cursor = newest_selection_head?;
6599 let cursor_row_layout =
6600 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6601 let cursor_column = cursor.column() as usize;
6602
6603 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6604
6605 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6606
6607 element.prepaint_at(origin, window, cx);
6608 Some((element, origin))
6609 }
6610
6611 fn render_edit_prediction_eager_jump_popover(
6612 &mut self,
6613 text_bounds: &Bounds<Pixels>,
6614 content_origin: gpui::Point<Pixels>,
6615 editor_snapshot: &EditorSnapshot,
6616 visible_row_range: Range<DisplayRow>,
6617 scroll_top: f32,
6618 scroll_bottom: f32,
6619 line_height: Pixels,
6620 scroll_pixel_position: gpui::Point<Pixels>,
6621 target_display_point: DisplayPoint,
6622 editor_width: Pixels,
6623 window: &mut Window,
6624 cx: &mut App,
6625 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6626 if target_display_point.row().as_f32() < scroll_top {
6627 let mut element = self
6628 .render_edit_prediction_line_popover(
6629 "Jump to Edit",
6630 Some(IconName::ArrowUp),
6631 window,
6632 cx,
6633 )?
6634 .into_any();
6635
6636 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6637 let offset = point(
6638 (text_bounds.size.width - size.width) / 2.,
6639 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6640 );
6641
6642 let origin = text_bounds.origin + offset;
6643 element.prepaint_at(origin, window, cx);
6644 Some((element, origin))
6645 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6646 let mut element = self
6647 .render_edit_prediction_line_popover(
6648 "Jump to Edit",
6649 Some(IconName::ArrowDown),
6650 window,
6651 cx,
6652 )?
6653 .into_any();
6654
6655 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6656 let offset = point(
6657 (text_bounds.size.width - size.width) / 2.,
6658 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6659 );
6660
6661 let origin = text_bounds.origin + offset;
6662 element.prepaint_at(origin, window, cx);
6663 Some((element, origin))
6664 } else {
6665 self.render_edit_prediction_end_of_line_popover(
6666 "Jump to Edit",
6667 editor_snapshot,
6668 visible_row_range,
6669 target_display_point,
6670 line_height,
6671 scroll_pixel_position,
6672 content_origin,
6673 editor_width,
6674 window,
6675 cx,
6676 )
6677 }
6678 }
6679
6680 fn render_edit_prediction_end_of_line_popover(
6681 self: &mut Editor,
6682 label: &'static str,
6683 editor_snapshot: &EditorSnapshot,
6684 visible_row_range: Range<DisplayRow>,
6685 target_display_point: DisplayPoint,
6686 line_height: Pixels,
6687 scroll_pixel_position: gpui::Point<Pixels>,
6688 content_origin: gpui::Point<Pixels>,
6689 editor_width: Pixels,
6690 window: &mut Window,
6691 cx: &mut App,
6692 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6693 let target_line_end = DisplayPoint::new(
6694 target_display_point.row(),
6695 editor_snapshot.line_len(target_display_point.row()),
6696 );
6697
6698 let mut element = self
6699 .render_edit_prediction_line_popover(label, None, window, cx)?
6700 .into_any();
6701
6702 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6703
6704 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6705
6706 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6707 let mut origin = start_point
6708 + line_origin
6709 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6710 origin.x = origin.x.max(content_origin.x);
6711
6712 let max_x = content_origin.x + editor_width - size.width;
6713
6714 if origin.x > max_x {
6715 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6716
6717 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6718 origin.y += offset;
6719 IconName::ArrowUp
6720 } else {
6721 origin.y -= offset;
6722 IconName::ArrowDown
6723 };
6724
6725 element = self
6726 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6727 .into_any();
6728
6729 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6730
6731 origin.x = content_origin.x + editor_width - size.width - px(2.);
6732 }
6733
6734 element.prepaint_at(origin, window, cx);
6735 Some((element, origin))
6736 }
6737
6738 fn render_edit_prediction_diff_popover(
6739 self: &Editor,
6740 text_bounds: &Bounds<Pixels>,
6741 content_origin: gpui::Point<Pixels>,
6742 editor_snapshot: &EditorSnapshot,
6743 visible_row_range: Range<DisplayRow>,
6744 line_layouts: &[LineWithInvisibles],
6745 line_height: Pixels,
6746 scroll_pixel_position: gpui::Point<Pixels>,
6747 newest_selection_head: Option<DisplayPoint>,
6748 editor_width: Pixels,
6749 style: &EditorStyle,
6750 edits: &Vec<(Range<Anchor>, String)>,
6751 edit_preview: &Option<language::EditPreview>,
6752 snapshot: &language::BufferSnapshot,
6753 window: &mut Window,
6754 cx: &mut App,
6755 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6756 let edit_start = edits
6757 .first()
6758 .unwrap()
6759 .0
6760 .start
6761 .to_display_point(editor_snapshot);
6762 let edit_end = edits
6763 .last()
6764 .unwrap()
6765 .0
6766 .end
6767 .to_display_point(editor_snapshot);
6768
6769 let is_visible = visible_row_range.contains(&edit_start.row())
6770 || visible_row_range.contains(&edit_end.row());
6771 if !is_visible {
6772 return None;
6773 }
6774
6775 let highlighted_edits =
6776 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6777
6778 let styled_text = highlighted_edits.to_styled_text(&style.text);
6779 let line_count = highlighted_edits.text.lines().count();
6780
6781 const BORDER_WIDTH: Pixels = px(1.);
6782
6783 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6784 let has_keybind = keybind.is_some();
6785
6786 let mut element = h_flex()
6787 .items_start()
6788 .child(
6789 h_flex()
6790 .bg(cx.theme().colors().editor_background)
6791 .border(BORDER_WIDTH)
6792 .shadow_sm()
6793 .border_color(cx.theme().colors().border)
6794 .rounded_l_lg()
6795 .when(line_count > 1, |el| el.rounded_br_lg())
6796 .pr_1()
6797 .child(styled_text),
6798 )
6799 .child(
6800 h_flex()
6801 .h(line_height + BORDER_WIDTH * px(2.))
6802 .px_1p5()
6803 .gap_1()
6804 // Workaround: For some reason, there's a gap if we don't do this
6805 .ml(-BORDER_WIDTH)
6806 .shadow(smallvec![gpui::BoxShadow {
6807 color: gpui::black().opacity(0.05),
6808 offset: point(px(1.), px(1.)),
6809 blur_radius: px(2.),
6810 spread_radius: px(0.),
6811 }])
6812 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6813 .border(BORDER_WIDTH)
6814 .border_color(cx.theme().colors().border)
6815 .rounded_r_lg()
6816 .id("edit_prediction_diff_popover_keybind")
6817 .when(!has_keybind, |el| {
6818 let status_colors = cx.theme().status();
6819
6820 el.bg(status_colors.error_background)
6821 .border_color(status_colors.error.opacity(0.6))
6822 .child(Icon::new(IconName::Info).color(Color::Error))
6823 .cursor_default()
6824 .hoverable_tooltip(move |_window, cx| {
6825 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6826 })
6827 })
6828 .children(keybind),
6829 )
6830 .into_any();
6831
6832 let longest_row =
6833 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6834 let longest_line_width = if visible_row_range.contains(&longest_row) {
6835 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6836 } else {
6837 layout_line(
6838 longest_row,
6839 editor_snapshot,
6840 style,
6841 editor_width,
6842 |_| false,
6843 window,
6844 cx,
6845 )
6846 .width
6847 };
6848
6849 let viewport_bounds =
6850 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6851 right: -EditorElement::SCROLLBAR_WIDTH,
6852 ..Default::default()
6853 });
6854
6855 let x_after_longest =
6856 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6857 - scroll_pixel_position.x;
6858
6859 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6860
6861 // Fully visible if it can be displayed within the window (allow overlapping other
6862 // panes). However, this is only allowed if the popover starts within text_bounds.
6863 let can_position_to_the_right = x_after_longest < text_bounds.right()
6864 && x_after_longest + element_bounds.width < viewport_bounds.right();
6865
6866 let mut origin = if can_position_to_the_right {
6867 point(
6868 x_after_longest,
6869 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6870 - scroll_pixel_position.y,
6871 )
6872 } else {
6873 let cursor_row = newest_selection_head.map(|head| head.row());
6874 let above_edit = edit_start
6875 .row()
6876 .0
6877 .checked_sub(line_count as u32)
6878 .map(DisplayRow);
6879 let below_edit = Some(edit_end.row() + 1);
6880 let above_cursor =
6881 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6882 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6883
6884 // Place the edit popover adjacent to the edit if there is a location
6885 // available that is onscreen and does not obscure the cursor. Otherwise,
6886 // place it adjacent to the cursor.
6887 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6888 .into_iter()
6889 .flatten()
6890 .find(|&start_row| {
6891 let end_row = start_row + line_count as u32;
6892 visible_row_range.contains(&start_row)
6893 && visible_row_range.contains(&end_row)
6894 && cursor_row.map_or(true, |cursor_row| {
6895 !((start_row..end_row).contains(&cursor_row))
6896 })
6897 })?;
6898
6899 content_origin
6900 + point(
6901 -scroll_pixel_position.x,
6902 row_target.as_f32() * line_height - scroll_pixel_position.y,
6903 )
6904 };
6905
6906 origin.x -= BORDER_WIDTH;
6907
6908 window.defer_draw(element, origin, 1);
6909
6910 // Do not return an element, since it will already be drawn due to defer_draw.
6911 None
6912 }
6913
6914 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6915 px(30.)
6916 }
6917
6918 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6919 if self.read_only(cx) {
6920 cx.theme().players().read_only()
6921 } else {
6922 self.style.as_ref().unwrap().local_player
6923 }
6924 }
6925
6926 fn render_edit_prediction_accept_keybind(
6927 &self,
6928 window: &mut Window,
6929 cx: &App,
6930 ) -> Option<AnyElement> {
6931 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6932 let accept_keystroke = accept_binding.keystroke()?;
6933
6934 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6935
6936 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6937 Color::Accent
6938 } else {
6939 Color::Muted
6940 };
6941
6942 h_flex()
6943 .px_0p5()
6944 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6945 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6946 .text_size(TextSize::XSmall.rems(cx))
6947 .child(h_flex().children(ui::render_modifiers(
6948 &accept_keystroke.modifiers,
6949 PlatformStyle::platform(),
6950 Some(modifiers_color),
6951 Some(IconSize::XSmall.rems().into()),
6952 true,
6953 )))
6954 .when(is_platform_style_mac, |parent| {
6955 parent.child(accept_keystroke.key.clone())
6956 })
6957 .when(!is_platform_style_mac, |parent| {
6958 parent.child(
6959 Key::new(
6960 util::capitalize(&accept_keystroke.key),
6961 Some(Color::Default),
6962 )
6963 .size(Some(IconSize::XSmall.rems().into())),
6964 )
6965 })
6966 .into_any()
6967 .into()
6968 }
6969
6970 fn render_edit_prediction_line_popover(
6971 &self,
6972 label: impl Into<SharedString>,
6973 icon: Option<IconName>,
6974 window: &mut Window,
6975 cx: &App,
6976 ) -> Option<Stateful<Div>> {
6977 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6978
6979 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6980 let has_keybind = keybind.is_some();
6981
6982 let result = h_flex()
6983 .id("ep-line-popover")
6984 .py_0p5()
6985 .pl_1()
6986 .pr(padding_right)
6987 .gap_1()
6988 .rounded_md()
6989 .border_1()
6990 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6991 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6992 .shadow_sm()
6993 .when(!has_keybind, |el| {
6994 let status_colors = cx.theme().status();
6995
6996 el.bg(status_colors.error_background)
6997 .border_color(status_colors.error.opacity(0.6))
6998 .pl_2()
6999 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7000 .cursor_default()
7001 .hoverable_tooltip(move |_window, cx| {
7002 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7003 })
7004 })
7005 .children(keybind)
7006 .child(
7007 Label::new(label)
7008 .size(LabelSize::Small)
7009 .when(!has_keybind, |el| {
7010 el.color(cx.theme().status().error.into()).strikethrough()
7011 }),
7012 )
7013 .when(!has_keybind, |el| {
7014 el.child(
7015 h_flex().ml_1().child(
7016 Icon::new(IconName::Info)
7017 .size(IconSize::Small)
7018 .color(cx.theme().status().error.into()),
7019 ),
7020 )
7021 })
7022 .when_some(icon, |element, icon| {
7023 element.child(
7024 div()
7025 .mt(px(1.5))
7026 .child(Icon::new(icon).size(IconSize::Small)),
7027 )
7028 });
7029
7030 Some(result)
7031 }
7032
7033 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7034 let accent_color = cx.theme().colors().text_accent;
7035 let editor_bg_color = cx.theme().colors().editor_background;
7036 editor_bg_color.blend(accent_color.opacity(0.1))
7037 }
7038
7039 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7040 let accent_color = cx.theme().colors().text_accent;
7041 let editor_bg_color = cx.theme().colors().editor_background;
7042 editor_bg_color.blend(accent_color.opacity(0.6))
7043 }
7044
7045 fn render_edit_prediction_cursor_popover(
7046 &self,
7047 min_width: Pixels,
7048 max_width: Pixels,
7049 cursor_point: Point,
7050 style: &EditorStyle,
7051 accept_keystroke: Option<&gpui::Keystroke>,
7052 _window: &Window,
7053 cx: &mut Context<Editor>,
7054 ) -> Option<AnyElement> {
7055 let provider = self.edit_prediction_provider.as_ref()?;
7056
7057 if provider.provider.needs_terms_acceptance(cx) {
7058 return Some(
7059 h_flex()
7060 .min_w(min_width)
7061 .flex_1()
7062 .px_2()
7063 .py_1()
7064 .gap_3()
7065 .elevation_2(cx)
7066 .hover(|style| style.bg(cx.theme().colors().element_hover))
7067 .id("accept-terms")
7068 .cursor_pointer()
7069 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7070 .on_click(cx.listener(|this, _event, window, cx| {
7071 cx.stop_propagation();
7072 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7073 window.dispatch_action(
7074 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7075 cx,
7076 );
7077 }))
7078 .child(
7079 h_flex()
7080 .flex_1()
7081 .gap_2()
7082 .child(Icon::new(IconName::ZedPredict))
7083 .child(Label::new("Accept Terms of Service"))
7084 .child(div().w_full())
7085 .child(
7086 Icon::new(IconName::ArrowUpRight)
7087 .color(Color::Muted)
7088 .size(IconSize::Small),
7089 )
7090 .into_any_element(),
7091 )
7092 .into_any(),
7093 );
7094 }
7095
7096 let is_refreshing = provider.provider.is_refreshing(cx);
7097
7098 fn pending_completion_container() -> Div {
7099 h_flex()
7100 .h_full()
7101 .flex_1()
7102 .gap_2()
7103 .child(Icon::new(IconName::ZedPredict))
7104 }
7105
7106 let completion = match &self.active_inline_completion {
7107 Some(prediction) => {
7108 if !self.has_visible_completions_menu() {
7109 const RADIUS: Pixels = px(6.);
7110 const BORDER_WIDTH: Pixels = px(1.);
7111
7112 return Some(
7113 h_flex()
7114 .elevation_2(cx)
7115 .border(BORDER_WIDTH)
7116 .border_color(cx.theme().colors().border)
7117 .when(accept_keystroke.is_none(), |el| {
7118 el.border_color(cx.theme().status().error)
7119 })
7120 .rounded(RADIUS)
7121 .rounded_tl(px(0.))
7122 .overflow_hidden()
7123 .child(div().px_1p5().child(match &prediction.completion {
7124 InlineCompletion::Move { target, snapshot } => {
7125 use text::ToPoint as _;
7126 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7127 {
7128 Icon::new(IconName::ZedPredictDown)
7129 } else {
7130 Icon::new(IconName::ZedPredictUp)
7131 }
7132 }
7133 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7134 }))
7135 .child(
7136 h_flex()
7137 .gap_1()
7138 .py_1()
7139 .px_2()
7140 .rounded_r(RADIUS - BORDER_WIDTH)
7141 .border_l_1()
7142 .border_color(cx.theme().colors().border)
7143 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7144 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7145 el.child(
7146 Label::new("Hold")
7147 .size(LabelSize::Small)
7148 .when(accept_keystroke.is_none(), |el| {
7149 el.strikethrough()
7150 })
7151 .line_height_style(LineHeightStyle::UiLabel),
7152 )
7153 })
7154 .id("edit_prediction_cursor_popover_keybind")
7155 .when(accept_keystroke.is_none(), |el| {
7156 let status_colors = cx.theme().status();
7157
7158 el.bg(status_colors.error_background)
7159 .border_color(status_colors.error.opacity(0.6))
7160 .child(Icon::new(IconName::Info).color(Color::Error))
7161 .cursor_default()
7162 .hoverable_tooltip(move |_window, cx| {
7163 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7164 .into()
7165 })
7166 })
7167 .when_some(
7168 accept_keystroke.as_ref(),
7169 |el, accept_keystroke| {
7170 el.child(h_flex().children(ui::render_modifiers(
7171 &accept_keystroke.modifiers,
7172 PlatformStyle::platform(),
7173 Some(Color::Default),
7174 Some(IconSize::XSmall.rems().into()),
7175 false,
7176 )))
7177 },
7178 ),
7179 )
7180 .into_any(),
7181 );
7182 }
7183
7184 self.render_edit_prediction_cursor_popover_preview(
7185 prediction,
7186 cursor_point,
7187 style,
7188 cx,
7189 )?
7190 }
7191
7192 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7193 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7194 stale_completion,
7195 cursor_point,
7196 style,
7197 cx,
7198 )?,
7199
7200 None => {
7201 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7202 }
7203 },
7204
7205 None => pending_completion_container().child(Label::new("No Prediction")),
7206 };
7207
7208 let completion = if is_refreshing {
7209 completion
7210 .with_animation(
7211 "loading-completion",
7212 Animation::new(Duration::from_secs(2))
7213 .repeat()
7214 .with_easing(pulsating_between(0.4, 0.8)),
7215 |label, delta| label.opacity(delta),
7216 )
7217 .into_any_element()
7218 } else {
7219 completion.into_any_element()
7220 };
7221
7222 let has_completion = self.active_inline_completion.is_some();
7223
7224 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7225 Some(
7226 h_flex()
7227 .min_w(min_width)
7228 .max_w(max_width)
7229 .flex_1()
7230 .elevation_2(cx)
7231 .border_color(cx.theme().colors().border)
7232 .child(
7233 div()
7234 .flex_1()
7235 .py_1()
7236 .px_2()
7237 .overflow_hidden()
7238 .child(completion),
7239 )
7240 .when_some(accept_keystroke, |el, accept_keystroke| {
7241 if !accept_keystroke.modifiers.modified() {
7242 return el;
7243 }
7244
7245 el.child(
7246 h_flex()
7247 .h_full()
7248 .border_l_1()
7249 .rounded_r_lg()
7250 .border_color(cx.theme().colors().border)
7251 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7252 .gap_1()
7253 .py_1()
7254 .px_2()
7255 .child(
7256 h_flex()
7257 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7258 .when(is_platform_style_mac, |parent| parent.gap_1())
7259 .child(h_flex().children(ui::render_modifiers(
7260 &accept_keystroke.modifiers,
7261 PlatformStyle::platform(),
7262 Some(if !has_completion {
7263 Color::Muted
7264 } else {
7265 Color::Default
7266 }),
7267 None,
7268 false,
7269 ))),
7270 )
7271 .child(Label::new("Preview").into_any_element())
7272 .opacity(if has_completion { 1.0 } else { 0.4 }),
7273 )
7274 })
7275 .into_any(),
7276 )
7277 }
7278
7279 fn render_edit_prediction_cursor_popover_preview(
7280 &self,
7281 completion: &InlineCompletionState,
7282 cursor_point: Point,
7283 style: &EditorStyle,
7284 cx: &mut Context<Editor>,
7285 ) -> Option<Div> {
7286 use text::ToPoint as _;
7287
7288 fn render_relative_row_jump(
7289 prefix: impl Into<String>,
7290 current_row: u32,
7291 target_row: u32,
7292 ) -> Div {
7293 let (row_diff, arrow) = if target_row < current_row {
7294 (current_row - target_row, IconName::ArrowUp)
7295 } else {
7296 (target_row - current_row, IconName::ArrowDown)
7297 };
7298
7299 h_flex()
7300 .child(
7301 Label::new(format!("{}{}", prefix.into(), row_diff))
7302 .color(Color::Muted)
7303 .size(LabelSize::Small),
7304 )
7305 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7306 }
7307
7308 match &completion.completion {
7309 InlineCompletion::Move {
7310 target, snapshot, ..
7311 } => Some(
7312 h_flex()
7313 .px_2()
7314 .gap_2()
7315 .flex_1()
7316 .child(
7317 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7318 Icon::new(IconName::ZedPredictDown)
7319 } else {
7320 Icon::new(IconName::ZedPredictUp)
7321 },
7322 )
7323 .child(Label::new("Jump to Edit")),
7324 ),
7325
7326 InlineCompletion::Edit {
7327 edits,
7328 edit_preview,
7329 snapshot,
7330 display_mode: _,
7331 } => {
7332 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7333
7334 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7335 &snapshot,
7336 &edits,
7337 edit_preview.as_ref()?,
7338 true,
7339 cx,
7340 )
7341 .first_line_preview();
7342
7343 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7344 .with_default_highlights(&style.text, highlighted_edits.highlights);
7345
7346 let preview = h_flex()
7347 .gap_1()
7348 .min_w_16()
7349 .child(styled_text)
7350 .when(has_more_lines, |parent| parent.child("…"));
7351
7352 let left = if first_edit_row != cursor_point.row {
7353 render_relative_row_jump("", cursor_point.row, first_edit_row)
7354 .into_any_element()
7355 } else {
7356 Icon::new(IconName::ZedPredict).into_any_element()
7357 };
7358
7359 Some(
7360 h_flex()
7361 .h_full()
7362 .flex_1()
7363 .gap_2()
7364 .pr_1()
7365 .overflow_x_hidden()
7366 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7367 .child(left)
7368 .child(preview),
7369 )
7370 }
7371 }
7372 }
7373
7374 fn render_context_menu(
7375 &self,
7376 style: &EditorStyle,
7377 max_height_in_lines: u32,
7378 y_flipped: bool,
7379 window: &mut Window,
7380 cx: &mut Context<Editor>,
7381 ) -> Option<AnyElement> {
7382 let menu = self.context_menu.borrow();
7383 let menu = menu.as_ref()?;
7384 if !menu.visible() {
7385 return None;
7386 };
7387 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7388 }
7389
7390 fn render_context_menu_aside(
7391 &mut self,
7392 max_size: Size<Pixels>,
7393 window: &mut Window,
7394 cx: &mut Context<Editor>,
7395 ) -> Option<AnyElement> {
7396 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7397 if menu.visible() {
7398 menu.render_aside(self, max_size, window, cx)
7399 } else {
7400 None
7401 }
7402 })
7403 }
7404
7405 fn hide_context_menu(
7406 &mut self,
7407 window: &mut Window,
7408 cx: &mut Context<Self>,
7409 ) -> Option<CodeContextMenu> {
7410 cx.notify();
7411 self.completion_tasks.clear();
7412 let context_menu = self.context_menu.borrow_mut().take();
7413 self.stale_inline_completion_in_menu.take();
7414 self.update_visible_inline_completion(window, cx);
7415 context_menu
7416 }
7417
7418 fn show_snippet_choices(
7419 &mut self,
7420 choices: &Vec<String>,
7421 selection: Range<Anchor>,
7422 cx: &mut Context<Self>,
7423 ) {
7424 if selection.start.buffer_id.is_none() {
7425 return;
7426 }
7427 let buffer_id = selection.start.buffer_id.unwrap();
7428 let buffer = self.buffer().read(cx).buffer(buffer_id);
7429 let id = post_inc(&mut self.next_completion_id);
7430
7431 if let Some(buffer) = buffer {
7432 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7433 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7434 ));
7435 }
7436 }
7437
7438 pub fn insert_snippet(
7439 &mut self,
7440 insertion_ranges: &[Range<usize>],
7441 snippet: Snippet,
7442 window: &mut Window,
7443 cx: &mut Context<Self>,
7444 ) -> Result<()> {
7445 struct Tabstop<T> {
7446 is_end_tabstop: bool,
7447 ranges: Vec<Range<T>>,
7448 choices: Option<Vec<String>>,
7449 }
7450
7451 let tabstops = self.buffer.update(cx, |buffer, cx| {
7452 let snippet_text: Arc<str> = snippet.text.clone().into();
7453 buffer.edit(
7454 insertion_ranges
7455 .iter()
7456 .cloned()
7457 .map(|range| (range, snippet_text.clone())),
7458 Some(AutoindentMode::EachLine),
7459 cx,
7460 );
7461
7462 let snapshot = &*buffer.read(cx);
7463 let snippet = &snippet;
7464 snippet
7465 .tabstops
7466 .iter()
7467 .map(|tabstop| {
7468 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7469 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7470 });
7471 let mut tabstop_ranges = tabstop
7472 .ranges
7473 .iter()
7474 .flat_map(|tabstop_range| {
7475 let mut delta = 0_isize;
7476 insertion_ranges.iter().map(move |insertion_range| {
7477 let insertion_start = insertion_range.start as isize + delta;
7478 delta +=
7479 snippet.text.len() as isize - insertion_range.len() as isize;
7480
7481 let start = ((insertion_start + tabstop_range.start) as usize)
7482 .min(snapshot.len());
7483 let end = ((insertion_start + tabstop_range.end) as usize)
7484 .min(snapshot.len());
7485 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7486 })
7487 })
7488 .collect::<Vec<_>>();
7489 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7490
7491 Tabstop {
7492 is_end_tabstop,
7493 ranges: tabstop_ranges,
7494 choices: tabstop.choices.clone(),
7495 }
7496 })
7497 .collect::<Vec<_>>()
7498 });
7499 if let Some(tabstop) = tabstops.first() {
7500 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7501 s.select_ranges(tabstop.ranges.iter().cloned());
7502 });
7503
7504 if let Some(choices) = &tabstop.choices {
7505 if let Some(selection) = tabstop.ranges.first() {
7506 self.show_snippet_choices(choices, selection.clone(), cx)
7507 }
7508 }
7509
7510 // If we're already at the last tabstop and it's at the end of the snippet,
7511 // we're done, we don't need to keep the state around.
7512 if !tabstop.is_end_tabstop {
7513 let choices = tabstops
7514 .iter()
7515 .map(|tabstop| tabstop.choices.clone())
7516 .collect();
7517
7518 let ranges = tabstops
7519 .into_iter()
7520 .map(|tabstop| tabstop.ranges)
7521 .collect::<Vec<_>>();
7522
7523 self.snippet_stack.push(SnippetState {
7524 active_index: 0,
7525 ranges,
7526 choices,
7527 });
7528 }
7529
7530 // Check whether the just-entered snippet ends with an auto-closable bracket.
7531 if self.autoclose_regions.is_empty() {
7532 let snapshot = self.buffer.read(cx).snapshot(cx);
7533 for selection in &mut self.selections.all::<Point>(cx) {
7534 let selection_head = selection.head();
7535 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7536 continue;
7537 };
7538
7539 let mut bracket_pair = None;
7540 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7541 let prev_chars = snapshot
7542 .reversed_chars_at(selection_head)
7543 .collect::<String>();
7544 for (pair, enabled) in scope.brackets() {
7545 if enabled
7546 && pair.close
7547 && prev_chars.starts_with(pair.start.as_str())
7548 && next_chars.starts_with(pair.end.as_str())
7549 {
7550 bracket_pair = Some(pair.clone());
7551 break;
7552 }
7553 }
7554 if let Some(pair) = bracket_pair {
7555 let start = snapshot.anchor_after(selection_head);
7556 let end = snapshot.anchor_after(selection_head);
7557 self.autoclose_regions.push(AutocloseRegion {
7558 selection_id: selection.id,
7559 range: start..end,
7560 pair,
7561 });
7562 }
7563 }
7564 }
7565 }
7566 Ok(())
7567 }
7568
7569 pub fn move_to_next_snippet_tabstop(
7570 &mut self,
7571 window: &mut Window,
7572 cx: &mut Context<Self>,
7573 ) -> bool {
7574 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7575 }
7576
7577 pub fn move_to_prev_snippet_tabstop(
7578 &mut self,
7579 window: &mut Window,
7580 cx: &mut Context<Self>,
7581 ) -> bool {
7582 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7583 }
7584
7585 pub fn move_to_snippet_tabstop(
7586 &mut self,
7587 bias: Bias,
7588 window: &mut Window,
7589 cx: &mut Context<Self>,
7590 ) -> bool {
7591 if let Some(mut snippet) = self.snippet_stack.pop() {
7592 match bias {
7593 Bias::Left => {
7594 if snippet.active_index > 0 {
7595 snippet.active_index -= 1;
7596 } else {
7597 self.snippet_stack.push(snippet);
7598 return false;
7599 }
7600 }
7601 Bias::Right => {
7602 if snippet.active_index + 1 < snippet.ranges.len() {
7603 snippet.active_index += 1;
7604 } else {
7605 self.snippet_stack.push(snippet);
7606 return false;
7607 }
7608 }
7609 }
7610 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7611 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7612 s.select_anchor_ranges(current_ranges.iter().cloned())
7613 });
7614
7615 if let Some(choices) = &snippet.choices[snippet.active_index] {
7616 if let Some(selection) = current_ranges.first() {
7617 self.show_snippet_choices(&choices, selection.clone(), cx);
7618 }
7619 }
7620
7621 // If snippet state is not at the last tabstop, push it back on the stack
7622 if snippet.active_index + 1 < snippet.ranges.len() {
7623 self.snippet_stack.push(snippet);
7624 }
7625 return true;
7626 }
7627 }
7628
7629 false
7630 }
7631
7632 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7633 self.transact(window, cx, |this, window, cx| {
7634 this.select_all(&SelectAll, window, cx);
7635 this.insert("", window, cx);
7636 });
7637 }
7638
7639 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7640 self.transact(window, cx, |this, window, cx| {
7641 this.select_autoclose_pair(window, cx);
7642 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7643 if !this.linked_edit_ranges.is_empty() {
7644 let selections = this.selections.all::<MultiBufferPoint>(cx);
7645 let snapshot = this.buffer.read(cx).snapshot(cx);
7646
7647 for selection in selections.iter() {
7648 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7649 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7650 if selection_start.buffer_id != selection_end.buffer_id {
7651 continue;
7652 }
7653 if let Some(ranges) =
7654 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7655 {
7656 for (buffer, entries) in ranges {
7657 linked_ranges.entry(buffer).or_default().extend(entries);
7658 }
7659 }
7660 }
7661 }
7662
7663 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7664 if !this.selections.line_mode {
7665 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7666 for selection in &mut selections {
7667 if selection.is_empty() {
7668 let old_head = selection.head();
7669 let mut new_head =
7670 movement::left(&display_map, old_head.to_display_point(&display_map))
7671 .to_point(&display_map);
7672 if let Some((buffer, line_buffer_range)) = display_map
7673 .buffer_snapshot
7674 .buffer_line_for_row(MultiBufferRow(old_head.row))
7675 {
7676 let indent_size =
7677 buffer.indent_size_for_line(line_buffer_range.start.row);
7678 let indent_len = match indent_size.kind {
7679 IndentKind::Space => {
7680 buffer.settings_at(line_buffer_range.start, cx).tab_size
7681 }
7682 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7683 };
7684 if old_head.column <= indent_size.len && old_head.column > 0 {
7685 let indent_len = indent_len.get();
7686 new_head = cmp::min(
7687 new_head,
7688 MultiBufferPoint::new(
7689 old_head.row,
7690 ((old_head.column - 1) / indent_len) * indent_len,
7691 ),
7692 );
7693 }
7694 }
7695
7696 selection.set_head(new_head, SelectionGoal::None);
7697 }
7698 }
7699 }
7700
7701 this.signature_help_state.set_backspace_pressed(true);
7702 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7703 s.select(selections)
7704 });
7705 this.insert("", window, cx);
7706 let empty_str: Arc<str> = Arc::from("");
7707 for (buffer, edits) in linked_ranges {
7708 let snapshot = buffer.read(cx).snapshot();
7709 use text::ToPoint as TP;
7710
7711 let edits = edits
7712 .into_iter()
7713 .map(|range| {
7714 let end_point = TP::to_point(&range.end, &snapshot);
7715 let mut start_point = TP::to_point(&range.start, &snapshot);
7716
7717 if end_point == start_point {
7718 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7719 .saturating_sub(1);
7720 start_point =
7721 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7722 };
7723
7724 (start_point..end_point, empty_str.clone())
7725 })
7726 .sorted_by_key(|(range, _)| range.start)
7727 .collect::<Vec<_>>();
7728 buffer.update(cx, |this, cx| {
7729 this.edit(edits, None, cx);
7730 })
7731 }
7732 this.refresh_inline_completion(true, false, window, cx);
7733 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7734 });
7735 }
7736
7737 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7738 self.transact(window, cx, |this, window, cx| {
7739 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7740 let line_mode = s.line_mode;
7741 s.move_with(|map, selection| {
7742 if selection.is_empty() && !line_mode {
7743 let cursor = movement::right(map, selection.head());
7744 selection.end = cursor;
7745 selection.reversed = true;
7746 selection.goal = SelectionGoal::None;
7747 }
7748 })
7749 });
7750 this.insert("", window, cx);
7751 this.refresh_inline_completion(true, false, window, cx);
7752 });
7753 }
7754
7755 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7756 if self.move_to_prev_snippet_tabstop(window, cx) {
7757 return;
7758 }
7759
7760 self.outdent(&Outdent, window, cx);
7761 }
7762
7763 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7764 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7765 return;
7766 }
7767
7768 let mut selections = self.selections.all_adjusted(cx);
7769 let buffer = self.buffer.read(cx);
7770 let snapshot = buffer.snapshot(cx);
7771 let rows_iter = selections.iter().map(|s| s.head().row);
7772 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7773
7774 let mut edits = Vec::new();
7775 let mut prev_edited_row = 0;
7776 let mut row_delta = 0;
7777 for selection in &mut selections {
7778 if selection.start.row != prev_edited_row {
7779 row_delta = 0;
7780 }
7781 prev_edited_row = selection.end.row;
7782
7783 // If the selection is non-empty, then increase the indentation of the selected lines.
7784 if !selection.is_empty() {
7785 row_delta =
7786 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7787 continue;
7788 }
7789
7790 // If the selection is empty and the cursor is in the leading whitespace before the
7791 // suggested indentation, then auto-indent the line.
7792 let cursor = selection.head();
7793 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7794 if let Some(suggested_indent) =
7795 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7796 {
7797 if cursor.column < suggested_indent.len
7798 && cursor.column <= current_indent.len
7799 && current_indent.len <= suggested_indent.len
7800 {
7801 selection.start = Point::new(cursor.row, suggested_indent.len);
7802 selection.end = selection.start;
7803 if row_delta == 0 {
7804 edits.extend(Buffer::edit_for_indent_size_adjustment(
7805 cursor.row,
7806 current_indent,
7807 suggested_indent,
7808 ));
7809 row_delta = suggested_indent.len - current_indent.len;
7810 }
7811 continue;
7812 }
7813 }
7814
7815 // Otherwise, insert a hard or soft tab.
7816 let settings = buffer.language_settings_at(cursor, cx);
7817 let tab_size = if settings.hard_tabs {
7818 IndentSize::tab()
7819 } else {
7820 let tab_size = settings.tab_size.get();
7821 let char_column = snapshot
7822 .text_for_range(Point::new(cursor.row, 0)..cursor)
7823 .flat_map(str::chars)
7824 .count()
7825 + row_delta as usize;
7826 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7827 IndentSize::spaces(chars_to_next_tab_stop)
7828 };
7829 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7830 selection.end = selection.start;
7831 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7832 row_delta += tab_size.len;
7833 }
7834
7835 self.transact(window, cx, |this, window, cx| {
7836 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7837 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7838 s.select(selections)
7839 });
7840 this.refresh_inline_completion(true, false, window, cx);
7841 });
7842 }
7843
7844 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7845 if self.read_only(cx) {
7846 return;
7847 }
7848 let mut selections = self.selections.all::<Point>(cx);
7849 let mut prev_edited_row = 0;
7850 let mut row_delta = 0;
7851 let mut edits = Vec::new();
7852 let buffer = self.buffer.read(cx);
7853 let snapshot = buffer.snapshot(cx);
7854 for selection in &mut selections {
7855 if selection.start.row != prev_edited_row {
7856 row_delta = 0;
7857 }
7858 prev_edited_row = selection.end.row;
7859
7860 row_delta =
7861 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7862 }
7863
7864 self.transact(window, cx, |this, window, cx| {
7865 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7866 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7867 s.select(selections)
7868 });
7869 });
7870 }
7871
7872 fn indent_selection(
7873 buffer: &MultiBuffer,
7874 snapshot: &MultiBufferSnapshot,
7875 selection: &mut Selection<Point>,
7876 edits: &mut Vec<(Range<Point>, String)>,
7877 delta_for_start_row: u32,
7878 cx: &App,
7879 ) -> u32 {
7880 let settings = buffer.language_settings_at(selection.start, cx);
7881 let tab_size = settings.tab_size.get();
7882 let indent_kind = if settings.hard_tabs {
7883 IndentKind::Tab
7884 } else {
7885 IndentKind::Space
7886 };
7887 let mut start_row = selection.start.row;
7888 let mut end_row = selection.end.row + 1;
7889
7890 // If a selection ends at the beginning of a line, don't indent
7891 // that last line.
7892 if selection.end.column == 0 && selection.end.row > selection.start.row {
7893 end_row -= 1;
7894 }
7895
7896 // Avoid re-indenting a row that has already been indented by a
7897 // previous selection, but still update this selection's column
7898 // to reflect that indentation.
7899 if delta_for_start_row > 0 {
7900 start_row += 1;
7901 selection.start.column += delta_for_start_row;
7902 if selection.end.row == selection.start.row {
7903 selection.end.column += delta_for_start_row;
7904 }
7905 }
7906
7907 let mut delta_for_end_row = 0;
7908 let has_multiple_rows = start_row + 1 != end_row;
7909 for row in start_row..end_row {
7910 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7911 let indent_delta = match (current_indent.kind, indent_kind) {
7912 (IndentKind::Space, IndentKind::Space) => {
7913 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7914 IndentSize::spaces(columns_to_next_tab_stop)
7915 }
7916 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7917 (_, IndentKind::Tab) => IndentSize::tab(),
7918 };
7919
7920 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7921 0
7922 } else {
7923 selection.start.column
7924 };
7925 let row_start = Point::new(row, start);
7926 edits.push((
7927 row_start..row_start,
7928 indent_delta.chars().collect::<String>(),
7929 ));
7930
7931 // Update this selection's endpoints to reflect the indentation.
7932 if row == selection.start.row {
7933 selection.start.column += indent_delta.len;
7934 }
7935 if row == selection.end.row {
7936 selection.end.column += indent_delta.len;
7937 delta_for_end_row = indent_delta.len;
7938 }
7939 }
7940
7941 if selection.start.row == selection.end.row {
7942 delta_for_start_row + delta_for_end_row
7943 } else {
7944 delta_for_end_row
7945 }
7946 }
7947
7948 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7949 if self.read_only(cx) {
7950 return;
7951 }
7952 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7953 let selections = self.selections.all::<Point>(cx);
7954 let mut deletion_ranges = Vec::new();
7955 let mut last_outdent = None;
7956 {
7957 let buffer = self.buffer.read(cx);
7958 let snapshot = buffer.snapshot(cx);
7959 for selection in &selections {
7960 let settings = buffer.language_settings_at(selection.start, cx);
7961 let tab_size = settings.tab_size.get();
7962 let mut rows = selection.spanned_rows(false, &display_map);
7963
7964 // Avoid re-outdenting a row that has already been outdented by a
7965 // previous selection.
7966 if let Some(last_row) = last_outdent {
7967 if last_row == rows.start {
7968 rows.start = rows.start.next_row();
7969 }
7970 }
7971 let has_multiple_rows = rows.len() > 1;
7972 for row in rows.iter_rows() {
7973 let indent_size = snapshot.indent_size_for_line(row);
7974 if indent_size.len > 0 {
7975 let deletion_len = match indent_size.kind {
7976 IndentKind::Space => {
7977 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7978 if columns_to_prev_tab_stop == 0 {
7979 tab_size
7980 } else {
7981 columns_to_prev_tab_stop
7982 }
7983 }
7984 IndentKind::Tab => 1,
7985 };
7986 let start = if has_multiple_rows
7987 || deletion_len > selection.start.column
7988 || indent_size.len < selection.start.column
7989 {
7990 0
7991 } else {
7992 selection.start.column - deletion_len
7993 };
7994 deletion_ranges.push(
7995 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7996 );
7997 last_outdent = Some(row);
7998 }
7999 }
8000 }
8001 }
8002
8003 self.transact(window, cx, |this, window, cx| {
8004 this.buffer.update(cx, |buffer, cx| {
8005 let empty_str: Arc<str> = Arc::default();
8006 buffer.edit(
8007 deletion_ranges
8008 .into_iter()
8009 .map(|range| (range, empty_str.clone())),
8010 None,
8011 cx,
8012 );
8013 });
8014 let selections = this.selections.all::<usize>(cx);
8015 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8016 s.select(selections)
8017 });
8018 });
8019 }
8020
8021 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8022 if self.read_only(cx) {
8023 return;
8024 }
8025 let selections = self
8026 .selections
8027 .all::<usize>(cx)
8028 .into_iter()
8029 .map(|s| s.range());
8030
8031 self.transact(window, cx, |this, window, cx| {
8032 this.buffer.update(cx, |buffer, cx| {
8033 buffer.autoindent_ranges(selections, cx);
8034 });
8035 let selections = this.selections.all::<usize>(cx);
8036 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8037 s.select(selections)
8038 });
8039 });
8040 }
8041
8042 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8043 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8044 let selections = self.selections.all::<Point>(cx);
8045
8046 let mut new_cursors = Vec::new();
8047 let mut edit_ranges = Vec::new();
8048 let mut selections = selections.iter().peekable();
8049 while let Some(selection) = selections.next() {
8050 let mut rows = selection.spanned_rows(false, &display_map);
8051 let goal_display_column = selection.head().to_display_point(&display_map).column();
8052
8053 // Accumulate contiguous regions of rows that we want to delete.
8054 while let Some(next_selection) = selections.peek() {
8055 let next_rows = next_selection.spanned_rows(false, &display_map);
8056 if next_rows.start <= rows.end {
8057 rows.end = next_rows.end;
8058 selections.next().unwrap();
8059 } else {
8060 break;
8061 }
8062 }
8063
8064 let buffer = &display_map.buffer_snapshot;
8065 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8066 let edit_end;
8067 let cursor_buffer_row;
8068 if buffer.max_point().row >= rows.end.0 {
8069 // If there's a line after the range, delete the \n from the end of the row range
8070 // and position the cursor on the next line.
8071 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8072 cursor_buffer_row = rows.end;
8073 } else {
8074 // If there isn't a line after the range, delete the \n from the line before the
8075 // start of the row range and position the cursor there.
8076 edit_start = edit_start.saturating_sub(1);
8077 edit_end = buffer.len();
8078 cursor_buffer_row = rows.start.previous_row();
8079 }
8080
8081 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8082 *cursor.column_mut() =
8083 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8084
8085 new_cursors.push((
8086 selection.id,
8087 buffer.anchor_after(cursor.to_point(&display_map)),
8088 ));
8089 edit_ranges.push(edit_start..edit_end);
8090 }
8091
8092 self.transact(window, cx, |this, window, cx| {
8093 let buffer = this.buffer.update(cx, |buffer, cx| {
8094 let empty_str: Arc<str> = Arc::default();
8095 buffer.edit(
8096 edit_ranges
8097 .into_iter()
8098 .map(|range| (range, empty_str.clone())),
8099 None,
8100 cx,
8101 );
8102 buffer.snapshot(cx)
8103 });
8104 let new_selections = new_cursors
8105 .into_iter()
8106 .map(|(id, cursor)| {
8107 let cursor = cursor.to_point(&buffer);
8108 Selection {
8109 id,
8110 start: cursor,
8111 end: cursor,
8112 reversed: false,
8113 goal: SelectionGoal::None,
8114 }
8115 })
8116 .collect();
8117
8118 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8119 s.select(new_selections);
8120 });
8121 });
8122 }
8123
8124 pub fn join_lines_impl(
8125 &mut self,
8126 insert_whitespace: bool,
8127 window: &mut Window,
8128 cx: &mut Context<Self>,
8129 ) {
8130 if self.read_only(cx) {
8131 return;
8132 }
8133 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8134 for selection in self.selections.all::<Point>(cx) {
8135 let start = MultiBufferRow(selection.start.row);
8136 // Treat single line selections as if they include the next line. Otherwise this action
8137 // would do nothing for single line selections individual cursors.
8138 let end = if selection.start.row == selection.end.row {
8139 MultiBufferRow(selection.start.row + 1)
8140 } else {
8141 MultiBufferRow(selection.end.row)
8142 };
8143
8144 if let Some(last_row_range) = row_ranges.last_mut() {
8145 if start <= last_row_range.end {
8146 last_row_range.end = end;
8147 continue;
8148 }
8149 }
8150 row_ranges.push(start..end);
8151 }
8152
8153 let snapshot = self.buffer.read(cx).snapshot(cx);
8154 let mut cursor_positions = Vec::new();
8155 for row_range in &row_ranges {
8156 let anchor = snapshot.anchor_before(Point::new(
8157 row_range.end.previous_row().0,
8158 snapshot.line_len(row_range.end.previous_row()),
8159 ));
8160 cursor_positions.push(anchor..anchor);
8161 }
8162
8163 self.transact(window, cx, |this, window, cx| {
8164 for row_range in row_ranges.into_iter().rev() {
8165 for row in row_range.iter_rows().rev() {
8166 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8167 let next_line_row = row.next_row();
8168 let indent = snapshot.indent_size_for_line(next_line_row);
8169 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8170
8171 let replace =
8172 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8173 " "
8174 } else {
8175 ""
8176 };
8177
8178 this.buffer.update(cx, |buffer, cx| {
8179 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8180 });
8181 }
8182 }
8183
8184 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8185 s.select_anchor_ranges(cursor_positions)
8186 });
8187 });
8188 }
8189
8190 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8191 self.join_lines_impl(true, window, cx);
8192 }
8193
8194 pub fn sort_lines_case_sensitive(
8195 &mut self,
8196 _: &SortLinesCaseSensitive,
8197 window: &mut Window,
8198 cx: &mut Context<Self>,
8199 ) {
8200 self.manipulate_lines(window, cx, |lines| lines.sort())
8201 }
8202
8203 pub fn sort_lines_case_insensitive(
8204 &mut self,
8205 _: &SortLinesCaseInsensitive,
8206 window: &mut Window,
8207 cx: &mut Context<Self>,
8208 ) {
8209 self.manipulate_lines(window, cx, |lines| {
8210 lines.sort_by_key(|line| line.to_lowercase())
8211 })
8212 }
8213
8214 pub fn unique_lines_case_insensitive(
8215 &mut self,
8216 _: &UniqueLinesCaseInsensitive,
8217 window: &mut Window,
8218 cx: &mut Context<Self>,
8219 ) {
8220 self.manipulate_lines(window, cx, |lines| {
8221 let mut seen = HashSet::default();
8222 lines.retain(|line| seen.insert(line.to_lowercase()));
8223 })
8224 }
8225
8226 pub fn unique_lines_case_sensitive(
8227 &mut self,
8228 _: &UniqueLinesCaseSensitive,
8229 window: &mut Window,
8230 cx: &mut Context<Self>,
8231 ) {
8232 self.manipulate_lines(window, cx, |lines| {
8233 let mut seen = HashSet::default();
8234 lines.retain(|line| seen.insert(*line));
8235 })
8236 }
8237
8238 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8239 let Some(project) = self.project.clone() else {
8240 return;
8241 };
8242 self.reload(project, window, cx)
8243 .detach_and_notify_err(window, cx);
8244 }
8245
8246 pub fn restore_file(
8247 &mut self,
8248 _: &::git::RestoreFile,
8249 window: &mut Window,
8250 cx: &mut Context<Self>,
8251 ) {
8252 let mut buffer_ids = HashSet::default();
8253 let snapshot = self.buffer().read(cx).snapshot(cx);
8254 for selection in self.selections.all::<usize>(cx) {
8255 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8256 }
8257
8258 let buffer = self.buffer().read(cx);
8259 let ranges = buffer_ids
8260 .into_iter()
8261 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8262 .collect::<Vec<_>>();
8263
8264 self.restore_hunks_in_ranges(ranges, window, cx);
8265 }
8266
8267 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8268 let selections = self
8269 .selections
8270 .all(cx)
8271 .into_iter()
8272 .map(|s| s.range())
8273 .collect();
8274 self.restore_hunks_in_ranges(selections, window, cx);
8275 }
8276
8277 fn restore_hunks_in_ranges(
8278 &mut self,
8279 ranges: Vec<Range<Point>>,
8280 window: &mut Window,
8281 cx: &mut Context<Editor>,
8282 ) {
8283 let mut revert_changes = HashMap::default();
8284 let chunk_by = self
8285 .snapshot(window, cx)
8286 .hunks_for_ranges(ranges)
8287 .into_iter()
8288 .chunk_by(|hunk| hunk.buffer_id);
8289 for (buffer_id, hunks) in &chunk_by {
8290 let hunks = hunks.collect::<Vec<_>>();
8291 for hunk in &hunks {
8292 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8293 }
8294 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8295 }
8296 drop(chunk_by);
8297 if !revert_changes.is_empty() {
8298 self.transact(window, cx, |editor, window, cx| {
8299 editor.restore(revert_changes, window, cx);
8300 });
8301 }
8302 }
8303
8304 pub fn open_active_item_in_terminal(
8305 &mut self,
8306 _: &OpenInTerminal,
8307 window: &mut Window,
8308 cx: &mut Context<Self>,
8309 ) {
8310 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8311 let project_path = buffer.read(cx).project_path(cx)?;
8312 let project = self.project.as_ref()?.read(cx);
8313 let entry = project.entry_for_path(&project_path, cx)?;
8314 let parent = match &entry.canonical_path {
8315 Some(canonical_path) => canonical_path.to_path_buf(),
8316 None => project.absolute_path(&project_path, cx)?,
8317 }
8318 .parent()?
8319 .to_path_buf();
8320 Some(parent)
8321 }) {
8322 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8323 }
8324 }
8325
8326 fn set_breakpoint_context_menu(
8327 &mut self,
8328 row: DisplayRow,
8329 position: Option<Anchor>,
8330 kind: Arc<BreakpointKind>,
8331 clicked_point: gpui::Point<Pixels>,
8332 window: &mut Window,
8333 cx: &mut Context<Self>,
8334 ) {
8335 if !cx.has_flag::<Debugger>() {
8336 return;
8337 }
8338 let source = self
8339 .buffer
8340 .read(cx)
8341 .snapshot(cx)
8342 .anchor_before(Point::new(row.0, 0u32));
8343
8344 let context_menu =
8345 self.breakpoint_context_menu(position.unwrap_or(source), kind, window, cx);
8346
8347 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8348 self,
8349 source,
8350 clicked_point,
8351 context_menu,
8352 window,
8353 cx,
8354 );
8355 }
8356
8357 fn add_edit_breakpoint_block(
8358 &mut self,
8359 anchor: Anchor,
8360 kind: &BreakpointKind,
8361 window: &mut Window,
8362 cx: &mut Context<Self>,
8363 ) {
8364 let weak_editor = cx.weak_entity();
8365 let bp_prompt =
8366 cx.new(|cx| BreakpointPromptEditor::new(weak_editor, anchor, kind.clone(), window, cx));
8367
8368 let height = bp_prompt.update(cx, |this, cx| {
8369 this.prompt
8370 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8371 });
8372 let cloned_prompt = bp_prompt.clone();
8373 let blocks = vec![BlockProperties {
8374 style: BlockStyle::Sticky,
8375 placement: BlockPlacement::Above(anchor),
8376 height,
8377 render: Arc::new(move |cx| {
8378 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8379 cloned_prompt.clone().into_any_element()
8380 }),
8381 priority: 0,
8382 }];
8383
8384 let focus_handle = bp_prompt.focus_handle(cx);
8385 window.focus(&focus_handle);
8386
8387 let block_ids = self.insert_blocks(blocks, None, cx);
8388 bp_prompt.update(cx, |prompt, _| {
8389 prompt.add_block_ids(block_ids);
8390 });
8391 }
8392
8393 pub(crate) fn breakpoint_at_cursor_head(
8394 &self,
8395 window: &mut Window,
8396 cx: &mut Context<Self>,
8397 ) -> Option<(Anchor, Breakpoint)> {
8398 let cursor_position: Point = self.selections.newest(cx).head();
8399 let snapshot = self.snapshot(window, cx);
8400 // We Set the column position to zero so this function interacts correctly
8401 // between calls by clicking on the gutter & using an action to toggle a
8402 // breakpoint. Otherwise, toggling a breakpoint through an action wouldn't
8403 // untoggle a breakpoint that was added through clicking on the gutter
8404 let cursor_position = snapshot
8405 .display_snapshot
8406 .buffer_snapshot
8407 .anchor_before(Point::new(cursor_position.row, 0));
8408
8409 let project = self.project.clone();
8410
8411 let buffer_id = cursor_position.text_anchor.buffer_id?;
8412 let enclosing_excerpt = snapshot
8413 .buffer_snapshot
8414 .excerpt_ids_for_range(cursor_position..cursor_position)
8415 .next()?;
8416 let buffer = project?.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8417 let buffer_snapshot = buffer.read(cx).snapshot();
8418
8419 let row = buffer_snapshot
8420 .summary_for_anchor::<text::PointUtf16>(&cursor_position.text_anchor)
8421 .row;
8422
8423 let bp = self
8424 .breakpoint_store
8425 .as_ref()?
8426 .read_with(cx, |breakpoint_store, cx| {
8427 breakpoint_store
8428 .breakpoints(
8429 &buffer,
8430 Some(cursor_position.text_anchor..(text::Anchor::MAX)),
8431 buffer_snapshot.clone(),
8432 cx,
8433 )
8434 .next()
8435 .and_then(move |(anchor, bp)| {
8436 let breakpoint_row = buffer_snapshot
8437 .summary_for_anchor::<text::PointUtf16>(anchor)
8438 .row;
8439
8440 if breakpoint_row == row {
8441 snapshot
8442 .buffer_snapshot
8443 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8444 .map(|anchor| (anchor, bp.clone()))
8445 } else {
8446 None
8447 }
8448 })
8449 });
8450 bp
8451 }
8452
8453 pub fn edit_log_breakpoint(
8454 &mut self,
8455 _: &EditLogBreakpoint,
8456 window: &mut Window,
8457 cx: &mut Context<Self>,
8458 ) {
8459 let (anchor, bp) = self
8460 .breakpoint_at_cursor_head(window, cx)
8461 .unwrap_or_else(|| {
8462 let cursor_position: Point = self.selections.newest(cx).head();
8463
8464 let breakpoint_position = self
8465 .snapshot(window, cx)
8466 .display_snapshot
8467 .buffer_snapshot
8468 .anchor_before(Point::new(cursor_position.row, 0));
8469
8470 (
8471 breakpoint_position,
8472 Breakpoint {
8473 kind: BreakpointKind::Standard,
8474 },
8475 )
8476 });
8477
8478 self.add_edit_breakpoint_block(anchor, &bp.kind, window, cx);
8479 }
8480
8481 pub fn toggle_breakpoint(
8482 &mut self,
8483 _: &crate::actions::ToggleBreakpoint,
8484 window: &mut Window,
8485 cx: &mut Context<Self>,
8486 ) {
8487 let edit_action = BreakpointEditAction::Toggle;
8488
8489 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8490 self.edit_breakpoint_at_anchor(anchor, breakpoint.kind, edit_action, cx);
8491 } else {
8492 let cursor_position: Point = self.selections.newest(cx).head();
8493
8494 let breakpoint_position = self
8495 .snapshot(window, cx)
8496 .display_snapshot
8497 .buffer_snapshot
8498 .anchor_before(Point::new(cursor_position.row, 0));
8499
8500 self.edit_breakpoint_at_anchor(
8501 breakpoint_position,
8502 BreakpointKind::Standard,
8503 edit_action,
8504 cx,
8505 );
8506 }
8507 }
8508
8509 pub fn edit_breakpoint_at_anchor(
8510 &mut self,
8511 breakpoint_position: Anchor,
8512 kind: BreakpointKind,
8513 edit_action: BreakpointEditAction,
8514 cx: &mut Context<Self>,
8515 ) {
8516 let Some(breakpoint_store) = &self.breakpoint_store else {
8517 return;
8518 };
8519
8520 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8521 if breakpoint_position == Anchor::min() {
8522 self.buffer()
8523 .read(cx)
8524 .excerpt_buffer_ids()
8525 .into_iter()
8526 .next()
8527 } else {
8528 None
8529 }
8530 }) else {
8531 return;
8532 };
8533
8534 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8535 return;
8536 };
8537
8538 breakpoint_store.update(cx, |breakpoint_store, cx| {
8539 breakpoint_store.toggle_breakpoint(
8540 buffer,
8541 (breakpoint_position.text_anchor, Breakpoint { kind }),
8542 edit_action,
8543 cx,
8544 );
8545 });
8546
8547 cx.notify();
8548 }
8549
8550 #[cfg(any(test, feature = "test-support"))]
8551 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8552 self.breakpoint_store.clone()
8553 }
8554
8555 pub fn prepare_restore_change(
8556 &self,
8557 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8558 hunk: &MultiBufferDiffHunk,
8559 cx: &mut App,
8560 ) -> Option<()> {
8561 if hunk.is_created_file() {
8562 return None;
8563 }
8564 let buffer = self.buffer.read(cx);
8565 let diff = buffer.diff_for(hunk.buffer_id)?;
8566 let buffer = buffer.buffer(hunk.buffer_id)?;
8567 let buffer = buffer.read(cx);
8568 let original_text = diff
8569 .read(cx)
8570 .base_text()
8571 .as_rope()
8572 .slice(hunk.diff_base_byte_range.clone());
8573 let buffer_snapshot = buffer.snapshot();
8574 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8575 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8576 probe
8577 .0
8578 .start
8579 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8580 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8581 }) {
8582 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8583 Some(())
8584 } else {
8585 None
8586 }
8587 }
8588
8589 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8590 self.manipulate_lines(window, cx, |lines| lines.reverse())
8591 }
8592
8593 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8594 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8595 }
8596
8597 fn manipulate_lines<Fn>(
8598 &mut self,
8599 window: &mut Window,
8600 cx: &mut Context<Self>,
8601 mut callback: Fn,
8602 ) where
8603 Fn: FnMut(&mut Vec<&str>),
8604 {
8605 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8606 let buffer = self.buffer.read(cx).snapshot(cx);
8607
8608 let mut edits = Vec::new();
8609
8610 let selections = self.selections.all::<Point>(cx);
8611 let mut selections = selections.iter().peekable();
8612 let mut contiguous_row_selections = Vec::new();
8613 let mut new_selections = Vec::new();
8614 let mut added_lines = 0;
8615 let mut removed_lines = 0;
8616
8617 while let Some(selection) = selections.next() {
8618 let (start_row, end_row) = consume_contiguous_rows(
8619 &mut contiguous_row_selections,
8620 selection,
8621 &display_map,
8622 &mut selections,
8623 );
8624
8625 let start_point = Point::new(start_row.0, 0);
8626 let end_point = Point::new(
8627 end_row.previous_row().0,
8628 buffer.line_len(end_row.previous_row()),
8629 );
8630 let text = buffer
8631 .text_for_range(start_point..end_point)
8632 .collect::<String>();
8633
8634 let mut lines = text.split('\n').collect_vec();
8635
8636 let lines_before = lines.len();
8637 callback(&mut lines);
8638 let lines_after = lines.len();
8639
8640 edits.push((start_point..end_point, lines.join("\n")));
8641
8642 // Selections must change based on added and removed line count
8643 let start_row =
8644 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8645 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8646 new_selections.push(Selection {
8647 id: selection.id,
8648 start: start_row,
8649 end: end_row,
8650 goal: SelectionGoal::None,
8651 reversed: selection.reversed,
8652 });
8653
8654 if lines_after > lines_before {
8655 added_lines += lines_after - lines_before;
8656 } else if lines_before > lines_after {
8657 removed_lines += lines_before - lines_after;
8658 }
8659 }
8660
8661 self.transact(window, cx, |this, window, cx| {
8662 let buffer = this.buffer.update(cx, |buffer, cx| {
8663 buffer.edit(edits, None, cx);
8664 buffer.snapshot(cx)
8665 });
8666
8667 // Recalculate offsets on newly edited buffer
8668 let new_selections = new_selections
8669 .iter()
8670 .map(|s| {
8671 let start_point = Point::new(s.start.0, 0);
8672 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8673 Selection {
8674 id: s.id,
8675 start: buffer.point_to_offset(start_point),
8676 end: buffer.point_to_offset(end_point),
8677 goal: s.goal,
8678 reversed: s.reversed,
8679 }
8680 })
8681 .collect();
8682
8683 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8684 s.select(new_selections);
8685 });
8686
8687 this.request_autoscroll(Autoscroll::fit(), cx);
8688 });
8689 }
8690
8691 pub fn convert_to_upper_case(
8692 &mut self,
8693 _: &ConvertToUpperCase,
8694 window: &mut Window,
8695 cx: &mut Context<Self>,
8696 ) {
8697 self.manipulate_text(window, cx, |text| text.to_uppercase())
8698 }
8699
8700 pub fn convert_to_lower_case(
8701 &mut self,
8702 _: &ConvertToLowerCase,
8703 window: &mut Window,
8704 cx: &mut Context<Self>,
8705 ) {
8706 self.manipulate_text(window, cx, |text| text.to_lowercase())
8707 }
8708
8709 pub fn convert_to_title_case(
8710 &mut self,
8711 _: &ConvertToTitleCase,
8712 window: &mut Window,
8713 cx: &mut Context<Self>,
8714 ) {
8715 self.manipulate_text(window, cx, |text| {
8716 text.split('\n')
8717 .map(|line| line.to_case(Case::Title))
8718 .join("\n")
8719 })
8720 }
8721
8722 pub fn convert_to_snake_case(
8723 &mut self,
8724 _: &ConvertToSnakeCase,
8725 window: &mut Window,
8726 cx: &mut Context<Self>,
8727 ) {
8728 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8729 }
8730
8731 pub fn convert_to_kebab_case(
8732 &mut self,
8733 _: &ConvertToKebabCase,
8734 window: &mut Window,
8735 cx: &mut Context<Self>,
8736 ) {
8737 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8738 }
8739
8740 pub fn convert_to_upper_camel_case(
8741 &mut self,
8742 _: &ConvertToUpperCamelCase,
8743 window: &mut Window,
8744 cx: &mut Context<Self>,
8745 ) {
8746 self.manipulate_text(window, cx, |text| {
8747 text.split('\n')
8748 .map(|line| line.to_case(Case::UpperCamel))
8749 .join("\n")
8750 })
8751 }
8752
8753 pub fn convert_to_lower_camel_case(
8754 &mut self,
8755 _: &ConvertToLowerCamelCase,
8756 window: &mut Window,
8757 cx: &mut Context<Self>,
8758 ) {
8759 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8760 }
8761
8762 pub fn convert_to_opposite_case(
8763 &mut self,
8764 _: &ConvertToOppositeCase,
8765 window: &mut Window,
8766 cx: &mut Context<Self>,
8767 ) {
8768 self.manipulate_text(window, cx, |text| {
8769 text.chars()
8770 .fold(String::with_capacity(text.len()), |mut t, c| {
8771 if c.is_uppercase() {
8772 t.extend(c.to_lowercase());
8773 } else {
8774 t.extend(c.to_uppercase());
8775 }
8776 t
8777 })
8778 })
8779 }
8780
8781 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8782 where
8783 Fn: FnMut(&str) -> String,
8784 {
8785 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8786 let buffer = self.buffer.read(cx).snapshot(cx);
8787
8788 let mut new_selections = Vec::new();
8789 let mut edits = Vec::new();
8790 let mut selection_adjustment = 0i32;
8791
8792 for selection in self.selections.all::<usize>(cx) {
8793 let selection_is_empty = selection.is_empty();
8794
8795 let (start, end) = if selection_is_empty {
8796 let word_range = movement::surrounding_word(
8797 &display_map,
8798 selection.start.to_display_point(&display_map),
8799 );
8800 let start = word_range.start.to_offset(&display_map, Bias::Left);
8801 let end = word_range.end.to_offset(&display_map, Bias::Left);
8802 (start, end)
8803 } else {
8804 (selection.start, selection.end)
8805 };
8806
8807 let text = buffer.text_for_range(start..end).collect::<String>();
8808 let old_length = text.len() as i32;
8809 let text = callback(&text);
8810
8811 new_selections.push(Selection {
8812 start: (start as i32 - selection_adjustment) as usize,
8813 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8814 goal: SelectionGoal::None,
8815 ..selection
8816 });
8817
8818 selection_adjustment += old_length - text.len() as i32;
8819
8820 edits.push((start..end, text));
8821 }
8822
8823 self.transact(window, cx, |this, window, cx| {
8824 this.buffer.update(cx, |buffer, cx| {
8825 buffer.edit(edits, None, cx);
8826 });
8827
8828 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8829 s.select(new_selections);
8830 });
8831
8832 this.request_autoscroll(Autoscroll::fit(), cx);
8833 });
8834 }
8835
8836 pub fn duplicate(
8837 &mut self,
8838 upwards: bool,
8839 whole_lines: bool,
8840 window: &mut Window,
8841 cx: &mut Context<Self>,
8842 ) {
8843 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8844 let buffer = &display_map.buffer_snapshot;
8845 let selections = self.selections.all::<Point>(cx);
8846
8847 let mut edits = Vec::new();
8848 let mut selections_iter = selections.iter().peekable();
8849 while let Some(selection) = selections_iter.next() {
8850 let mut rows = selection.spanned_rows(false, &display_map);
8851 // duplicate line-wise
8852 if whole_lines || selection.start == selection.end {
8853 // Avoid duplicating the same lines twice.
8854 while let Some(next_selection) = selections_iter.peek() {
8855 let next_rows = next_selection.spanned_rows(false, &display_map);
8856 if next_rows.start < rows.end {
8857 rows.end = next_rows.end;
8858 selections_iter.next().unwrap();
8859 } else {
8860 break;
8861 }
8862 }
8863
8864 // Copy the text from the selected row region and splice it either at the start
8865 // or end of the region.
8866 let start = Point::new(rows.start.0, 0);
8867 let end = Point::new(
8868 rows.end.previous_row().0,
8869 buffer.line_len(rows.end.previous_row()),
8870 );
8871 let text = buffer
8872 .text_for_range(start..end)
8873 .chain(Some("\n"))
8874 .collect::<String>();
8875 let insert_location = if upwards {
8876 Point::new(rows.end.0, 0)
8877 } else {
8878 start
8879 };
8880 edits.push((insert_location..insert_location, text));
8881 } else {
8882 // duplicate character-wise
8883 let start = selection.start;
8884 let end = selection.end;
8885 let text = buffer.text_for_range(start..end).collect::<String>();
8886 edits.push((selection.end..selection.end, text));
8887 }
8888 }
8889
8890 self.transact(window, cx, |this, _, cx| {
8891 this.buffer.update(cx, |buffer, cx| {
8892 buffer.edit(edits, None, cx);
8893 });
8894
8895 this.request_autoscroll(Autoscroll::fit(), cx);
8896 });
8897 }
8898
8899 pub fn duplicate_line_up(
8900 &mut self,
8901 _: &DuplicateLineUp,
8902 window: &mut Window,
8903 cx: &mut Context<Self>,
8904 ) {
8905 self.duplicate(true, true, window, cx);
8906 }
8907
8908 pub fn duplicate_line_down(
8909 &mut self,
8910 _: &DuplicateLineDown,
8911 window: &mut Window,
8912 cx: &mut Context<Self>,
8913 ) {
8914 self.duplicate(false, true, window, cx);
8915 }
8916
8917 pub fn duplicate_selection(
8918 &mut self,
8919 _: &DuplicateSelection,
8920 window: &mut Window,
8921 cx: &mut Context<Self>,
8922 ) {
8923 self.duplicate(false, false, window, cx);
8924 }
8925
8926 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8927 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8928 let buffer = self.buffer.read(cx).snapshot(cx);
8929
8930 let mut edits = Vec::new();
8931 let mut unfold_ranges = Vec::new();
8932 let mut refold_creases = Vec::new();
8933
8934 let selections = self.selections.all::<Point>(cx);
8935 let mut selections = selections.iter().peekable();
8936 let mut contiguous_row_selections = Vec::new();
8937 let mut new_selections = Vec::new();
8938
8939 while let Some(selection) = selections.next() {
8940 // Find all the selections that span a contiguous row range
8941 let (start_row, end_row) = consume_contiguous_rows(
8942 &mut contiguous_row_selections,
8943 selection,
8944 &display_map,
8945 &mut selections,
8946 );
8947
8948 // Move the text spanned by the row range to be before the line preceding the row range
8949 if start_row.0 > 0 {
8950 let range_to_move = Point::new(
8951 start_row.previous_row().0,
8952 buffer.line_len(start_row.previous_row()),
8953 )
8954 ..Point::new(
8955 end_row.previous_row().0,
8956 buffer.line_len(end_row.previous_row()),
8957 );
8958 let insertion_point = display_map
8959 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8960 .0;
8961
8962 // Don't move lines across excerpts
8963 if buffer
8964 .excerpt_containing(insertion_point..range_to_move.end)
8965 .is_some()
8966 {
8967 let text = buffer
8968 .text_for_range(range_to_move.clone())
8969 .flat_map(|s| s.chars())
8970 .skip(1)
8971 .chain(['\n'])
8972 .collect::<String>();
8973
8974 edits.push((
8975 buffer.anchor_after(range_to_move.start)
8976 ..buffer.anchor_before(range_to_move.end),
8977 String::new(),
8978 ));
8979 let insertion_anchor = buffer.anchor_after(insertion_point);
8980 edits.push((insertion_anchor..insertion_anchor, text));
8981
8982 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8983
8984 // Move selections up
8985 new_selections.extend(contiguous_row_selections.drain(..).map(
8986 |mut selection| {
8987 selection.start.row -= row_delta;
8988 selection.end.row -= row_delta;
8989 selection
8990 },
8991 ));
8992
8993 // Move folds up
8994 unfold_ranges.push(range_to_move.clone());
8995 for fold in display_map.folds_in_range(
8996 buffer.anchor_before(range_to_move.start)
8997 ..buffer.anchor_after(range_to_move.end),
8998 ) {
8999 let mut start = fold.range.start.to_point(&buffer);
9000 let mut end = fold.range.end.to_point(&buffer);
9001 start.row -= row_delta;
9002 end.row -= row_delta;
9003 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9004 }
9005 }
9006 }
9007
9008 // If we didn't move line(s), preserve the existing selections
9009 new_selections.append(&mut contiguous_row_selections);
9010 }
9011
9012 self.transact(window, cx, |this, window, cx| {
9013 this.unfold_ranges(&unfold_ranges, true, true, cx);
9014 this.buffer.update(cx, |buffer, cx| {
9015 for (range, text) in edits {
9016 buffer.edit([(range, text)], None, cx);
9017 }
9018 });
9019 this.fold_creases(refold_creases, true, window, cx);
9020 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9021 s.select(new_selections);
9022 })
9023 });
9024 }
9025
9026 pub fn move_line_down(
9027 &mut self,
9028 _: &MoveLineDown,
9029 window: &mut Window,
9030 cx: &mut Context<Self>,
9031 ) {
9032 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9033 let buffer = self.buffer.read(cx).snapshot(cx);
9034
9035 let mut edits = Vec::new();
9036 let mut unfold_ranges = Vec::new();
9037 let mut refold_creases = Vec::new();
9038
9039 let selections = self.selections.all::<Point>(cx);
9040 let mut selections = selections.iter().peekable();
9041 let mut contiguous_row_selections = Vec::new();
9042 let mut new_selections = Vec::new();
9043
9044 while let Some(selection) = selections.next() {
9045 // Find all the selections that span a contiguous row range
9046 let (start_row, end_row) = consume_contiguous_rows(
9047 &mut contiguous_row_selections,
9048 selection,
9049 &display_map,
9050 &mut selections,
9051 );
9052
9053 // Move the text spanned by the row range to be after the last line of the row range
9054 if end_row.0 <= buffer.max_point().row {
9055 let range_to_move =
9056 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9057 let insertion_point = display_map
9058 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9059 .0;
9060
9061 // Don't move lines across excerpt boundaries
9062 if buffer
9063 .excerpt_containing(range_to_move.start..insertion_point)
9064 .is_some()
9065 {
9066 let mut text = String::from("\n");
9067 text.extend(buffer.text_for_range(range_to_move.clone()));
9068 text.pop(); // Drop trailing newline
9069 edits.push((
9070 buffer.anchor_after(range_to_move.start)
9071 ..buffer.anchor_before(range_to_move.end),
9072 String::new(),
9073 ));
9074 let insertion_anchor = buffer.anchor_after(insertion_point);
9075 edits.push((insertion_anchor..insertion_anchor, text));
9076
9077 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9078
9079 // Move selections down
9080 new_selections.extend(contiguous_row_selections.drain(..).map(
9081 |mut selection| {
9082 selection.start.row += row_delta;
9083 selection.end.row += row_delta;
9084 selection
9085 },
9086 ));
9087
9088 // Move folds down
9089 unfold_ranges.push(range_to_move.clone());
9090 for fold in display_map.folds_in_range(
9091 buffer.anchor_before(range_to_move.start)
9092 ..buffer.anchor_after(range_to_move.end),
9093 ) {
9094 let mut start = fold.range.start.to_point(&buffer);
9095 let mut end = fold.range.end.to_point(&buffer);
9096 start.row += row_delta;
9097 end.row += row_delta;
9098 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9099 }
9100 }
9101 }
9102
9103 // If we didn't move line(s), preserve the existing selections
9104 new_selections.append(&mut contiguous_row_selections);
9105 }
9106
9107 self.transact(window, cx, |this, window, cx| {
9108 this.unfold_ranges(&unfold_ranges, true, true, cx);
9109 this.buffer.update(cx, |buffer, cx| {
9110 for (range, text) in edits {
9111 buffer.edit([(range, text)], None, cx);
9112 }
9113 });
9114 this.fold_creases(refold_creases, true, window, cx);
9115 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9116 s.select(new_selections)
9117 });
9118 });
9119 }
9120
9121 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9122 let text_layout_details = &self.text_layout_details(window);
9123 self.transact(window, cx, |this, window, cx| {
9124 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9125 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9126 let line_mode = s.line_mode;
9127 s.move_with(|display_map, selection| {
9128 if !selection.is_empty() || line_mode {
9129 return;
9130 }
9131
9132 let mut head = selection.head();
9133 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9134 if head.column() == display_map.line_len(head.row()) {
9135 transpose_offset = display_map
9136 .buffer_snapshot
9137 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9138 }
9139
9140 if transpose_offset == 0 {
9141 return;
9142 }
9143
9144 *head.column_mut() += 1;
9145 head = display_map.clip_point(head, Bias::Right);
9146 let goal = SelectionGoal::HorizontalPosition(
9147 display_map
9148 .x_for_display_point(head, text_layout_details)
9149 .into(),
9150 );
9151 selection.collapse_to(head, goal);
9152
9153 let transpose_start = display_map
9154 .buffer_snapshot
9155 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9156 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9157 let transpose_end = display_map
9158 .buffer_snapshot
9159 .clip_offset(transpose_offset + 1, Bias::Right);
9160 if let Some(ch) =
9161 display_map.buffer_snapshot.chars_at(transpose_start).next()
9162 {
9163 edits.push((transpose_start..transpose_offset, String::new()));
9164 edits.push((transpose_end..transpose_end, ch.to_string()));
9165 }
9166 }
9167 });
9168 edits
9169 });
9170 this.buffer
9171 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9172 let selections = this.selections.all::<usize>(cx);
9173 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9174 s.select(selections);
9175 });
9176 });
9177 }
9178
9179 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9180 self.rewrap_impl(RewrapOptions::default(), cx)
9181 }
9182
9183 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9184 let buffer = self.buffer.read(cx).snapshot(cx);
9185 let selections = self.selections.all::<Point>(cx);
9186 let mut selections = selections.iter().peekable();
9187
9188 let mut edits = Vec::new();
9189 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9190
9191 while let Some(selection) = selections.next() {
9192 let mut start_row = selection.start.row;
9193 let mut end_row = selection.end.row;
9194
9195 // Skip selections that overlap with a range that has already been rewrapped.
9196 let selection_range = start_row..end_row;
9197 if rewrapped_row_ranges
9198 .iter()
9199 .any(|range| range.overlaps(&selection_range))
9200 {
9201 continue;
9202 }
9203
9204 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9205
9206 // Since not all lines in the selection may be at the same indent
9207 // level, choose the indent size that is the most common between all
9208 // of the lines.
9209 //
9210 // If there is a tie, we use the deepest indent.
9211 let (indent_size, indent_end) = {
9212 let mut indent_size_occurrences = HashMap::default();
9213 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9214
9215 for row in start_row..=end_row {
9216 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9217 rows_by_indent_size.entry(indent).or_default().push(row);
9218 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9219 }
9220
9221 let indent_size = indent_size_occurrences
9222 .into_iter()
9223 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9224 .map(|(indent, _)| indent)
9225 .unwrap_or_default();
9226 let row = rows_by_indent_size[&indent_size][0];
9227 let indent_end = Point::new(row, indent_size.len);
9228
9229 (indent_size, indent_end)
9230 };
9231
9232 let mut line_prefix = indent_size.chars().collect::<String>();
9233
9234 let mut inside_comment = false;
9235 if let Some(comment_prefix) =
9236 buffer
9237 .language_scope_at(selection.head())
9238 .and_then(|language| {
9239 language
9240 .line_comment_prefixes()
9241 .iter()
9242 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9243 .cloned()
9244 })
9245 {
9246 line_prefix.push_str(&comment_prefix);
9247 inside_comment = true;
9248 }
9249
9250 let language_settings = buffer.language_settings_at(selection.head(), cx);
9251 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9252 RewrapBehavior::InComments => inside_comment,
9253 RewrapBehavior::InSelections => !selection.is_empty(),
9254 RewrapBehavior::Anywhere => true,
9255 };
9256
9257 let should_rewrap = options.override_language_settings
9258 || allow_rewrap_based_on_language
9259 || self.hard_wrap.is_some();
9260 if !should_rewrap {
9261 continue;
9262 }
9263
9264 if selection.is_empty() {
9265 'expand_upwards: while start_row > 0 {
9266 let prev_row = start_row - 1;
9267 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9268 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9269 {
9270 start_row = prev_row;
9271 } else {
9272 break 'expand_upwards;
9273 }
9274 }
9275
9276 'expand_downwards: while end_row < buffer.max_point().row {
9277 let next_row = end_row + 1;
9278 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9279 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9280 {
9281 end_row = next_row;
9282 } else {
9283 break 'expand_downwards;
9284 }
9285 }
9286 }
9287
9288 let start = Point::new(start_row, 0);
9289 let start_offset = start.to_offset(&buffer);
9290 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9291 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9292 let Some(lines_without_prefixes) = selection_text
9293 .lines()
9294 .map(|line| {
9295 line.strip_prefix(&line_prefix)
9296 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9297 .ok_or_else(|| {
9298 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9299 })
9300 })
9301 .collect::<Result<Vec<_>, _>>()
9302 .log_err()
9303 else {
9304 continue;
9305 };
9306
9307 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9308 buffer
9309 .language_settings_at(Point::new(start_row, 0), cx)
9310 .preferred_line_length as usize
9311 });
9312 let wrapped_text = wrap_with_prefix(
9313 line_prefix,
9314 lines_without_prefixes.join("\n"),
9315 wrap_column,
9316 tab_size,
9317 options.preserve_existing_whitespace,
9318 );
9319
9320 // TODO: should always use char-based diff while still supporting cursor behavior that
9321 // matches vim.
9322 let mut diff_options = DiffOptions::default();
9323 if options.override_language_settings {
9324 diff_options.max_word_diff_len = 0;
9325 diff_options.max_word_diff_line_count = 0;
9326 } else {
9327 diff_options.max_word_diff_len = usize::MAX;
9328 diff_options.max_word_diff_line_count = usize::MAX;
9329 }
9330
9331 for (old_range, new_text) in
9332 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9333 {
9334 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9335 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9336 edits.push((edit_start..edit_end, new_text));
9337 }
9338
9339 rewrapped_row_ranges.push(start_row..=end_row);
9340 }
9341
9342 self.buffer
9343 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9344 }
9345
9346 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9347 let mut text = String::new();
9348 let buffer = self.buffer.read(cx).snapshot(cx);
9349 let mut selections = self.selections.all::<Point>(cx);
9350 let mut clipboard_selections = Vec::with_capacity(selections.len());
9351 {
9352 let max_point = buffer.max_point();
9353 let mut is_first = true;
9354 for selection in &mut selections {
9355 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9356 if is_entire_line {
9357 selection.start = Point::new(selection.start.row, 0);
9358 if !selection.is_empty() && selection.end.column == 0 {
9359 selection.end = cmp::min(max_point, selection.end);
9360 } else {
9361 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9362 }
9363 selection.goal = SelectionGoal::None;
9364 }
9365 if is_first {
9366 is_first = false;
9367 } else {
9368 text += "\n";
9369 }
9370 let mut len = 0;
9371 for chunk in buffer.text_for_range(selection.start..selection.end) {
9372 text.push_str(chunk);
9373 len += chunk.len();
9374 }
9375 clipboard_selections.push(ClipboardSelection {
9376 len,
9377 is_entire_line,
9378 first_line_indent: buffer
9379 .indent_size_for_line(MultiBufferRow(selection.start.row))
9380 .len,
9381 });
9382 }
9383 }
9384
9385 self.transact(window, cx, |this, window, cx| {
9386 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9387 s.select(selections);
9388 });
9389 this.insert("", window, cx);
9390 });
9391 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9392 }
9393
9394 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9395 let item = self.cut_common(window, cx);
9396 cx.write_to_clipboard(item);
9397 }
9398
9399 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9400 self.change_selections(None, window, cx, |s| {
9401 s.move_with(|snapshot, sel| {
9402 if sel.is_empty() {
9403 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9404 }
9405 });
9406 });
9407 let item = self.cut_common(window, cx);
9408 cx.set_global(KillRing(item))
9409 }
9410
9411 pub fn kill_ring_yank(
9412 &mut self,
9413 _: &KillRingYank,
9414 window: &mut Window,
9415 cx: &mut Context<Self>,
9416 ) {
9417 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9418 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9419 (kill_ring.text().to_string(), kill_ring.metadata_json())
9420 } else {
9421 return;
9422 }
9423 } else {
9424 return;
9425 };
9426 self.do_paste(&text, metadata, false, window, cx);
9427 }
9428
9429 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9430 let selections = self.selections.all::<Point>(cx);
9431 let buffer = self.buffer.read(cx).read(cx);
9432 let mut text = String::new();
9433
9434 let mut clipboard_selections = Vec::with_capacity(selections.len());
9435 {
9436 let max_point = buffer.max_point();
9437 let mut is_first = true;
9438 for selection in selections.iter() {
9439 let mut start = selection.start;
9440 let mut end = selection.end;
9441 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9442 if is_entire_line {
9443 start = Point::new(start.row, 0);
9444 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9445 }
9446 if is_first {
9447 is_first = false;
9448 } else {
9449 text += "\n";
9450 }
9451 let mut len = 0;
9452 for chunk in buffer.text_for_range(start..end) {
9453 text.push_str(chunk);
9454 len += chunk.len();
9455 }
9456 clipboard_selections.push(ClipboardSelection {
9457 len,
9458 is_entire_line,
9459 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
9460 });
9461 }
9462 }
9463
9464 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9465 text,
9466 clipboard_selections,
9467 ));
9468 }
9469
9470 pub fn do_paste(
9471 &mut self,
9472 text: &String,
9473 clipboard_selections: Option<Vec<ClipboardSelection>>,
9474 handle_entire_lines: bool,
9475 window: &mut Window,
9476 cx: &mut Context<Self>,
9477 ) {
9478 if self.read_only(cx) {
9479 return;
9480 }
9481
9482 let clipboard_text = Cow::Borrowed(text);
9483
9484 self.transact(window, cx, |this, window, cx| {
9485 if let Some(mut clipboard_selections) = clipboard_selections {
9486 let old_selections = this.selections.all::<usize>(cx);
9487 let all_selections_were_entire_line =
9488 clipboard_selections.iter().all(|s| s.is_entire_line);
9489 let first_selection_indent_column =
9490 clipboard_selections.first().map(|s| s.first_line_indent);
9491 if clipboard_selections.len() != old_selections.len() {
9492 clipboard_selections.drain(..);
9493 }
9494 let cursor_offset = this.selections.last::<usize>(cx).head();
9495 let mut auto_indent_on_paste = true;
9496
9497 this.buffer.update(cx, |buffer, cx| {
9498 let snapshot = buffer.read(cx);
9499 auto_indent_on_paste = snapshot
9500 .language_settings_at(cursor_offset, cx)
9501 .auto_indent_on_paste;
9502
9503 let mut start_offset = 0;
9504 let mut edits = Vec::new();
9505 let mut original_indent_columns = Vec::new();
9506 for (ix, selection) in old_selections.iter().enumerate() {
9507 let to_insert;
9508 let entire_line;
9509 let original_indent_column;
9510 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
9511 let end_offset = start_offset + clipboard_selection.len;
9512 to_insert = &clipboard_text[start_offset..end_offset];
9513 entire_line = clipboard_selection.is_entire_line;
9514 start_offset = end_offset + 1;
9515 original_indent_column = Some(clipboard_selection.first_line_indent);
9516 } else {
9517 to_insert = clipboard_text.as_str();
9518 entire_line = all_selections_were_entire_line;
9519 original_indent_column = first_selection_indent_column
9520 }
9521
9522 // If the corresponding selection was empty when this slice of the
9523 // clipboard text was written, then the entire line containing the
9524 // selection was copied. If this selection is also currently empty,
9525 // then paste the line before the current line of the buffer.
9526 let range = if selection.is_empty() && handle_entire_lines && entire_line {
9527 let column = selection.start.to_point(&snapshot).column as usize;
9528 let line_start = selection.start - column;
9529 line_start..line_start
9530 } else {
9531 selection.range()
9532 };
9533
9534 edits.push((range, to_insert));
9535 original_indent_columns.push(original_indent_column);
9536 }
9537 drop(snapshot);
9538
9539 buffer.edit(
9540 edits,
9541 if auto_indent_on_paste {
9542 Some(AutoindentMode::Block {
9543 original_indent_columns,
9544 })
9545 } else {
9546 None
9547 },
9548 cx,
9549 );
9550 });
9551
9552 let selections = this.selections.all::<usize>(cx);
9553 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9554 s.select(selections)
9555 });
9556 } else {
9557 this.insert(&clipboard_text, window, cx);
9558 }
9559 });
9560 }
9561
9562 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
9563 if let Some(item) = cx.read_from_clipboard() {
9564 let entries = item.entries();
9565
9566 match entries.first() {
9567 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
9568 // of all the pasted entries.
9569 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9570 .do_paste(
9571 clipboard_string.text(),
9572 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9573 true,
9574 window,
9575 cx,
9576 ),
9577 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9578 }
9579 }
9580 }
9581
9582 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9583 if self.read_only(cx) {
9584 return;
9585 }
9586
9587 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9588 if let Some((selections, _)) =
9589 self.selection_history.transaction(transaction_id).cloned()
9590 {
9591 self.change_selections(None, window, cx, |s| {
9592 s.select_anchors(selections.to_vec());
9593 });
9594 } else {
9595 log::error!(
9596 "No entry in selection_history found for undo. \
9597 This may correspond to a bug where undo does not update the selection. \
9598 If this is occurring, please add details to \
9599 https://github.com/zed-industries/zed/issues/22692"
9600 );
9601 }
9602 self.request_autoscroll(Autoscroll::fit(), cx);
9603 self.unmark_text(window, cx);
9604 self.refresh_inline_completion(true, false, window, cx);
9605 cx.emit(EditorEvent::Edited { transaction_id });
9606 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9607 }
9608 }
9609
9610 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9611 if self.read_only(cx) {
9612 return;
9613 }
9614
9615 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9616 if let Some((_, Some(selections))) =
9617 self.selection_history.transaction(transaction_id).cloned()
9618 {
9619 self.change_selections(None, window, cx, |s| {
9620 s.select_anchors(selections.to_vec());
9621 });
9622 } else {
9623 log::error!(
9624 "No entry in selection_history found for redo. \
9625 This may correspond to a bug where undo does not update the selection. \
9626 If this is occurring, please add details to \
9627 https://github.com/zed-industries/zed/issues/22692"
9628 );
9629 }
9630 self.request_autoscroll(Autoscroll::fit(), cx);
9631 self.unmark_text(window, cx);
9632 self.refresh_inline_completion(true, false, window, cx);
9633 cx.emit(EditorEvent::Edited { transaction_id });
9634 }
9635 }
9636
9637 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9638 self.buffer
9639 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9640 }
9641
9642 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9643 self.buffer
9644 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9645 }
9646
9647 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9648 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9649 let line_mode = s.line_mode;
9650 s.move_with(|map, selection| {
9651 let cursor = if selection.is_empty() && !line_mode {
9652 movement::left(map, selection.start)
9653 } else {
9654 selection.start
9655 };
9656 selection.collapse_to(cursor, SelectionGoal::None);
9657 });
9658 })
9659 }
9660
9661 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9662 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9663 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9664 })
9665 }
9666
9667 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9668 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9669 let line_mode = s.line_mode;
9670 s.move_with(|map, selection| {
9671 let cursor = if selection.is_empty() && !line_mode {
9672 movement::right(map, selection.end)
9673 } else {
9674 selection.end
9675 };
9676 selection.collapse_to(cursor, SelectionGoal::None)
9677 });
9678 })
9679 }
9680
9681 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9682 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9683 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9684 })
9685 }
9686
9687 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9688 if self.take_rename(true, window, cx).is_some() {
9689 return;
9690 }
9691
9692 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9693 cx.propagate();
9694 return;
9695 }
9696
9697 let text_layout_details = &self.text_layout_details(window);
9698 let selection_count = self.selections.count();
9699 let first_selection = self.selections.first_anchor();
9700
9701 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9702 let line_mode = s.line_mode;
9703 s.move_with(|map, selection| {
9704 if !selection.is_empty() && !line_mode {
9705 selection.goal = SelectionGoal::None;
9706 }
9707 let (cursor, goal) = movement::up(
9708 map,
9709 selection.start,
9710 selection.goal,
9711 false,
9712 text_layout_details,
9713 );
9714 selection.collapse_to(cursor, goal);
9715 });
9716 });
9717
9718 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9719 {
9720 cx.propagate();
9721 }
9722 }
9723
9724 pub fn move_up_by_lines(
9725 &mut self,
9726 action: &MoveUpByLines,
9727 window: &mut Window,
9728 cx: &mut Context<Self>,
9729 ) {
9730 if self.take_rename(true, window, cx).is_some() {
9731 return;
9732 }
9733
9734 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9735 cx.propagate();
9736 return;
9737 }
9738
9739 let text_layout_details = &self.text_layout_details(window);
9740
9741 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9742 let line_mode = s.line_mode;
9743 s.move_with(|map, selection| {
9744 if !selection.is_empty() && !line_mode {
9745 selection.goal = SelectionGoal::None;
9746 }
9747 let (cursor, goal) = movement::up_by_rows(
9748 map,
9749 selection.start,
9750 action.lines,
9751 selection.goal,
9752 false,
9753 text_layout_details,
9754 );
9755 selection.collapse_to(cursor, goal);
9756 });
9757 })
9758 }
9759
9760 pub fn move_down_by_lines(
9761 &mut self,
9762 action: &MoveDownByLines,
9763 window: &mut Window,
9764 cx: &mut Context<Self>,
9765 ) {
9766 if self.take_rename(true, window, cx).is_some() {
9767 return;
9768 }
9769
9770 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9771 cx.propagate();
9772 return;
9773 }
9774
9775 let text_layout_details = &self.text_layout_details(window);
9776
9777 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9778 let line_mode = s.line_mode;
9779 s.move_with(|map, selection| {
9780 if !selection.is_empty() && !line_mode {
9781 selection.goal = SelectionGoal::None;
9782 }
9783 let (cursor, goal) = movement::down_by_rows(
9784 map,
9785 selection.start,
9786 action.lines,
9787 selection.goal,
9788 false,
9789 text_layout_details,
9790 );
9791 selection.collapse_to(cursor, goal);
9792 });
9793 })
9794 }
9795
9796 pub fn select_down_by_lines(
9797 &mut self,
9798 action: &SelectDownByLines,
9799 window: &mut Window,
9800 cx: &mut Context<Self>,
9801 ) {
9802 let text_layout_details = &self.text_layout_details(window);
9803 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9804 s.move_heads_with(|map, head, goal| {
9805 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9806 })
9807 })
9808 }
9809
9810 pub fn select_up_by_lines(
9811 &mut self,
9812 action: &SelectUpByLines,
9813 window: &mut Window,
9814 cx: &mut Context<Self>,
9815 ) {
9816 let text_layout_details = &self.text_layout_details(window);
9817 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9818 s.move_heads_with(|map, head, goal| {
9819 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9820 })
9821 })
9822 }
9823
9824 pub fn select_page_up(
9825 &mut self,
9826 _: &SelectPageUp,
9827 window: &mut Window,
9828 cx: &mut Context<Self>,
9829 ) {
9830 let Some(row_count) = self.visible_row_count() else {
9831 return;
9832 };
9833
9834 let text_layout_details = &self.text_layout_details(window);
9835
9836 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9837 s.move_heads_with(|map, head, goal| {
9838 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9839 })
9840 })
9841 }
9842
9843 pub fn move_page_up(
9844 &mut self,
9845 action: &MovePageUp,
9846 window: &mut Window,
9847 cx: &mut Context<Self>,
9848 ) {
9849 if self.take_rename(true, window, cx).is_some() {
9850 return;
9851 }
9852
9853 if self
9854 .context_menu
9855 .borrow_mut()
9856 .as_mut()
9857 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9858 .unwrap_or(false)
9859 {
9860 return;
9861 }
9862
9863 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9864 cx.propagate();
9865 return;
9866 }
9867
9868 let Some(row_count) = self.visible_row_count() else {
9869 return;
9870 };
9871
9872 let autoscroll = if action.center_cursor {
9873 Autoscroll::center()
9874 } else {
9875 Autoscroll::fit()
9876 };
9877
9878 let text_layout_details = &self.text_layout_details(window);
9879
9880 self.change_selections(Some(autoscroll), window, cx, |s| {
9881 let line_mode = s.line_mode;
9882 s.move_with(|map, selection| {
9883 if !selection.is_empty() && !line_mode {
9884 selection.goal = SelectionGoal::None;
9885 }
9886 let (cursor, goal) = movement::up_by_rows(
9887 map,
9888 selection.end,
9889 row_count,
9890 selection.goal,
9891 false,
9892 text_layout_details,
9893 );
9894 selection.collapse_to(cursor, goal);
9895 });
9896 });
9897 }
9898
9899 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9900 let text_layout_details = &self.text_layout_details(window);
9901 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9902 s.move_heads_with(|map, head, goal| {
9903 movement::up(map, head, goal, false, text_layout_details)
9904 })
9905 })
9906 }
9907
9908 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9909 self.take_rename(true, window, cx);
9910
9911 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9912 cx.propagate();
9913 return;
9914 }
9915
9916 let text_layout_details = &self.text_layout_details(window);
9917 let selection_count = self.selections.count();
9918 let first_selection = self.selections.first_anchor();
9919
9920 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9921 let line_mode = s.line_mode;
9922 s.move_with(|map, selection| {
9923 if !selection.is_empty() && !line_mode {
9924 selection.goal = SelectionGoal::None;
9925 }
9926 let (cursor, goal) = movement::down(
9927 map,
9928 selection.end,
9929 selection.goal,
9930 false,
9931 text_layout_details,
9932 );
9933 selection.collapse_to(cursor, goal);
9934 });
9935 });
9936
9937 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9938 {
9939 cx.propagate();
9940 }
9941 }
9942
9943 pub fn select_page_down(
9944 &mut self,
9945 _: &SelectPageDown,
9946 window: &mut Window,
9947 cx: &mut Context<Self>,
9948 ) {
9949 let Some(row_count) = self.visible_row_count() else {
9950 return;
9951 };
9952
9953 let text_layout_details = &self.text_layout_details(window);
9954
9955 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9956 s.move_heads_with(|map, head, goal| {
9957 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9958 })
9959 })
9960 }
9961
9962 pub fn move_page_down(
9963 &mut self,
9964 action: &MovePageDown,
9965 window: &mut Window,
9966 cx: &mut Context<Self>,
9967 ) {
9968 if self.take_rename(true, window, cx).is_some() {
9969 return;
9970 }
9971
9972 if self
9973 .context_menu
9974 .borrow_mut()
9975 .as_mut()
9976 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9977 .unwrap_or(false)
9978 {
9979 return;
9980 }
9981
9982 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9983 cx.propagate();
9984 return;
9985 }
9986
9987 let Some(row_count) = self.visible_row_count() else {
9988 return;
9989 };
9990
9991 let autoscroll = if action.center_cursor {
9992 Autoscroll::center()
9993 } else {
9994 Autoscroll::fit()
9995 };
9996
9997 let text_layout_details = &self.text_layout_details(window);
9998 self.change_selections(Some(autoscroll), window, cx, |s| {
9999 let line_mode = s.line_mode;
10000 s.move_with(|map, selection| {
10001 if !selection.is_empty() && !line_mode {
10002 selection.goal = SelectionGoal::None;
10003 }
10004 let (cursor, goal) = movement::down_by_rows(
10005 map,
10006 selection.end,
10007 row_count,
10008 selection.goal,
10009 false,
10010 text_layout_details,
10011 );
10012 selection.collapse_to(cursor, goal);
10013 });
10014 });
10015 }
10016
10017 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10018 let text_layout_details = &self.text_layout_details(window);
10019 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10020 s.move_heads_with(|map, head, goal| {
10021 movement::down(map, head, goal, false, text_layout_details)
10022 })
10023 });
10024 }
10025
10026 pub fn context_menu_first(
10027 &mut self,
10028 _: &ContextMenuFirst,
10029 _window: &mut Window,
10030 cx: &mut Context<Self>,
10031 ) {
10032 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10033 context_menu.select_first(self.completion_provider.as_deref(), cx);
10034 }
10035 }
10036
10037 pub fn context_menu_prev(
10038 &mut self,
10039 _: &ContextMenuPrevious,
10040 _window: &mut Window,
10041 cx: &mut Context<Self>,
10042 ) {
10043 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10044 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10045 }
10046 }
10047
10048 pub fn context_menu_next(
10049 &mut self,
10050 _: &ContextMenuNext,
10051 _window: &mut Window,
10052 cx: &mut Context<Self>,
10053 ) {
10054 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10055 context_menu.select_next(self.completion_provider.as_deref(), cx);
10056 }
10057 }
10058
10059 pub fn context_menu_last(
10060 &mut self,
10061 _: &ContextMenuLast,
10062 _window: &mut Window,
10063 cx: &mut Context<Self>,
10064 ) {
10065 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10066 context_menu.select_last(self.completion_provider.as_deref(), cx);
10067 }
10068 }
10069
10070 pub fn move_to_previous_word_start(
10071 &mut self,
10072 _: &MoveToPreviousWordStart,
10073 window: &mut Window,
10074 cx: &mut Context<Self>,
10075 ) {
10076 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10077 s.move_cursors_with(|map, head, _| {
10078 (
10079 movement::previous_word_start(map, head),
10080 SelectionGoal::None,
10081 )
10082 });
10083 })
10084 }
10085
10086 pub fn move_to_previous_subword_start(
10087 &mut self,
10088 _: &MoveToPreviousSubwordStart,
10089 window: &mut Window,
10090 cx: &mut Context<Self>,
10091 ) {
10092 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10093 s.move_cursors_with(|map, head, _| {
10094 (
10095 movement::previous_subword_start(map, head),
10096 SelectionGoal::None,
10097 )
10098 });
10099 })
10100 }
10101
10102 pub fn select_to_previous_word_start(
10103 &mut self,
10104 _: &SelectToPreviousWordStart,
10105 window: &mut Window,
10106 cx: &mut Context<Self>,
10107 ) {
10108 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10109 s.move_heads_with(|map, head, _| {
10110 (
10111 movement::previous_word_start(map, head),
10112 SelectionGoal::None,
10113 )
10114 });
10115 })
10116 }
10117
10118 pub fn select_to_previous_subword_start(
10119 &mut self,
10120 _: &SelectToPreviousSubwordStart,
10121 window: &mut Window,
10122 cx: &mut Context<Self>,
10123 ) {
10124 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10125 s.move_heads_with(|map, head, _| {
10126 (
10127 movement::previous_subword_start(map, head),
10128 SelectionGoal::None,
10129 )
10130 });
10131 })
10132 }
10133
10134 pub fn delete_to_previous_word_start(
10135 &mut self,
10136 action: &DeleteToPreviousWordStart,
10137 window: &mut Window,
10138 cx: &mut Context<Self>,
10139 ) {
10140 self.transact(window, cx, |this, window, cx| {
10141 this.select_autoclose_pair(window, cx);
10142 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10143 let line_mode = s.line_mode;
10144 s.move_with(|map, selection| {
10145 if selection.is_empty() && !line_mode {
10146 let cursor = if action.ignore_newlines {
10147 movement::previous_word_start(map, selection.head())
10148 } else {
10149 movement::previous_word_start_or_newline(map, selection.head())
10150 };
10151 selection.set_head(cursor, SelectionGoal::None);
10152 }
10153 });
10154 });
10155 this.insert("", window, cx);
10156 });
10157 }
10158
10159 pub fn delete_to_previous_subword_start(
10160 &mut self,
10161 _: &DeleteToPreviousSubwordStart,
10162 window: &mut Window,
10163 cx: &mut Context<Self>,
10164 ) {
10165 self.transact(window, cx, |this, window, cx| {
10166 this.select_autoclose_pair(window, cx);
10167 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10168 let line_mode = s.line_mode;
10169 s.move_with(|map, selection| {
10170 if selection.is_empty() && !line_mode {
10171 let cursor = movement::previous_subword_start(map, selection.head());
10172 selection.set_head(cursor, SelectionGoal::None);
10173 }
10174 });
10175 });
10176 this.insert("", window, cx);
10177 });
10178 }
10179
10180 pub fn move_to_next_word_end(
10181 &mut self,
10182 _: &MoveToNextWordEnd,
10183 window: &mut Window,
10184 cx: &mut Context<Self>,
10185 ) {
10186 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10187 s.move_cursors_with(|map, head, _| {
10188 (movement::next_word_end(map, head), SelectionGoal::None)
10189 });
10190 })
10191 }
10192
10193 pub fn move_to_next_subword_end(
10194 &mut self,
10195 _: &MoveToNextSubwordEnd,
10196 window: &mut Window,
10197 cx: &mut Context<Self>,
10198 ) {
10199 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10200 s.move_cursors_with(|map, head, _| {
10201 (movement::next_subword_end(map, head), SelectionGoal::None)
10202 });
10203 })
10204 }
10205
10206 pub fn select_to_next_word_end(
10207 &mut self,
10208 _: &SelectToNextWordEnd,
10209 window: &mut Window,
10210 cx: &mut Context<Self>,
10211 ) {
10212 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10213 s.move_heads_with(|map, head, _| {
10214 (movement::next_word_end(map, head), SelectionGoal::None)
10215 });
10216 })
10217 }
10218
10219 pub fn select_to_next_subword_end(
10220 &mut self,
10221 _: &SelectToNextSubwordEnd,
10222 window: &mut Window,
10223 cx: &mut Context<Self>,
10224 ) {
10225 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10226 s.move_heads_with(|map, head, _| {
10227 (movement::next_subword_end(map, head), SelectionGoal::None)
10228 });
10229 })
10230 }
10231
10232 pub fn delete_to_next_word_end(
10233 &mut self,
10234 action: &DeleteToNextWordEnd,
10235 window: &mut Window,
10236 cx: &mut Context<Self>,
10237 ) {
10238 self.transact(window, cx, |this, window, cx| {
10239 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10240 let line_mode = s.line_mode;
10241 s.move_with(|map, selection| {
10242 if selection.is_empty() && !line_mode {
10243 let cursor = if action.ignore_newlines {
10244 movement::next_word_end(map, selection.head())
10245 } else {
10246 movement::next_word_end_or_newline(map, selection.head())
10247 };
10248 selection.set_head(cursor, SelectionGoal::None);
10249 }
10250 });
10251 });
10252 this.insert("", window, cx);
10253 });
10254 }
10255
10256 pub fn delete_to_next_subword_end(
10257 &mut self,
10258 _: &DeleteToNextSubwordEnd,
10259 window: &mut Window,
10260 cx: &mut Context<Self>,
10261 ) {
10262 self.transact(window, cx, |this, window, cx| {
10263 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10264 s.move_with(|map, selection| {
10265 if selection.is_empty() {
10266 let cursor = movement::next_subword_end(map, selection.head());
10267 selection.set_head(cursor, SelectionGoal::None);
10268 }
10269 });
10270 });
10271 this.insert("", window, cx);
10272 });
10273 }
10274
10275 pub fn move_to_beginning_of_line(
10276 &mut self,
10277 action: &MoveToBeginningOfLine,
10278 window: &mut Window,
10279 cx: &mut Context<Self>,
10280 ) {
10281 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10282 s.move_cursors_with(|map, head, _| {
10283 (
10284 movement::indented_line_beginning(
10285 map,
10286 head,
10287 action.stop_at_soft_wraps,
10288 action.stop_at_indent,
10289 ),
10290 SelectionGoal::None,
10291 )
10292 });
10293 })
10294 }
10295
10296 pub fn select_to_beginning_of_line(
10297 &mut self,
10298 action: &SelectToBeginningOfLine,
10299 window: &mut Window,
10300 cx: &mut Context<Self>,
10301 ) {
10302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10303 s.move_heads_with(|map, head, _| {
10304 (
10305 movement::indented_line_beginning(
10306 map,
10307 head,
10308 action.stop_at_soft_wraps,
10309 action.stop_at_indent,
10310 ),
10311 SelectionGoal::None,
10312 )
10313 });
10314 });
10315 }
10316
10317 pub fn delete_to_beginning_of_line(
10318 &mut self,
10319 action: &DeleteToBeginningOfLine,
10320 window: &mut Window,
10321 cx: &mut Context<Self>,
10322 ) {
10323 self.transact(window, cx, |this, window, cx| {
10324 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10325 s.move_with(|_, selection| {
10326 selection.reversed = true;
10327 });
10328 });
10329
10330 this.select_to_beginning_of_line(
10331 &SelectToBeginningOfLine {
10332 stop_at_soft_wraps: false,
10333 stop_at_indent: action.stop_at_indent,
10334 },
10335 window,
10336 cx,
10337 );
10338 this.backspace(&Backspace, window, cx);
10339 });
10340 }
10341
10342 pub fn move_to_end_of_line(
10343 &mut self,
10344 action: &MoveToEndOfLine,
10345 window: &mut Window,
10346 cx: &mut Context<Self>,
10347 ) {
10348 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10349 s.move_cursors_with(|map, head, _| {
10350 (
10351 movement::line_end(map, head, action.stop_at_soft_wraps),
10352 SelectionGoal::None,
10353 )
10354 });
10355 })
10356 }
10357
10358 pub fn select_to_end_of_line(
10359 &mut self,
10360 action: &SelectToEndOfLine,
10361 window: &mut Window,
10362 cx: &mut Context<Self>,
10363 ) {
10364 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10365 s.move_heads_with(|map, head, _| {
10366 (
10367 movement::line_end(map, head, action.stop_at_soft_wraps),
10368 SelectionGoal::None,
10369 )
10370 });
10371 })
10372 }
10373
10374 pub fn delete_to_end_of_line(
10375 &mut self,
10376 _: &DeleteToEndOfLine,
10377 window: &mut Window,
10378 cx: &mut Context<Self>,
10379 ) {
10380 self.transact(window, cx, |this, window, cx| {
10381 this.select_to_end_of_line(
10382 &SelectToEndOfLine {
10383 stop_at_soft_wraps: false,
10384 },
10385 window,
10386 cx,
10387 );
10388 this.delete(&Delete, window, cx);
10389 });
10390 }
10391
10392 pub fn cut_to_end_of_line(
10393 &mut self,
10394 _: &CutToEndOfLine,
10395 window: &mut Window,
10396 cx: &mut Context<Self>,
10397 ) {
10398 self.transact(window, cx, |this, window, cx| {
10399 this.select_to_end_of_line(
10400 &SelectToEndOfLine {
10401 stop_at_soft_wraps: false,
10402 },
10403 window,
10404 cx,
10405 );
10406 this.cut(&Cut, window, cx);
10407 });
10408 }
10409
10410 pub fn move_to_start_of_paragraph(
10411 &mut self,
10412 _: &MoveToStartOfParagraph,
10413 window: &mut Window,
10414 cx: &mut Context<Self>,
10415 ) {
10416 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10417 cx.propagate();
10418 return;
10419 }
10420
10421 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10422 s.move_with(|map, selection| {
10423 selection.collapse_to(
10424 movement::start_of_paragraph(map, selection.head(), 1),
10425 SelectionGoal::None,
10426 )
10427 });
10428 })
10429 }
10430
10431 pub fn move_to_end_of_paragraph(
10432 &mut self,
10433 _: &MoveToEndOfParagraph,
10434 window: &mut Window,
10435 cx: &mut Context<Self>,
10436 ) {
10437 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10438 cx.propagate();
10439 return;
10440 }
10441
10442 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10443 s.move_with(|map, selection| {
10444 selection.collapse_to(
10445 movement::end_of_paragraph(map, selection.head(), 1),
10446 SelectionGoal::None,
10447 )
10448 });
10449 })
10450 }
10451
10452 pub fn select_to_start_of_paragraph(
10453 &mut self,
10454 _: &SelectToStartOfParagraph,
10455 window: &mut Window,
10456 cx: &mut Context<Self>,
10457 ) {
10458 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10459 cx.propagate();
10460 return;
10461 }
10462
10463 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10464 s.move_heads_with(|map, head, _| {
10465 (
10466 movement::start_of_paragraph(map, head, 1),
10467 SelectionGoal::None,
10468 )
10469 });
10470 })
10471 }
10472
10473 pub fn select_to_end_of_paragraph(
10474 &mut self,
10475 _: &SelectToEndOfParagraph,
10476 window: &mut Window,
10477 cx: &mut Context<Self>,
10478 ) {
10479 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10480 cx.propagate();
10481 return;
10482 }
10483
10484 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10485 s.move_heads_with(|map, head, _| {
10486 (
10487 movement::end_of_paragraph(map, head, 1),
10488 SelectionGoal::None,
10489 )
10490 });
10491 })
10492 }
10493
10494 pub fn move_to_start_of_excerpt(
10495 &mut self,
10496 _: &MoveToStartOfExcerpt,
10497 window: &mut Window,
10498 cx: &mut Context<Self>,
10499 ) {
10500 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10501 cx.propagate();
10502 return;
10503 }
10504
10505 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10506 s.move_with(|map, selection| {
10507 selection.collapse_to(
10508 movement::start_of_excerpt(
10509 map,
10510 selection.head(),
10511 workspace::searchable::Direction::Prev,
10512 ),
10513 SelectionGoal::None,
10514 )
10515 });
10516 })
10517 }
10518
10519 pub fn move_to_start_of_next_excerpt(
10520 &mut self,
10521 _: &MoveToStartOfNextExcerpt,
10522 window: &mut Window,
10523 cx: &mut Context<Self>,
10524 ) {
10525 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10526 cx.propagate();
10527 return;
10528 }
10529
10530 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10531 s.move_with(|map, selection| {
10532 selection.collapse_to(
10533 movement::start_of_excerpt(
10534 map,
10535 selection.head(),
10536 workspace::searchable::Direction::Next,
10537 ),
10538 SelectionGoal::None,
10539 )
10540 });
10541 })
10542 }
10543
10544 pub fn move_to_end_of_excerpt(
10545 &mut self,
10546 _: &MoveToEndOfExcerpt,
10547 window: &mut Window,
10548 cx: &mut Context<Self>,
10549 ) {
10550 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10551 cx.propagate();
10552 return;
10553 }
10554
10555 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10556 s.move_with(|map, selection| {
10557 selection.collapse_to(
10558 movement::end_of_excerpt(
10559 map,
10560 selection.head(),
10561 workspace::searchable::Direction::Next,
10562 ),
10563 SelectionGoal::None,
10564 )
10565 });
10566 })
10567 }
10568
10569 pub fn move_to_end_of_previous_excerpt(
10570 &mut self,
10571 _: &MoveToEndOfPreviousExcerpt,
10572 window: &mut Window,
10573 cx: &mut Context<Self>,
10574 ) {
10575 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10576 cx.propagate();
10577 return;
10578 }
10579
10580 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10581 s.move_with(|map, selection| {
10582 selection.collapse_to(
10583 movement::end_of_excerpt(
10584 map,
10585 selection.head(),
10586 workspace::searchable::Direction::Prev,
10587 ),
10588 SelectionGoal::None,
10589 )
10590 });
10591 })
10592 }
10593
10594 pub fn select_to_start_of_excerpt(
10595 &mut self,
10596 _: &SelectToStartOfExcerpt,
10597 window: &mut Window,
10598 cx: &mut Context<Self>,
10599 ) {
10600 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10601 cx.propagate();
10602 return;
10603 }
10604
10605 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10606 s.move_heads_with(|map, head, _| {
10607 (
10608 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10609 SelectionGoal::None,
10610 )
10611 });
10612 })
10613 }
10614
10615 pub fn select_to_start_of_next_excerpt(
10616 &mut self,
10617 _: &SelectToStartOfNextExcerpt,
10618 window: &mut Window,
10619 cx: &mut Context<Self>,
10620 ) {
10621 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10622 cx.propagate();
10623 return;
10624 }
10625
10626 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10627 s.move_heads_with(|map, head, _| {
10628 (
10629 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10630 SelectionGoal::None,
10631 )
10632 });
10633 })
10634 }
10635
10636 pub fn select_to_end_of_excerpt(
10637 &mut self,
10638 _: &SelectToEndOfExcerpt,
10639 window: &mut Window,
10640 cx: &mut Context<Self>,
10641 ) {
10642 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10643 cx.propagate();
10644 return;
10645 }
10646
10647 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10648 s.move_heads_with(|map, head, _| {
10649 (
10650 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10651 SelectionGoal::None,
10652 )
10653 });
10654 })
10655 }
10656
10657 pub fn select_to_end_of_previous_excerpt(
10658 &mut self,
10659 _: &SelectToEndOfPreviousExcerpt,
10660 window: &mut Window,
10661 cx: &mut Context<Self>,
10662 ) {
10663 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10664 cx.propagate();
10665 return;
10666 }
10667
10668 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10669 s.move_heads_with(|map, head, _| {
10670 (
10671 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10672 SelectionGoal::None,
10673 )
10674 });
10675 })
10676 }
10677
10678 pub fn move_to_beginning(
10679 &mut self,
10680 _: &MoveToBeginning,
10681 window: &mut Window,
10682 cx: &mut Context<Self>,
10683 ) {
10684 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10685 cx.propagate();
10686 return;
10687 }
10688
10689 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10690 s.select_ranges(vec![0..0]);
10691 });
10692 }
10693
10694 pub fn select_to_beginning(
10695 &mut self,
10696 _: &SelectToBeginning,
10697 window: &mut Window,
10698 cx: &mut Context<Self>,
10699 ) {
10700 let mut selection = self.selections.last::<Point>(cx);
10701 selection.set_head(Point::zero(), SelectionGoal::None);
10702
10703 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10704 s.select(vec![selection]);
10705 });
10706 }
10707
10708 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10709 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10710 cx.propagate();
10711 return;
10712 }
10713
10714 let cursor = self.buffer.read(cx).read(cx).len();
10715 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10716 s.select_ranges(vec![cursor..cursor])
10717 });
10718 }
10719
10720 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10721 self.nav_history = nav_history;
10722 }
10723
10724 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10725 self.nav_history.as_ref()
10726 }
10727
10728 fn push_to_nav_history(
10729 &mut self,
10730 cursor_anchor: Anchor,
10731 new_position: Option<Point>,
10732 cx: &mut Context<Self>,
10733 ) {
10734 if let Some(nav_history) = self.nav_history.as_mut() {
10735 let buffer = self.buffer.read(cx).read(cx);
10736 let cursor_position = cursor_anchor.to_point(&buffer);
10737 let scroll_state = self.scroll_manager.anchor();
10738 let scroll_top_row = scroll_state.top_row(&buffer);
10739 drop(buffer);
10740
10741 if let Some(new_position) = new_position {
10742 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10743 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10744 return;
10745 }
10746 }
10747
10748 nav_history.push(
10749 Some(NavigationData {
10750 cursor_anchor,
10751 cursor_position,
10752 scroll_anchor: scroll_state,
10753 scroll_top_row,
10754 }),
10755 cx,
10756 );
10757 }
10758 }
10759
10760 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10761 let buffer = self.buffer.read(cx).snapshot(cx);
10762 let mut selection = self.selections.first::<usize>(cx);
10763 selection.set_head(buffer.len(), SelectionGoal::None);
10764 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10765 s.select(vec![selection]);
10766 });
10767 }
10768
10769 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10770 let end = self.buffer.read(cx).read(cx).len();
10771 self.change_selections(None, window, cx, |s| {
10772 s.select_ranges(vec![0..end]);
10773 });
10774 }
10775
10776 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10777 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10778 let mut selections = self.selections.all::<Point>(cx);
10779 let max_point = display_map.buffer_snapshot.max_point();
10780 for selection in &mut selections {
10781 let rows = selection.spanned_rows(true, &display_map);
10782 selection.start = Point::new(rows.start.0, 0);
10783 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10784 selection.reversed = false;
10785 }
10786 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10787 s.select(selections);
10788 });
10789 }
10790
10791 pub fn split_selection_into_lines(
10792 &mut self,
10793 _: &SplitSelectionIntoLines,
10794 window: &mut Window,
10795 cx: &mut Context<Self>,
10796 ) {
10797 let selections = self
10798 .selections
10799 .all::<Point>(cx)
10800 .into_iter()
10801 .map(|selection| selection.start..selection.end)
10802 .collect::<Vec<_>>();
10803 self.unfold_ranges(&selections, true, true, cx);
10804
10805 let mut new_selection_ranges = Vec::new();
10806 {
10807 let buffer = self.buffer.read(cx).read(cx);
10808 for selection in selections {
10809 for row in selection.start.row..selection.end.row {
10810 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10811 new_selection_ranges.push(cursor..cursor);
10812 }
10813
10814 let is_multiline_selection = selection.start.row != selection.end.row;
10815 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10816 // so this action feels more ergonomic when paired with other selection operations
10817 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10818 if !should_skip_last {
10819 new_selection_ranges.push(selection.end..selection.end);
10820 }
10821 }
10822 }
10823 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10824 s.select_ranges(new_selection_ranges);
10825 });
10826 }
10827
10828 pub fn add_selection_above(
10829 &mut self,
10830 _: &AddSelectionAbove,
10831 window: &mut Window,
10832 cx: &mut Context<Self>,
10833 ) {
10834 self.add_selection(true, window, cx);
10835 }
10836
10837 pub fn add_selection_below(
10838 &mut self,
10839 _: &AddSelectionBelow,
10840 window: &mut Window,
10841 cx: &mut Context<Self>,
10842 ) {
10843 self.add_selection(false, window, cx);
10844 }
10845
10846 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10847 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10848 let mut selections = self.selections.all::<Point>(cx);
10849 let text_layout_details = self.text_layout_details(window);
10850 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10851 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10852 let range = oldest_selection.display_range(&display_map).sorted();
10853
10854 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10855 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10856 let positions = start_x.min(end_x)..start_x.max(end_x);
10857
10858 selections.clear();
10859 let mut stack = Vec::new();
10860 for row in range.start.row().0..=range.end.row().0 {
10861 if let Some(selection) = self.selections.build_columnar_selection(
10862 &display_map,
10863 DisplayRow(row),
10864 &positions,
10865 oldest_selection.reversed,
10866 &text_layout_details,
10867 ) {
10868 stack.push(selection.id);
10869 selections.push(selection);
10870 }
10871 }
10872
10873 if above {
10874 stack.reverse();
10875 }
10876
10877 AddSelectionsState { above, stack }
10878 });
10879
10880 let last_added_selection = *state.stack.last().unwrap();
10881 let mut new_selections = Vec::new();
10882 if above == state.above {
10883 let end_row = if above {
10884 DisplayRow(0)
10885 } else {
10886 display_map.max_point().row()
10887 };
10888
10889 'outer: for selection in selections {
10890 if selection.id == last_added_selection {
10891 let range = selection.display_range(&display_map).sorted();
10892 debug_assert_eq!(range.start.row(), range.end.row());
10893 let mut row = range.start.row();
10894 let positions =
10895 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10896 px(start)..px(end)
10897 } else {
10898 let start_x =
10899 display_map.x_for_display_point(range.start, &text_layout_details);
10900 let end_x =
10901 display_map.x_for_display_point(range.end, &text_layout_details);
10902 start_x.min(end_x)..start_x.max(end_x)
10903 };
10904
10905 while row != end_row {
10906 if above {
10907 row.0 -= 1;
10908 } else {
10909 row.0 += 1;
10910 }
10911
10912 if let Some(new_selection) = self.selections.build_columnar_selection(
10913 &display_map,
10914 row,
10915 &positions,
10916 selection.reversed,
10917 &text_layout_details,
10918 ) {
10919 state.stack.push(new_selection.id);
10920 if above {
10921 new_selections.push(new_selection);
10922 new_selections.push(selection);
10923 } else {
10924 new_selections.push(selection);
10925 new_selections.push(new_selection);
10926 }
10927
10928 continue 'outer;
10929 }
10930 }
10931 }
10932
10933 new_selections.push(selection);
10934 }
10935 } else {
10936 new_selections = selections;
10937 new_selections.retain(|s| s.id != last_added_selection);
10938 state.stack.pop();
10939 }
10940
10941 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10942 s.select(new_selections);
10943 });
10944 if state.stack.len() > 1 {
10945 self.add_selections_state = Some(state);
10946 }
10947 }
10948
10949 pub fn select_next_match_internal(
10950 &mut self,
10951 display_map: &DisplaySnapshot,
10952 replace_newest: bool,
10953 autoscroll: Option<Autoscroll>,
10954 window: &mut Window,
10955 cx: &mut Context<Self>,
10956 ) -> Result<()> {
10957 fn select_next_match_ranges(
10958 this: &mut Editor,
10959 range: Range<usize>,
10960 replace_newest: bool,
10961 auto_scroll: Option<Autoscroll>,
10962 window: &mut Window,
10963 cx: &mut Context<Editor>,
10964 ) {
10965 this.unfold_ranges(&[range.clone()], false, true, cx);
10966 this.change_selections(auto_scroll, window, cx, |s| {
10967 if replace_newest {
10968 s.delete(s.newest_anchor().id);
10969 }
10970 s.insert_range(range.clone());
10971 });
10972 }
10973
10974 let buffer = &display_map.buffer_snapshot;
10975 let mut selections = self.selections.all::<usize>(cx);
10976 if let Some(mut select_next_state) = self.select_next_state.take() {
10977 let query = &select_next_state.query;
10978 if !select_next_state.done {
10979 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10980 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10981 let mut next_selected_range = None;
10982
10983 let bytes_after_last_selection =
10984 buffer.bytes_in_range(last_selection.end..buffer.len());
10985 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10986 let query_matches = query
10987 .stream_find_iter(bytes_after_last_selection)
10988 .map(|result| (last_selection.end, result))
10989 .chain(
10990 query
10991 .stream_find_iter(bytes_before_first_selection)
10992 .map(|result| (0, result)),
10993 );
10994
10995 for (start_offset, query_match) in query_matches {
10996 let query_match = query_match.unwrap(); // can only fail due to I/O
10997 let offset_range =
10998 start_offset + query_match.start()..start_offset + query_match.end();
10999 let display_range = offset_range.start.to_display_point(display_map)
11000 ..offset_range.end.to_display_point(display_map);
11001
11002 if !select_next_state.wordwise
11003 || (!movement::is_inside_word(display_map, display_range.start)
11004 && !movement::is_inside_word(display_map, display_range.end))
11005 {
11006 // TODO: This is n^2, because we might check all the selections
11007 if !selections
11008 .iter()
11009 .any(|selection| selection.range().overlaps(&offset_range))
11010 {
11011 next_selected_range = Some(offset_range);
11012 break;
11013 }
11014 }
11015 }
11016
11017 if let Some(next_selected_range) = next_selected_range {
11018 select_next_match_ranges(
11019 self,
11020 next_selected_range,
11021 replace_newest,
11022 autoscroll,
11023 window,
11024 cx,
11025 );
11026 } else {
11027 select_next_state.done = true;
11028 }
11029 }
11030
11031 self.select_next_state = Some(select_next_state);
11032 } else {
11033 let mut only_carets = true;
11034 let mut same_text_selected = true;
11035 let mut selected_text = None;
11036
11037 let mut selections_iter = selections.iter().peekable();
11038 while let Some(selection) = selections_iter.next() {
11039 if selection.start != selection.end {
11040 only_carets = false;
11041 }
11042
11043 if same_text_selected {
11044 if selected_text.is_none() {
11045 selected_text =
11046 Some(buffer.text_for_range(selection.range()).collect::<String>());
11047 }
11048
11049 if let Some(next_selection) = selections_iter.peek() {
11050 if next_selection.range().len() == selection.range().len() {
11051 let next_selected_text = buffer
11052 .text_for_range(next_selection.range())
11053 .collect::<String>();
11054 if Some(next_selected_text) != selected_text {
11055 same_text_selected = false;
11056 selected_text = None;
11057 }
11058 } else {
11059 same_text_selected = false;
11060 selected_text = None;
11061 }
11062 }
11063 }
11064 }
11065
11066 if only_carets {
11067 for selection in &mut selections {
11068 let word_range = movement::surrounding_word(
11069 display_map,
11070 selection.start.to_display_point(display_map),
11071 );
11072 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11073 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11074 selection.goal = SelectionGoal::None;
11075 selection.reversed = false;
11076 select_next_match_ranges(
11077 self,
11078 selection.start..selection.end,
11079 replace_newest,
11080 autoscroll,
11081 window,
11082 cx,
11083 );
11084 }
11085
11086 if selections.len() == 1 {
11087 let selection = selections
11088 .last()
11089 .expect("ensured that there's only one selection");
11090 let query = buffer
11091 .text_for_range(selection.start..selection.end)
11092 .collect::<String>();
11093 let is_empty = query.is_empty();
11094 let select_state = SelectNextState {
11095 query: AhoCorasick::new(&[query])?,
11096 wordwise: true,
11097 done: is_empty,
11098 };
11099 self.select_next_state = Some(select_state);
11100 } else {
11101 self.select_next_state = None;
11102 }
11103 } else if let Some(selected_text) = selected_text {
11104 self.select_next_state = Some(SelectNextState {
11105 query: AhoCorasick::new(&[selected_text])?,
11106 wordwise: false,
11107 done: false,
11108 });
11109 self.select_next_match_internal(
11110 display_map,
11111 replace_newest,
11112 autoscroll,
11113 window,
11114 cx,
11115 )?;
11116 }
11117 }
11118 Ok(())
11119 }
11120
11121 pub fn select_all_matches(
11122 &mut self,
11123 _action: &SelectAllMatches,
11124 window: &mut Window,
11125 cx: &mut Context<Self>,
11126 ) -> Result<()> {
11127 self.push_to_selection_history();
11128 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11129
11130 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11131 let Some(select_next_state) = self.select_next_state.as_mut() else {
11132 return Ok(());
11133 };
11134 if select_next_state.done {
11135 return Ok(());
11136 }
11137
11138 let mut new_selections = self.selections.all::<usize>(cx);
11139
11140 let buffer = &display_map.buffer_snapshot;
11141 let query_matches = select_next_state
11142 .query
11143 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11144
11145 for query_match in query_matches {
11146 let query_match = query_match.unwrap(); // can only fail due to I/O
11147 let offset_range = query_match.start()..query_match.end();
11148 let display_range = offset_range.start.to_display_point(&display_map)
11149 ..offset_range.end.to_display_point(&display_map);
11150
11151 if !select_next_state.wordwise
11152 || (!movement::is_inside_word(&display_map, display_range.start)
11153 && !movement::is_inside_word(&display_map, display_range.end))
11154 {
11155 self.selections.change_with(cx, |selections| {
11156 new_selections.push(Selection {
11157 id: selections.new_selection_id(),
11158 start: offset_range.start,
11159 end: offset_range.end,
11160 reversed: false,
11161 goal: SelectionGoal::None,
11162 });
11163 });
11164 }
11165 }
11166
11167 new_selections.sort_by_key(|selection| selection.start);
11168 let mut ix = 0;
11169 while ix + 1 < new_selections.len() {
11170 let current_selection = &new_selections[ix];
11171 let next_selection = &new_selections[ix + 1];
11172 if current_selection.range().overlaps(&next_selection.range()) {
11173 if current_selection.id < next_selection.id {
11174 new_selections.remove(ix + 1);
11175 } else {
11176 new_selections.remove(ix);
11177 }
11178 } else {
11179 ix += 1;
11180 }
11181 }
11182
11183 let reversed = self.selections.oldest::<usize>(cx).reversed;
11184
11185 for selection in new_selections.iter_mut() {
11186 selection.reversed = reversed;
11187 }
11188
11189 select_next_state.done = true;
11190 self.unfold_ranges(
11191 &new_selections
11192 .iter()
11193 .map(|selection| selection.range())
11194 .collect::<Vec<_>>(),
11195 false,
11196 false,
11197 cx,
11198 );
11199 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11200 selections.select(new_selections)
11201 });
11202
11203 Ok(())
11204 }
11205
11206 pub fn select_next(
11207 &mut self,
11208 action: &SelectNext,
11209 window: &mut Window,
11210 cx: &mut Context<Self>,
11211 ) -> Result<()> {
11212 self.push_to_selection_history();
11213 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11214 self.select_next_match_internal(
11215 &display_map,
11216 action.replace_newest,
11217 Some(Autoscroll::newest()),
11218 window,
11219 cx,
11220 )?;
11221 Ok(())
11222 }
11223
11224 pub fn select_previous(
11225 &mut self,
11226 action: &SelectPrevious,
11227 window: &mut Window,
11228 cx: &mut Context<Self>,
11229 ) -> Result<()> {
11230 self.push_to_selection_history();
11231 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11232 let buffer = &display_map.buffer_snapshot;
11233 let mut selections = self.selections.all::<usize>(cx);
11234 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11235 let query = &select_prev_state.query;
11236 if !select_prev_state.done {
11237 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11238 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11239 let mut next_selected_range = None;
11240 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11241 let bytes_before_last_selection =
11242 buffer.reversed_bytes_in_range(0..last_selection.start);
11243 let bytes_after_first_selection =
11244 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11245 let query_matches = query
11246 .stream_find_iter(bytes_before_last_selection)
11247 .map(|result| (last_selection.start, result))
11248 .chain(
11249 query
11250 .stream_find_iter(bytes_after_first_selection)
11251 .map(|result| (buffer.len(), result)),
11252 );
11253 for (end_offset, query_match) in query_matches {
11254 let query_match = query_match.unwrap(); // can only fail due to I/O
11255 let offset_range =
11256 end_offset - query_match.end()..end_offset - query_match.start();
11257 let display_range = offset_range.start.to_display_point(&display_map)
11258 ..offset_range.end.to_display_point(&display_map);
11259
11260 if !select_prev_state.wordwise
11261 || (!movement::is_inside_word(&display_map, display_range.start)
11262 && !movement::is_inside_word(&display_map, display_range.end))
11263 {
11264 next_selected_range = Some(offset_range);
11265 break;
11266 }
11267 }
11268
11269 if let Some(next_selected_range) = next_selected_range {
11270 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11271 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11272 if action.replace_newest {
11273 s.delete(s.newest_anchor().id);
11274 }
11275 s.insert_range(next_selected_range);
11276 });
11277 } else {
11278 select_prev_state.done = true;
11279 }
11280 }
11281
11282 self.select_prev_state = Some(select_prev_state);
11283 } else {
11284 let mut only_carets = true;
11285 let mut same_text_selected = true;
11286 let mut selected_text = None;
11287
11288 let mut selections_iter = selections.iter().peekable();
11289 while let Some(selection) = selections_iter.next() {
11290 if selection.start != selection.end {
11291 only_carets = false;
11292 }
11293
11294 if same_text_selected {
11295 if selected_text.is_none() {
11296 selected_text =
11297 Some(buffer.text_for_range(selection.range()).collect::<String>());
11298 }
11299
11300 if let Some(next_selection) = selections_iter.peek() {
11301 if next_selection.range().len() == selection.range().len() {
11302 let next_selected_text = buffer
11303 .text_for_range(next_selection.range())
11304 .collect::<String>();
11305 if Some(next_selected_text) != selected_text {
11306 same_text_selected = false;
11307 selected_text = None;
11308 }
11309 } else {
11310 same_text_selected = false;
11311 selected_text = None;
11312 }
11313 }
11314 }
11315 }
11316
11317 if only_carets {
11318 for selection in &mut selections {
11319 let word_range = movement::surrounding_word(
11320 &display_map,
11321 selection.start.to_display_point(&display_map),
11322 );
11323 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11324 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11325 selection.goal = SelectionGoal::None;
11326 selection.reversed = false;
11327 }
11328 if selections.len() == 1 {
11329 let selection = selections
11330 .last()
11331 .expect("ensured that there's only one selection");
11332 let query = buffer
11333 .text_for_range(selection.start..selection.end)
11334 .collect::<String>();
11335 let is_empty = query.is_empty();
11336 let select_state = SelectNextState {
11337 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11338 wordwise: true,
11339 done: is_empty,
11340 };
11341 self.select_prev_state = Some(select_state);
11342 } else {
11343 self.select_prev_state = None;
11344 }
11345
11346 self.unfold_ranges(
11347 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11348 false,
11349 true,
11350 cx,
11351 );
11352 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11353 s.select(selections);
11354 });
11355 } else if let Some(selected_text) = selected_text {
11356 self.select_prev_state = Some(SelectNextState {
11357 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11358 wordwise: false,
11359 done: false,
11360 });
11361 self.select_previous(action, window, cx)?;
11362 }
11363 }
11364 Ok(())
11365 }
11366
11367 pub fn toggle_comments(
11368 &mut self,
11369 action: &ToggleComments,
11370 window: &mut Window,
11371 cx: &mut Context<Self>,
11372 ) {
11373 if self.read_only(cx) {
11374 return;
11375 }
11376 let text_layout_details = &self.text_layout_details(window);
11377 self.transact(window, cx, |this, window, cx| {
11378 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11379 let mut edits = Vec::new();
11380 let mut selection_edit_ranges = Vec::new();
11381 let mut last_toggled_row = None;
11382 let snapshot = this.buffer.read(cx).read(cx);
11383 let empty_str: Arc<str> = Arc::default();
11384 let mut suffixes_inserted = Vec::new();
11385 let ignore_indent = action.ignore_indent;
11386
11387 fn comment_prefix_range(
11388 snapshot: &MultiBufferSnapshot,
11389 row: MultiBufferRow,
11390 comment_prefix: &str,
11391 comment_prefix_whitespace: &str,
11392 ignore_indent: bool,
11393 ) -> Range<Point> {
11394 let indent_size = if ignore_indent {
11395 0
11396 } else {
11397 snapshot.indent_size_for_line(row).len
11398 };
11399
11400 let start = Point::new(row.0, indent_size);
11401
11402 let mut line_bytes = snapshot
11403 .bytes_in_range(start..snapshot.max_point())
11404 .flatten()
11405 .copied();
11406
11407 // If this line currently begins with the line comment prefix, then record
11408 // the range containing the prefix.
11409 if line_bytes
11410 .by_ref()
11411 .take(comment_prefix.len())
11412 .eq(comment_prefix.bytes())
11413 {
11414 // Include any whitespace that matches the comment prefix.
11415 let matching_whitespace_len = line_bytes
11416 .zip(comment_prefix_whitespace.bytes())
11417 .take_while(|(a, b)| a == b)
11418 .count() as u32;
11419 let end = Point::new(
11420 start.row,
11421 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11422 );
11423 start..end
11424 } else {
11425 start..start
11426 }
11427 }
11428
11429 fn comment_suffix_range(
11430 snapshot: &MultiBufferSnapshot,
11431 row: MultiBufferRow,
11432 comment_suffix: &str,
11433 comment_suffix_has_leading_space: bool,
11434 ) -> Range<Point> {
11435 let end = Point::new(row.0, snapshot.line_len(row));
11436 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11437
11438 let mut line_end_bytes = snapshot
11439 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11440 .flatten()
11441 .copied();
11442
11443 let leading_space_len = if suffix_start_column > 0
11444 && line_end_bytes.next() == Some(b' ')
11445 && comment_suffix_has_leading_space
11446 {
11447 1
11448 } else {
11449 0
11450 };
11451
11452 // If this line currently begins with the line comment prefix, then record
11453 // the range containing the prefix.
11454 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11455 let start = Point::new(end.row, suffix_start_column - leading_space_len);
11456 start..end
11457 } else {
11458 end..end
11459 }
11460 }
11461
11462 // TODO: Handle selections that cross excerpts
11463 for selection in &mut selections {
11464 let start_column = snapshot
11465 .indent_size_for_line(MultiBufferRow(selection.start.row))
11466 .len;
11467 let language = if let Some(language) =
11468 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11469 {
11470 language
11471 } else {
11472 continue;
11473 };
11474
11475 selection_edit_ranges.clear();
11476
11477 // If multiple selections contain a given row, avoid processing that
11478 // row more than once.
11479 let mut start_row = MultiBufferRow(selection.start.row);
11480 if last_toggled_row == Some(start_row) {
11481 start_row = start_row.next_row();
11482 }
11483 let end_row =
11484 if selection.end.row > selection.start.row && selection.end.column == 0 {
11485 MultiBufferRow(selection.end.row - 1)
11486 } else {
11487 MultiBufferRow(selection.end.row)
11488 };
11489 last_toggled_row = Some(end_row);
11490
11491 if start_row > end_row {
11492 continue;
11493 }
11494
11495 // If the language has line comments, toggle those.
11496 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11497
11498 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11499 if ignore_indent {
11500 full_comment_prefixes = full_comment_prefixes
11501 .into_iter()
11502 .map(|s| Arc::from(s.trim_end()))
11503 .collect();
11504 }
11505
11506 if !full_comment_prefixes.is_empty() {
11507 let first_prefix = full_comment_prefixes
11508 .first()
11509 .expect("prefixes is non-empty");
11510 let prefix_trimmed_lengths = full_comment_prefixes
11511 .iter()
11512 .map(|p| p.trim_end_matches(' ').len())
11513 .collect::<SmallVec<[usize; 4]>>();
11514
11515 let mut all_selection_lines_are_comments = true;
11516
11517 for row in start_row.0..=end_row.0 {
11518 let row = MultiBufferRow(row);
11519 if start_row < end_row && snapshot.is_line_blank(row) {
11520 continue;
11521 }
11522
11523 let prefix_range = full_comment_prefixes
11524 .iter()
11525 .zip(prefix_trimmed_lengths.iter().copied())
11526 .map(|(prefix, trimmed_prefix_len)| {
11527 comment_prefix_range(
11528 snapshot.deref(),
11529 row,
11530 &prefix[..trimmed_prefix_len],
11531 &prefix[trimmed_prefix_len..],
11532 ignore_indent,
11533 )
11534 })
11535 .max_by_key(|range| range.end.column - range.start.column)
11536 .expect("prefixes is non-empty");
11537
11538 if prefix_range.is_empty() {
11539 all_selection_lines_are_comments = false;
11540 }
11541
11542 selection_edit_ranges.push(prefix_range);
11543 }
11544
11545 if all_selection_lines_are_comments {
11546 edits.extend(
11547 selection_edit_ranges
11548 .iter()
11549 .cloned()
11550 .map(|range| (range, empty_str.clone())),
11551 );
11552 } else {
11553 let min_column = selection_edit_ranges
11554 .iter()
11555 .map(|range| range.start.column)
11556 .min()
11557 .unwrap_or(0);
11558 edits.extend(selection_edit_ranges.iter().map(|range| {
11559 let position = Point::new(range.start.row, min_column);
11560 (position..position, first_prefix.clone())
11561 }));
11562 }
11563 } else if let Some((full_comment_prefix, comment_suffix)) =
11564 language.block_comment_delimiters()
11565 {
11566 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11567 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11568 let prefix_range = comment_prefix_range(
11569 snapshot.deref(),
11570 start_row,
11571 comment_prefix,
11572 comment_prefix_whitespace,
11573 ignore_indent,
11574 );
11575 let suffix_range = comment_suffix_range(
11576 snapshot.deref(),
11577 end_row,
11578 comment_suffix.trim_start_matches(' '),
11579 comment_suffix.starts_with(' '),
11580 );
11581
11582 if prefix_range.is_empty() || suffix_range.is_empty() {
11583 edits.push((
11584 prefix_range.start..prefix_range.start,
11585 full_comment_prefix.clone(),
11586 ));
11587 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11588 suffixes_inserted.push((end_row, comment_suffix.len()));
11589 } else {
11590 edits.push((prefix_range, empty_str.clone()));
11591 edits.push((suffix_range, empty_str.clone()));
11592 }
11593 } else {
11594 continue;
11595 }
11596 }
11597
11598 drop(snapshot);
11599 this.buffer.update(cx, |buffer, cx| {
11600 buffer.edit(edits, None, cx);
11601 });
11602
11603 // Adjust selections so that they end before any comment suffixes that
11604 // were inserted.
11605 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11606 let mut selections = this.selections.all::<Point>(cx);
11607 let snapshot = this.buffer.read(cx).read(cx);
11608 for selection in &mut selections {
11609 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11610 match row.cmp(&MultiBufferRow(selection.end.row)) {
11611 Ordering::Less => {
11612 suffixes_inserted.next();
11613 continue;
11614 }
11615 Ordering::Greater => break,
11616 Ordering::Equal => {
11617 if selection.end.column == snapshot.line_len(row) {
11618 if selection.is_empty() {
11619 selection.start.column -= suffix_len as u32;
11620 }
11621 selection.end.column -= suffix_len as u32;
11622 }
11623 break;
11624 }
11625 }
11626 }
11627 }
11628
11629 drop(snapshot);
11630 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11631 s.select(selections)
11632 });
11633
11634 let selections = this.selections.all::<Point>(cx);
11635 let selections_on_single_row = selections.windows(2).all(|selections| {
11636 selections[0].start.row == selections[1].start.row
11637 && selections[0].end.row == selections[1].end.row
11638 && selections[0].start.row == selections[0].end.row
11639 });
11640 let selections_selecting = selections
11641 .iter()
11642 .any(|selection| selection.start != selection.end);
11643 let advance_downwards = action.advance_downwards
11644 && selections_on_single_row
11645 && !selections_selecting
11646 && !matches!(this.mode, EditorMode::SingleLine { .. });
11647
11648 if advance_downwards {
11649 let snapshot = this.buffer.read(cx).snapshot(cx);
11650
11651 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11652 s.move_cursors_with(|display_snapshot, display_point, _| {
11653 let mut point = display_point.to_point(display_snapshot);
11654 point.row += 1;
11655 point = snapshot.clip_point(point, Bias::Left);
11656 let display_point = point.to_display_point(display_snapshot);
11657 let goal = SelectionGoal::HorizontalPosition(
11658 display_snapshot
11659 .x_for_display_point(display_point, text_layout_details)
11660 .into(),
11661 );
11662 (display_point, goal)
11663 })
11664 });
11665 }
11666 });
11667 }
11668
11669 pub fn select_enclosing_symbol(
11670 &mut self,
11671 _: &SelectEnclosingSymbol,
11672 window: &mut Window,
11673 cx: &mut Context<Self>,
11674 ) {
11675 let buffer = self.buffer.read(cx).snapshot(cx);
11676 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11677
11678 fn update_selection(
11679 selection: &Selection<usize>,
11680 buffer_snap: &MultiBufferSnapshot,
11681 ) -> Option<Selection<usize>> {
11682 let cursor = selection.head();
11683 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11684 for symbol in symbols.iter().rev() {
11685 let start = symbol.range.start.to_offset(buffer_snap);
11686 let end = symbol.range.end.to_offset(buffer_snap);
11687 let new_range = start..end;
11688 if start < selection.start || end > selection.end {
11689 return Some(Selection {
11690 id: selection.id,
11691 start: new_range.start,
11692 end: new_range.end,
11693 goal: SelectionGoal::None,
11694 reversed: selection.reversed,
11695 });
11696 }
11697 }
11698 None
11699 }
11700
11701 let mut selected_larger_symbol = false;
11702 let new_selections = old_selections
11703 .iter()
11704 .map(|selection| match update_selection(selection, &buffer) {
11705 Some(new_selection) => {
11706 if new_selection.range() != selection.range() {
11707 selected_larger_symbol = true;
11708 }
11709 new_selection
11710 }
11711 None => selection.clone(),
11712 })
11713 .collect::<Vec<_>>();
11714
11715 if selected_larger_symbol {
11716 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11717 s.select(new_selections);
11718 });
11719 }
11720 }
11721
11722 pub fn select_larger_syntax_node(
11723 &mut self,
11724 _: &SelectLargerSyntaxNode,
11725 window: &mut Window,
11726 cx: &mut Context<Self>,
11727 ) {
11728 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11729 let buffer = self.buffer.read(cx).snapshot(cx);
11730 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11731
11732 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11733 let mut selected_larger_node = false;
11734 let new_selections = old_selections
11735 .iter()
11736 .map(|selection| {
11737 let old_range = selection.start..selection.end;
11738 let mut new_range = old_range.clone();
11739 let mut new_node = None;
11740 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11741 {
11742 new_node = Some(node);
11743 new_range = match containing_range {
11744 MultiOrSingleBufferOffsetRange::Single(_) => break,
11745 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11746 };
11747 if !display_map.intersects_fold(new_range.start)
11748 && !display_map.intersects_fold(new_range.end)
11749 {
11750 break;
11751 }
11752 }
11753
11754 if let Some(node) = new_node {
11755 // Log the ancestor, to support using this action as a way to explore TreeSitter
11756 // nodes. Parent and grandparent are also logged because this operation will not
11757 // visit nodes that have the same range as their parent.
11758 log::info!("Node: {node:?}");
11759 let parent = node.parent();
11760 log::info!("Parent: {parent:?}");
11761 let grandparent = parent.and_then(|x| x.parent());
11762 log::info!("Grandparent: {grandparent:?}");
11763 }
11764
11765 selected_larger_node |= new_range != old_range;
11766 Selection {
11767 id: selection.id,
11768 start: new_range.start,
11769 end: new_range.end,
11770 goal: SelectionGoal::None,
11771 reversed: selection.reversed,
11772 }
11773 })
11774 .collect::<Vec<_>>();
11775
11776 if selected_larger_node {
11777 stack.push(old_selections);
11778 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11779 s.select(new_selections);
11780 });
11781 }
11782 self.select_larger_syntax_node_stack = stack;
11783 }
11784
11785 pub fn select_smaller_syntax_node(
11786 &mut self,
11787 _: &SelectSmallerSyntaxNode,
11788 window: &mut Window,
11789 cx: &mut Context<Self>,
11790 ) {
11791 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11792 if let Some(selections) = stack.pop() {
11793 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11794 s.select(selections.to_vec());
11795 });
11796 }
11797 self.select_larger_syntax_node_stack = stack;
11798 }
11799
11800 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11801 if !EditorSettings::get_global(cx).gutter.runnables {
11802 self.clear_tasks();
11803 return Task::ready(());
11804 }
11805 let project = self.project.as_ref().map(Entity::downgrade);
11806 cx.spawn_in(window, async move |this, cx| {
11807 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11808 let Some(project) = project.and_then(|p| p.upgrade()) else {
11809 return;
11810 };
11811 let Ok(display_snapshot) = this.update(cx, |this, cx| {
11812 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11813 }) else {
11814 return;
11815 };
11816
11817 let hide_runnables = project
11818 .update(cx, |project, cx| {
11819 // Do not display any test indicators in non-dev server remote projects.
11820 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11821 })
11822 .unwrap_or(true);
11823 if hide_runnables {
11824 return;
11825 }
11826 let new_rows =
11827 cx.background_spawn({
11828 let snapshot = display_snapshot.clone();
11829 async move {
11830 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11831 }
11832 })
11833 .await;
11834
11835 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11836 this.update(cx, |this, _| {
11837 this.clear_tasks();
11838 for (key, value) in rows {
11839 this.insert_tasks(key, value);
11840 }
11841 })
11842 .ok();
11843 })
11844 }
11845 fn fetch_runnable_ranges(
11846 snapshot: &DisplaySnapshot,
11847 range: Range<Anchor>,
11848 ) -> Vec<language::RunnableRange> {
11849 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11850 }
11851
11852 fn runnable_rows(
11853 project: Entity<Project>,
11854 snapshot: DisplaySnapshot,
11855 runnable_ranges: Vec<RunnableRange>,
11856 mut cx: AsyncWindowContext,
11857 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11858 runnable_ranges
11859 .into_iter()
11860 .filter_map(|mut runnable| {
11861 let tasks = cx
11862 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11863 .ok()?;
11864 if tasks.is_empty() {
11865 return None;
11866 }
11867
11868 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11869
11870 let row = snapshot
11871 .buffer_snapshot
11872 .buffer_line_for_row(MultiBufferRow(point.row))?
11873 .1
11874 .start
11875 .row;
11876
11877 let context_range =
11878 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11879 Some((
11880 (runnable.buffer_id, row),
11881 RunnableTasks {
11882 templates: tasks,
11883 offset: snapshot
11884 .buffer_snapshot
11885 .anchor_before(runnable.run_range.start),
11886 context_range,
11887 column: point.column,
11888 extra_variables: runnable.extra_captures,
11889 },
11890 ))
11891 })
11892 .collect()
11893 }
11894
11895 fn templates_with_tags(
11896 project: &Entity<Project>,
11897 runnable: &mut Runnable,
11898 cx: &mut App,
11899 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11900 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11901 let (worktree_id, file) = project
11902 .buffer_for_id(runnable.buffer, cx)
11903 .and_then(|buffer| buffer.read(cx).file())
11904 .map(|file| (file.worktree_id(cx), file.clone()))
11905 .unzip();
11906
11907 (
11908 project.task_store().read(cx).task_inventory().cloned(),
11909 worktree_id,
11910 file,
11911 )
11912 });
11913
11914 let tags = mem::take(&mut runnable.tags);
11915 let mut tags: Vec<_> = tags
11916 .into_iter()
11917 .flat_map(|tag| {
11918 let tag = tag.0.clone();
11919 inventory
11920 .as_ref()
11921 .into_iter()
11922 .flat_map(|inventory| {
11923 inventory.read(cx).list_tasks(
11924 file.clone(),
11925 Some(runnable.language.clone()),
11926 worktree_id,
11927 cx,
11928 )
11929 })
11930 .filter(move |(_, template)| {
11931 template.tags.iter().any(|source_tag| source_tag == &tag)
11932 })
11933 })
11934 .sorted_by_key(|(kind, _)| kind.to_owned())
11935 .collect();
11936 if let Some((leading_tag_source, _)) = tags.first() {
11937 // Strongest source wins; if we have worktree tag binding, prefer that to
11938 // global and language bindings;
11939 // if we have a global binding, prefer that to language binding.
11940 let first_mismatch = tags
11941 .iter()
11942 .position(|(tag_source, _)| tag_source != leading_tag_source);
11943 if let Some(index) = first_mismatch {
11944 tags.truncate(index);
11945 }
11946 }
11947
11948 tags
11949 }
11950
11951 pub fn move_to_enclosing_bracket(
11952 &mut self,
11953 _: &MoveToEnclosingBracket,
11954 window: &mut Window,
11955 cx: &mut Context<Self>,
11956 ) {
11957 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11958 s.move_offsets_with(|snapshot, selection| {
11959 let Some(enclosing_bracket_ranges) =
11960 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11961 else {
11962 return;
11963 };
11964
11965 let mut best_length = usize::MAX;
11966 let mut best_inside = false;
11967 let mut best_in_bracket_range = false;
11968 let mut best_destination = None;
11969 for (open, close) in enclosing_bracket_ranges {
11970 let close = close.to_inclusive();
11971 let length = close.end() - open.start;
11972 let inside = selection.start >= open.end && selection.end <= *close.start();
11973 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11974 || close.contains(&selection.head());
11975
11976 // If best is next to a bracket and current isn't, skip
11977 if !in_bracket_range && best_in_bracket_range {
11978 continue;
11979 }
11980
11981 // Prefer smaller lengths unless best is inside and current isn't
11982 if length > best_length && (best_inside || !inside) {
11983 continue;
11984 }
11985
11986 best_length = length;
11987 best_inside = inside;
11988 best_in_bracket_range = in_bracket_range;
11989 best_destination = Some(
11990 if close.contains(&selection.start) && close.contains(&selection.end) {
11991 if inside {
11992 open.end
11993 } else {
11994 open.start
11995 }
11996 } else if inside {
11997 *close.start()
11998 } else {
11999 *close.end()
12000 },
12001 );
12002 }
12003
12004 if let Some(destination) = best_destination {
12005 selection.collapse_to(destination, SelectionGoal::None);
12006 }
12007 })
12008 });
12009 }
12010
12011 pub fn undo_selection(
12012 &mut self,
12013 _: &UndoSelection,
12014 window: &mut Window,
12015 cx: &mut Context<Self>,
12016 ) {
12017 self.end_selection(window, cx);
12018 self.selection_history.mode = SelectionHistoryMode::Undoing;
12019 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12020 self.change_selections(None, window, cx, |s| {
12021 s.select_anchors(entry.selections.to_vec())
12022 });
12023 self.select_next_state = entry.select_next_state;
12024 self.select_prev_state = entry.select_prev_state;
12025 self.add_selections_state = entry.add_selections_state;
12026 self.request_autoscroll(Autoscroll::newest(), cx);
12027 }
12028 self.selection_history.mode = SelectionHistoryMode::Normal;
12029 }
12030
12031 pub fn redo_selection(
12032 &mut self,
12033 _: &RedoSelection,
12034 window: &mut Window,
12035 cx: &mut Context<Self>,
12036 ) {
12037 self.end_selection(window, cx);
12038 self.selection_history.mode = SelectionHistoryMode::Redoing;
12039 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12040 self.change_selections(None, window, cx, |s| {
12041 s.select_anchors(entry.selections.to_vec())
12042 });
12043 self.select_next_state = entry.select_next_state;
12044 self.select_prev_state = entry.select_prev_state;
12045 self.add_selections_state = entry.add_selections_state;
12046 self.request_autoscroll(Autoscroll::newest(), cx);
12047 }
12048 self.selection_history.mode = SelectionHistoryMode::Normal;
12049 }
12050
12051 pub fn expand_excerpts(
12052 &mut self,
12053 action: &ExpandExcerpts,
12054 _: &mut Window,
12055 cx: &mut Context<Self>,
12056 ) {
12057 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12058 }
12059
12060 pub fn expand_excerpts_down(
12061 &mut self,
12062 action: &ExpandExcerptsDown,
12063 _: &mut Window,
12064 cx: &mut Context<Self>,
12065 ) {
12066 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12067 }
12068
12069 pub fn expand_excerpts_up(
12070 &mut self,
12071 action: &ExpandExcerptsUp,
12072 _: &mut Window,
12073 cx: &mut Context<Self>,
12074 ) {
12075 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12076 }
12077
12078 pub fn expand_excerpts_for_direction(
12079 &mut self,
12080 lines: u32,
12081 direction: ExpandExcerptDirection,
12082
12083 cx: &mut Context<Self>,
12084 ) {
12085 let selections = self.selections.disjoint_anchors();
12086
12087 let lines = if lines == 0 {
12088 EditorSettings::get_global(cx).expand_excerpt_lines
12089 } else {
12090 lines
12091 };
12092
12093 self.buffer.update(cx, |buffer, cx| {
12094 let snapshot = buffer.snapshot(cx);
12095 let mut excerpt_ids = selections
12096 .iter()
12097 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12098 .collect::<Vec<_>>();
12099 excerpt_ids.sort();
12100 excerpt_ids.dedup();
12101 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12102 })
12103 }
12104
12105 pub fn expand_excerpt(
12106 &mut self,
12107 excerpt: ExcerptId,
12108 direction: ExpandExcerptDirection,
12109 window: &mut Window,
12110 cx: &mut Context<Self>,
12111 ) {
12112 let current_scroll_position = self.scroll_position(cx);
12113 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12114 self.buffer.update(cx, |buffer, cx| {
12115 buffer.expand_excerpts([excerpt], lines, direction, cx)
12116 });
12117 if direction == ExpandExcerptDirection::Down {
12118 let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12119 self.set_scroll_position(new_scroll_position, window, cx);
12120 }
12121 }
12122
12123 pub fn go_to_singleton_buffer_point(
12124 &mut self,
12125 point: Point,
12126 window: &mut Window,
12127 cx: &mut Context<Self>,
12128 ) {
12129 self.go_to_singleton_buffer_range(point..point, window, cx);
12130 }
12131
12132 pub fn go_to_singleton_buffer_range(
12133 &mut self,
12134 range: Range<Point>,
12135 window: &mut Window,
12136 cx: &mut Context<Self>,
12137 ) {
12138 let multibuffer = self.buffer().read(cx);
12139 let Some(buffer) = multibuffer.as_singleton() else {
12140 return;
12141 };
12142 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12143 return;
12144 };
12145 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12146 return;
12147 };
12148 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12149 s.select_anchor_ranges([start..end])
12150 });
12151 }
12152
12153 fn go_to_diagnostic(
12154 &mut self,
12155 _: &GoToDiagnostic,
12156 window: &mut Window,
12157 cx: &mut Context<Self>,
12158 ) {
12159 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12160 }
12161
12162 fn go_to_prev_diagnostic(
12163 &mut self,
12164 _: &GoToPreviousDiagnostic,
12165 window: &mut Window,
12166 cx: &mut Context<Self>,
12167 ) {
12168 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12169 }
12170
12171 pub fn go_to_diagnostic_impl(
12172 &mut self,
12173 direction: Direction,
12174 window: &mut Window,
12175 cx: &mut Context<Self>,
12176 ) {
12177 let buffer = self.buffer.read(cx).snapshot(cx);
12178 let selection = self.selections.newest::<usize>(cx);
12179
12180 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12181 if direction == Direction::Next {
12182 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12183 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12184 return;
12185 };
12186 self.activate_diagnostics(
12187 buffer_id,
12188 popover.local_diagnostic.diagnostic.group_id,
12189 window,
12190 cx,
12191 );
12192 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12193 let primary_range_start = active_diagnostics.primary_range.start;
12194 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12195 let mut new_selection = s.newest_anchor().clone();
12196 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12197 s.select_anchors(vec![new_selection.clone()]);
12198 });
12199 self.refresh_inline_completion(false, true, window, cx);
12200 }
12201 return;
12202 }
12203 }
12204
12205 let active_group_id = self
12206 .active_diagnostics
12207 .as_ref()
12208 .map(|active_group| active_group.group_id);
12209 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12210 active_diagnostics
12211 .primary_range
12212 .to_offset(&buffer)
12213 .to_inclusive()
12214 });
12215 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12216 if active_primary_range.contains(&selection.head()) {
12217 *active_primary_range.start()
12218 } else {
12219 selection.head()
12220 }
12221 } else {
12222 selection.head()
12223 };
12224
12225 let snapshot = self.snapshot(window, cx);
12226 let primary_diagnostics_before = buffer
12227 .diagnostics_in_range::<usize>(0..search_start)
12228 .filter(|entry| entry.diagnostic.is_primary)
12229 .filter(|entry| entry.range.start != entry.range.end)
12230 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12231 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12232 .collect::<Vec<_>>();
12233 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12234 primary_diagnostics_before
12235 .iter()
12236 .position(|entry| entry.diagnostic.group_id == active_group_id)
12237 });
12238
12239 let primary_diagnostics_after = buffer
12240 .diagnostics_in_range::<usize>(search_start..buffer.len())
12241 .filter(|entry| entry.diagnostic.is_primary)
12242 .filter(|entry| entry.range.start != entry.range.end)
12243 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12244 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12245 .collect::<Vec<_>>();
12246 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12247 primary_diagnostics_after
12248 .iter()
12249 .enumerate()
12250 .rev()
12251 .find_map(|(i, entry)| {
12252 if entry.diagnostic.group_id == active_group_id {
12253 Some(i)
12254 } else {
12255 None
12256 }
12257 })
12258 });
12259
12260 let next_primary_diagnostic = match direction {
12261 Direction::Prev => primary_diagnostics_before
12262 .iter()
12263 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12264 .rev()
12265 .next(),
12266 Direction::Next => primary_diagnostics_after
12267 .iter()
12268 .skip(
12269 last_same_group_diagnostic_after
12270 .map(|index| index + 1)
12271 .unwrap_or(0),
12272 )
12273 .next(),
12274 };
12275
12276 // Cycle around to the start of the buffer, potentially moving back to the start of
12277 // the currently active diagnostic.
12278 let cycle_around = || match direction {
12279 Direction::Prev => primary_diagnostics_after
12280 .iter()
12281 .rev()
12282 .chain(primary_diagnostics_before.iter().rev())
12283 .next(),
12284 Direction::Next => primary_diagnostics_before
12285 .iter()
12286 .chain(primary_diagnostics_after.iter())
12287 .next(),
12288 };
12289
12290 if let Some((primary_range, group_id)) = next_primary_diagnostic
12291 .or_else(cycle_around)
12292 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12293 {
12294 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12295 return;
12296 };
12297 self.activate_diagnostics(buffer_id, group_id, window, cx);
12298 if self.active_diagnostics.is_some() {
12299 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12300 s.select(vec![Selection {
12301 id: selection.id,
12302 start: primary_range.start,
12303 end: primary_range.start,
12304 reversed: false,
12305 goal: SelectionGoal::None,
12306 }]);
12307 });
12308 self.refresh_inline_completion(false, true, window, cx);
12309 }
12310 }
12311 }
12312
12313 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12314 let snapshot = self.snapshot(window, cx);
12315 let selection = self.selections.newest::<Point>(cx);
12316 self.go_to_hunk_before_or_after_position(
12317 &snapshot,
12318 selection.head(),
12319 Direction::Next,
12320 window,
12321 cx,
12322 );
12323 }
12324
12325 fn go_to_hunk_before_or_after_position(
12326 &mut self,
12327 snapshot: &EditorSnapshot,
12328 position: Point,
12329 direction: Direction,
12330 window: &mut Window,
12331 cx: &mut Context<Editor>,
12332 ) {
12333 let row = if direction == Direction::Next {
12334 self.hunk_after_position(snapshot, position)
12335 .map(|hunk| hunk.row_range.start)
12336 } else {
12337 self.hunk_before_position(snapshot, position)
12338 };
12339
12340 if let Some(row) = row {
12341 let destination = Point::new(row.0, 0);
12342 let autoscroll = Autoscroll::center();
12343
12344 self.unfold_ranges(&[destination..destination], false, false, cx);
12345 self.change_selections(Some(autoscroll), window, cx, |s| {
12346 s.select_ranges([destination..destination]);
12347 });
12348 }
12349 }
12350
12351 fn hunk_after_position(
12352 &mut self,
12353 snapshot: &EditorSnapshot,
12354 position: Point,
12355 ) -> Option<MultiBufferDiffHunk> {
12356 snapshot
12357 .buffer_snapshot
12358 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12359 .find(|hunk| hunk.row_range.start.0 > position.row)
12360 .or_else(|| {
12361 snapshot
12362 .buffer_snapshot
12363 .diff_hunks_in_range(Point::zero()..position)
12364 .find(|hunk| hunk.row_range.end.0 < position.row)
12365 })
12366 }
12367
12368 fn go_to_prev_hunk(
12369 &mut self,
12370 _: &GoToPreviousHunk,
12371 window: &mut Window,
12372 cx: &mut Context<Self>,
12373 ) {
12374 let snapshot = self.snapshot(window, cx);
12375 let selection = self.selections.newest::<Point>(cx);
12376 self.go_to_hunk_before_or_after_position(
12377 &snapshot,
12378 selection.head(),
12379 Direction::Prev,
12380 window,
12381 cx,
12382 );
12383 }
12384
12385 fn hunk_before_position(
12386 &mut self,
12387 snapshot: &EditorSnapshot,
12388 position: Point,
12389 ) -> Option<MultiBufferRow> {
12390 snapshot
12391 .buffer_snapshot
12392 .diff_hunk_before(position)
12393 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12394 }
12395
12396 fn go_to_line<T: 'static>(
12397 &mut self,
12398 position: Anchor,
12399 highlight_color: Option<Hsla>,
12400 window: &mut Window,
12401 cx: &mut Context<Self>,
12402 ) {
12403 let snapshot = self.snapshot(window, cx).display_snapshot;
12404 let position = position.to_point(&snapshot.buffer_snapshot);
12405 let start = snapshot
12406 .buffer_snapshot
12407 .clip_point(Point::new(position.row, 0), Bias::Left);
12408 let end = start + Point::new(1, 0);
12409 let start = snapshot.buffer_snapshot.anchor_before(start);
12410 let end = snapshot.buffer_snapshot.anchor_before(end);
12411
12412 self.clear_row_highlights::<T>();
12413 self.highlight_rows::<T>(
12414 start..end,
12415 highlight_color
12416 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12417 true,
12418 cx,
12419 );
12420 self.request_autoscroll(Autoscroll::center(), cx);
12421 }
12422
12423 pub fn go_to_definition(
12424 &mut self,
12425 _: &GoToDefinition,
12426 window: &mut Window,
12427 cx: &mut Context<Self>,
12428 ) -> Task<Result<Navigated>> {
12429 let definition =
12430 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12431 cx.spawn_in(window, async move |editor, cx| {
12432 if definition.await? == Navigated::Yes {
12433 return Ok(Navigated::Yes);
12434 }
12435 match editor.update_in(cx, |editor, window, cx| {
12436 editor.find_all_references(&FindAllReferences, window, cx)
12437 })? {
12438 Some(references) => references.await,
12439 None => Ok(Navigated::No),
12440 }
12441 })
12442 }
12443
12444 pub fn go_to_declaration(
12445 &mut self,
12446 _: &GoToDeclaration,
12447 window: &mut Window,
12448 cx: &mut Context<Self>,
12449 ) -> Task<Result<Navigated>> {
12450 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
12451 }
12452
12453 pub fn go_to_declaration_split(
12454 &mut self,
12455 _: &GoToDeclaration,
12456 window: &mut Window,
12457 cx: &mut Context<Self>,
12458 ) -> Task<Result<Navigated>> {
12459 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12460 }
12461
12462 pub fn go_to_implementation(
12463 &mut self,
12464 _: &GoToImplementation,
12465 window: &mut Window,
12466 cx: &mut Context<Self>,
12467 ) -> Task<Result<Navigated>> {
12468 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12469 }
12470
12471 pub fn go_to_implementation_split(
12472 &mut self,
12473 _: &GoToImplementationSplit,
12474 window: &mut Window,
12475 cx: &mut Context<Self>,
12476 ) -> Task<Result<Navigated>> {
12477 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12478 }
12479
12480 pub fn go_to_type_definition(
12481 &mut self,
12482 _: &GoToTypeDefinition,
12483 window: &mut Window,
12484 cx: &mut Context<Self>,
12485 ) -> Task<Result<Navigated>> {
12486 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12487 }
12488
12489 pub fn go_to_definition_split(
12490 &mut self,
12491 _: &GoToDefinitionSplit,
12492 window: &mut Window,
12493 cx: &mut Context<Self>,
12494 ) -> Task<Result<Navigated>> {
12495 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12496 }
12497
12498 pub fn go_to_type_definition_split(
12499 &mut self,
12500 _: &GoToTypeDefinitionSplit,
12501 window: &mut Window,
12502 cx: &mut Context<Self>,
12503 ) -> Task<Result<Navigated>> {
12504 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12505 }
12506
12507 fn go_to_definition_of_kind(
12508 &mut self,
12509 kind: GotoDefinitionKind,
12510 split: bool,
12511 window: &mut Window,
12512 cx: &mut Context<Self>,
12513 ) -> Task<Result<Navigated>> {
12514 let Some(provider) = self.semantics_provider.clone() else {
12515 return Task::ready(Ok(Navigated::No));
12516 };
12517 let head = self.selections.newest::<usize>(cx).head();
12518 let buffer = self.buffer.read(cx);
12519 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12520 text_anchor
12521 } else {
12522 return Task::ready(Ok(Navigated::No));
12523 };
12524
12525 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12526 return Task::ready(Ok(Navigated::No));
12527 };
12528
12529 cx.spawn_in(window, async move |editor, cx| {
12530 let definitions = definitions.await?;
12531 let navigated = editor
12532 .update_in(cx, |editor, window, cx| {
12533 editor.navigate_to_hover_links(
12534 Some(kind),
12535 definitions
12536 .into_iter()
12537 .filter(|location| {
12538 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12539 })
12540 .map(HoverLink::Text)
12541 .collect::<Vec<_>>(),
12542 split,
12543 window,
12544 cx,
12545 )
12546 })?
12547 .await?;
12548 anyhow::Ok(navigated)
12549 })
12550 }
12551
12552 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12553 let selection = self.selections.newest_anchor();
12554 let head = selection.head();
12555 let tail = selection.tail();
12556
12557 let Some((buffer, start_position)) =
12558 self.buffer.read(cx).text_anchor_for_position(head, cx)
12559 else {
12560 return;
12561 };
12562
12563 let end_position = if head != tail {
12564 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12565 return;
12566 };
12567 Some(pos)
12568 } else {
12569 None
12570 };
12571
12572 let url_finder = cx.spawn_in(window, async move |editor, cx| {
12573 let url = if let Some(end_pos) = end_position {
12574 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12575 } else {
12576 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12577 };
12578
12579 if let Some(url) = url {
12580 editor.update(cx, |_, cx| {
12581 cx.open_url(&url);
12582 })
12583 } else {
12584 Ok(())
12585 }
12586 });
12587
12588 url_finder.detach();
12589 }
12590
12591 pub fn open_selected_filename(
12592 &mut self,
12593 _: &OpenSelectedFilename,
12594 window: &mut Window,
12595 cx: &mut Context<Self>,
12596 ) {
12597 let Some(workspace) = self.workspace() else {
12598 return;
12599 };
12600
12601 let position = self.selections.newest_anchor().head();
12602
12603 let Some((buffer, buffer_position)) =
12604 self.buffer.read(cx).text_anchor_for_position(position, cx)
12605 else {
12606 return;
12607 };
12608
12609 let project = self.project.clone();
12610
12611 cx.spawn_in(window, async move |_, cx| {
12612 let result = find_file(&buffer, project, buffer_position, cx).await;
12613
12614 if let Some((_, path)) = result {
12615 workspace
12616 .update_in(cx, |workspace, window, cx| {
12617 workspace.open_resolved_path(path, window, cx)
12618 })?
12619 .await?;
12620 }
12621 anyhow::Ok(())
12622 })
12623 .detach();
12624 }
12625
12626 pub(crate) fn navigate_to_hover_links(
12627 &mut self,
12628 kind: Option<GotoDefinitionKind>,
12629 mut definitions: Vec<HoverLink>,
12630 split: bool,
12631 window: &mut Window,
12632 cx: &mut Context<Editor>,
12633 ) -> Task<Result<Navigated>> {
12634 // If there is one definition, just open it directly
12635 if definitions.len() == 1 {
12636 let definition = definitions.pop().unwrap();
12637
12638 enum TargetTaskResult {
12639 Location(Option<Location>),
12640 AlreadyNavigated,
12641 }
12642
12643 let target_task = match definition {
12644 HoverLink::Text(link) => {
12645 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12646 }
12647 HoverLink::InlayHint(lsp_location, server_id) => {
12648 let computation =
12649 self.compute_target_location(lsp_location, server_id, window, cx);
12650 cx.background_spawn(async move {
12651 let location = computation.await?;
12652 Ok(TargetTaskResult::Location(location))
12653 })
12654 }
12655 HoverLink::Url(url) => {
12656 cx.open_url(&url);
12657 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12658 }
12659 HoverLink::File(path) => {
12660 if let Some(workspace) = self.workspace() {
12661 cx.spawn_in(window, async move |_, cx| {
12662 workspace
12663 .update_in(cx, |workspace, window, cx| {
12664 workspace.open_resolved_path(path, window, cx)
12665 })?
12666 .await
12667 .map(|_| TargetTaskResult::AlreadyNavigated)
12668 })
12669 } else {
12670 Task::ready(Ok(TargetTaskResult::Location(None)))
12671 }
12672 }
12673 };
12674 cx.spawn_in(window, async move |editor, cx| {
12675 let target = match target_task.await.context("target resolution task")? {
12676 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12677 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12678 TargetTaskResult::Location(Some(target)) => target,
12679 };
12680
12681 editor.update_in(cx, |editor, window, cx| {
12682 let Some(workspace) = editor.workspace() else {
12683 return Navigated::No;
12684 };
12685 let pane = workspace.read(cx).active_pane().clone();
12686
12687 let range = target.range.to_point(target.buffer.read(cx));
12688 let range = editor.range_for_match(&range);
12689 let range = collapse_multiline_range(range);
12690
12691 if !split
12692 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12693 {
12694 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12695 } else {
12696 window.defer(cx, move |window, cx| {
12697 let target_editor: Entity<Self> =
12698 workspace.update(cx, |workspace, cx| {
12699 let pane = if split {
12700 workspace.adjacent_pane(window, cx)
12701 } else {
12702 workspace.active_pane().clone()
12703 };
12704
12705 workspace.open_project_item(
12706 pane,
12707 target.buffer.clone(),
12708 true,
12709 true,
12710 window,
12711 cx,
12712 )
12713 });
12714 target_editor.update(cx, |target_editor, cx| {
12715 // When selecting a definition in a different buffer, disable the nav history
12716 // to avoid creating a history entry at the previous cursor location.
12717 pane.update(cx, |pane, _| pane.disable_history());
12718 target_editor.go_to_singleton_buffer_range(range, window, cx);
12719 pane.update(cx, |pane, _| pane.enable_history());
12720 });
12721 });
12722 }
12723 Navigated::Yes
12724 })
12725 })
12726 } else if !definitions.is_empty() {
12727 cx.spawn_in(window, async move |editor, cx| {
12728 let (title, location_tasks, workspace) = editor
12729 .update_in(cx, |editor, window, cx| {
12730 let tab_kind = match kind {
12731 Some(GotoDefinitionKind::Implementation) => "Implementations",
12732 _ => "Definitions",
12733 };
12734 let title = definitions
12735 .iter()
12736 .find_map(|definition| match definition {
12737 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12738 let buffer = origin.buffer.read(cx);
12739 format!(
12740 "{} for {}",
12741 tab_kind,
12742 buffer
12743 .text_for_range(origin.range.clone())
12744 .collect::<String>()
12745 )
12746 }),
12747 HoverLink::InlayHint(_, _) => None,
12748 HoverLink::Url(_) => None,
12749 HoverLink::File(_) => None,
12750 })
12751 .unwrap_or(tab_kind.to_string());
12752 let location_tasks = definitions
12753 .into_iter()
12754 .map(|definition| match definition {
12755 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12756 HoverLink::InlayHint(lsp_location, server_id) => editor
12757 .compute_target_location(lsp_location, server_id, window, cx),
12758 HoverLink::Url(_) => Task::ready(Ok(None)),
12759 HoverLink::File(_) => Task::ready(Ok(None)),
12760 })
12761 .collect::<Vec<_>>();
12762 (title, location_tasks, editor.workspace().clone())
12763 })
12764 .context("location tasks preparation")?;
12765
12766 let locations = future::join_all(location_tasks)
12767 .await
12768 .into_iter()
12769 .filter_map(|location| location.transpose())
12770 .collect::<Result<_>>()
12771 .context("location tasks")?;
12772
12773 let Some(workspace) = workspace else {
12774 return Ok(Navigated::No);
12775 };
12776 let opened = workspace
12777 .update_in(cx, |workspace, window, cx| {
12778 Self::open_locations_in_multibuffer(
12779 workspace,
12780 locations,
12781 title,
12782 split,
12783 MultibufferSelectionMode::First,
12784 window,
12785 cx,
12786 )
12787 })
12788 .ok();
12789
12790 anyhow::Ok(Navigated::from_bool(opened.is_some()))
12791 })
12792 } else {
12793 Task::ready(Ok(Navigated::No))
12794 }
12795 }
12796
12797 fn compute_target_location(
12798 &self,
12799 lsp_location: lsp::Location,
12800 server_id: LanguageServerId,
12801 window: &mut Window,
12802 cx: &mut Context<Self>,
12803 ) -> Task<anyhow::Result<Option<Location>>> {
12804 let Some(project) = self.project.clone() else {
12805 return Task::ready(Ok(None));
12806 };
12807
12808 cx.spawn_in(window, async move |editor, cx| {
12809 let location_task = editor.update(cx, |_, cx| {
12810 project.update(cx, |project, cx| {
12811 let language_server_name = project
12812 .language_server_statuses(cx)
12813 .find(|(id, _)| server_id == *id)
12814 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12815 language_server_name.map(|language_server_name| {
12816 project.open_local_buffer_via_lsp(
12817 lsp_location.uri.clone(),
12818 server_id,
12819 language_server_name,
12820 cx,
12821 )
12822 })
12823 })
12824 })?;
12825 let location = match location_task {
12826 Some(task) => Some({
12827 let target_buffer_handle = task.await.context("open local buffer")?;
12828 let range = target_buffer_handle.update(cx, |target_buffer, _| {
12829 let target_start = target_buffer
12830 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12831 let target_end = target_buffer
12832 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12833 target_buffer.anchor_after(target_start)
12834 ..target_buffer.anchor_before(target_end)
12835 })?;
12836 Location {
12837 buffer: target_buffer_handle,
12838 range,
12839 }
12840 }),
12841 None => None,
12842 };
12843 Ok(location)
12844 })
12845 }
12846
12847 pub fn find_all_references(
12848 &mut self,
12849 _: &FindAllReferences,
12850 window: &mut Window,
12851 cx: &mut Context<Self>,
12852 ) -> Option<Task<Result<Navigated>>> {
12853 let selection = self.selections.newest::<usize>(cx);
12854 let multi_buffer = self.buffer.read(cx);
12855 let head = selection.head();
12856
12857 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12858 let head_anchor = multi_buffer_snapshot.anchor_at(
12859 head,
12860 if head < selection.tail() {
12861 Bias::Right
12862 } else {
12863 Bias::Left
12864 },
12865 );
12866
12867 match self
12868 .find_all_references_task_sources
12869 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12870 {
12871 Ok(_) => {
12872 log::info!(
12873 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12874 );
12875 return None;
12876 }
12877 Err(i) => {
12878 self.find_all_references_task_sources.insert(i, head_anchor);
12879 }
12880 }
12881
12882 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12883 let workspace = self.workspace()?;
12884 let project = workspace.read(cx).project().clone();
12885 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12886 Some(cx.spawn_in(window, async move |editor, cx| {
12887 let _cleanup = cx.on_drop(&editor, move |editor, _| {
12888 if let Ok(i) = editor
12889 .find_all_references_task_sources
12890 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12891 {
12892 editor.find_all_references_task_sources.remove(i);
12893 }
12894 });
12895
12896 let locations = references.await?;
12897 if locations.is_empty() {
12898 return anyhow::Ok(Navigated::No);
12899 }
12900
12901 workspace.update_in(cx, |workspace, window, cx| {
12902 let title = locations
12903 .first()
12904 .as_ref()
12905 .map(|location| {
12906 let buffer = location.buffer.read(cx);
12907 format!(
12908 "References to `{}`",
12909 buffer
12910 .text_for_range(location.range.clone())
12911 .collect::<String>()
12912 )
12913 })
12914 .unwrap();
12915 Self::open_locations_in_multibuffer(
12916 workspace,
12917 locations,
12918 title,
12919 false,
12920 MultibufferSelectionMode::First,
12921 window,
12922 cx,
12923 );
12924 Navigated::Yes
12925 })
12926 }))
12927 }
12928
12929 /// Opens a multibuffer with the given project locations in it
12930 pub fn open_locations_in_multibuffer(
12931 workspace: &mut Workspace,
12932 mut locations: Vec<Location>,
12933 title: String,
12934 split: bool,
12935 multibuffer_selection_mode: MultibufferSelectionMode,
12936 window: &mut Window,
12937 cx: &mut Context<Workspace>,
12938 ) {
12939 // If there are multiple definitions, open them in a multibuffer
12940 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12941 let mut locations = locations.into_iter().peekable();
12942 let mut ranges = Vec::new();
12943 let capability = workspace.project().read(cx).capability();
12944
12945 let excerpt_buffer = cx.new(|cx| {
12946 let mut multibuffer = MultiBuffer::new(capability);
12947 while let Some(location) = locations.next() {
12948 let buffer = location.buffer.read(cx);
12949 let mut ranges_for_buffer = Vec::new();
12950 let range = location.range.to_offset(buffer);
12951 ranges_for_buffer.push(range.clone());
12952
12953 while let Some(next_location) = locations.peek() {
12954 if next_location.buffer == location.buffer {
12955 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12956 locations.next();
12957 } else {
12958 break;
12959 }
12960 }
12961
12962 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12963 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12964 location.buffer.clone(),
12965 ranges_for_buffer,
12966 DEFAULT_MULTIBUFFER_CONTEXT,
12967 cx,
12968 ))
12969 }
12970
12971 multibuffer.with_title(title)
12972 });
12973
12974 let editor = cx.new(|cx| {
12975 Editor::for_multibuffer(
12976 excerpt_buffer,
12977 Some(workspace.project().clone()),
12978 window,
12979 cx,
12980 )
12981 });
12982 editor.update(cx, |editor, cx| {
12983 match multibuffer_selection_mode {
12984 MultibufferSelectionMode::First => {
12985 if let Some(first_range) = ranges.first() {
12986 editor.change_selections(None, window, cx, |selections| {
12987 selections.clear_disjoint();
12988 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12989 });
12990 }
12991 editor.highlight_background::<Self>(
12992 &ranges,
12993 |theme| theme.editor_highlighted_line_background,
12994 cx,
12995 );
12996 }
12997 MultibufferSelectionMode::All => {
12998 editor.change_selections(None, window, cx, |selections| {
12999 selections.clear_disjoint();
13000 selections.select_anchor_ranges(ranges);
13001 });
13002 }
13003 }
13004 editor.register_buffers_with_language_servers(cx);
13005 });
13006
13007 let item = Box::new(editor);
13008 let item_id = item.item_id();
13009
13010 if split {
13011 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13012 } else {
13013 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13014 let (preview_item_id, preview_item_idx) =
13015 workspace.active_pane().update(cx, |pane, _| {
13016 (pane.preview_item_id(), pane.preview_item_idx())
13017 });
13018
13019 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13020
13021 if let Some(preview_item_id) = preview_item_id {
13022 workspace.active_pane().update(cx, |pane, cx| {
13023 pane.remove_item(preview_item_id, false, false, window, cx);
13024 });
13025 }
13026 } else {
13027 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13028 }
13029 }
13030 workspace.active_pane().update(cx, |pane, cx| {
13031 pane.set_preview_item_id(Some(item_id), cx);
13032 });
13033 }
13034
13035 pub fn rename(
13036 &mut self,
13037 _: &Rename,
13038 window: &mut Window,
13039 cx: &mut Context<Self>,
13040 ) -> Option<Task<Result<()>>> {
13041 use language::ToOffset as _;
13042
13043 let provider = self.semantics_provider.clone()?;
13044 let selection = self.selections.newest_anchor().clone();
13045 let (cursor_buffer, cursor_buffer_position) = self
13046 .buffer
13047 .read(cx)
13048 .text_anchor_for_position(selection.head(), cx)?;
13049 let (tail_buffer, cursor_buffer_position_end) = self
13050 .buffer
13051 .read(cx)
13052 .text_anchor_for_position(selection.tail(), cx)?;
13053 if tail_buffer != cursor_buffer {
13054 return None;
13055 }
13056
13057 let snapshot = cursor_buffer.read(cx).snapshot();
13058 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13059 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13060 let prepare_rename = provider
13061 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13062 .unwrap_or_else(|| Task::ready(Ok(None)));
13063 drop(snapshot);
13064
13065 Some(cx.spawn_in(window, async move |this, cx| {
13066 let rename_range = if let Some(range) = prepare_rename.await? {
13067 Some(range)
13068 } else {
13069 this.update(cx, |this, cx| {
13070 let buffer = this.buffer.read(cx).snapshot(cx);
13071 let mut buffer_highlights = this
13072 .document_highlights_for_position(selection.head(), &buffer)
13073 .filter(|highlight| {
13074 highlight.start.excerpt_id == selection.head().excerpt_id
13075 && highlight.end.excerpt_id == selection.head().excerpt_id
13076 });
13077 buffer_highlights
13078 .next()
13079 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13080 })?
13081 };
13082 if let Some(rename_range) = rename_range {
13083 this.update_in(cx, |this, window, cx| {
13084 let snapshot = cursor_buffer.read(cx).snapshot();
13085 let rename_buffer_range = rename_range.to_offset(&snapshot);
13086 let cursor_offset_in_rename_range =
13087 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13088 let cursor_offset_in_rename_range_end =
13089 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13090
13091 this.take_rename(false, window, cx);
13092 let buffer = this.buffer.read(cx).read(cx);
13093 let cursor_offset = selection.head().to_offset(&buffer);
13094 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13095 let rename_end = rename_start + rename_buffer_range.len();
13096 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13097 let mut old_highlight_id = None;
13098 let old_name: Arc<str> = buffer
13099 .chunks(rename_start..rename_end, true)
13100 .map(|chunk| {
13101 if old_highlight_id.is_none() {
13102 old_highlight_id = chunk.syntax_highlight_id;
13103 }
13104 chunk.text
13105 })
13106 .collect::<String>()
13107 .into();
13108
13109 drop(buffer);
13110
13111 // Position the selection in the rename editor so that it matches the current selection.
13112 this.show_local_selections = false;
13113 let rename_editor = cx.new(|cx| {
13114 let mut editor = Editor::single_line(window, cx);
13115 editor.buffer.update(cx, |buffer, cx| {
13116 buffer.edit([(0..0, old_name.clone())], None, cx)
13117 });
13118 let rename_selection_range = match cursor_offset_in_rename_range
13119 .cmp(&cursor_offset_in_rename_range_end)
13120 {
13121 Ordering::Equal => {
13122 editor.select_all(&SelectAll, window, cx);
13123 return editor;
13124 }
13125 Ordering::Less => {
13126 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13127 }
13128 Ordering::Greater => {
13129 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13130 }
13131 };
13132 if rename_selection_range.end > old_name.len() {
13133 editor.select_all(&SelectAll, window, cx);
13134 } else {
13135 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13136 s.select_ranges([rename_selection_range]);
13137 });
13138 }
13139 editor
13140 });
13141 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13142 if e == &EditorEvent::Focused {
13143 cx.emit(EditorEvent::FocusedIn)
13144 }
13145 })
13146 .detach();
13147
13148 let write_highlights =
13149 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13150 let read_highlights =
13151 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13152 let ranges = write_highlights
13153 .iter()
13154 .flat_map(|(_, ranges)| ranges.iter())
13155 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13156 .cloned()
13157 .collect();
13158
13159 this.highlight_text::<Rename>(
13160 ranges,
13161 HighlightStyle {
13162 fade_out: Some(0.6),
13163 ..Default::default()
13164 },
13165 cx,
13166 );
13167 let rename_focus_handle = rename_editor.focus_handle(cx);
13168 window.focus(&rename_focus_handle);
13169 let block_id = this.insert_blocks(
13170 [BlockProperties {
13171 style: BlockStyle::Flex,
13172 placement: BlockPlacement::Below(range.start),
13173 height: 1,
13174 render: Arc::new({
13175 let rename_editor = rename_editor.clone();
13176 move |cx: &mut BlockContext| {
13177 let mut text_style = cx.editor_style.text.clone();
13178 if let Some(highlight_style) = old_highlight_id
13179 .and_then(|h| h.style(&cx.editor_style.syntax))
13180 {
13181 text_style = text_style.highlight(highlight_style);
13182 }
13183 div()
13184 .block_mouse_down()
13185 .pl(cx.anchor_x)
13186 .child(EditorElement::new(
13187 &rename_editor,
13188 EditorStyle {
13189 background: cx.theme().system().transparent,
13190 local_player: cx.editor_style.local_player,
13191 text: text_style,
13192 scrollbar_width: cx.editor_style.scrollbar_width,
13193 syntax: cx.editor_style.syntax.clone(),
13194 status: cx.editor_style.status.clone(),
13195 inlay_hints_style: HighlightStyle {
13196 font_weight: Some(FontWeight::BOLD),
13197 ..make_inlay_hints_style(cx.app)
13198 },
13199 inline_completion_styles: make_suggestion_styles(
13200 cx.app,
13201 ),
13202 ..EditorStyle::default()
13203 },
13204 ))
13205 .into_any_element()
13206 }
13207 }),
13208 priority: 0,
13209 }],
13210 Some(Autoscroll::fit()),
13211 cx,
13212 )[0];
13213 this.pending_rename = Some(RenameState {
13214 range,
13215 old_name,
13216 editor: rename_editor,
13217 block_id,
13218 });
13219 })?;
13220 }
13221
13222 Ok(())
13223 }))
13224 }
13225
13226 pub fn confirm_rename(
13227 &mut self,
13228 _: &ConfirmRename,
13229 window: &mut Window,
13230 cx: &mut Context<Self>,
13231 ) -> Option<Task<Result<()>>> {
13232 let rename = self.take_rename(false, window, cx)?;
13233 let workspace = self.workspace()?.downgrade();
13234 let (buffer, start) = self
13235 .buffer
13236 .read(cx)
13237 .text_anchor_for_position(rename.range.start, cx)?;
13238 let (end_buffer, _) = self
13239 .buffer
13240 .read(cx)
13241 .text_anchor_for_position(rename.range.end, cx)?;
13242 if buffer != end_buffer {
13243 return None;
13244 }
13245
13246 let old_name = rename.old_name;
13247 let new_name = rename.editor.read(cx).text(cx);
13248
13249 let rename = self.semantics_provider.as_ref()?.perform_rename(
13250 &buffer,
13251 start,
13252 new_name.clone(),
13253 cx,
13254 )?;
13255
13256 Some(cx.spawn_in(window, async move |editor, cx| {
13257 let project_transaction = rename.await?;
13258 Self::open_project_transaction(
13259 &editor,
13260 workspace,
13261 project_transaction,
13262 format!("Rename: {} → {}", old_name, new_name),
13263 cx,
13264 )
13265 .await?;
13266
13267 editor.update(cx, |editor, cx| {
13268 editor.refresh_document_highlights(cx);
13269 })?;
13270 Ok(())
13271 }))
13272 }
13273
13274 fn take_rename(
13275 &mut self,
13276 moving_cursor: bool,
13277 window: &mut Window,
13278 cx: &mut Context<Self>,
13279 ) -> Option<RenameState> {
13280 let rename = self.pending_rename.take()?;
13281 if rename.editor.focus_handle(cx).is_focused(window) {
13282 window.focus(&self.focus_handle);
13283 }
13284
13285 self.remove_blocks(
13286 [rename.block_id].into_iter().collect(),
13287 Some(Autoscroll::fit()),
13288 cx,
13289 );
13290 self.clear_highlights::<Rename>(cx);
13291 self.show_local_selections = true;
13292
13293 if moving_cursor {
13294 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13295 editor.selections.newest::<usize>(cx).head()
13296 });
13297
13298 // Update the selection to match the position of the selection inside
13299 // the rename editor.
13300 let snapshot = self.buffer.read(cx).read(cx);
13301 let rename_range = rename.range.to_offset(&snapshot);
13302 let cursor_in_editor = snapshot
13303 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13304 .min(rename_range.end);
13305 drop(snapshot);
13306
13307 self.change_selections(None, window, cx, |s| {
13308 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13309 });
13310 } else {
13311 self.refresh_document_highlights(cx);
13312 }
13313
13314 Some(rename)
13315 }
13316
13317 pub fn pending_rename(&self) -> Option<&RenameState> {
13318 self.pending_rename.as_ref()
13319 }
13320
13321 fn format(
13322 &mut self,
13323 _: &Format,
13324 window: &mut Window,
13325 cx: &mut Context<Self>,
13326 ) -> Option<Task<Result<()>>> {
13327 let project = match &self.project {
13328 Some(project) => project.clone(),
13329 None => return None,
13330 };
13331
13332 Some(self.perform_format(
13333 project,
13334 FormatTrigger::Manual,
13335 FormatTarget::Buffers,
13336 window,
13337 cx,
13338 ))
13339 }
13340
13341 fn format_selections(
13342 &mut self,
13343 _: &FormatSelections,
13344 window: &mut Window,
13345 cx: &mut Context<Self>,
13346 ) -> Option<Task<Result<()>>> {
13347 let project = match &self.project {
13348 Some(project) => project.clone(),
13349 None => return None,
13350 };
13351
13352 let ranges = self
13353 .selections
13354 .all_adjusted(cx)
13355 .into_iter()
13356 .map(|selection| selection.range())
13357 .collect_vec();
13358
13359 Some(self.perform_format(
13360 project,
13361 FormatTrigger::Manual,
13362 FormatTarget::Ranges(ranges),
13363 window,
13364 cx,
13365 ))
13366 }
13367
13368 fn perform_format(
13369 &mut self,
13370 project: Entity<Project>,
13371 trigger: FormatTrigger,
13372 target: FormatTarget,
13373 window: &mut Window,
13374 cx: &mut Context<Self>,
13375 ) -> Task<Result<()>> {
13376 let buffer = self.buffer.clone();
13377 let (buffers, target) = match target {
13378 FormatTarget::Buffers => {
13379 let mut buffers = buffer.read(cx).all_buffers();
13380 if trigger == FormatTrigger::Save {
13381 buffers.retain(|buffer| buffer.read(cx).is_dirty());
13382 }
13383 (buffers, LspFormatTarget::Buffers)
13384 }
13385 FormatTarget::Ranges(selection_ranges) => {
13386 let multi_buffer = buffer.read(cx);
13387 let snapshot = multi_buffer.read(cx);
13388 let mut buffers = HashSet::default();
13389 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13390 BTreeMap::new();
13391 for selection_range in selection_ranges {
13392 for (buffer, buffer_range, _) in
13393 snapshot.range_to_buffer_ranges(selection_range)
13394 {
13395 let buffer_id = buffer.remote_id();
13396 let start = buffer.anchor_before(buffer_range.start);
13397 let end = buffer.anchor_after(buffer_range.end);
13398 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13399 buffer_id_to_ranges
13400 .entry(buffer_id)
13401 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13402 .or_insert_with(|| vec![start..end]);
13403 }
13404 }
13405 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13406 }
13407 };
13408
13409 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13410 let format = project.update(cx, |project, cx| {
13411 project.format(buffers, target, true, trigger, cx)
13412 });
13413
13414 cx.spawn_in(window, async move |_, cx| {
13415 let transaction = futures::select_biased! {
13416 transaction = format.log_err().fuse() => transaction,
13417 () = timeout => {
13418 log::warn!("timed out waiting for formatting");
13419 None
13420 }
13421 };
13422
13423 buffer
13424 .update(cx, |buffer, cx| {
13425 if let Some(transaction) = transaction {
13426 if !buffer.is_singleton() {
13427 buffer.push_transaction(&transaction.0, cx);
13428 }
13429 }
13430 cx.notify();
13431 })
13432 .ok();
13433
13434 Ok(())
13435 })
13436 }
13437
13438 fn organize_imports(
13439 &mut self,
13440 _: &OrganizeImports,
13441 window: &mut Window,
13442 cx: &mut Context<Self>,
13443 ) -> Option<Task<Result<()>>> {
13444 let project = match &self.project {
13445 Some(project) => project.clone(),
13446 None => return None,
13447 };
13448 Some(self.perform_code_action_kind(
13449 project,
13450 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13451 window,
13452 cx,
13453 ))
13454 }
13455
13456 fn perform_code_action_kind(
13457 &mut self,
13458 project: Entity<Project>,
13459 kind: CodeActionKind,
13460 window: &mut Window,
13461 cx: &mut Context<Self>,
13462 ) -> Task<Result<()>> {
13463 let buffer = self.buffer.clone();
13464 let buffers = buffer.read(cx).all_buffers();
13465 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13466 let apply_action = project.update(cx, |project, cx| {
13467 project.apply_code_action_kind(buffers, kind, true, cx)
13468 });
13469 cx.spawn_in(window, async move |_, cx| {
13470 let transaction = futures::select_biased! {
13471 () = timeout => {
13472 log::warn!("timed out waiting for executing code action");
13473 None
13474 }
13475 transaction = apply_action.log_err().fuse() => transaction,
13476 };
13477 buffer
13478 .update(cx, |buffer, cx| {
13479 // check if we need this
13480 if let Some(transaction) = transaction {
13481 if !buffer.is_singleton() {
13482 buffer.push_transaction(&transaction.0, cx);
13483 }
13484 }
13485 cx.notify();
13486 })
13487 .ok();
13488 Ok(())
13489 })
13490 }
13491
13492 fn restart_language_server(
13493 &mut self,
13494 _: &RestartLanguageServer,
13495 _: &mut Window,
13496 cx: &mut Context<Self>,
13497 ) {
13498 if let Some(project) = self.project.clone() {
13499 self.buffer.update(cx, |multi_buffer, cx| {
13500 project.update(cx, |project, cx| {
13501 project.restart_language_servers_for_buffers(
13502 multi_buffer.all_buffers().into_iter().collect(),
13503 cx,
13504 );
13505 });
13506 })
13507 }
13508 }
13509
13510 fn cancel_language_server_work(
13511 workspace: &mut Workspace,
13512 _: &actions::CancelLanguageServerWork,
13513 _: &mut Window,
13514 cx: &mut Context<Workspace>,
13515 ) {
13516 let project = workspace.project();
13517 let buffers = workspace
13518 .active_item(cx)
13519 .and_then(|item| item.act_as::<Editor>(cx))
13520 .map_or(HashSet::default(), |editor| {
13521 editor.read(cx).buffer.read(cx).all_buffers()
13522 });
13523 project.update(cx, |project, cx| {
13524 project.cancel_language_server_work_for_buffers(buffers, cx);
13525 });
13526 }
13527
13528 fn show_character_palette(
13529 &mut self,
13530 _: &ShowCharacterPalette,
13531 window: &mut Window,
13532 _: &mut Context<Self>,
13533 ) {
13534 window.show_character_palette();
13535 }
13536
13537 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13538 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13539 let buffer = self.buffer.read(cx).snapshot(cx);
13540 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13541 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13542 let is_valid = buffer
13543 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13544 .any(|entry| {
13545 entry.diagnostic.is_primary
13546 && !entry.range.is_empty()
13547 && entry.range.start == primary_range_start
13548 && entry.diagnostic.message == active_diagnostics.primary_message
13549 });
13550
13551 if is_valid != active_diagnostics.is_valid {
13552 active_diagnostics.is_valid = is_valid;
13553 if is_valid {
13554 let mut new_styles = HashMap::default();
13555 for (block_id, diagnostic) in &active_diagnostics.blocks {
13556 new_styles.insert(
13557 *block_id,
13558 diagnostic_block_renderer(diagnostic.clone(), None, true),
13559 );
13560 }
13561 self.display_map.update(cx, |display_map, _cx| {
13562 display_map.replace_blocks(new_styles);
13563 });
13564 } else {
13565 self.dismiss_diagnostics(cx);
13566 }
13567 }
13568 }
13569 }
13570
13571 fn activate_diagnostics(
13572 &mut self,
13573 buffer_id: BufferId,
13574 group_id: usize,
13575 window: &mut Window,
13576 cx: &mut Context<Self>,
13577 ) {
13578 self.dismiss_diagnostics(cx);
13579 let snapshot = self.snapshot(window, cx);
13580 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13581 let buffer = self.buffer.read(cx).snapshot(cx);
13582
13583 let mut primary_range = None;
13584 let mut primary_message = None;
13585 let diagnostic_group = buffer
13586 .diagnostic_group(buffer_id, group_id)
13587 .filter_map(|entry| {
13588 let start = entry.range.start;
13589 let end = entry.range.end;
13590 if snapshot.is_line_folded(MultiBufferRow(start.row))
13591 && (start.row == end.row
13592 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13593 {
13594 return None;
13595 }
13596 if entry.diagnostic.is_primary {
13597 primary_range = Some(entry.range.clone());
13598 primary_message = Some(entry.diagnostic.message.clone());
13599 }
13600 Some(entry)
13601 })
13602 .collect::<Vec<_>>();
13603 let primary_range = primary_range?;
13604 let primary_message = primary_message?;
13605
13606 let blocks = display_map
13607 .insert_blocks(
13608 diagnostic_group.iter().map(|entry| {
13609 let diagnostic = entry.diagnostic.clone();
13610 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13611 BlockProperties {
13612 style: BlockStyle::Fixed,
13613 placement: BlockPlacement::Below(
13614 buffer.anchor_after(entry.range.start),
13615 ),
13616 height: message_height,
13617 render: diagnostic_block_renderer(diagnostic, None, true),
13618 priority: 0,
13619 }
13620 }),
13621 cx,
13622 )
13623 .into_iter()
13624 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13625 .collect();
13626
13627 Some(ActiveDiagnosticGroup {
13628 primary_range: buffer.anchor_before(primary_range.start)
13629 ..buffer.anchor_after(primary_range.end),
13630 primary_message,
13631 group_id,
13632 blocks,
13633 is_valid: true,
13634 })
13635 });
13636 }
13637
13638 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13639 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13640 self.display_map.update(cx, |display_map, cx| {
13641 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13642 });
13643 cx.notify();
13644 }
13645 }
13646
13647 /// Disable inline diagnostics rendering for this editor.
13648 pub fn disable_inline_diagnostics(&mut self) {
13649 self.inline_diagnostics_enabled = false;
13650 self.inline_diagnostics_update = Task::ready(());
13651 self.inline_diagnostics.clear();
13652 }
13653
13654 pub fn inline_diagnostics_enabled(&self) -> bool {
13655 self.inline_diagnostics_enabled
13656 }
13657
13658 pub fn show_inline_diagnostics(&self) -> bool {
13659 self.show_inline_diagnostics
13660 }
13661
13662 pub fn toggle_inline_diagnostics(
13663 &mut self,
13664 _: &ToggleInlineDiagnostics,
13665 window: &mut Window,
13666 cx: &mut Context<'_, Editor>,
13667 ) {
13668 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13669 self.refresh_inline_diagnostics(false, window, cx);
13670 }
13671
13672 fn refresh_inline_diagnostics(
13673 &mut self,
13674 debounce: bool,
13675 window: &mut Window,
13676 cx: &mut Context<Self>,
13677 ) {
13678 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13679 self.inline_diagnostics_update = Task::ready(());
13680 self.inline_diagnostics.clear();
13681 return;
13682 }
13683
13684 let debounce_ms = ProjectSettings::get_global(cx)
13685 .diagnostics
13686 .inline
13687 .update_debounce_ms;
13688 let debounce = if debounce && debounce_ms > 0 {
13689 Some(Duration::from_millis(debounce_ms))
13690 } else {
13691 None
13692 };
13693 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
13694 if let Some(debounce) = debounce {
13695 cx.background_executor().timer(debounce).await;
13696 }
13697 let Some(snapshot) = editor
13698 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13699 .ok()
13700 else {
13701 return;
13702 };
13703
13704 let new_inline_diagnostics = cx
13705 .background_spawn(async move {
13706 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13707 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13708 let message = diagnostic_entry
13709 .diagnostic
13710 .message
13711 .split_once('\n')
13712 .map(|(line, _)| line)
13713 .map(SharedString::new)
13714 .unwrap_or_else(|| {
13715 SharedString::from(diagnostic_entry.diagnostic.message)
13716 });
13717 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13718 let (Ok(i) | Err(i)) = inline_diagnostics
13719 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13720 inline_diagnostics.insert(
13721 i,
13722 (
13723 start_anchor,
13724 InlineDiagnostic {
13725 message,
13726 group_id: diagnostic_entry.diagnostic.group_id,
13727 start: diagnostic_entry.range.start.to_point(&snapshot),
13728 is_primary: diagnostic_entry.diagnostic.is_primary,
13729 severity: diagnostic_entry.diagnostic.severity,
13730 },
13731 ),
13732 );
13733 }
13734 inline_diagnostics
13735 })
13736 .await;
13737
13738 editor
13739 .update(cx, |editor, cx| {
13740 editor.inline_diagnostics = new_inline_diagnostics;
13741 cx.notify();
13742 })
13743 .ok();
13744 });
13745 }
13746
13747 pub fn set_selections_from_remote(
13748 &mut self,
13749 selections: Vec<Selection<Anchor>>,
13750 pending_selection: Option<Selection<Anchor>>,
13751 window: &mut Window,
13752 cx: &mut Context<Self>,
13753 ) {
13754 let old_cursor_position = self.selections.newest_anchor().head();
13755 self.selections.change_with(cx, |s| {
13756 s.select_anchors(selections);
13757 if let Some(pending_selection) = pending_selection {
13758 s.set_pending(pending_selection, SelectMode::Character);
13759 } else {
13760 s.clear_pending();
13761 }
13762 });
13763 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13764 }
13765
13766 fn push_to_selection_history(&mut self) {
13767 self.selection_history.push(SelectionHistoryEntry {
13768 selections: self.selections.disjoint_anchors(),
13769 select_next_state: self.select_next_state.clone(),
13770 select_prev_state: self.select_prev_state.clone(),
13771 add_selections_state: self.add_selections_state.clone(),
13772 });
13773 }
13774
13775 pub fn transact(
13776 &mut self,
13777 window: &mut Window,
13778 cx: &mut Context<Self>,
13779 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13780 ) -> Option<TransactionId> {
13781 self.start_transaction_at(Instant::now(), window, cx);
13782 update(self, window, cx);
13783 self.end_transaction_at(Instant::now(), cx)
13784 }
13785
13786 pub fn start_transaction_at(
13787 &mut self,
13788 now: Instant,
13789 window: &mut Window,
13790 cx: &mut Context<Self>,
13791 ) {
13792 self.end_selection(window, cx);
13793 if let Some(tx_id) = self
13794 .buffer
13795 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13796 {
13797 self.selection_history
13798 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13799 cx.emit(EditorEvent::TransactionBegun {
13800 transaction_id: tx_id,
13801 })
13802 }
13803 }
13804
13805 pub fn end_transaction_at(
13806 &mut self,
13807 now: Instant,
13808 cx: &mut Context<Self>,
13809 ) -> Option<TransactionId> {
13810 if let Some(transaction_id) = self
13811 .buffer
13812 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13813 {
13814 if let Some((_, end_selections)) =
13815 self.selection_history.transaction_mut(transaction_id)
13816 {
13817 *end_selections = Some(self.selections.disjoint_anchors());
13818 } else {
13819 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13820 }
13821
13822 cx.emit(EditorEvent::Edited { transaction_id });
13823 Some(transaction_id)
13824 } else {
13825 None
13826 }
13827 }
13828
13829 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13830 if self.selection_mark_mode {
13831 self.change_selections(None, window, cx, |s| {
13832 s.move_with(|_, sel| {
13833 sel.collapse_to(sel.head(), SelectionGoal::None);
13834 });
13835 })
13836 }
13837 self.selection_mark_mode = true;
13838 cx.notify();
13839 }
13840
13841 pub fn swap_selection_ends(
13842 &mut self,
13843 _: &actions::SwapSelectionEnds,
13844 window: &mut Window,
13845 cx: &mut Context<Self>,
13846 ) {
13847 self.change_selections(None, window, cx, |s| {
13848 s.move_with(|_, sel| {
13849 if sel.start != sel.end {
13850 sel.reversed = !sel.reversed
13851 }
13852 });
13853 });
13854 self.request_autoscroll(Autoscroll::newest(), cx);
13855 cx.notify();
13856 }
13857
13858 pub fn toggle_fold(
13859 &mut self,
13860 _: &actions::ToggleFold,
13861 window: &mut Window,
13862 cx: &mut Context<Self>,
13863 ) {
13864 if self.is_singleton(cx) {
13865 let selection = self.selections.newest::<Point>(cx);
13866
13867 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13868 let range = if selection.is_empty() {
13869 let point = selection.head().to_display_point(&display_map);
13870 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13871 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13872 .to_point(&display_map);
13873 start..end
13874 } else {
13875 selection.range()
13876 };
13877 if display_map.folds_in_range(range).next().is_some() {
13878 self.unfold_lines(&Default::default(), window, cx)
13879 } else {
13880 self.fold(&Default::default(), window, cx)
13881 }
13882 } else {
13883 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13884 let buffer_ids: HashSet<_> = self
13885 .selections
13886 .disjoint_anchor_ranges()
13887 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13888 .collect();
13889
13890 let should_unfold = buffer_ids
13891 .iter()
13892 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13893
13894 for buffer_id in buffer_ids {
13895 if should_unfold {
13896 self.unfold_buffer(buffer_id, cx);
13897 } else {
13898 self.fold_buffer(buffer_id, cx);
13899 }
13900 }
13901 }
13902 }
13903
13904 pub fn toggle_fold_recursive(
13905 &mut self,
13906 _: &actions::ToggleFoldRecursive,
13907 window: &mut Window,
13908 cx: &mut Context<Self>,
13909 ) {
13910 let selection = self.selections.newest::<Point>(cx);
13911
13912 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13913 let range = if selection.is_empty() {
13914 let point = selection.head().to_display_point(&display_map);
13915 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13916 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13917 .to_point(&display_map);
13918 start..end
13919 } else {
13920 selection.range()
13921 };
13922 if display_map.folds_in_range(range).next().is_some() {
13923 self.unfold_recursive(&Default::default(), window, cx)
13924 } else {
13925 self.fold_recursive(&Default::default(), window, cx)
13926 }
13927 }
13928
13929 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13930 if self.is_singleton(cx) {
13931 let mut to_fold = Vec::new();
13932 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13933 let selections = self.selections.all_adjusted(cx);
13934
13935 for selection in selections {
13936 let range = selection.range().sorted();
13937 let buffer_start_row = range.start.row;
13938
13939 if range.start.row != range.end.row {
13940 let mut found = false;
13941 let mut row = range.start.row;
13942 while row <= range.end.row {
13943 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13944 {
13945 found = true;
13946 row = crease.range().end.row + 1;
13947 to_fold.push(crease);
13948 } else {
13949 row += 1
13950 }
13951 }
13952 if found {
13953 continue;
13954 }
13955 }
13956
13957 for row in (0..=range.start.row).rev() {
13958 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13959 if crease.range().end.row >= buffer_start_row {
13960 to_fold.push(crease);
13961 if row <= range.start.row {
13962 break;
13963 }
13964 }
13965 }
13966 }
13967 }
13968
13969 self.fold_creases(to_fold, true, window, cx);
13970 } else {
13971 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13972 let buffer_ids = self
13973 .selections
13974 .disjoint_anchor_ranges()
13975 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13976 .collect::<HashSet<_>>();
13977 for buffer_id in buffer_ids {
13978 self.fold_buffer(buffer_id, cx);
13979 }
13980 }
13981 }
13982
13983 fn fold_at_level(
13984 &mut self,
13985 fold_at: &FoldAtLevel,
13986 window: &mut Window,
13987 cx: &mut Context<Self>,
13988 ) {
13989 if !self.buffer.read(cx).is_singleton() {
13990 return;
13991 }
13992
13993 let fold_at_level = fold_at.0;
13994 let snapshot = self.buffer.read(cx).snapshot(cx);
13995 let mut to_fold = Vec::new();
13996 let mut stack = vec![(0, snapshot.max_row().0, 1)];
13997
13998 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
13999 while start_row < end_row {
14000 match self
14001 .snapshot(window, cx)
14002 .crease_for_buffer_row(MultiBufferRow(start_row))
14003 {
14004 Some(crease) => {
14005 let nested_start_row = crease.range().start.row + 1;
14006 let nested_end_row = crease.range().end.row;
14007
14008 if current_level < fold_at_level {
14009 stack.push((nested_start_row, nested_end_row, current_level + 1));
14010 } else if current_level == fold_at_level {
14011 to_fold.push(crease);
14012 }
14013
14014 start_row = nested_end_row + 1;
14015 }
14016 None => start_row += 1,
14017 }
14018 }
14019 }
14020
14021 self.fold_creases(to_fold, true, window, cx);
14022 }
14023
14024 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14025 if self.buffer.read(cx).is_singleton() {
14026 let mut fold_ranges = Vec::new();
14027 let snapshot = self.buffer.read(cx).snapshot(cx);
14028
14029 for row in 0..snapshot.max_row().0 {
14030 if let Some(foldable_range) = self
14031 .snapshot(window, cx)
14032 .crease_for_buffer_row(MultiBufferRow(row))
14033 {
14034 fold_ranges.push(foldable_range);
14035 }
14036 }
14037
14038 self.fold_creases(fold_ranges, true, window, cx);
14039 } else {
14040 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14041 editor
14042 .update_in(cx, |editor, _, cx| {
14043 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14044 editor.fold_buffer(buffer_id, cx);
14045 }
14046 })
14047 .ok();
14048 });
14049 }
14050 }
14051
14052 pub fn fold_function_bodies(
14053 &mut self,
14054 _: &actions::FoldFunctionBodies,
14055 window: &mut Window,
14056 cx: &mut Context<Self>,
14057 ) {
14058 let snapshot = self.buffer.read(cx).snapshot(cx);
14059
14060 let ranges = snapshot
14061 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14062 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14063 .collect::<Vec<_>>();
14064
14065 let creases = ranges
14066 .into_iter()
14067 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14068 .collect();
14069
14070 self.fold_creases(creases, true, window, cx);
14071 }
14072
14073 pub fn fold_recursive(
14074 &mut self,
14075 _: &actions::FoldRecursive,
14076 window: &mut Window,
14077 cx: &mut Context<Self>,
14078 ) {
14079 let mut to_fold = Vec::new();
14080 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14081 let selections = self.selections.all_adjusted(cx);
14082
14083 for selection in selections {
14084 let range = selection.range().sorted();
14085 let buffer_start_row = range.start.row;
14086
14087 if range.start.row != range.end.row {
14088 let mut found = false;
14089 for row in range.start.row..=range.end.row {
14090 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14091 found = true;
14092 to_fold.push(crease);
14093 }
14094 }
14095 if found {
14096 continue;
14097 }
14098 }
14099
14100 for row in (0..=range.start.row).rev() {
14101 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14102 if crease.range().end.row >= buffer_start_row {
14103 to_fold.push(crease);
14104 } else {
14105 break;
14106 }
14107 }
14108 }
14109 }
14110
14111 self.fold_creases(to_fold, true, window, cx);
14112 }
14113
14114 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14115 let buffer_row = fold_at.buffer_row;
14116 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14117
14118 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14119 let autoscroll = self
14120 .selections
14121 .all::<Point>(cx)
14122 .iter()
14123 .any(|selection| crease.range().overlaps(&selection.range()));
14124
14125 self.fold_creases(vec![crease], autoscroll, window, cx);
14126 }
14127 }
14128
14129 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14130 if self.is_singleton(cx) {
14131 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14132 let buffer = &display_map.buffer_snapshot;
14133 let selections = self.selections.all::<Point>(cx);
14134 let ranges = selections
14135 .iter()
14136 .map(|s| {
14137 let range = s.display_range(&display_map).sorted();
14138 let mut start = range.start.to_point(&display_map);
14139 let mut end = range.end.to_point(&display_map);
14140 start.column = 0;
14141 end.column = buffer.line_len(MultiBufferRow(end.row));
14142 start..end
14143 })
14144 .collect::<Vec<_>>();
14145
14146 self.unfold_ranges(&ranges, true, true, cx);
14147 } else {
14148 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14149 let buffer_ids = self
14150 .selections
14151 .disjoint_anchor_ranges()
14152 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14153 .collect::<HashSet<_>>();
14154 for buffer_id in buffer_ids {
14155 self.unfold_buffer(buffer_id, cx);
14156 }
14157 }
14158 }
14159
14160 pub fn unfold_recursive(
14161 &mut self,
14162 _: &UnfoldRecursive,
14163 _window: &mut Window,
14164 cx: &mut Context<Self>,
14165 ) {
14166 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14167 let selections = self.selections.all::<Point>(cx);
14168 let ranges = selections
14169 .iter()
14170 .map(|s| {
14171 let mut range = s.display_range(&display_map).sorted();
14172 *range.start.column_mut() = 0;
14173 *range.end.column_mut() = display_map.line_len(range.end.row());
14174 let start = range.start.to_point(&display_map);
14175 let end = range.end.to_point(&display_map);
14176 start..end
14177 })
14178 .collect::<Vec<_>>();
14179
14180 self.unfold_ranges(&ranges, true, true, cx);
14181 }
14182
14183 pub fn unfold_at(
14184 &mut self,
14185 unfold_at: &UnfoldAt,
14186 _window: &mut Window,
14187 cx: &mut Context<Self>,
14188 ) {
14189 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14190
14191 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14192 ..Point::new(
14193 unfold_at.buffer_row.0,
14194 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14195 );
14196
14197 let autoscroll = self
14198 .selections
14199 .all::<Point>(cx)
14200 .iter()
14201 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14202
14203 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14204 }
14205
14206 pub fn unfold_all(
14207 &mut self,
14208 _: &actions::UnfoldAll,
14209 _window: &mut Window,
14210 cx: &mut Context<Self>,
14211 ) {
14212 if self.buffer.read(cx).is_singleton() {
14213 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14214 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14215 } else {
14216 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14217 editor
14218 .update(cx, |editor, cx| {
14219 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14220 editor.unfold_buffer(buffer_id, cx);
14221 }
14222 })
14223 .ok();
14224 });
14225 }
14226 }
14227
14228 pub fn fold_selected_ranges(
14229 &mut self,
14230 _: &FoldSelectedRanges,
14231 window: &mut Window,
14232 cx: &mut Context<Self>,
14233 ) {
14234 let selections = self.selections.all::<Point>(cx);
14235 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14236 let line_mode = self.selections.line_mode;
14237 let ranges = selections
14238 .into_iter()
14239 .map(|s| {
14240 if line_mode {
14241 let start = Point::new(s.start.row, 0);
14242 let end = Point::new(
14243 s.end.row,
14244 display_map
14245 .buffer_snapshot
14246 .line_len(MultiBufferRow(s.end.row)),
14247 );
14248 Crease::simple(start..end, display_map.fold_placeholder.clone())
14249 } else {
14250 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14251 }
14252 })
14253 .collect::<Vec<_>>();
14254 self.fold_creases(ranges, true, window, cx);
14255 }
14256
14257 pub fn fold_ranges<T: ToOffset + Clone>(
14258 &mut self,
14259 ranges: Vec<Range<T>>,
14260 auto_scroll: bool,
14261 window: &mut Window,
14262 cx: &mut Context<Self>,
14263 ) {
14264 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14265 let ranges = ranges
14266 .into_iter()
14267 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14268 .collect::<Vec<_>>();
14269 self.fold_creases(ranges, auto_scroll, window, cx);
14270 }
14271
14272 pub fn fold_creases<T: ToOffset + Clone>(
14273 &mut self,
14274 creases: Vec<Crease<T>>,
14275 auto_scroll: bool,
14276 window: &mut Window,
14277 cx: &mut Context<Self>,
14278 ) {
14279 if creases.is_empty() {
14280 return;
14281 }
14282
14283 let mut buffers_affected = HashSet::default();
14284 let multi_buffer = self.buffer().read(cx);
14285 for crease in &creases {
14286 if let Some((_, buffer, _)) =
14287 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14288 {
14289 buffers_affected.insert(buffer.read(cx).remote_id());
14290 };
14291 }
14292
14293 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14294
14295 if auto_scroll {
14296 self.request_autoscroll(Autoscroll::fit(), cx);
14297 }
14298
14299 cx.notify();
14300
14301 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14302 // Clear diagnostics block when folding a range that contains it.
14303 let snapshot = self.snapshot(window, cx);
14304 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14305 drop(snapshot);
14306 self.active_diagnostics = Some(active_diagnostics);
14307 self.dismiss_diagnostics(cx);
14308 } else {
14309 self.active_diagnostics = Some(active_diagnostics);
14310 }
14311 }
14312
14313 self.scrollbar_marker_state.dirty = true;
14314 }
14315
14316 /// Removes any folds whose ranges intersect any of the given ranges.
14317 pub fn unfold_ranges<T: ToOffset + Clone>(
14318 &mut self,
14319 ranges: &[Range<T>],
14320 inclusive: bool,
14321 auto_scroll: bool,
14322 cx: &mut Context<Self>,
14323 ) {
14324 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14325 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14326 });
14327 }
14328
14329 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14330 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14331 return;
14332 }
14333 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14334 self.display_map.update(cx, |display_map, cx| {
14335 display_map.fold_buffers([buffer_id], cx)
14336 });
14337 cx.emit(EditorEvent::BufferFoldToggled {
14338 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14339 folded: true,
14340 });
14341 cx.notify();
14342 }
14343
14344 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14345 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14346 return;
14347 }
14348 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14349 self.display_map.update(cx, |display_map, cx| {
14350 display_map.unfold_buffers([buffer_id], cx);
14351 });
14352 cx.emit(EditorEvent::BufferFoldToggled {
14353 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14354 folded: false,
14355 });
14356 cx.notify();
14357 }
14358
14359 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14360 self.display_map.read(cx).is_buffer_folded(buffer)
14361 }
14362
14363 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14364 self.display_map.read(cx).folded_buffers()
14365 }
14366
14367 /// Removes any folds with the given ranges.
14368 pub fn remove_folds_with_type<T: ToOffset + Clone>(
14369 &mut self,
14370 ranges: &[Range<T>],
14371 type_id: TypeId,
14372 auto_scroll: bool,
14373 cx: &mut Context<Self>,
14374 ) {
14375 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14376 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14377 });
14378 }
14379
14380 fn remove_folds_with<T: ToOffset + Clone>(
14381 &mut self,
14382 ranges: &[Range<T>],
14383 auto_scroll: bool,
14384 cx: &mut Context<Self>,
14385 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14386 ) {
14387 if ranges.is_empty() {
14388 return;
14389 }
14390
14391 let mut buffers_affected = HashSet::default();
14392 let multi_buffer = self.buffer().read(cx);
14393 for range in ranges {
14394 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14395 buffers_affected.insert(buffer.read(cx).remote_id());
14396 };
14397 }
14398
14399 self.display_map.update(cx, update);
14400
14401 if auto_scroll {
14402 self.request_autoscroll(Autoscroll::fit(), cx);
14403 }
14404
14405 cx.notify();
14406 self.scrollbar_marker_state.dirty = true;
14407 self.active_indent_guides_state.dirty = true;
14408 }
14409
14410 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14411 self.display_map.read(cx).fold_placeholder.clone()
14412 }
14413
14414 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14415 self.buffer.update(cx, |buffer, cx| {
14416 buffer.set_all_diff_hunks_expanded(cx);
14417 });
14418 }
14419
14420 pub fn expand_all_diff_hunks(
14421 &mut self,
14422 _: &ExpandAllDiffHunks,
14423 _window: &mut Window,
14424 cx: &mut Context<Self>,
14425 ) {
14426 self.buffer.update(cx, |buffer, cx| {
14427 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14428 });
14429 }
14430
14431 pub fn toggle_selected_diff_hunks(
14432 &mut self,
14433 _: &ToggleSelectedDiffHunks,
14434 _window: &mut Window,
14435 cx: &mut Context<Self>,
14436 ) {
14437 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14438 self.toggle_diff_hunks_in_ranges(ranges, cx);
14439 }
14440
14441 pub fn diff_hunks_in_ranges<'a>(
14442 &'a self,
14443 ranges: &'a [Range<Anchor>],
14444 buffer: &'a MultiBufferSnapshot,
14445 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14446 ranges.iter().flat_map(move |range| {
14447 let end_excerpt_id = range.end.excerpt_id;
14448 let range = range.to_point(buffer);
14449 let mut peek_end = range.end;
14450 if range.end.row < buffer.max_row().0 {
14451 peek_end = Point::new(range.end.row + 1, 0);
14452 }
14453 buffer
14454 .diff_hunks_in_range(range.start..peek_end)
14455 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14456 })
14457 }
14458
14459 pub fn has_stageable_diff_hunks_in_ranges(
14460 &self,
14461 ranges: &[Range<Anchor>],
14462 snapshot: &MultiBufferSnapshot,
14463 ) -> bool {
14464 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14465 hunks.any(|hunk| hunk.status().has_secondary_hunk())
14466 }
14467
14468 pub fn toggle_staged_selected_diff_hunks(
14469 &mut self,
14470 _: &::git::ToggleStaged,
14471 _: &mut Window,
14472 cx: &mut Context<Self>,
14473 ) {
14474 let snapshot = self.buffer.read(cx).snapshot(cx);
14475 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14476 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14477 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14478 }
14479
14480 pub fn stage_and_next(
14481 &mut self,
14482 _: &::git::StageAndNext,
14483 window: &mut Window,
14484 cx: &mut Context<Self>,
14485 ) {
14486 self.do_stage_or_unstage_and_next(true, window, cx);
14487 }
14488
14489 pub fn unstage_and_next(
14490 &mut self,
14491 _: &::git::UnstageAndNext,
14492 window: &mut Window,
14493 cx: &mut Context<Self>,
14494 ) {
14495 self.do_stage_or_unstage_and_next(false, window, cx);
14496 }
14497
14498 pub fn stage_or_unstage_diff_hunks(
14499 &mut self,
14500 stage: bool,
14501 ranges: Vec<Range<Anchor>>,
14502 cx: &mut Context<Self>,
14503 ) {
14504 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14505 cx.spawn(async move |this, cx| {
14506 task.await?;
14507 this.update(cx, |this, cx| {
14508 let snapshot = this.buffer.read(cx).snapshot(cx);
14509 let chunk_by = this
14510 .diff_hunks_in_ranges(&ranges, &snapshot)
14511 .chunk_by(|hunk| hunk.buffer_id);
14512 for (buffer_id, hunks) in &chunk_by {
14513 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14514 }
14515 })
14516 })
14517 .detach_and_log_err(cx);
14518 }
14519
14520 fn save_buffers_for_ranges_if_needed(
14521 &mut self,
14522 ranges: &[Range<Anchor>],
14523 cx: &mut Context<'_, Editor>,
14524 ) -> Task<Result<()>> {
14525 let multibuffer = self.buffer.read(cx);
14526 let snapshot = multibuffer.read(cx);
14527 let buffer_ids: HashSet<_> = ranges
14528 .iter()
14529 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14530 .collect();
14531 drop(snapshot);
14532
14533 let mut buffers = HashSet::default();
14534 for buffer_id in buffer_ids {
14535 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14536 let buffer = buffer_entity.read(cx);
14537 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14538 {
14539 buffers.insert(buffer_entity);
14540 }
14541 }
14542 }
14543
14544 if let Some(project) = &self.project {
14545 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14546 } else {
14547 Task::ready(Ok(()))
14548 }
14549 }
14550
14551 fn do_stage_or_unstage_and_next(
14552 &mut self,
14553 stage: bool,
14554 window: &mut Window,
14555 cx: &mut Context<Self>,
14556 ) {
14557 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14558
14559 if ranges.iter().any(|range| range.start != range.end) {
14560 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14561 return;
14562 }
14563
14564 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14565 let snapshot = self.snapshot(window, cx);
14566 let position = self.selections.newest::<Point>(cx).head();
14567 let mut row = snapshot
14568 .buffer_snapshot
14569 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14570 .find(|hunk| hunk.row_range.start.0 > position.row)
14571 .map(|hunk| hunk.row_range.start);
14572
14573 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14574 // Outside of the project diff editor, wrap around to the beginning.
14575 if !all_diff_hunks_expanded {
14576 row = row.or_else(|| {
14577 snapshot
14578 .buffer_snapshot
14579 .diff_hunks_in_range(Point::zero()..position)
14580 .find(|hunk| hunk.row_range.end.0 < position.row)
14581 .map(|hunk| hunk.row_range.start)
14582 });
14583 }
14584
14585 if let Some(row) = row {
14586 let destination = Point::new(row.0, 0);
14587 let autoscroll = Autoscroll::center();
14588
14589 self.unfold_ranges(&[destination..destination], false, false, cx);
14590 self.change_selections(Some(autoscroll), window, cx, |s| {
14591 s.select_ranges([destination..destination]);
14592 });
14593 }
14594 }
14595
14596 fn do_stage_or_unstage(
14597 &self,
14598 stage: bool,
14599 buffer_id: BufferId,
14600 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14601 cx: &mut App,
14602 ) -> Option<()> {
14603 let project = self.project.as_ref()?;
14604 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14605 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14606 let buffer_snapshot = buffer.read(cx).snapshot();
14607 let file_exists = buffer_snapshot
14608 .file()
14609 .is_some_and(|file| file.disk_state().exists());
14610 diff.update(cx, |diff, cx| {
14611 diff.stage_or_unstage_hunks(
14612 stage,
14613 &hunks
14614 .map(|hunk| buffer_diff::DiffHunk {
14615 buffer_range: hunk.buffer_range,
14616 diff_base_byte_range: hunk.diff_base_byte_range,
14617 secondary_status: hunk.secondary_status,
14618 range: Point::zero()..Point::zero(), // unused
14619 })
14620 .collect::<Vec<_>>(),
14621 &buffer_snapshot,
14622 file_exists,
14623 cx,
14624 )
14625 });
14626 None
14627 }
14628
14629 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14630 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14631 self.buffer
14632 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14633 }
14634
14635 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14636 self.buffer.update(cx, |buffer, cx| {
14637 let ranges = vec![Anchor::min()..Anchor::max()];
14638 if !buffer.all_diff_hunks_expanded()
14639 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14640 {
14641 buffer.collapse_diff_hunks(ranges, cx);
14642 true
14643 } else {
14644 false
14645 }
14646 })
14647 }
14648
14649 fn toggle_diff_hunks_in_ranges(
14650 &mut self,
14651 ranges: Vec<Range<Anchor>>,
14652 cx: &mut Context<'_, Editor>,
14653 ) {
14654 self.buffer.update(cx, |buffer, cx| {
14655 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14656 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14657 })
14658 }
14659
14660 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14661 self.buffer.update(cx, |buffer, cx| {
14662 let snapshot = buffer.snapshot(cx);
14663 let excerpt_id = range.end.excerpt_id;
14664 let point_range = range.to_point(&snapshot);
14665 let expand = !buffer.single_hunk_is_expanded(range, cx);
14666 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14667 })
14668 }
14669
14670 pub(crate) fn apply_all_diff_hunks(
14671 &mut self,
14672 _: &ApplyAllDiffHunks,
14673 window: &mut Window,
14674 cx: &mut Context<Self>,
14675 ) {
14676 let buffers = self.buffer.read(cx).all_buffers();
14677 for branch_buffer in buffers {
14678 branch_buffer.update(cx, |branch_buffer, cx| {
14679 branch_buffer.merge_into_base(Vec::new(), cx);
14680 });
14681 }
14682
14683 if let Some(project) = self.project.clone() {
14684 self.save(true, project, window, cx).detach_and_log_err(cx);
14685 }
14686 }
14687
14688 pub(crate) fn apply_selected_diff_hunks(
14689 &mut self,
14690 _: &ApplyDiffHunk,
14691 window: &mut Window,
14692 cx: &mut Context<Self>,
14693 ) {
14694 let snapshot = self.snapshot(window, cx);
14695 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14696 let mut ranges_by_buffer = HashMap::default();
14697 self.transact(window, cx, |editor, _window, cx| {
14698 for hunk in hunks {
14699 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14700 ranges_by_buffer
14701 .entry(buffer.clone())
14702 .or_insert_with(Vec::new)
14703 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14704 }
14705 }
14706
14707 for (buffer, ranges) in ranges_by_buffer {
14708 buffer.update(cx, |buffer, cx| {
14709 buffer.merge_into_base(ranges, cx);
14710 });
14711 }
14712 });
14713
14714 if let Some(project) = self.project.clone() {
14715 self.save(true, project, window, cx).detach_and_log_err(cx);
14716 }
14717 }
14718
14719 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14720 if hovered != self.gutter_hovered {
14721 self.gutter_hovered = hovered;
14722 cx.notify();
14723 }
14724 }
14725
14726 pub fn insert_blocks(
14727 &mut self,
14728 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14729 autoscroll: Option<Autoscroll>,
14730 cx: &mut Context<Self>,
14731 ) -> Vec<CustomBlockId> {
14732 let blocks = self
14733 .display_map
14734 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14735 if let Some(autoscroll) = autoscroll {
14736 self.request_autoscroll(autoscroll, cx);
14737 }
14738 cx.notify();
14739 blocks
14740 }
14741
14742 pub fn resize_blocks(
14743 &mut self,
14744 heights: HashMap<CustomBlockId, u32>,
14745 autoscroll: Option<Autoscroll>,
14746 cx: &mut Context<Self>,
14747 ) {
14748 self.display_map
14749 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14750 if let Some(autoscroll) = autoscroll {
14751 self.request_autoscroll(autoscroll, cx);
14752 }
14753 cx.notify();
14754 }
14755
14756 pub fn replace_blocks(
14757 &mut self,
14758 renderers: HashMap<CustomBlockId, RenderBlock>,
14759 autoscroll: Option<Autoscroll>,
14760 cx: &mut Context<Self>,
14761 ) {
14762 self.display_map
14763 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14764 if let Some(autoscroll) = autoscroll {
14765 self.request_autoscroll(autoscroll, cx);
14766 }
14767 cx.notify();
14768 }
14769
14770 pub fn remove_blocks(
14771 &mut self,
14772 block_ids: HashSet<CustomBlockId>,
14773 autoscroll: Option<Autoscroll>,
14774 cx: &mut Context<Self>,
14775 ) {
14776 self.display_map.update(cx, |display_map, cx| {
14777 display_map.remove_blocks(block_ids, cx)
14778 });
14779 if let Some(autoscroll) = autoscroll {
14780 self.request_autoscroll(autoscroll, cx);
14781 }
14782 cx.notify();
14783 }
14784
14785 pub fn row_for_block(
14786 &self,
14787 block_id: CustomBlockId,
14788 cx: &mut Context<Self>,
14789 ) -> Option<DisplayRow> {
14790 self.display_map
14791 .update(cx, |map, cx| map.row_for_block(block_id, cx))
14792 }
14793
14794 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14795 self.focused_block = Some(focused_block);
14796 }
14797
14798 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14799 self.focused_block.take()
14800 }
14801
14802 pub fn insert_creases(
14803 &mut self,
14804 creases: impl IntoIterator<Item = Crease<Anchor>>,
14805 cx: &mut Context<Self>,
14806 ) -> Vec<CreaseId> {
14807 self.display_map
14808 .update(cx, |map, cx| map.insert_creases(creases, cx))
14809 }
14810
14811 pub fn remove_creases(
14812 &mut self,
14813 ids: impl IntoIterator<Item = CreaseId>,
14814 cx: &mut Context<Self>,
14815 ) {
14816 self.display_map
14817 .update(cx, |map, cx| map.remove_creases(ids, cx));
14818 }
14819
14820 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14821 self.display_map
14822 .update(cx, |map, cx| map.snapshot(cx))
14823 .longest_row()
14824 }
14825
14826 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14827 self.display_map
14828 .update(cx, |map, cx| map.snapshot(cx))
14829 .max_point()
14830 }
14831
14832 pub fn text(&self, cx: &App) -> String {
14833 self.buffer.read(cx).read(cx).text()
14834 }
14835
14836 pub fn is_empty(&self, cx: &App) -> bool {
14837 self.buffer.read(cx).read(cx).is_empty()
14838 }
14839
14840 pub fn text_option(&self, cx: &App) -> Option<String> {
14841 let text = self.text(cx);
14842 let text = text.trim();
14843
14844 if text.is_empty() {
14845 return None;
14846 }
14847
14848 Some(text.to_string())
14849 }
14850
14851 pub fn set_text(
14852 &mut self,
14853 text: impl Into<Arc<str>>,
14854 window: &mut Window,
14855 cx: &mut Context<Self>,
14856 ) {
14857 self.transact(window, cx, |this, _, cx| {
14858 this.buffer
14859 .read(cx)
14860 .as_singleton()
14861 .expect("you can only call set_text on editors for singleton buffers")
14862 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14863 });
14864 }
14865
14866 pub fn display_text(&self, cx: &mut App) -> String {
14867 self.display_map
14868 .update(cx, |map, cx| map.snapshot(cx))
14869 .text()
14870 }
14871
14872 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14873 let mut wrap_guides = smallvec::smallvec![];
14874
14875 if self.show_wrap_guides == Some(false) {
14876 return wrap_guides;
14877 }
14878
14879 let settings = self.buffer.read(cx).language_settings(cx);
14880 if settings.show_wrap_guides {
14881 match self.soft_wrap_mode(cx) {
14882 SoftWrap::Column(soft_wrap) => {
14883 wrap_guides.push((soft_wrap as usize, true));
14884 }
14885 SoftWrap::Bounded(soft_wrap) => {
14886 wrap_guides.push((soft_wrap as usize, true));
14887 }
14888 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14889 }
14890 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14891 }
14892
14893 wrap_guides
14894 }
14895
14896 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14897 let settings = self.buffer.read(cx).language_settings(cx);
14898 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14899 match mode {
14900 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14901 SoftWrap::None
14902 }
14903 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14904 language_settings::SoftWrap::PreferredLineLength => {
14905 SoftWrap::Column(settings.preferred_line_length)
14906 }
14907 language_settings::SoftWrap::Bounded => {
14908 SoftWrap::Bounded(settings.preferred_line_length)
14909 }
14910 }
14911 }
14912
14913 pub fn set_soft_wrap_mode(
14914 &mut self,
14915 mode: language_settings::SoftWrap,
14916
14917 cx: &mut Context<Self>,
14918 ) {
14919 self.soft_wrap_mode_override = Some(mode);
14920 cx.notify();
14921 }
14922
14923 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14924 self.hard_wrap = hard_wrap;
14925 cx.notify();
14926 }
14927
14928 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14929 self.text_style_refinement = Some(style);
14930 }
14931
14932 /// called by the Element so we know what style we were most recently rendered with.
14933 pub(crate) fn set_style(
14934 &mut self,
14935 style: EditorStyle,
14936 window: &mut Window,
14937 cx: &mut Context<Self>,
14938 ) {
14939 let rem_size = window.rem_size();
14940 self.display_map.update(cx, |map, cx| {
14941 map.set_font(
14942 style.text.font(),
14943 style.text.font_size.to_pixels(rem_size),
14944 cx,
14945 )
14946 });
14947 self.style = Some(style);
14948 }
14949
14950 pub fn style(&self) -> Option<&EditorStyle> {
14951 self.style.as_ref()
14952 }
14953
14954 // Called by the element. This method is not designed to be called outside of the editor
14955 // element's layout code because it does not notify when rewrapping is computed synchronously.
14956 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14957 self.display_map
14958 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14959 }
14960
14961 pub fn set_soft_wrap(&mut self) {
14962 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14963 }
14964
14965 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14966 if self.soft_wrap_mode_override.is_some() {
14967 self.soft_wrap_mode_override.take();
14968 } else {
14969 let soft_wrap = match self.soft_wrap_mode(cx) {
14970 SoftWrap::GitDiff => return,
14971 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14972 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14973 language_settings::SoftWrap::None
14974 }
14975 };
14976 self.soft_wrap_mode_override = Some(soft_wrap);
14977 }
14978 cx.notify();
14979 }
14980
14981 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14982 let Some(workspace) = self.workspace() else {
14983 return;
14984 };
14985 let fs = workspace.read(cx).app_state().fs.clone();
14986 let current_show = TabBarSettings::get_global(cx).show;
14987 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14988 setting.show = Some(!current_show);
14989 });
14990 }
14991
14992 pub fn toggle_indent_guides(
14993 &mut self,
14994 _: &ToggleIndentGuides,
14995 _: &mut Window,
14996 cx: &mut Context<Self>,
14997 ) {
14998 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
14999 self.buffer
15000 .read(cx)
15001 .language_settings(cx)
15002 .indent_guides
15003 .enabled
15004 });
15005 self.show_indent_guides = Some(!currently_enabled);
15006 cx.notify();
15007 }
15008
15009 fn should_show_indent_guides(&self) -> Option<bool> {
15010 self.show_indent_guides
15011 }
15012
15013 pub fn toggle_line_numbers(
15014 &mut self,
15015 _: &ToggleLineNumbers,
15016 _: &mut Window,
15017 cx: &mut Context<Self>,
15018 ) {
15019 let mut editor_settings = EditorSettings::get_global(cx).clone();
15020 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15021 EditorSettings::override_global(editor_settings, cx);
15022 }
15023
15024 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15025 if let Some(show_line_numbers) = self.show_line_numbers {
15026 return show_line_numbers;
15027 }
15028 EditorSettings::get_global(cx).gutter.line_numbers
15029 }
15030
15031 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15032 self.use_relative_line_numbers
15033 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15034 }
15035
15036 pub fn toggle_relative_line_numbers(
15037 &mut self,
15038 _: &ToggleRelativeLineNumbers,
15039 _: &mut Window,
15040 cx: &mut Context<Self>,
15041 ) {
15042 let is_relative = self.should_use_relative_line_numbers(cx);
15043 self.set_relative_line_number(Some(!is_relative), cx)
15044 }
15045
15046 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15047 self.use_relative_line_numbers = is_relative;
15048 cx.notify();
15049 }
15050
15051 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15052 self.show_gutter = show_gutter;
15053 cx.notify();
15054 }
15055
15056 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15057 self.show_scrollbars = show_scrollbars;
15058 cx.notify();
15059 }
15060
15061 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15062 self.show_line_numbers = Some(show_line_numbers);
15063 cx.notify();
15064 }
15065
15066 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15067 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15068 cx.notify();
15069 }
15070
15071 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15072 self.show_code_actions = Some(show_code_actions);
15073 cx.notify();
15074 }
15075
15076 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15077 self.show_runnables = Some(show_runnables);
15078 cx.notify();
15079 }
15080
15081 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15082 self.show_breakpoints = Some(show_breakpoints);
15083 cx.notify();
15084 }
15085
15086 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15087 if self.display_map.read(cx).masked != masked {
15088 self.display_map.update(cx, |map, _| map.masked = masked);
15089 }
15090 cx.notify()
15091 }
15092
15093 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15094 self.show_wrap_guides = Some(show_wrap_guides);
15095 cx.notify();
15096 }
15097
15098 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15099 self.show_indent_guides = Some(show_indent_guides);
15100 cx.notify();
15101 }
15102
15103 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15104 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15105 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15106 if let Some(dir) = file.abs_path(cx).parent() {
15107 return Some(dir.to_owned());
15108 }
15109 }
15110
15111 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15112 return Some(project_path.path.to_path_buf());
15113 }
15114 }
15115
15116 None
15117 }
15118
15119 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15120 self.active_excerpt(cx)?
15121 .1
15122 .read(cx)
15123 .file()
15124 .and_then(|f| f.as_local())
15125 }
15126
15127 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15128 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15129 let buffer = buffer.read(cx);
15130 if let Some(project_path) = buffer.project_path(cx) {
15131 let project = self.project.as_ref()?.read(cx);
15132 project.absolute_path(&project_path, cx)
15133 } else {
15134 buffer
15135 .file()
15136 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15137 }
15138 })
15139 }
15140
15141 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15142 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15143 let project_path = buffer.read(cx).project_path(cx)?;
15144 let project = self.project.as_ref()?.read(cx);
15145 let entry = project.entry_for_path(&project_path, cx)?;
15146 let path = entry.path.to_path_buf();
15147 Some(path)
15148 })
15149 }
15150
15151 pub fn reveal_in_finder(
15152 &mut self,
15153 _: &RevealInFileManager,
15154 _window: &mut Window,
15155 cx: &mut Context<Self>,
15156 ) {
15157 if let Some(target) = self.target_file(cx) {
15158 cx.reveal_path(&target.abs_path(cx));
15159 }
15160 }
15161
15162 pub fn copy_path(
15163 &mut self,
15164 _: &zed_actions::workspace::CopyPath,
15165 _window: &mut Window,
15166 cx: &mut Context<Self>,
15167 ) {
15168 if let Some(path) = self.target_file_abs_path(cx) {
15169 if let Some(path) = path.to_str() {
15170 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15171 }
15172 }
15173 }
15174
15175 pub fn copy_relative_path(
15176 &mut self,
15177 _: &zed_actions::workspace::CopyRelativePath,
15178 _window: &mut Window,
15179 cx: &mut Context<Self>,
15180 ) {
15181 if let Some(path) = self.target_file_path(cx) {
15182 if let Some(path) = path.to_str() {
15183 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15184 }
15185 }
15186 }
15187
15188 pub fn project_path(&self, cx: &mut Context<Self>) -> Option<ProjectPath> {
15189 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15190 buffer.read_with(cx, |buffer, cx| buffer.project_path(cx))
15191 } else {
15192 None
15193 }
15194 }
15195
15196 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15197 let _ = maybe!({
15198 let breakpoint_store = self.breakpoint_store.as_ref()?;
15199
15200 let Some((_, _, active_position)) =
15201 breakpoint_store.read(cx).active_position().cloned()
15202 else {
15203 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15204 return None;
15205 };
15206
15207 let snapshot = self
15208 .project
15209 .as_ref()?
15210 .read(cx)
15211 .buffer_for_id(active_position.buffer_id?, cx)?
15212 .read(cx)
15213 .snapshot();
15214
15215 for (id, ExcerptRange { context, .. }) in self
15216 .buffer
15217 .read(cx)
15218 .excerpts_for_buffer(active_position.buffer_id?, cx)
15219 {
15220 if context.start.cmp(&active_position, &snapshot).is_ge()
15221 || context.end.cmp(&active_position, &snapshot).is_lt()
15222 {
15223 continue;
15224 }
15225 let snapshot = self.buffer.read(cx).snapshot(cx);
15226 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15227
15228 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15229 self.go_to_line::<DebugCurrentRowHighlight>(
15230 multibuffer_anchor,
15231 Some(cx.theme().colors().editor_debugger_active_line_background),
15232 window,
15233 cx,
15234 );
15235
15236 cx.notify();
15237 }
15238
15239 Some(())
15240 });
15241 }
15242
15243 pub fn copy_file_name_without_extension(
15244 &mut self,
15245 _: &CopyFileNameWithoutExtension,
15246 _: &mut Window,
15247 cx: &mut Context<Self>,
15248 ) {
15249 if let Some(file) = self.target_file(cx) {
15250 if let Some(file_stem) = file.path().file_stem() {
15251 if let Some(name) = file_stem.to_str() {
15252 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15253 }
15254 }
15255 }
15256 }
15257
15258 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15259 if let Some(file) = self.target_file(cx) {
15260 if let Some(file_name) = file.path().file_name() {
15261 if let Some(name) = file_name.to_str() {
15262 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15263 }
15264 }
15265 }
15266 }
15267
15268 pub fn toggle_git_blame(
15269 &mut self,
15270 _: &::git::Blame,
15271 window: &mut Window,
15272 cx: &mut Context<Self>,
15273 ) {
15274 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15275
15276 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15277 self.start_git_blame(true, window, cx);
15278 }
15279
15280 cx.notify();
15281 }
15282
15283 pub fn toggle_git_blame_inline(
15284 &mut self,
15285 _: &ToggleGitBlameInline,
15286 window: &mut Window,
15287 cx: &mut Context<Self>,
15288 ) {
15289 self.toggle_git_blame_inline_internal(true, window, cx);
15290 cx.notify();
15291 }
15292
15293 pub fn git_blame_inline_enabled(&self) -> bool {
15294 self.git_blame_inline_enabled
15295 }
15296
15297 pub fn toggle_selection_menu(
15298 &mut self,
15299 _: &ToggleSelectionMenu,
15300 _: &mut Window,
15301 cx: &mut Context<Self>,
15302 ) {
15303 self.show_selection_menu = self
15304 .show_selection_menu
15305 .map(|show_selections_menu| !show_selections_menu)
15306 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15307
15308 cx.notify();
15309 }
15310
15311 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15312 self.show_selection_menu
15313 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15314 }
15315
15316 fn start_git_blame(
15317 &mut self,
15318 user_triggered: bool,
15319 window: &mut Window,
15320 cx: &mut Context<Self>,
15321 ) {
15322 if let Some(project) = self.project.as_ref() {
15323 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15324 return;
15325 };
15326
15327 if buffer.read(cx).file().is_none() {
15328 return;
15329 }
15330
15331 let focused = self.focus_handle(cx).contains_focused(window, cx);
15332
15333 let project = project.clone();
15334 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15335 self.blame_subscription =
15336 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15337 self.blame = Some(blame);
15338 }
15339 }
15340
15341 fn toggle_git_blame_inline_internal(
15342 &mut self,
15343 user_triggered: bool,
15344 window: &mut Window,
15345 cx: &mut Context<Self>,
15346 ) {
15347 if self.git_blame_inline_enabled {
15348 self.git_blame_inline_enabled = false;
15349 self.show_git_blame_inline = false;
15350 self.show_git_blame_inline_delay_task.take();
15351 } else {
15352 self.git_blame_inline_enabled = true;
15353 self.start_git_blame_inline(user_triggered, window, cx);
15354 }
15355
15356 cx.notify();
15357 }
15358
15359 fn start_git_blame_inline(
15360 &mut self,
15361 user_triggered: bool,
15362 window: &mut Window,
15363 cx: &mut Context<Self>,
15364 ) {
15365 self.start_git_blame(user_triggered, window, cx);
15366
15367 if ProjectSettings::get_global(cx)
15368 .git
15369 .inline_blame_delay()
15370 .is_some()
15371 {
15372 self.start_inline_blame_timer(window, cx);
15373 } else {
15374 self.show_git_blame_inline = true
15375 }
15376 }
15377
15378 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15379 self.blame.as_ref()
15380 }
15381
15382 pub fn show_git_blame_gutter(&self) -> bool {
15383 self.show_git_blame_gutter
15384 }
15385
15386 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15387 self.show_git_blame_gutter && self.has_blame_entries(cx)
15388 }
15389
15390 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15391 self.show_git_blame_inline
15392 && (self.focus_handle.is_focused(window)
15393 || self
15394 .git_blame_inline_tooltip
15395 .as_ref()
15396 .and_then(|t| t.upgrade())
15397 .is_some())
15398 && !self.newest_selection_head_on_empty_line(cx)
15399 && self.has_blame_entries(cx)
15400 }
15401
15402 fn has_blame_entries(&self, cx: &App) -> bool {
15403 self.blame()
15404 .map_or(false, |blame| blame.read(cx).has_generated_entries())
15405 }
15406
15407 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15408 let cursor_anchor = self.selections.newest_anchor().head();
15409
15410 let snapshot = self.buffer.read(cx).snapshot(cx);
15411 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15412
15413 snapshot.line_len(buffer_row) == 0
15414 }
15415
15416 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15417 let buffer_and_selection = maybe!({
15418 let selection = self.selections.newest::<Point>(cx);
15419 let selection_range = selection.range();
15420
15421 let multi_buffer = self.buffer().read(cx);
15422 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15423 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15424
15425 let (buffer, range, _) = if selection.reversed {
15426 buffer_ranges.first()
15427 } else {
15428 buffer_ranges.last()
15429 }?;
15430
15431 let selection = text::ToPoint::to_point(&range.start, &buffer).row
15432 ..text::ToPoint::to_point(&range.end, &buffer).row;
15433 Some((
15434 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15435 selection,
15436 ))
15437 });
15438
15439 let Some((buffer, selection)) = buffer_and_selection else {
15440 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15441 };
15442
15443 let Some(project) = self.project.as_ref() else {
15444 return Task::ready(Err(anyhow!("editor does not have project")));
15445 };
15446
15447 project.update(cx, |project, cx| {
15448 project.get_permalink_to_line(&buffer, selection, cx)
15449 })
15450 }
15451
15452 pub fn copy_permalink_to_line(
15453 &mut self,
15454 _: &CopyPermalinkToLine,
15455 window: &mut Window,
15456 cx: &mut Context<Self>,
15457 ) {
15458 let permalink_task = self.get_permalink_to_line(cx);
15459 let workspace = self.workspace();
15460
15461 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15462 Ok(permalink) => {
15463 cx.update(|_, cx| {
15464 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15465 })
15466 .ok();
15467 }
15468 Err(err) => {
15469 let message = format!("Failed to copy permalink: {err}");
15470
15471 Err::<(), anyhow::Error>(err).log_err();
15472
15473 if let Some(workspace) = workspace {
15474 workspace
15475 .update_in(cx, |workspace, _, cx| {
15476 struct CopyPermalinkToLine;
15477
15478 workspace.show_toast(
15479 Toast::new(
15480 NotificationId::unique::<CopyPermalinkToLine>(),
15481 message,
15482 ),
15483 cx,
15484 )
15485 })
15486 .ok();
15487 }
15488 }
15489 })
15490 .detach();
15491 }
15492
15493 pub fn copy_file_location(
15494 &mut self,
15495 _: &CopyFileLocation,
15496 _: &mut Window,
15497 cx: &mut Context<Self>,
15498 ) {
15499 let selection = self.selections.newest::<Point>(cx).start.row + 1;
15500 if let Some(file) = self.target_file(cx) {
15501 if let Some(path) = file.path().to_str() {
15502 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15503 }
15504 }
15505 }
15506
15507 pub fn open_permalink_to_line(
15508 &mut self,
15509 _: &OpenPermalinkToLine,
15510 window: &mut Window,
15511 cx: &mut Context<Self>,
15512 ) {
15513 let permalink_task = self.get_permalink_to_line(cx);
15514 let workspace = self.workspace();
15515
15516 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15517 Ok(permalink) => {
15518 cx.update(|_, cx| {
15519 cx.open_url(permalink.as_ref());
15520 })
15521 .ok();
15522 }
15523 Err(err) => {
15524 let message = format!("Failed to open permalink: {err}");
15525
15526 Err::<(), anyhow::Error>(err).log_err();
15527
15528 if let Some(workspace) = workspace {
15529 workspace
15530 .update(cx, |workspace, cx| {
15531 struct OpenPermalinkToLine;
15532
15533 workspace.show_toast(
15534 Toast::new(
15535 NotificationId::unique::<OpenPermalinkToLine>(),
15536 message,
15537 ),
15538 cx,
15539 )
15540 })
15541 .ok();
15542 }
15543 }
15544 })
15545 .detach();
15546 }
15547
15548 pub fn insert_uuid_v4(
15549 &mut self,
15550 _: &InsertUuidV4,
15551 window: &mut Window,
15552 cx: &mut Context<Self>,
15553 ) {
15554 self.insert_uuid(UuidVersion::V4, window, cx);
15555 }
15556
15557 pub fn insert_uuid_v7(
15558 &mut self,
15559 _: &InsertUuidV7,
15560 window: &mut Window,
15561 cx: &mut Context<Self>,
15562 ) {
15563 self.insert_uuid(UuidVersion::V7, window, cx);
15564 }
15565
15566 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15567 self.transact(window, cx, |this, window, cx| {
15568 let edits = this
15569 .selections
15570 .all::<Point>(cx)
15571 .into_iter()
15572 .map(|selection| {
15573 let uuid = match version {
15574 UuidVersion::V4 => uuid::Uuid::new_v4(),
15575 UuidVersion::V7 => uuid::Uuid::now_v7(),
15576 };
15577
15578 (selection.range(), uuid.to_string())
15579 });
15580 this.edit(edits, cx);
15581 this.refresh_inline_completion(true, false, window, cx);
15582 });
15583 }
15584
15585 pub fn open_selections_in_multibuffer(
15586 &mut self,
15587 _: &OpenSelectionsInMultibuffer,
15588 window: &mut Window,
15589 cx: &mut Context<Self>,
15590 ) {
15591 let multibuffer = self.buffer.read(cx);
15592
15593 let Some(buffer) = multibuffer.as_singleton() else {
15594 return;
15595 };
15596
15597 let Some(workspace) = self.workspace() else {
15598 return;
15599 };
15600
15601 let locations = self
15602 .selections
15603 .disjoint_anchors()
15604 .iter()
15605 .map(|range| Location {
15606 buffer: buffer.clone(),
15607 range: range.start.text_anchor..range.end.text_anchor,
15608 })
15609 .collect::<Vec<_>>();
15610
15611 let title = multibuffer.title(cx).to_string();
15612
15613 cx.spawn_in(window, async move |_, cx| {
15614 workspace.update_in(cx, |workspace, window, cx| {
15615 Self::open_locations_in_multibuffer(
15616 workspace,
15617 locations,
15618 format!("Selections for '{title}'"),
15619 false,
15620 MultibufferSelectionMode::All,
15621 window,
15622 cx,
15623 );
15624 })
15625 })
15626 .detach();
15627 }
15628
15629 /// Adds a row highlight for the given range. If a row has multiple highlights, the
15630 /// last highlight added will be used.
15631 ///
15632 /// If the range ends at the beginning of a line, then that line will not be highlighted.
15633 pub fn highlight_rows<T: 'static>(
15634 &mut self,
15635 range: Range<Anchor>,
15636 color: Hsla,
15637 should_autoscroll: bool,
15638 cx: &mut Context<Self>,
15639 ) {
15640 let snapshot = self.buffer().read(cx).snapshot(cx);
15641 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15642 let ix = row_highlights.binary_search_by(|highlight| {
15643 Ordering::Equal
15644 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15645 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15646 });
15647
15648 if let Err(mut ix) = ix {
15649 let index = post_inc(&mut self.highlight_order);
15650
15651 // If this range intersects with the preceding highlight, then merge it with
15652 // the preceding highlight. Otherwise insert a new highlight.
15653 let mut merged = false;
15654 if ix > 0 {
15655 let prev_highlight = &mut row_highlights[ix - 1];
15656 if prev_highlight
15657 .range
15658 .end
15659 .cmp(&range.start, &snapshot)
15660 .is_ge()
15661 {
15662 ix -= 1;
15663 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15664 prev_highlight.range.end = range.end;
15665 }
15666 merged = true;
15667 prev_highlight.index = index;
15668 prev_highlight.color = color;
15669 prev_highlight.should_autoscroll = should_autoscroll;
15670 }
15671 }
15672
15673 if !merged {
15674 row_highlights.insert(
15675 ix,
15676 RowHighlight {
15677 range: range.clone(),
15678 index,
15679 color,
15680 should_autoscroll,
15681 },
15682 );
15683 }
15684
15685 // If any of the following highlights intersect with this one, merge them.
15686 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15687 let highlight = &row_highlights[ix];
15688 if next_highlight
15689 .range
15690 .start
15691 .cmp(&highlight.range.end, &snapshot)
15692 .is_le()
15693 {
15694 if next_highlight
15695 .range
15696 .end
15697 .cmp(&highlight.range.end, &snapshot)
15698 .is_gt()
15699 {
15700 row_highlights[ix].range.end = next_highlight.range.end;
15701 }
15702 row_highlights.remove(ix + 1);
15703 } else {
15704 break;
15705 }
15706 }
15707 }
15708 }
15709
15710 /// Remove any highlighted row ranges of the given type that intersect the
15711 /// given ranges.
15712 pub fn remove_highlighted_rows<T: 'static>(
15713 &mut self,
15714 ranges_to_remove: Vec<Range<Anchor>>,
15715 cx: &mut Context<Self>,
15716 ) {
15717 let snapshot = self.buffer().read(cx).snapshot(cx);
15718 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15719 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15720 row_highlights.retain(|highlight| {
15721 while let Some(range_to_remove) = ranges_to_remove.peek() {
15722 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15723 Ordering::Less | Ordering::Equal => {
15724 ranges_to_remove.next();
15725 }
15726 Ordering::Greater => {
15727 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15728 Ordering::Less | Ordering::Equal => {
15729 return false;
15730 }
15731 Ordering::Greater => break,
15732 }
15733 }
15734 }
15735 }
15736
15737 true
15738 })
15739 }
15740
15741 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15742 pub fn clear_row_highlights<T: 'static>(&mut self) {
15743 self.highlighted_rows.remove(&TypeId::of::<T>());
15744 }
15745
15746 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15747 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15748 self.highlighted_rows
15749 .get(&TypeId::of::<T>())
15750 .map_or(&[] as &[_], |vec| vec.as_slice())
15751 .iter()
15752 .map(|highlight| (highlight.range.clone(), highlight.color))
15753 }
15754
15755 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15756 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15757 /// Allows to ignore certain kinds of highlights.
15758 pub fn highlighted_display_rows(
15759 &self,
15760 window: &mut Window,
15761 cx: &mut App,
15762 ) -> BTreeMap<DisplayRow, LineHighlight> {
15763 let snapshot = self.snapshot(window, cx);
15764 let mut used_highlight_orders = HashMap::default();
15765 self.highlighted_rows
15766 .iter()
15767 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15768 .fold(
15769 BTreeMap::<DisplayRow, LineHighlight>::new(),
15770 |mut unique_rows, highlight| {
15771 let start = highlight.range.start.to_display_point(&snapshot);
15772 let end = highlight.range.end.to_display_point(&snapshot);
15773 let start_row = start.row().0;
15774 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15775 && end.column() == 0
15776 {
15777 end.row().0.saturating_sub(1)
15778 } else {
15779 end.row().0
15780 };
15781 for row in start_row..=end_row {
15782 let used_index =
15783 used_highlight_orders.entry(row).or_insert(highlight.index);
15784 if highlight.index >= *used_index {
15785 *used_index = highlight.index;
15786 unique_rows.insert(DisplayRow(row), highlight.color.into());
15787 }
15788 }
15789 unique_rows
15790 },
15791 )
15792 }
15793
15794 pub fn highlighted_display_row_for_autoscroll(
15795 &self,
15796 snapshot: &DisplaySnapshot,
15797 ) -> Option<DisplayRow> {
15798 self.highlighted_rows
15799 .values()
15800 .flat_map(|highlighted_rows| highlighted_rows.iter())
15801 .filter_map(|highlight| {
15802 if highlight.should_autoscroll {
15803 Some(highlight.range.start.to_display_point(snapshot).row())
15804 } else {
15805 None
15806 }
15807 })
15808 .min()
15809 }
15810
15811 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15812 self.highlight_background::<SearchWithinRange>(
15813 ranges,
15814 |colors| colors.editor_document_highlight_read_background,
15815 cx,
15816 )
15817 }
15818
15819 pub fn set_breadcrumb_header(&mut self, new_header: String) {
15820 self.breadcrumb_header = Some(new_header);
15821 }
15822
15823 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15824 self.clear_background_highlights::<SearchWithinRange>(cx);
15825 }
15826
15827 pub fn highlight_background<T: 'static>(
15828 &mut self,
15829 ranges: &[Range<Anchor>],
15830 color_fetcher: fn(&ThemeColors) -> Hsla,
15831 cx: &mut Context<Self>,
15832 ) {
15833 self.background_highlights
15834 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15835 self.scrollbar_marker_state.dirty = true;
15836 cx.notify();
15837 }
15838
15839 pub fn clear_background_highlights<T: 'static>(
15840 &mut self,
15841 cx: &mut Context<Self>,
15842 ) -> Option<BackgroundHighlight> {
15843 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15844 if !text_highlights.1.is_empty() {
15845 self.scrollbar_marker_state.dirty = true;
15846 cx.notify();
15847 }
15848 Some(text_highlights)
15849 }
15850
15851 pub fn highlight_gutter<T: 'static>(
15852 &mut self,
15853 ranges: &[Range<Anchor>],
15854 color_fetcher: fn(&App) -> Hsla,
15855 cx: &mut Context<Self>,
15856 ) {
15857 self.gutter_highlights
15858 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15859 cx.notify();
15860 }
15861
15862 pub fn clear_gutter_highlights<T: 'static>(
15863 &mut self,
15864 cx: &mut Context<Self>,
15865 ) -> Option<GutterHighlight> {
15866 cx.notify();
15867 self.gutter_highlights.remove(&TypeId::of::<T>())
15868 }
15869
15870 #[cfg(feature = "test-support")]
15871 pub fn all_text_background_highlights(
15872 &self,
15873 window: &mut Window,
15874 cx: &mut Context<Self>,
15875 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15876 let snapshot = self.snapshot(window, cx);
15877 let buffer = &snapshot.buffer_snapshot;
15878 let start = buffer.anchor_before(0);
15879 let end = buffer.anchor_after(buffer.len());
15880 let theme = cx.theme().colors();
15881 self.background_highlights_in_range(start..end, &snapshot, theme)
15882 }
15883
15884 #[cfg(feature = "test-support")]
15885 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15886 let snapshot = self.buffer().read(cx).snapshot(cx);
15887
15888 let highlights = self
15889 .background_highlights
15890 .get(&TypeId::of::<items::BufferSearchHighlights>());
15891
15892 if let Some((_color, ranges)) = highlights {
15893 ranges
15894 .iter()
15895 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15896 .collect_vec()
15897 } else {
15898 vec![]
15899 }
15900 }
15901
15902 fn document_highlights_for_position<'a>(
15903 &'a self,
15904 position: Anchor,
15905 buffer: &'a MultiBufferSnapshot,
15906 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15907 let read_highlights = self
15908 .background_highlights
15909 .get(&TypeId::of::<DocumentHighlightRead>())
15910 .map(|h| &h.1);
15911 let write_highlights = self
15912 .background_highlights
15913 .get(&TypeId::of::<DocumentHighlightWrite>())
15914 .map(|h| &h.1);
15915 let left_position = position.bias_left(buffer);
15916 let right_position = position.bias_right(buffer);
15917 read_highlights
15918 .into_iter()
15919 .chain(write_highlights)
15920 .flat_map(move |ranges| {
15921 let start_ix = match ranges.binary_search_by(|probe| {
15922 let cmp = probe.end.cmp(&left_position, buffer);
15923 if cmp.is_ge() {
15924 Ordering::Greater
15925 } else {
15926 Ordering::Less
15927 }
15928 }) {
15929 Ok(i) | Err(i) => i,
15930 };
15931
15932 ranges[start_ix..]
15933 .iter()
15934 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15935 })
15936 }
15937
15938 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15939 self.background_highlights
15940 .get(&TypeId::of::<T>())
15941 .map_or(false, |(_, highlights)| !highlights.is_empty())
15942 }
15943
15944 pub fn background_highlights_in_range(
15945 &self,
15946 search_range: Range<Anchor>,
15947 display_snapshot: &DisplaySnapshot,
15948 theme: &ThemeColors,
15949 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15950 let mut results = Vec::new();
15951 for (color_fetcher, ranges) in self.background_highlights.values() {
15952 let color = color_fetcher(theme);
15953 let start_ix = match ranges.binary_search_by(|probe| {
15954 let cmp = probe
15955 .end
15956 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15957 if cmp.is_gt() {
15958 Ordering::Greater
15959 } else {
15960 Ordering::Less
15961 }
15962 }) {
15963 Ok(i) | Err(i) => i,
15964 };
15965 for range in &ranges[start_ix..] {
15966 if range
15967 .start
15968 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15969 .is_ge()
15970 {
15971 break;
15972 }
15973
15974 let start = range.start.to_display_point(display_snapshot);
15975 let end = range.end.to_display_point(display_snapshot);
15976 results.push((start..end, color))
15977 }
15978 }
15979 results
15980 }
15981
15982 pub fn background_highlight_row_ranges<T: 'static>(
15983 &self,
15984 search_range: Range<Anchor>,
15985 display_snapshot: &DisplaySnapshot,
15986 count: usize,
15987 ) -> Vec<RangeInclusive<DisplayPoint>> {
15988 let mut results = Vec::new();
15989 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15990 return vec![];
15991 };
15992
15993 let start_ix = match ranges.binary_search_by(|probe| {
15994 let cmp = probe
15995 .end
15996 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15997 if cmp.is_gt() {
15998 Ordering::Greater
15999 } else {
16000 Ordering::Less
16001 }
16002 }) {
16003 Ok(i) | Err(i) => i,
16004 };
16005 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16006 if let (Some(start_display), Some(end_display)) = (start, end) {
16007 results.push(
16008 start_display.to_display_point(display_snapshot)
16009 ..=end_display.to_display_point(display_snapshot),
16010 );
16011 }
16012 };
16013 let mut start_row: Option<Point> = None;
16014 let mut end_row: Option<Point> = None;
16015 if ranges.len() > count {
16016 return Vec::new();
16017 }
16018 for range in &ranges[start_ix..] {
16019 if range
16020 .start
16021 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16022 .is_ge()
16023 {
16024 break;
16025 }
16026 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16027 if let Some(current_row) = &end_row {
16028 if end.row == current_row.row {
16029 continue;
16030 }
16031 }
16032 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16033 if start_row.is_none() {
16034 assert_eq!(end_row, None);
16035 start_row = Some(start);
16036 end_row = Some(end);
16037 continue;
16038 }
16039 if let Some(current_end) = end_row.as_mut() {
16040 if start.row > current_end.row + 1 {
16041 push_region(start_row, end_row);
16042 start_row = Some(start);
16043 end_row = Some(end);
16044 } else {
16045 // Merge two hunks.
16046 *current_end = end;
16047 }
16048 } else {
16049 unreachable!();
16050 }
16051 }
16052 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16053 push_region(start_row, end_row);
16054 results
16055 }
16056
16057 pub fn gutter_highlights_in_range(
16058 &self,
16059 search_range: Range<Anchor>,
16060 display_snapshot: &DisplaySnapshot,
16061 cx: &App,
16062 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16063 let mut results = Vec::new();
16064 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16065 let color = color_fetcher(cx);
16066 let start_ix = match ranges.binary_search_by(|probe| {
16067 let cmp = probe
16068 .end
16069 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16070 if cmp.is_gt() {
16071 Ordering::Greater
16072 } else {
16073 Ordering::Less
16074 }
16075 }) {
16076 Ok(i) | Err(i) => i,
16077 };
16078 for range in &ranges[start_ix..] {
16079 if range
16080 .start
16081 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16082 .is_ge()
16083 {
16084 break;
16085 }
16086
16087 let start = range.start.to_display_point(display_snapshot);
16088 let end = range.end.to_display_point(display_snapshot);
16089 results.push((start..end, color))
16090 }
16091 }
16092 results
16093 }
16094
16095 /// Get the text ranges corresponding to the redaction query
16096 pub fn redacted_ranges(
16097 &self,
16098 search_range: Range<Anchor>,
16099 display_snapshot: &DisplaySnapshot,
16100 cx: &App,
16101 ) -> Vec<Range<DisplayPoint>> {
16102 display_snapshot
16103 .buffer_snapshot
16104 .redacted_ranges(search_range, |file| {
16105 if let Some(file) = file {
16106 file.is_private()
16107 && EditorSettings::get(
16108 Some(SettingsLocation {
16109 worktree_id: file.worktree_id(cx),
16110 path: file.path().as_ref(),
16111 }),
16112 cx,
16113 )
16114 .redact_private_values
16115 } else {
16116 false
16117 }
16118 })
16119 .map(|range| {
16120 range.start.to_display_point(display_snapshot)
16121 ..range.end.to_display_point(display_snapshot)
16122 })
16123 .collect()
16124 }
16125
16126 pub fn highlight_text<T: 'static>(
16127 &mut self,
16128 ranges: Vec<Range<Anchor>>,
16129 style: HighlightStyle,
16130 cx: &mut Context<Self>,
16131 ) {
16132 self.display_map.update(cx, |map, _| {
16133 map.highlight_text(TypeId::of::<T>(), ranges, style)
16134 });
16135 cx.notify();
16136 }
16137
16138 pub(crate) fn highlight_inlays<T: 'static>(
16139 &mut self,
16140 highlights: Vec<InlayHighlight>,
16141 style: HighlightStyle,
16142 cx: &mut Context<Self>,
16143 ) {
16144 self.display_map.update(cx, |map, _| {
16145 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16146 });
16147 cx.notify();
16148 }
16149
16150 pub fn text_highlights<'a, T: 'static>(
16151 &'a self,
16152 cx: &'a App,
16153 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16154 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16155 }
16156
16157 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16158 let cleared = self
16159 .display_map
16160 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16161 if cleared {
16162 cx.notify();
16163 }
16164 }
16165
16166 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16167 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16168 && self.focus_handle.is_focused(window)
16169 }
16170
16171 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16172 self.show_cursor_when_unfocused = is_enabled;
16173 cx.notify();
16174 }
16175
16176 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16177 cx.notify();
16178 }
16179
16180 fn on_buffer_event(
16181 &mut self,
16182 multibuffer: &Entity<MultiBuffer>,
16183 event: &multi_buffer::Event,
16184 window: &mut Window,
16185 cx: &mut Context<Self>,
16186 ) {
16187 match event {
16188 multi_buffer::Event::Edited {
16189 singleton_buffer_edited,
16190 edited_buffer: buffer_edited,
16191 } => {
16192 self.scrollbar_marker_state.dirty = true;
16193 self.active_indent_guides_state.dirty = true;
16194 self.refresh_active_diagnostics(cx);
16195 self.refresh_code_actions(window, cx);
16196 if self.has_active_inline_completion() {
16197 self.update_visible_inline_completion(window, cx);
16198 }
16199 if let Some(buffer) = buffer_edited {
16200 let buffer_id = buffer.read(cx).remote_id();
16201 if !self.registered_buffers.contains_key(&buffer_id) {
16202 if let Some(project) = self.project.as_ref() {
16203 project.update(cx, |project, cx| {
16204 self.registered_buffers.insert(
16205 buffer_id,
16206 project.register_buffer_with_language_servers(&buffer, cx),
16207 );
16208 })
16209 }
16210 }
16211 }
16212 cx.emit(EditorEvent::BufferEdited);
16213 cx.emit(SearchEvent::MatchesInvalidated);
16214 if *singleton_buffer_edited {
16215 if let Some(project) = &self.project {
16216 #[allow(clippy::mutable_key_type)]
16217 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16218 multibuffer
16219 .all_buffers()
16220 .into_iter()
16221 .filter_map(|buffer| {
16222 buffer.update(cx, |buffer, cx| {
16223 let language = buffer.language()?;
16224 let should_discard = project.update(cx, |project, cx| {
16225 project.is_local()
16226 && !project.has_language_servers_for(buffer, cx)
16227 });
16228 should_discard.not().then_some(language.clone())
16229 })
16230 })
16231 .collect::<HashSet<_>>()
16232 });
16233 if !languages_affected.is_empty() {
16234 self.refresh_inlay_hints(
16235 InlayHintRefreshReason::BufferEdited(languages_affected),
16236 cx,
16237 );
16238 }
16239 }
16240 }
16241
16242 let Some(project) = &self.project else { return };
16243 let (telemetry, is_via_ssh) = {
16244 let project = project.read(cx);
16245 let telemetry = project.client().telemetry().clone();
16246 let is_via_ssh = project.is_via_ssh();
16247 (telemetry, is_via_ssh)
16248 };
16249 refresh_linked_ranges(self, window, cx);
16250 telemetry.log_edit_event("editor", is_via_ssh);
16251 }
16252 multi_buffer::Event::ExcerptsAdded {
16253 buffer,
16254 predecessor,
16255 excerpts,
16256 } => {
16257 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16258 let buffer_id = buffer.read(cx).remote_id();
16259 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16260 if let Some(project) = &self.project {
16261 get_uncommitted_diff_for_buffer(
16262 project,
16263 [buffer.clone()],
16264 self.buffer.clone(),
16265 cx,
16266 )
16267 .detach();
16268 }
16269 }
16270 cx.emit(EditorEvent::ExcerptsAdded {
16271 buffer: buffer.clone(),
16272 predecessor: *predecessor,
16273 excerpts: excerpts.clone(),
16274 });
16275 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16276 }
16277 multi_buffer::Event::ExcerptsRemoved { ids } => {
16278 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16279 let buffer = self.buffer.read(cx);
16280 self.registered_buffers
16281 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16282 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16283 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16284 }
16285 multi_buffer::Event::ExcerptsEdited {
16286 excerpt_ids,
16287 buffer_ids,
16288 } => {
16289 self.display_map.update(cx, |map, cx| {
16290 map.unfold_buffers(buffer_ids.iter().copied(), cx)
16291 });
16292 cx.emit(EditorEvent::ExcerptsEdited {
16293 ids: excerpt_ids.clone(),
16294 })
16295 }
16296 multi_buffer::Event::ExcerptsExpanded { ids } => {
16297 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16298 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16299 }
16300 multi_buffer::Event::Reparsed(buffer_id) => {
16301 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16302 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16303
16304 cx.emit(EditorEvent::Reparsed(*buffer_id));
16305 }
16306 multi_buffer::Event::DiffHunksToggled => {
16307 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16308 }
16309 multi_buffer::Event::LanguageChanged(buffer_id) => {
16310 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16311 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16312 cx.emit(EditorEvent::Reparsed(*buffer_id));
16313 cx.notify();
16314 }
16315 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16316 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16317 multi_buffer::Event::FileHandleChanged
16318 | multi_buffer::Event::Reloaded
16319 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16320 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16321 multi_buffer::Event::DiagnosticsUpdated => {
16322 self.refresh_active_diagnostics(cx);
16323 self.refresh_inline_diagnostics(true, window, cx);
16324 self.scrollbar_marker_state.dirty = true;
16325 cx.notify();
16326 }
16327 _ => {}
16328 };
16329 }
16330
16331 fn on_display_map_changed(
16332 &mut self,
16333 _: Entity<DisplayMap>,
16334 _: &mut Window,
16335 cx: &mut Context<Self>,
16336 ) {
16337 cx.notify();
16338 }
16339
16340 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16341 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16342 self.update_edit_prediction_settings(cx);
16343 self.refresh_inline_completion(true, false, window, cx);
16344 self.refresh_inlay_hints(
16345 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16346 self.selections.newest_anchor().head(),
16347 &self.buffer.read(cx).snapshot(cx),
16348 cx,
16349 )),
16350 cx,
16351 );
16352
16353 let old_cursor_shape = self.cursor_shape;
16354
16355 {
16356 let editor_settings = EditorSettings::get_global(cx);
16357 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16358 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16359 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16360 }
16361
16362 if old_cursor_shape != self.cursor_shape {
16363 cx.emit(EditorEvent::CursorShapeChanged);
16364 }
16365
16366 let project_settings = ProjectSettings::get_global(cx);
16367 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16368
16369 if self.mode == EditorMode::Full {
16370 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16371 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16372 if self.show_inline_diagnostics != show_inline_diagnostics {
16373 self.show_inline_diagnostics = show_inline_diagnostics;
16374 self.refresh_inline_diagnostics(false, window, cx);
16375 }
16376
16377 if self.git_blame_inline_enabled != inline_blame_enabled {
16378 self.toggle_git_blame_inline_internal(false, window, cx);
16379 }
16380 }
16381
16382 cx.notify();
16383 }
16384
16385 pub fn set_searchable(&mut self, searchable: bool) {
16386 self.searchable = searchable;
16387 }
16388
16389 pub fn searchable(&self) -> bool {
16390 self.searchable
16391 }
16392
16393 fn open_proposed_changes_editor(
16394 &mut self,
16395 _: &OpenProposedChangesEditor,
16396 window: &mut Window,
16397 cx: &mut Context<Self>,
16398 ) {
16399 let Some(workspace) = self.workspace() else {
16400 cx.propagate();
16401 return;
16402 };
16403
16404 let selections = self.selections.all::<usize>(cx);
16405 let multi_buffer = self.buffer.read(cx);
16406 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16407 let mut new_selections_by_buffer = HashMap::default();
16408 for selection in selections {
16409 for (buffer, range, _) in
16410 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16411 {
16412 let mut range = range.to_point(buffer);
16413 range.start.column = 0;
16414 range.end.column = buffer.line_len(range.end.row);
16415 new_selections_by_buffer
16416 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16417 .or_insert(Vec::new())
16418 .push(range)
16419 }
16420 }
16421
16422 let proposed_changes_buffers = new_selections_by_buffer
16423 .into_iter()
16424 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16425 .collect::<Vec<_>>();
16426 let proposed_changes_editor = cx.new(|cx| {
16427 ProposedChangesEditor::new(
16428 "Proposed changes",
16429 proposed_changes_buffers,
16430 self.project.clone(),
16431 window,
16432 cx,
16433 )
16434 });
16435
16436 window.defer(cx, move |window, cx| {
16437 workspace.update(cx, |workspace, cx| {
16438 workspace.active_pane().update(cx, |pane, cx| {
16439 pane.add_item(
16440 Box::new(proposed_changes_editor),
16441 true,
16442 true,
16443 None,
16444 window,
16445 cx,
16446 );
16447 });
16448 });
16449 });
16450 }
16451
16452 pub fn open_excerpts_in_split(
16453 &mut self,
16454 _: &OpenExcerptsSplit,
16455 window: &mut Window,
16456 cx: &mut Context<Self>,
16457 ) {
16458 self.open_excerpts_common(None, true, window, cx)
16459 }
16460
16461 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16462 self.open_excerpts_common(None, false, window, cx)
16463 }
16464
16465 fn open_excerpts_common(
16466 &mut self,
16467 jump_data: Option<JumpData>,
16468 split: bool,
16469 window: &mut Window,
16470 cx: &mut Context<Self>,
16471 ) {
16472 let Some(workspace) = self.workspace() else {
16473 cx.propagate();
16474 return;
16475 };
16476
16477 if self.buffer.read(cx).is_singleton() {
16478 cx.propagate();
16479 return;
16480 }
16481
16482 let mut new_selections_by_buffer = HashMap::default();
16483 match &jump_data {
16484 Some(JumpData::MultiBufferPoint {
16485 excerpt_id,
16486 position,
16487 anchor,
16488 line_offset_from_top,
16489 }) => {
16490 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16491 if let Some(buffer) = multi_buffer_snapshot
16492 .buffer_id_for_excerpt(*excerpt_id)
16493 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16494 {
16495 let buffer_snapshot = buffer.read(cx).snapshot();
16496 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16497 language::ToPoint::to_point(anchor, &buffer_snapshot)
16498 } else {
16499 buffer_snapshot.clip_point(*position, Bias::Left)
16500 };
16501 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16502 new_selections_by_buffer.insert(
16503 buffer,
16504 (
16505 vec![jump_to_offset..jump_to_offset],
16506 Some(*line_offset_from_top),
16507 ),
16508 );
16509 }
16510 }
16511 Some(JumpData::MultiBufferRow {
16512 row,
16513 line_offset_from_top,
16514 }) => {
16515 let point = MultiBufferPoint::new(row.0, 0);
16516 if let Some((buffer, buffer_point, _)) =
16517 self.buffer.read(cx).point_to_buffer_point(point, cx)
16518 {
16519 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16520 new_selections_by_buffer
16521 .entry(buffer)
16522 .or_insert((Vec::new(), Some(*line_offset_from_top)))
16523 .0
16524 .push(buffer_offset..buffer_offset)
16525 }
16526 }
16527 None => {
16528 let selections = self.selections.all::<usize>(cx);
16529 let multi_buffer = self.buffer.read(cx);
16530 for selection in selections {
16531 for (snapshot, range, _, anchor) in multi_buffer
16532 .snapshot(cx)
16533 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16534 {
16535 if let Some(anchor) = anchor {
16536 // selection is in a deleted hunk
16537 let Some(buffer_id) = anchor.buffer_id else {
16538 continue;
16539 };
16540 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16541 continue;
16542 };
16543 let offset = text::ToOffset::to_offset(
16544 &anchor.text_anchor,
16545 &buffer_handle.read(cx).snapshot(),
16546 );
16547 let range = offset..offset;
16548 new_selections_by_buffer
16549 .entry(buffer_handle)
16550 .or_insert((Vec::new(), None))
16551 .0
16552 .push(range)
16553 } else {
16554 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16555 else {
16556 continue;
16557 };
16558 new_selections_by_buffer
16559 .entry(buffer_handle)
16560 .or_insert((Vec::new(), None))
16561 .0
16562 .push(range)
16563 }
16564 }
16565 }
16566 }
16567 }
16568
16569 if new_selections_by_buffer.is_empty() {
16570 return;
16571 }
16572
16573 // We defer the pane interaction because we ourselves are a workspace item
16574 // and activating a new item causes the pane to call a method on us reentrantly,
16575 // which panics if we're on the stack.
16576 window.defer(cx, move |window, cx| {
16577 workspace.update(cx, |workspace, cx| {
16578 let pane = if split {
16579 workspace.adjacent_pane(window, cx)
16580 } else {
16581 workspace.active_pane().clone()
16582 };
16583
16584 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16585 let editor = buffer
16586 .read(cx)
16587 .file()
16588 .is_none()
16589 .then(|| {
16590 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16591 // so `workspace.open_project_item` will never find them, always opening a new editor.
16592 // Instead, we try to activate the existing editor in the pane first.
16593 let (editor, pane_item_index) =
16594 pane.read(cx).items().enumerate().find_map(|(i, item)| {
16595 let editor = item.downcast::<Editor>()?;
16596 let singleton_buffer =
16597 editor.read(cx).buffer().read(cx).as_singleton()?;
16598 if singleton_buffer == buffer {
16599 Some((editor, i))
16600 } else {
16601 None
16602 }
16603 })?;
16604 pane.update(cx, |pane, cx| {
16605 pane.activate_item(pane_item_index, true, true, window, cx)
16606 });
16607 Some(editor)
16608 })
16609 .flatten()
16610 .unwrap_or_else(|| {
16611 workspace.open_project_item::<Self>(
16612 pane.clone(),
16613 buffer,
16614 true,
16615 true,
16616 window,
16617 cx,
16618 )
16619 });
16620
16621 editor.update(cx, |editor, cx| {
16622 let autoscroll = match scroll_offset {
16623 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16624 None => Autoscroll::newest(),
16625 };
16626 let nav_history = editor.nav_history.take();
16627 editor.change_selections(Some(autoscroll), window, cx, |s| {
16628 s.select_ranges(ranges);
16629 });
16630 editor.nav_history = nav_history;
16631 });
16632 }
16633 })
16634 });
16635 }
16636
16637 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16638 let snapshot = self.buffer.read(cx).read(cx);
16639 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16640 Some(
16641 ranges
16642 .iter()
16643 .map(move |range| {
16644 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16645 })
16646 .collect(),
16647 )
16648 }
16649
16650 fn selection_replacement_ranges(
16651 &self,
16652 range: Range<OffsetUtf16>,
16653 cx: &mut App,
16654 ) -> Vec<Range<OffsetUtf16>> {
16655 let selections = self.selections.all::<OffsetUtf16>(cx);
16656 let newest_selection = selections
16657 .iter()
16658 .max_by_key(|selection| selection.id)
16659 .unwrap();
16660 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16661 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16662 let snapshot = self.buffer.read(cx).read(cx);
16663 selections
16664 .into_iter()
16665 .map(|mut selection| {
16666 selection.start.0 =
16667 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16668 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16669 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16670 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16671 })
16672 .collect()
16673 }
16674
16675 fn report_editor_event(
16676 &self,
16677 event_type: &'static str,
16678 file_extension: Option<String>,
16679 cx: &App,
16680 ) {
16681 if cfg!(any(test, feature = "test-support")) {
16682 return;
16683 }
16684
16685 let Some(project) = &self.project else { return };
16686
16687 // If None, we are in a file without an extension
16688 let file = self
16689 .buffer
16690 .read(cx)
16691 .as_singleton()
16692 .and_then(|b| b.read(cx).file());
16693 let file_extension = file_extension.or(file
16694 .as_ref()
16695 .and_then(|file| Path::new(file.file_name(cx)).extension())
16696 .and_then(|e| e.to_str())
16697 .map(|a| a.to_string()));
16698
16699 let vim_mode = cx
16700 .global::<SettingsStore>()
16701 .raw_user_settings()
16702 .get("vim_mode")
16703 == Some(&serde_json::Value::Bool(true));
16704
16705 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16706 let copilot_enabled = edit_predictions_provider
16707 == language::language_settings::EditPredictionProvider::Copilot;
16708 let copilot_enabled_for_language = self
16709 .buffer
16710 .read(cx)
16711 .language_settings(cx)
16712 .show_edit_predictions;
16713
16714 let project = project.read(cx);
16715 telemetry::event!(
16716 event_type,
16717 file_extension,
16718 vim_mode,
16719 copilot_enabled,
16720 copilot_enabled_for_language,
16721 edit_predictions_provider,
16722 is_via_ssh = project.is_via_ssh(),
16723 );
16724 }
16725
16726 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16727 /// with each line being an array of {text, highlight} objects.
16728 fn copy_highlight_json(
16729 &mut self,
16730 _: &CopyHighlightJson,
16731 window: &mut Window,
16732 cx: &mut Context<Self>,
16733 ) {
16734 #[derive(Serialize)]
16735 struct Chunk<'a> {
16736 text: String,
16737 highlight: Option<&'a str>,
16738 }
16739
16740 let snapshot = self.buffer.read(cx).snapshot(cx);
16741 let range = self
16742 .selected_text_range(false, window, cx)
16743 .and_then(|selection| {
16744 if selection.range.is_empty() {
16745 None
16746 } else {
16747 Some(selection.range)
16748 }
16749 })
16750 .unwrap_or_else(|| 0..snapshot.len());
16751
16752 let chunks = snapshot.chunks(range, true);
16753 let mut lines = Vec::new();
16754 let mut line: VecDeque<Chunk> = VecDeque::new();
16755
16756 let Some(style) = self.style.as_ref() else {
16757 return;
16758 };
16759
16760 for chunk in chunks {
16761 let highlight = chunk
16762 .syntax_highlight_id
16763 .and_then(|id| id.name(&style.syntax));
16764 let mut chunk_lines = chunk.text.split('\n').peekable();
16765 while let Some(text) = chunk_lines.next() {
16766 let mut merged_with_last_token = false;
16767 if let Some(last_token) = line.back_mut() {
16768 if last_token.highlight == highlight {
16769 last_token.text.push_str(text);
16770 merged_with_last_token = true;
16771 }
16772 }
16773
16774 if !merged_with_last_token {
16775 line.push_back(Chunk {
16776 text: text.into(),
16777 highlight,
16778 });
16779 }
16780
16781 if chunk_lines.peek().is_some() {
16782 if line.len() > 1 && line.front().unwrap().text.is_empty() {
16783 line.pop_front();
16784 }
16785 if line.len() > 1 && line.back().unwrap().text.is_empty() {
16786 line.pop_back();
16787 }
16788
16789 lines.push(mem::take(&mut line));
16790 }
16791 }
16792 }
16793
16794 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16795 return;
16796 };
16797 cx.write_to_clipboard(ClipboardItem::new_string(lines));
16798 }
16799
16800 pub fn open_context_menu(
16801 &mut self,
16802 _: &OpenContextMenu,
16803 window: &mut Window,
16804 cx: &mut Context<Self>,
16805 ) {
16806 self.request_autoscroll(Autoscroll::newest(), cx);
16807 let position = self.selections.newest_display(cx).start;
16808 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16809 }
16810
16811 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16812 &self.inlay_hint_cache
16813 }
16814
16815 pub fn replay_insert_event(
16816 &mut self,
16817 text: &str,
16818 relative_utf16_range: Option<Range<isize>>,
16819 window: &mut Window,
16820 cx: &mut Context<Self>,
16821 ) {
16822 if !self.input_enabled {
16823 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16824 return;
16825 }
16826 if let Some(relative_utf16_range) = relative_utf16_range {
16827 let selections = self.selections.all::<OffsetUtf16>(cx);
16828 self.change_selections(None, window, cx, |s| {
16829 let new_ranges = selections.into_iter().map(|range| {
16830 let start = OffsetUtf16(
16831 range
16832 .head()
16833 .0
16834 .saturating_add_signed(relative_utf16_range.start),
16835 );
16836 let end = OffsetUtf16(
16837 range
16838 .head()
16839 .0
16840 .saturating_add_signed(relative_utf16_range.end),
16841 );
16842 start..end
16843 });
16844 s.select_ranges(new_ranges);
16845 });
16846 }
16847
16848 self.handle_input(text, window, cx);
16849 }
16850
16851 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16852 let Some(provider) = self.semantics_provider.as_ref() else {
16853 return false;
16854 };
16855
16856 let mut supports = false;
16857 self.buffer().update(cx, |this, cx| {
16858 this.for_each_buffer(|buffer| {
16859 supports |= provider.supports_inlay_hints(buffer, cx);
16860 });
16861 });
16862
16863 supports
16864 }
16865
16866 pub fn is_focused(&self, window: &Window) -> bool {
16867 self.focus_handle.is_focused(window)
16868 }
16869
16870 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16871 cx.emit(EditorEvent::Focused);
16872
16873 if let Some(descendant) = self
16874 .last_focused_descendant
16875 .take()
16876 .and_then(|descendant| descendant.upgrade())
16877 {
16878 window.focus(&descendant);
16879 } else {
16880 if let Some(blame) = self.blame.as_ref() {
16881 blame.update(cx, GitBlame::focus)
16882 }
16883
16884 self.blink_manager.update(cx, BlinkManager::enable);
16885 self.show_cursor_names(window, cx);
16886 self.buffer.update(cx, |buffer, cx| {
16887 buffer.finalize_last_transaction(cx);
16888 if self.leader_peer_id.is_none() {
16889 buffer.set_active_selections(
16890 &self.selections.disjoint_anchors(),
16891 self.selections.line_mode,
16892 self.cursor_shape,
16893 cx,
16894 );
16895 }
16896 });
16897 }
16898 }
16899
16900 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16901 cx.emit(EditorEvent::FocusedIn)
16902 }
16903
16904 fn handle_focus_out(
16905 &mut self,
16906 event: FocusOutEvent,
16907 _window: &mut Window,
16908 cx: &mut Context<Self>,
16909 ) {
16910 if event.blurred != self.focus_handle {
16911 self.last_focused_descendant = Some(event.blurred);
16912 }
16913 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16914 }
16915
16916 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16917 self.blink_manager.update(cx, BlinkManager::disable);
16918 self.buffer
16919 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16920
16921 if let Some(blame) = self.blame.as_ref() {
16922 blame.update(cx, GitBlame::blur)
16923 }
16924 if !self.hover_state.focused(window, cx) {
16925 hide_hover(self, cx);
16926 }
16927 if !self
16928 .context_menu
16929 .borrow()
16930 .as_ref()
16931 .is_some_and(|context_menu| context_menu.focused(window, cx))
16932 {
16933 self.hide_context_menu(window, cx);
16934 }
16935 self.discard_inline_completion(false, cx);
16936 cx.emit(EditorEvent::Blurred);
16937 cx.notify();
16938 }
16939
16940 pub fn register_action<A: Action>(
16941 &mut self,
16942 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16943 ) -> Subscription {
16944 let id = self.next_editor_action_id.post_inc();
16945 let listener = Arc::new(listener);
16946 self.editor_actions.borrow_mut().insert(
16947 id,
16948 Box::new(move |window, _| {
16949 let listener = listener.clone();
16950 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16951 let action = action.downcast_ref().unwrap();
16952 if phase == DispatchPhase::Bubble {
16953 listener(action, window, cx)
16954 }
16955 })
16956 }),
16957 );
16958
16959 let editor_actions = self.editor_actions.clone();
16960 Subscription::new(move || {
16961 editor_actions.borrow_mut().remove(&id);
16962 })
16963 }
16964
16965 pub fn file_header_size(&self) -> u32 {
16966 FILE_HEADER_HEIGHT
16967 }
16968
16969 pub fn restore(
16970 &mut self,
16971 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16972 window: &mut Window,
16973 cx: &mut Context<Self>,
16974 ) {
16975 let workspace = self.workspace();
16976 let project = self.project.as_ref();
16977 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16978 let mut tasks = Vec::new();
16979 for (buffer_id, changes) in revert_changes {
16980 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16981 buffer.update(cx, |buffer, cx| {
16982 buffer.edit(
16983 changes
16984 .into_iter()
16985 .map(|(range, text)| (range, text.to_string())),
16986 None,
16987 cx,
16988 );
16989 });
16990
16991 if let Some(project) =
16992 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16993 {
16994 project.update(cx, |project, cx| {
16995 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16996 })
16997 }
16998 }
16999 }
17000 tasks
17001 });
17002 cx.spawn_in(window, async move |_, cx| {
17003 for (buffer, task) in save_tasks {
17004 let result = task.await;
17005 if result.is_err() {
17006 let Some(path) = buffer
17007 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17008 .ok()
17009 else {
17010 continue;
17011 };
17012 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17013 let Some(task) = cx
17014 .update_window_entity(&workspace, |workspace, window, cx| {
17015 workspace
17016 .open_path_preview(path, None, false, false, false, window, cx)
17017 })
17018 .ok()
17019 else {
17020 continue;
17021 };
17022 task.await.log_err();
17023 }
17024 }
17025 }
17026 })
17027 .detach();
17028 self.change_selections(None, window, cx, |selections| selections.refresh());
17029 }
17030
17031 pub fn to_pixel_point(
17032 &self,
17033 source: multi_buffer::Anchor,
17034 editor_snapshot: &EditorSnapshot,
17035 window: &mut Window,
17036 ) -> Option<gpui::Point<Pixels>> {
17037 let source_point = source.to_display_point(editor_snapshot);
17038 self.display_to_pixel_point(source_point, editor_snapshot, window)
17039 }
17040
17041 pub fn display_to_pixel_point(
17042 &self,
17043 source: DisplayPoint,
17044 editor_snapshot: &EditorSnapshot,
17045 window: &mut Window,
17046 ) -> Option<gpui::Point<Pixels>> {
17047 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17048 let text_layout_details = self.text_layout_details(window);
17049 let scroll_top = text_layout_details
17050 .scroll_anchor
17051 .scroll_position(editor_snapshot)
17052 .y;
17053
17054 if source.row().as_f32() < scroll_top.floor() {
17055 return None;
17056 }
17057 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17058 let source_y = line_height * (source.row().as_f32() - scroll_top);
17059 Some(gpui::Point::new(source_x, source_y))
17060 }
17061
17062 pub fn has_visible_completions_menu(&self) -> bool {
17063 !self.edit_prediction_preview_is_active()
17064 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17065 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17066 })
17067 }
17068
17069 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17070 self.addons
17071 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17072 }
17073
17074 pub fn unregister_addon<T: Addon>(&mut self) {
17075 self.addons.remove(&std::any::TypeId::of::<T>());
17076 }
17077
17078 pub fn addon<T: Addon>(&self) -> Option<&T> {
17079 let type_id = std::any::TypeId::of::<T>();
17080 self.addons
17081 .get(&type_id)
17082 .and_then(|item| item.to_any().downcast_ref::<T>())
17083 }
17084
17085 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17086 let text_layout_details = self.text_layout_details(window);
17087 let style = &text_layout_details.editor_style;
17088 let font_id = window.text_system().resolve_font(&style.text.font());
17089 let font_size = style.text.font_size.to_pixels(window.rem_size());
17090 let line_height = style.text.line_height_in_pixels(window.rem_size());
17091 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17092
17093 gpui::Size::new(em_width, line_height)
17094 }
17095
17096 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17097 self.load_diff_task.clone()
17098 }
17099
17100 fn read_selections_from_db(
17101 &mut self,
17102 item_id: u64,
17103 workspace_id: WorkspaceId,
17104 window: &mut Window,
17105 cx: &mut Context<Editor>,
17106 ) {
17107 if !self.is_singleton(cx)
17108 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
17109 {
17110 return;
17111 }
17112 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
17113 return;
17114 };
17115 if selections.is_empty() {
17116 return;
17117 }
17118
17119 let snapshot = self.buffer.read(cx).snapshot(cx);
17120 self.change_selections(None, window, cx, |s| {
17121 s.select_ranges(selections.into_iter().map(|(start, end)| {
17122 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
17123 }));
17124 });
17125 }
17126}
17127
17128fn insert_extra_newline_brackets(
17129 buffer: &MultiBufferSnapshot,
17130 range: Range<usize>,
17131 language: &language::LanguageScope,
17132) -> bool {
17133 let leading_whitespace_len = buffer
17134 .reversed_chars_at(range.start)
17135 .take_while(|c| c.is_whitespace() && *c != '\n')
17136 .map(|c| c.len_utf8())
17137 .sum::<usize>();
17138 let trailing_whitespace_len = buffer
17139 .chars_at(range.end)
17140 .take_while(|c| c.is_whitespace() && *c != '\n')
17141 .map(|c| c.len_utf8())
17142 .sum::<usize>();
17143 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17144
17145 language.brackets().any(|(pair, enabled)| {
17146 let pair_start = pair.start.trim_end();
17147 let pair_end = pair.end.trim_start();
17148
17149 enabled
17150 && pair.newline
17151 && buffer.contains_str_at(range.end, pair_end)
17152 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17153 })
17154}
17155
17156fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17157 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17158 [(buffer, range, _)] => (*buffer, range.clone()),
17159 _ => return false,
17160 };
17161 let pair = {
17162 let mut result: Option<BracketMatch> = None;
17163
17164 for pair in buffer
17165 .all_bracket_ranges(range.clone())
17166 .filter(move |pair| {
17167 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17168 })
17169 {
17170 let len = pair.close_range.end - pair.open_range.start;
17171
17172 if let Some(existing) = &result {
17173 let existing_len = existing.close_range.end - existing.open_range.start;
17174 if len > existing_len {
17175 continue;
17176 }
17177 }
17178
17179 result = Some(pair);
17180 }
17181
17182 result
17183 };
17184 let Some(pair) = pair else {
17185 return false;
17186 };
17187 pair.newline_only
17188 && buffer
17189 .chars_for_range(pair.open_range.end..range.start)
17190 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17191 .all(|c| c.is_whitespace() && c != '\n')
17192}
17193
17194fn get_uncommitted_diff_for_buffer(
17195 project: &Entity<Project>,
17196 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17197 buffer: Entity<MultiBuffer>,
17198 cx: &mut App,
17199) -> Task<()> {
17200 let mut tasks = Vec::new();
17201 project.update(cx, |project, cx| {
17202 for buffer in buffers {
17203 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17204 }
17205 });
17206 cx.spawn(async move |cx| {
17207 let diffs = future::join_all(tasks).await;
17208 buffer
17209 .update(cx, |buffer, cx| {
17210 for diff in diffs.into_iter().flatten() {
17211 buffer.add_diff(diff, cx);
17212 }
17213 })
17214 .ok();
17215 })
17216}
17217
17218fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17219 let tab_size = tab_size.get() as usize;
17220 let mut width = offset;
17221
17222 for ch in text.chars() {
17223 width += if ch == '\t' {
17224 tab_size - (width % tab_size)
17225 } else {
17226 1
17227 };
17228 }
17229
17230 width - offset
17231}
17232
17233#[cfg(test)]
17234mod tests {
17235 use super::*;
17236
17237 #[test]
17238 fn test_string_size_with_expanded_tabs() {
17239 let nz = |val| NonZeroU32::new(val).unwrap();
17240 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17241 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17242 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17243 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17244 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17245 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17246 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17247 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17248 }
17249}
17250
17251/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17252struct WordBreakingTokenizer<'a> {
17253 input: &'a str,
17254}
17255
17256impl<'a> WordBreakingTokenizer<'a> {
17257 fn new(input: &'a str) -> Self {
17258 Self { input }
17259 }
17260}
17261
17262fn is_char_ideographic(ch: char) -> bool {
17263 use unicode_script::Script::*;
17264 use unicode_script::UnicodeScript;
17265 matches!(ch.script(), Han | Tangut | Yi)
17266}
17267
17268fn is_grapheme_ideographic(text: &str) -> bool {
17269 text.chars().any(is_char_ideographic)
17270}
17271
17272fn is_grapheme_whitespace(text: &str) -> bool {
17273 text.chars().any(|x| x.is_whitespace())
17274}
17275
17276fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17277 text.chars().next().map_or(false, |ch| {
17278 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17279 })
17280}
17281
17282#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17283enum WordBreakToken<'a> {
17284 Word { token: &'a str, grapheme_len: usize },
17285 InlineWhitespace { token: &'a str, grapheme_len: usize },
17286 Newline,
17287}
17288
17289impl<'a> Iterator for WordBreakingTokenizer<'a> {
17290 /// Yields a span, the count of graphemes in the token, and whether it was
17291 /// whitespace. Note that it also breaks at word boundaries.
17292 type Item = WordBreakToken<'a>;
17293
17294 fn next(&mut self) -> Option<Self::Item> {
17295 use unicode_segmentation::UnicodeSegmentation;
17296 if self.input.is_empty() {
17297 return None;
17298 }
17299
17300 let mut iter = self.input.graphemes(true).peekable();
17301 let mut offset = 0;
17302 let mut grapheme_len = 0;
17303 if let Some(first_grapheme) = iter.next() {
17304 let is_newline = first_grapheme == "\n";
17305 let is_whitespace = is_grapheme_whitespace(first_grapheme);
17306 offset += first_grapheme.len();
17307 grapheme_len += 1;
17308 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17309 if let Some(grapheme) = iter.peek().copied() {
17310 if should_stay_with_preceding_ideograph(grapheme) {
17311 offset += grapheme.len();
17312 grapheme_len += 1;
17313 }
17314 }
17315 } else {
17316 let mut words = self.input[offset..].split_word_bound_indices().peekable();
17317 let mut next_word_bound = words.peek().copied();
17318 if next_word_bound.map_or(false, |(i, _)| i == 0) {
17319 next_word_bound = words.next();
17320 }
17321 while let Some(grapheme) = iter.peek().copied() {
17322 if next_word_bound.map_or(false, |(i, _)| i == offset) {
17323 break;
17324 };
17325 if is_grapheme_whitespace(grapheme) != is_whitespace
17326 || (grapheme == "\n") != is_newline
17327 {
17328 break;
17329 };
17330 offset += grapheme.len();
17331 grapheme_len += 1;
17332 iter.next();
17333 }
17334 }
17335 let token = &self.input[..offset];
17336 self.input = &self.input[offset..];
17337 if token == "\n" {
17338 Some(WordBreakToken::Newline)
17339 } else if is_whitespace {
17340 Some(WordBreakToken::InlineWhitespace {
17341 token,
17342 grapheme_len,
17343 })
17344 } else {
17345 Some(WordBreakToken::Word {
17346 token,
17347 grapheme_len,
17348 })
17349 }
17350 } else {
17351 None
17352 }
17353 }
17354}
17355
17356#[test]
17357fn test_word_breaking_tokenizer() {
17358 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17359 ("", &[]),
17360 (" ", &[whitespace(" ", 2)]),
17361 ("Ʒ", &[word("Ʒ", 1)]),
17362 ("Ǽ", &[word("Ǽ", 1)]),
17363 ("⋑", &[word("⋑", 1)]),
17364 ("⋑⋑", &[word("⋑⋑", 2)]),
17365 (
17366 "原理,进而",
17367 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
17368 ),
17369 (
17370 "hello world",
17371 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17372 ),
17373 (
17374 "hello, world",
17375 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17376 ),
17377 (
17378 " hello world",
17379 &[
17380 whitespace(" ", 2),
17381 word("hello", 5),
17382 whitespace(" ", 1),
17383 word("world", 5),
17384 ],
17385 ),
17386 (
17387 "这是什么 \n 钢笔",
17388 &[
17389 word("这", 1),
17390 word("是", 1),
17391 word("什", 1),
17392 word("么", 1),
17393 whitespace(" ", 1),
17394 newline(),
17395 whitespace(" ", 1),
17396 word("钢", 1),
17397 word("笔", 1),
17398 ],
17399 ),
17400 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
17401 ];
17402
17403 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17404 WordBreakToken::Word {
17405 token,
17406 grapheme_len,
17407 }
17408 }
17409
17410 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17411 WordBreakToken::InlineWhitespace {
17412 token,
17413 grapheme_len,
17414 }
17415 }
17416
17417 fn newline() -> WordBreakToken<'static> {
17418 WordBreakToken::Newline
17419 }
17420
17421 for (input, result) in tests {
17422 assert_eq!(
17423 WordBreakingTokenizer::new(input)
17424 .collect::<Vec<_>>()
17425 .as_slice(),
17426 *result,
17427 );
17428 }
17429}
17430
17431fn wrap_with_prefix(
17432 line_prefix: String,
17433 unwrapped_text: String,
17434 wrap_column: usize,
17435 tab_size: NonZeroU32,
17436 preserve_existing_whitespace: bool,
17437) -> String {
17438 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17439 let mut wrapped_text = String::new();
17440 let mut current_line = line_prefix.clone();
17441
17442 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17443 let mut current_line_len = line_prefix_len;
17444 let mut in_whitespace = false;
17445 for token in tokenizer {
17446 let have_preceding_whitespace = in_whitespace;
17447 match token {
17448 WordBreakToken::Word {
17449 token,
17450 grapheme_len,
17451 } => {
17452 in_whitespace = false;
17453 if current_line_len + grapheme_len > wrap_column
17454 && current_line_len != line_prefix_len
17455 {
17456 wrapped_text.push_str(current_line.trim_end());
17457 wrapped_text.push('\n');
17458 current_line.truncate(line_prefix.len());
17459 current_line_len = line_prefix_len;
17460 }
17461 current_line.push_str(token);
17462 current_line_len += grapheme_len;
17463 }
17464 WordBreakToken::InlineWhitespace {
17465 mut token,
17466 mut grapheme_len,
17467 } => {
17468 in_whitespace = true;
17469 if have_preceding_whitespace && !preserve_existing_whitespace {
17470 continue;
17471 }
17472 if !preserve_existing_whitespace {
17473 token = " ";
17474 grapheme_len = 1;
17475 }
17476 if current_line_len + grapheme_len > wrap_column {
17477 wrapped_text.push_str(current_line.trim_end());
17478 wrapped_text.push('\n');
17479 current_line.truncate(line_prefix.len());
17480 current_line_len = line_prefix_len;
17481 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17482 current_line.push_str(token);
17483 current_line_len += grapheme_len;
17484 }
17485 }
17486 WordBreakToken::Newline => {
17487 in_whitespace = true;
17488 if preserve_existing_whitespace {
17489 wrapped_text.push_str(current_line.trim_end());
17490 wrapped_text.push('\n');
17491 current_line.truncate(line_prefix.len());
17492 current_line_len = line_prefix_len;
17493 } else if have_preceding_whitespace {
17494 continue;
17495 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17496 {
17497 wrapped_text.push_str(current_line.trim_end());
17498 wrapped_text.push('\n');
17499 current_line.truncate(line_prefix.len());
17500 current_line_len = line_prefix_len;
17501 } else if current_line_len != line_prefix_len {
17502 current_line.push(' ');
17503 current_line_len += 1;
17504 }
17505 }
17506 }
17507 }
17508
17509 if !current_line.is_empty() {
17510 wrapped_text.push_str(¤t_line);
17511 }
17512 wrapped_text
17513}
17514
17515#[test]
17516fn test_wrap_with_prefix() {
17517 assert_eq!(
17518 wrap_with_prefix(
17519 "# ".to_string(),
17520 "abcdefg".to_string(),
17521 4,
17522 NonZeroU32::new(4).unwrap(),
17523 false,
17524 ),
17525 "# abcdefg"
17526 );
17527 assert_eq!(
17528 wrap_with_prefix(
17529 "".to_string(),
17530 "\thello world".to_string(),
17531 8,
17532 NonZeroU32::new(4).unwrap(),
17533 false,
17534 ),
17535 "hello\nworld"
17536 );
17537 assert_eq!(
17538 wrap_with_prefix(
17539 "// ".to_string(),
17540 "xx \nyy zz aa bb cc".to_string(),
17541 12,
17542 NonZeroU32::new(4).unwrap(),
17543 false,
17544 ),
17545 "// xx yy zz\n// aa bb cc"
17546 );
17547 assert_eq!(
17548 wrap_with_prefix(
17549 String::new(),
17550 "这是什么 \n 钢笔".to_string(),
17551 3,
17552 NonZeroU32::new(4).unwrap(),
17553 false,
17554 ),
17555 "这是什\n么 钢\n笔"
17556 );
17557}
17558
17559pub trait CollaborationHub {
17560 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17561 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17562 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17563}
17564
17565impl CollaborationHub for Entity<Project> {
17566 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17567 self.read(cx).collaborators()
17568 }
17569
17570 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17571 self.read(cx).user_store().read(cx).participant_indices()
17572 }
17573
17574 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17575 let this = self.read(cx);
17576 let user_ids = this.collaborators().values().map(|c| c.user_id);
17577 this.user_store().read_with(cx, |user_store, cx| {
17578 user_store.participant_names(user_ids, cx)
17579 })
17580 }
17581}
17582
17583pub trait SemanticsProvider {
17584 fn hover(
17585 &self,
17586 buffer: &Entity<Buffer>,
17587 position: text::Anchor,
17588 cx: &mut App,
17589 ) -> Option<Task<Vec<project::Hover>>>;
17590
17591 fn inlay_hints(
17592 &self,
17593 buffer_handle: Entity<Buffer>,
17594 range: Range<text::Anchor>,
17595 cx: &mut App,
17596 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17597
17598 fn resolve_inlay_hint(
17599 &self,
17600 hint: InlayHint,
17601 buffer_handle: Entity<Buffer>,
17602 server_id: LanguageServerId,
17603 cx: &mut App,
17604 ) -> Option<Task<anyhow::Result<InlayHint>>>;
17605
17606 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17607
17608 fn document_highlights(
17609 &self,
17610 buffer: &Entity<Buffer>,
17611 position: text::Anchor,
17612 cx: &mut App,
17613 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17614
17615 fn definitions(
17616 &self,
17617 buffer: &Entity<Buffer>,
17618 position: text::Anchor,
17619 kind: GotoDefinitionKind,
17620 cx: &mut App,
17621 ) -> Option<Task<Result<Vec<LocationLink>>>>;
17622
17623 fn range_for_rename(
17624 &self,
17625 buffer: &Entity<Buffer>,
17626 position: text::Anchor,
17627 cx: &mut App,
17628 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17629
17630 fn perform_rename(
17631 &self,
17632 buffer: &Entity<Buffer>,
17633 position: text::Anchor,
17634 new_name: String,
17635 cx: &mut App,
17636 ) -> Option<Task<Result<ProjectTransaction>>>;
17637}
17638
17639pub trait CompletionProvider {
17640 fn completions(
17641 &self,
17642 buffer: &Entity<Buffer>,
17643 buffer_position: text::Anchor,
17644 trigger: CompletionContext,
17645 window: &mut Window,
17646 cx: &mut Context<Editor>,
17647 ) -> Task<Result<Option<Vec<Completion>>>>;
17648
17649 fn resolve_completions(
17650 &self,
17651 buffer: Entity<Buffer>,
17652 completion_indices: Vec<usize>,
17653 completions: Rc<RefCell<Box<[Completion]>>>,
17654 cx: &mut Context<Editor>,
17655 ) -> Task<Result<bool>>;
17656
17657 fn apply_additional_edits_for_completion(
17658 &self,
17659 _buffer: Entity<Buffer>,
17660 _completions: Rc<RefCell<Box<[Completion]>>>,
17661 _completion_index: usize,
17662 _push_to_history: bool,
17663 _cx: &mut Context<Editor>,
17664 ) -> Task<Result<Option<language::Transaction>>> {
17665 Task::ready(Ok(None))
17666 }
17667
17668 fn is_completion_trigger(
17669 &self,
17670 buffer: &Entity<Buffer>,
17671 position: language::Anchor,
17672 text: &str,
17673 trigger_in_words: bool,
17674 cx: &mut Context<Editor>,
17675 ) -> bool;
17676
17677 fn sort_completions(&self) -> bool {
17678 true
17679 }
17680}
17681
17682pub trait CodeActionProvider {
17683 fn id(&self) -> Arc<str>;
17684
17685 fn code_actions(
17686 &self,
17687 buffer: &Entity<Buffer>,
17688 range: Range<text::Anchor>,
17689 window: &mut Window,
17690 cx: &mut App,
17691 ) -> Task<Result<Vec<CodeAction>>>;
17692
17693 fn apply_code_action(
17694 &self,
17695 buffer_handle: Entity<Buffer>,
17696 action: CodeAction,
17697 excerpt_id: ExcerptId,
17698 push_to_history: bool,
17699 window: &mut Window,
17700 cx: &mut App,
17701 ) -> Task<Result<ProjectTransaction>>;
17702}
17703
17704impl CodeActionProvider for Entity<Project> {
17705 fn id(&self) -> Arc<str> {
17706 "project".into()
17707 }
17708
17709 fn code_actions(
17710 &self,
17711 buffer: &Entity<Buffer>,
17712 range: Range<text::Anchor>,
17713 _window: &mut Window,
17714 cx: &mut App,
17715 ) -> Task<Result<Vec<CodeAction>>> {
17716 self.update(cx, |project, cx| {
17717 let code_lens = project.code_lens(buffer, range.clone(), cx);
17718 let code_actions = project.code_actions(buffer, range, None, cx);
17719 cx.background_spawn(async move {
17720 let (code_lens, code_actions) = join(code_lens, code_actions).await;
17721 Ok(code_lens
17722 .context("code lens fetch")?
17723 .into_iter()
17724 .chain(code_actions.context("code action fetch")?)
17725 .collect())
17726 })
17727 })
17728 }
17729
17730 fn apply_code_action(
17731 &self,
17732 buffer_handle: Entity<Buffer>,
17733 action: CodeAction,
17734 _excerpt_id: ExcerptId,
17735 push_to_history: bool,
17736 _window: &mut Window,
17737 cx: &mut App,
17738 ) -> Task<Result<ProjectTransaction>> {
17739 self.update(cx, |project, cx| {
17740 project.apply_code_action(buffer_handle, action, push_to_history, cx)
17741 })
17742 }
17743}
17744
17745fn snippet_completions(
17746 project: &Project,
17747 buffer: &Entity<Buffer>,
17748 buffer_position: text::Anchor,
17749 cx: &mut App,
17750) -> Task<Result<Vec<Completion>>> {
17751 let language = buffer.read(cx).language_at(buffer_position);
17752 let language_name = language.as_ref().map(|language| language.lsp_id());
17753 let snippet_store = project.snippets().read(cx);
17754 let snippets = snippet_store.snippets_for(language_name, cx);
17755
17756 if snippets.is_empty() {
17757 return Task::ready(Ok(vec![]));
17758 }
17759 let snapshot = buffer.read(cx).text_snapshot();
17760 let chars: String = snapshot
17761 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17762 .collect();
17763
17764 let scope = language.map(|language| language.default_scope());
17765 let executor = cx.background_executor().clone();
17766
17767 cx.background_spawn(async move {
17768 let classifier = CharClassifier::new(scope).for_completion(true);
17769 let mut last_word = chars
17770 .chars()
17771 .take_while(|c| classifier.is_word(*c))
17772 .collect::<String>();
17773 last_word = last_word.chars().rev().collect();
17774
17775 if last_word.is_empty() {
17776 return Ok(vec![]);
17777 }
17778
17779 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17780 let to_lsp = |point: &text::Anchor| {
17781 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17782 point_to_lsp(end)
17783 };
17784 let lsp_end = to_lsp(&buffer_position);
17785
17786 let candidates = snippets
17787 .iter()
17788 .enumerate()
17789 .flat_map(|(ix, snippet)| {
17790 snippet
17791 .prefix
17792 .iter()
17793 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17794 })
17795 .collect::<Vec<StringMatchCandidate>>();
17796
17797 let mut matches = fuzzy::match_strings(
17798 &candidates,
17799 &last_word,
17800 last_word.chars().any(|c| c.is_uppercase()),
17801 100,
17802 &Default::default(),
17803 executor,
17804 )
17805 .await;
17806
17807 // Remove all candidates where the query's start does not match the start of any word in the candidate
17808 if let Some(query_start) = last_word.chars().next() {
17809 matches.retain(|string_match| {
17810 split_words(&string_match.string).any(|word| {
17811 // Check that the first codepoint of the word as lowercase matches the first
17812 // codepoint of the query as lowercase
17813 word.chars()
17814 .flat_map(|codepoint| codepoint.to_lowercase())
17815 .zip(query_start.to_lowercase())
17816 .all(|(word_cp, query_cp)| word_cp == query_cp)
17817 })
17818 });
17819 }
17820
17821 let matched_strings = matches
17822 .into_iter()
17823 .map(|m| m.string)
17824 .collect::<HashSet<_>>();
17825
17826 let result: Vec<Completion> = snippets
17827 .into_iter()
17828 .filter_map(|snippet| {
17829 let matching_prefix = snippet
17830 .prefix
17831 .iter()
17832 .find(|prefix| matched_strings.contains(*prefix))?;
17833 let start = as_offset - last_word.len();
17834 let start = snapshot.anchor_before(start);
17835 let range = start..buffer_position;
17836 let lsp_start = to_lsp(&start);
17837 let lsp_range = lsp::Range {
17838 start: lsp_start,
17839 end: lsp_end,
17840 };
17841 Some(Completion {
17842 old_range: range,
17843 new_text: snippet.body.clone(),
17844 source: CompletionSource::Lsp {
17845 server_id: LanguageServerId(usize::MAX),
17846 resolved: true,
17847 lsp_completion: Box::new(lsp::CompletionItem {
17848 label: snippet.prefix.first().unwrap().clone(),
17849 kind: Some(CompletionItemKind::SNIPPET),
17850 label_details: snippet.description.as_ref().map(|description| {
17851 lsp::CompletionItemLabelDetails {
17852 detail: Some(description.clone()),
17853 description: None,
17854 }
17855 }),
17856 insert_text_format: Some(InsertTextFormat::SNIPPET),
17857 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17858 lsp::InsertReplaceEdit {
17859 new_text: snippet.body.clone(),
17860 insert: lsp_range,
17861 replace: lsp_range,
17862 },
17863 )),
17864 filter_text: Some(snippet.body.clone()),
17865 sort_text: Some(char::MAX.to_string()),
17866 ..lsp::CompletionItem::default()
17867 }),
17868 lsp_defaults: None,
17869 },
17870 label: CodeLabel {
17871 text: matching_prefix.clone(),
17872 runs: Vec::new(),
17873 filter_range: 0..matching_prefix.len(),
17874 },
17875 documentation: snippet
17876 .description
17877 .clone()
17878 .map(|description| CompletionDocumentation::SingleLine(description.into())),
17879 confirm: None,
17880 })
17881 })
17882 .collect();
17883
17884 Ok(result)
17885 })
17886}
17887
17888impl CompletionProvider for Entity<Project> {
17889 fn completions(
17890 &self,
17891 buffer: &Entity<Buffer>,
17892 buffer_position: text::Anchor,
17893 options: CompletionContext,
17894 _window: &mut Window,
17895 cx: &mut Context<Editor>,
17896 ) -> Task<Result<Option<Vec<Completion>>>> {
17897 self.update(cx, |project, cx| {
17898 let snippets = snippet_completions(project, buffer, buffer_position, cx);
17899 let project_completions = project.completions(buffer, buffer_position, options, cx);
17900 cx.background_spawn(async move {
17901 let snippets_completions = snippets.await?;
17902 match project_completions.await? {
17903 Some(mut completions) => {
17904 completions.extend(snippets_completions);
17905 Ok(Some(completions))
17906 }
17907 None => {
17908 if snippets_completions.is_empty() {
17909 Ok(None)
17910 } else {
17911 Ok(Some(snippets_completions))
17912 }
17913 }
17914 }
17915 })
17916 })
17917 }
17918
17919 fn resolve_completions(
17920 &self,
17921 buffer: Entity<Buffer>,
17922 completion_indices: Vec<usize>,
17923 completions: Rc<RefCell<Box<[Completion]>>>,
17924 cx: &mut Context<Editor>,
17925 ) -> Task<Result<bool>> {
17926 self.update(cx, |project, cx| {
17927 project.lsp_store().update(cx, |lsp_store, cx| {
17928 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17929 })
17930 })
17931 }
17932
17933 fn apply_additional_edits_for_completion(
17934 &self,
17935 buffer: Entity<Buffer>,
17936 completions: Rc<RefCell<Box<[Completion]>>>,
17937 completion_index: usize,
17938 push_to_history: bool,
17939 cx: &mut Context<Editor>,
17940 ) -> Task<Result<Option<language::Transaction>>> {
17941 self.update(cx, |project, cx| {
17942 project.lsp_store().update(cx, |lsp_store, cx| {
17943 lsp_store.apply_additional_edits_for_completion(
17944 buffer,
17945 completions,
17946 completion_index,
17947 push_to_history,
17948 cx,
17949 )
17950 })
17951 })
17952 }
17953
17954 fn is_completion_trigger(
17955 &self,
17956 buffer: &Entity<Buffer>,
17957 position: language::Anchor,
17958 text: &str,
17959 trigger_in_words: bool,
17960 cx: &mut Context<Editor>,
17961 ) -> bool {
17962 let mut chars = text.chars();
17963 let char = if let Some(char) = chars.next() {
17964 char
17965 } else {
17966 return false;
17967 };
17968 if chars.next().is_some() {
17969 return false;
17970 }
17971
17972 let buffer = buffer.read(cx);
17973 let snapshot = buffer.snapshot();
17974 if !snapshot.settings_at(position, cx).show_completions_on_input {
17975 return false;
17976 }
17977 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17978 if trigger_in_words && classifier.is_word(char) {
17979 return true;
17980 }
17981
17982 buffer.completion_triggers().contains(text)
17983 }
17984}
17985
17986impl SemanticsProvider for Entity<Project> {
17987 fn hover(
17988 &self,
17989 buffer: &Entity<Buffer>,
17990 position: text::Anchor,
17991 cx: &mut App,
17992 ) -> Option<Task<Vec<project::Hover>>> {
17993 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17994 }
17995
17996 fn document_highlights(
17997 &self,
17998 buffer: &Entity<Buffer>,
17999 position: text::Anchor,
18000 cx: &mut App,
18001 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18002 Some(self.update(cx, |project, cx| {
18003 project.document_highlights(buffer, position, cx)
18004 }))
18005 }
18006
18007 fn definitions(
18008 &self,
18009 buffer: &Entity<Buffer>,
18010 position: text::Anchor,
18011 kind: GotoDefinitionKind,
18012 cx: &mut App,
18013 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18014 Some(self.update(cx, |project, cx| match kind {
18015 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18016 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18017 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18018 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18019 }))
18020 }
18021
18022 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18023 // TODO: make this work for remote projects
18024 self.update(cx, |this, cx| {
18025 buffer.update(cx, |buffer, cx| {
18026 this.any_language_server_supports_inlay_hints(buffer, cx)
18027 })
18028 })
18029 }
18030
18031 fn inlay_hints(
18032 &self,
18033 buffer_handle: Entity<Buffer>,
18034 range: Range<text::Anchor>,
18035 cx: &mut App,
18036 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18037 Some(self.update(cx, |project, cx| {
18038 project.inlay_hints(buffer_handle, range, cx)
18039 }))
18040 }
18041
18042 fn resolve_inlay_hint(
18043 &self,
18044 hint: InlayHint,
18045 buffer_handle: Entity<Buffer>,
18046 server_id: LanguageServerId,
18047 cx: &mut App,
18048 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18049 Some(self.update(cx, |project, cx| {
18050 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18051 }))
18052 }
18053
18054 fn range_for_rename(
18055 &self,
18056 buffer: &Entity<Buffer>,
18057 position: text::Anchor,
18058 cx: &mut App,
18059 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18060 Some(self.update(cx, |project, cx| {
18061 let buffer = buffer.clone();
18062 let task = project.prepare_rename(buffer.clone(), position, cx);
18063 cx.spawn(async move |_, cx| {
18064 Ok(match task.await? {
18065 PrepareRenameResponse::Success(range) => Some(range),
18066 PrepareRenameResponse::InvalidPosition => None,
18067 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18068 // Fallback on using TreeSitter info to determine identifier range
18069 buffer.update(cx, |buffer, _| {
18070 let snapshot = buffer.snapshot();
18071 let (range, kind) = snapshot.surrounding_word(position);
18072 if kind != Some(CharKind::Word) {
18073 return None;
18074 }
18075 Some(
18076 snapshot.anchor_before(range.start)
18077 ..snapshot.anchor_after(range.end),
18078 )
18079 })?
18080 }
18081 })
18082 })
18083 }))
18084 }
18085
18086 fn perform_rename(
18087 &self,
18088 buffer: &Entity<Buffer>,
18089 position: text::Anchor,
18090 new_name: String,
18091 cx: &mut App,
18092 ) -> Option<Task<Result<ProjectTransaction>>> {
18093 Some(self.update(cx, |project, cx| {
18094 project.perform_rename(buffer.clone(), position, new_name, cx)
18095 }))
18096 }
18097}
18098
18099fn inlay_hint_settings(
18100 location: Anchor,
18101 snapshot: &MultiBufferSnapshot,
18102 cx: &mut Context<Editor>,
18103) -> InlayHintSettings {
18104 let file = snapshot.file_at(location);
18105 let language = snapshot.language_at(location).map(|l| l.name());
18106 language_settings(language, file, cx).inlay_hints
18107}
18108
18109fn consume_contiguous_rows(
18110 contiguous_row_selections: &mut Vec<Selection<Point>>,
18111 selection: &Selection<Point>,
18112 display_map: &DisplaySnapshot,
18113 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18114) -> (MultiBufferRow, MultiBufferRow) {
18115 contiguous_row_selections.push(selection.clone());
18116 let start_row = MultiBufferRow(selection.start.row);
18117 let mut end_row = ending_row(selection, display_map);
18118
18119 while let Some(next_selection) = selections.peek() {
18120 if next_selection.start.row <= end_row.0 {
18121 end_row = ending_row(next_selection, display_map);
18122 contiguous_row_selections.push(selections.next().unwrap().clone());
18123 } else {
18124 break;
18125 }
18126 }
18127 (start_row, end_row)
18128}
18129
18130fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18131 if next_selection.end.column > 0 || next_selection.is_empty() {
18132 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18133 } else {
18134 MultiBufferRow(next_selection.end.row)
18135 }
18136}
18137
18138impl EditorSnapshot {
18139 pub fn remote_selections_in_range<'a>(
18140 &'a self,
18141 range: &'a Range<Anchor>,
18142 collaboration_hub: &dyn CollaborationHub,
18143 cx: &'a App,
18144 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18145 let participant_names = collaboration_hub.user_names(cx);
18146 let participant_indices = collaboration_hub.user_participant_indices(cx);
18147 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18148 let collaborators_by_replica_id = collaborators_by_peer_id
18149 .iter()
18150 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18151 .collect::<HashMap<_, _>>();
18152 self.buffer_snapshot
18153 .selections_in_range(range, false)
18154 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18155 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18156 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18157 let user_name = participant_names.get(&collaborator.user_id).cloned();
18158 Some(RemoteSelection {
18159 replica_id,
18160 selection,
18161 cursor_shape,
18162 line_mode,
18163 participant_index,
18164 peer_id: collaborator.peer_id,
18165 user_name,
18166 })
18167 })
18168 }
18169
18170 pub fn hunks_for_ranges(
18171 &self,
18172 ranges: impl IntoIterator<Item = Range<Point>>,
18173 ) -> Vec<MultiBufferDiffHunk> {
18174 let mut hunks = Vec::new();
18175 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18176 HashMap::default();
18177 for query_range in ranges {
18178 let query_rows =
18179 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18180 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18181 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18182 ) {
18183 // Include deleted hunks that are adjacent to the query range, because
18184 // otherwise they would be missed.
18185 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18186 if hunk.status().is_deleted() {
18187 intersects_range |= hunk.row_range.start == query_rows.end;
18188 intersects_range |= hunk.row_range.end == query_rows.start;
18189 }
18190 if intersects_range {
18191 if !processed_buffer_rows
18192 .entry(hunk.buffer_id)
18193 .or_default()
18194 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18195 {
18196 continue;
18197 }
18198 hunks.push(hunk);
18199 }
18200 }
18201 }
18202
18203 hunks
18204 }
18205
18206 fn display_diff_hunks_for_rows<'a>(
18207 &'a self,
18208 display_rows: Range<DisplayRow>,
18209 folded_buffers: &'a HashSet<BufferId>,
18210 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18211 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18212 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18213
18214 self.buffer_snapshot
18215 .diff_hunks_in_range(buffer_start..buffer_end)
18216 .filter_map(|hunk| {
18217 if folded_buffers.contains(&hunk.buffer_id) {
18218 return None;
18219 }
18220
18221 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18222 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18223
18224 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18225 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18226
18227 let display_hunk = if hunk_display_start.column() != 0 {
18228 DisplayDiffHunk::Folded {
18229 display_row: hunk_display_start.row(),
18230 }
18231 } else {
18232 let mut end_row = hunk_display_end.row();
18233 if hunk_display_end.column() > 0 {
18234 end_row.0 += 1;
18235 }
18236 let is_created_file = hunk.is_created_file();
18237 DisplayDiffHunk::Unfolded {
18238 status: hunk.status(),
18239 diff_base_byte_range: hunk.diff_base_byte_range,
18240 display_row_range: hunk_display_start.row()..end_row,
18241 multi_buffer_range: Anchor::range_in_buffer(
18242 hunk.excerpt_id,
18243 hunk.buffer_id,
18244 hunk.buffer_range,
18245 ),
18246 is_created_file,
18247 }
18248 };
18249
18250 Some(display_hunk)
18251 })
18252 }
18253
18254 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18255 self.display_snapshot.buffer_snapshot.language_at(position)
18256 }
18257
18258 pub fn is_focused(&self) -> bool {
18259 self.is_focused
18260 }
18261
18262 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18263 self.placeholder_text.as_ref()
18264 }
18265
18266 pub fn scroll_position(&self) -> gpui::Point<f32> {
18267 self.scroll_anchor.scroll_position(&self.display_snapshot)
18268 }
18269
18270 fn gutter_dimensions(
18271 &self,
18272 font_id: FontId,
18273 font_size: Pixels,
18274 max_line_number_width: Pixels,
18275 cx: &App,
18276 ) -> Option<GutterDimensions> {
18277 if !self.show_gutter {
18278 return None;
18279 }
18280
18281 let descent = cx.text_system().descent(font_id, font_size);
18282 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18283 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18284
18285 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18286 matches!(
18287 ProjectSettings::get_global(cx).git.git_gutter,
18288 Some(GitGutterSetting::TrackedFiles)
18289 )
18290 });
18291 let gutter_settings = EditorSettings::get_global(cx).gutter;
18292 let show_line_numbers = self
18293 .show_line_numbers
18294 .unwrap_or(gutter_settings.line_numbers);
18295 let line_gutter_width = if show_line_numbers {
18296 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18297 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18298 max_line_number_width.max(min_width_for_number_on_gutter)
18299 } else {
18300 0.0.into()
18301 };
18302
18303 let show_code_actions = self
18304 .show_code_actions
18305 .unwrap_or(gutter_settings.code_actions);
18306
18307 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18308 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18309
18310 let git_blame_entries_width =
18311 self.git_blame_gutter_max_author_length
18312 .map(|max_author_length| {
18313 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18314
18315 /// The number of characters to dedicate to gaps and margins.
18316 const SPACING_WIDTH: usize = 4;
18317
18318 let max_char_count = max_author_length
18319 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18320 + ::git::SHORT_SHA_LENGTH
18321 + MAX_RELATIVE_TIMESTAMP.len()
18322 + SPACING_WIDTH;
18323
18324 em_advance * max_char_count
18325 });
18326
18327 let is_singleton = self.buffer_snapshot.is_singleton();
18328
18329 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18330 left_padding += if !is_singleton {
18331 em_width * 4.0
18332 } else if show_code_actions || show_runnables || show_breakpoints {
18333 em_width * 3.0
18334 } else if show_git_gutter && show_line_numbers {
18335 em_width * 2.0
18336 } else if show_git_gutter || show_line_numbers {
18337 em_width
18338 } else {
18339 px(0.)
18340 };
18341
18342 let shows_folds = is_singleton && gutter_settings.folds;
18343
18344 let right_padding = if shows_folds && show_line_numbers {
18345 em_width * 4.0
18346 } else if shows_folds || (!is_singleton && show_line_numbers) {
18347 em_width * 3.0
18348 } else if show_line_numbers {
18349 em_width
18350 } else {
18351 px(0.)
18352 };
18353
18354 Some(GutterDimensions {
18355 left_padding,
18356 right_padding,
18357 width: line_gutter_width + left_padding + right_padding,
18358 margin: -descent,
18359 git_blame_entries_width,
18360 })
18361 }
18362
18363 pub fn render_crease_toggle(
18364 &self,
18365 buffer_row: MultiBufferRow,
18366 row_contains_cursor: bool,
18367 editor: Entity<Editor>,
18368 window: &mut Window,
18369 cx: &mut App,
18370 ) -> Option<AnyElement> {
18371 let folded = self.is_line_folded(buffer_row);
18372 let mut is_foldable = false;
18373
18374 if let Some(crease) = self
18375 .crease_snapshot
18376 .query_row(buffer_row, &self.buffer_snapshot)
18377 {
18378 is_foldable = true;
18379 match crease {
18380 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18381 if let Some(render_toggle) = render_toggle {
18382 let toggle_callback =
18383 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18384 if folded {
18385 editor.update(cx, |editor, cx| {
18386 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18387 });
18388 } else {
18389 editor.update(cx, |editor, cx| {
18390 editor.unfold_at(
18391 &crate::UnfoldAt { buffer_row },
18392 window,
18393 cx,
18394 )
18395 });
18396 }
18397 });
18398 return Some((render_toggle)(
18399 buffer_row,
18400 folded,
18401 toggle_callback,
18402 window,
18403 cx,
18404 ));
18405 }
18406 }
18407 }
18408 }
18409
18410 is_foldable |= self.starts_indent(buffer_row);
18411
18412 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18413 Some(
18414 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18415 .toggle_state(folded)
18416 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18417 if folded {
18418 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18419 } else {
18420 this.fold_at(&FoldAt { buffer_row }, window, cx);
18421 }
18422 }))
18423 .into_any_element(),
18424 )
18425 } else {
18426 None
18427 }
18428 }
18429
18430 pub fn render_crease_trailer(
18431 &self,
18432 buffer_row: MultiBufferRow,
18433 window: &mut Window,
18434 cx: &mut App,
18435 ) -> Option<AnyElement> {
18436 let folded = self.is_line_folded(buffer_row);
18437 if let Crease::Inline { render_trailer, .. } = self
18438 .crease_snapshot
18439 .query_row(buffer_row, &self.buffer_snapshot)?
18440 {
18441 let render_trailer = render_trailer.as_ref()?;
18442 Some(render_trailer(buffer_row, folded, window, cx))
18443 } else {
18444 None
18445 }
18446 }
18447}
18448
18449impl Deref for EditorSnapshot {
18450 type Target = DisplaySnapshot;
18451
18452 fn deref(&self) -> &Self::Target {
18453 &self.display_snapshot
18454 }
18455}
18456
18457#[derive(Clone, Debug, PartialEq, Eq)]
18458pub enum EditorEvent {
18459 InputIgnored {
18460 text: Arc<str>,
18461 },
18462 InputHandled {
18463 utf16_range_to_replace: Option<Range<isize>>,
18464 text: Arc<str>,
18465 },
18466 ExcerptsAdded {
18467 buffer: Entity<Buffer>,
18468 predecessor: ExcerptId,
18469 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18470 },
18471 ExcerptsRemoved {
18472 ids: Vec<ExcerptId>,
18473 },
18474 BufferFoldToggled {
18475 ids: Vec<ExcerptId>,
18476 folded: bool,
18477 },
18478 ExcerptsEdited {
18479 ids: Vec<ExcerptId>,
18480 },
18481 ExcerptsExpanded {
18482 ids: Vec<ExcerptId>,
18483 },
18484 BufferEdited,
18485 Edited {
18486 transaction_id: clock::Lamport,
18487 },
18488 Reparsed(BufferId),
18489 Focused,
18490 FocusedIn,
18491 Blurred,
18492 DirtyChanged,
18493 Saved,
18494 TitleChanged,
18495 DiffBaseChanged,
18496 SelectionsChanged {
18497 local: bool,
18498 },
18499 ScrollPositionChanged {
18500 local: bool,
18501 autoscroll: bool,
18502 },
18503 Closed,
18504 TransactionUndone {
18505 transaction_id: clock::Lamport,
18506 },
18507 TransactionBegun {
18508 transaction_id: clock::Lamport,
18509 },
18510 Reloaded,
18511 CursorShapeChanged,
18512}
18513
18514impl EventEmitter<EditorEvent> for Editor {}
18515
18516impl Focusable for Editor {
18517 fn focus_handle(&self, _cx: &App) -> FocusHandle {
18518 self.focus_handle.clone()
18519 }
18520}
18521
18522impl Render for Editor {
18523 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18524 let settings = ThemeSettings::get_global(cx);
18525
18526 let mut text_style = match self.mode {
18527 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18528 color: cx.theme().colors().editor_foreground,
18529 font_family: settings.ui_font.family.clone(),
18530 font_features: settings.ui_font.features.clone(),
18531 font_fallbacks: settings.ui_font.fallbacks.clone(),
18532 font_size: rems(0.875).into(),
18533 font_weight: settings.ui_font.weight,
18534 line_height: relative(settings.buffer_line_height.value()),
18535 ..Default::default()
18536 },
18537 EditorMode::Full => TextStyle {
18538 color: cx.theme().colors().editor_foreground,
18539 font_family: settings.buffer_font.family.clone(),
18540 font_features: settings.buffer_font.features.clone(),
18541 font_fallbacks: settings.buffer_font.fallbacks.clone(),
18542 font_size: settings.buffer_font_size(cx).into(),
18543 font_weight: settings.buffer_font.weight,
18544 line_height: relative(settings.buffer_line_height.value()),
18545 ..Default::default()
18546 },
18547 };
18548 if let Some(text_style_refinement) = &self.text_style_refinement {
18549 text_style.refine(text_style_refinement)
18550 }
18551
18552 let background = match self.mode {
18553 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18554 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18555 EditorMode::Full => cx.theme().colors().editor_background,
18556 };
18557
18558 EditorElement::new(
18559 &cx.entity(),
18560 EditorStyle {
18561 background,
18562 local_player: cx.theme().players().local(),
18563 text: text_style,
18564 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18565 syntax: cx.theme().syntax().clone(),
18566 status: cx.theme().status().clone(),
18567 inlay_hints_style: make_inlay_hints_style(cx),
18568 inline_completion_styles: make_suggestion_styles(cx),
18569 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18570 },
18571 )
18572 }
18573}
18574
18575impl EntityInputHandler for Editor {
18576 fn text_for_range(
18577 &mut self,
18578 range_utf16: Range<usize>,
18579 adjusted_range: &mut Option<Range<usize>>,
18580 _: &mut Window,
18581 cx: &mut Context<Self>,
18582 ) -> Option<String> {
18583 let snapshot = self.buffer.read(cx).read(cx);
18584 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18585 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18586 if (start.0..end.0) != range_utf16 {
18587 adjusted_range.replace(start.0..end.0);
18588 }
18589 Some(snapshot.text_for_range(start..end).collect())
18590 }
18591
18592 fn selected_text_range(
18593 &mut self,
18594 ignore_disabled_input: bool,
18595 _: &mut Window,
18596 cx: &mut Context<Self>,
18597 ) -> Option<UTF16Selection> {
18598 // Prevent the IME menu from appearing when holding down an alphabetic key
18599 // while input is disabled.
18600 if !ignore_disabled_input && !self.input_enabled {
18601 return None;
18602 }
18603
18604 let selection = self.selections.newest::<OffsetUtf16>(cx);
18605 let range = selection.range();
18606
18607 Some(UTF16Selection {
18608 range: range.start.0..range.end.0,
18609 reversed: selection.reversed,
18610 })
18611 }
18612
18613 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18614 let snapshot = self.buffer.read(cx).read(cx);
18615 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18616 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18617 }
18618
18619 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18620 self.clear_highlights::<InputComposition>(cx);
18621 self.ime_transaction.take();
18622 }
18623
18624 fn replace_text_in_range(
18625 &mut self,
18626 range_utf16: Option<Range<usize>>,
18627 text: &str,
18628 window: &mut Window,
18629 cx: &mut Context<Self>,
18630 ) {
18631 if !self.input_enabled {
18632 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18633 return;
18634 }
18635
18636 self.transact(window, cx, |this, window, cx| {
18637 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
18638 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18639 Some(this.selection_replacement_ranges(range_utf16, cx))
18640 } else {
18641 this.marked_text_ranges(cx)
18642 };
18643
18644 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
18645 let newest_selection_id = this.selections.newest_anchor().id;
18646 this.selections
18647 .all::<OffsetUtf16>(cx)
18648 .iter()
18649 .zip(ranges_to_replace.iter())
18650 .find_map(|(selection, range)| {
18651 if selection.id == newest_selection_id {
18652 Some(
18653 (range.start.0 as isize - selection.head().0 as isize)
18654 ..(range.end.0 as isize - selection.head().0 as isize),
18655 )
18656 } else {
18657 None
18658 }
18659 })
18660 });
18661
18662 cx.emit(EditorEvent::InputHandled {
18663 utf16_range_to_replace: range_to_replace,
18664 text: text.into(),
18665 });
18666
18667 if let Some(new_selected_ranges) = new_selected_ranges {
18668 this.change_selections(None, window, cx, |selections| {
18669 selections.select_ranges(new_selected_ranges)
18670 });
18671 this.backspace(&Default::default(), window, cx);
18672 }
18673
18674 this.handle_input(text, window, cx);
18675 });
18676
18677 if let Some(transaction) = self.ime_transaction {
18678 self.buffer.update(cx, |buffer, cx| {
18679 buffer.group_until_transaction(transaction, cx);
18680 });
18681 }
18682
18683 self.unmark_text(window, cx);
18684 }
18685
18686 fn replace_and_mark_text_in_range(
18687 &mut self,
18688 range_utf16: Option<Range<usize>>,
18689 text: &str,
18690 new_selected_range_utf16: Option<Range<usize>>,
18691 window: &mut Window,
18692 cx: &mut Context<Self>,
18693 ) {
18694 if !self.input_enabled {
18695 return;
18696 }
18697
18698 let transaction = self.transact(window, cx, |this, window, cx| {
18699 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18700 let snapshot = this.buffer.read(cx).read(cx);
18701 if let Some(relative_range_utf16) = range_utf16.as_ref() {
18702 for marked_range in &mut marked_ranges {
18703 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18704 marked_range.start.0 += relative_range_utf16.start;
18705 marked_range.start =
18706 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18707 marked_range.end =
18708 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18709 }
18710 }
18711 Some(marked_ranges)
18712 } else if let Some(range_utf16) = range_utf16 {
18713 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18714 Some(this.selection_replacement_ranges(range_utf16, cx))
18715 } else {
18716 None
18717 };
18718
18719 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18720 let newest_selection_id = this.selections.newest_anchor().id;
18721 this.selections
18722 .all::<OffsetUtf16>(cx)
18723 .iter()
18724 .zip(ranges_to_replace.iter())
18725 .find_map(|(selection, range)| {
18726 if selection.id == newest_selection_id {
18727 Some(
18728 (range.start.0 as isize - selection.head().0 as isize)
18729 ..(range.end.0 as isize - selection.head().0 as isize),
18730 )
18731 } else {
18732 None
18733 }
18734 })
18735 });
18736
18737 cx.emit(EditorEvent::InputHandled {
18738 utf16_range_to_replace: range_to_replace,
18739 text: text.into(),
18740 });
18741
18742 if let Some(ranges) = ranges_to_replace {
18743 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18744 }
18745
18746 let marked_ranges = {
18747 let snapshot = this.buffer.read(cx).read(cx);
18748 this.selections
18749 .disjoint_anchors()
18750 .iter()
18751 .map(|selection| {
18752 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18753 })
18754 .collect::<Vec<_>>()
18755 };
18756
18757 if text.is_empty() {
18758 this.unmark_text(window, cx);
18759 } else {
18760 this.highlight_text::<InputComposition>(
18761 marked_ranges.clone(),
18762 HighlightStyle {
18763 underline: Some(UnderlineStyle {
18764 thickness: px(1.),
18765 color: None,
18766 wavy: false,
18767 }),
18768 ..Default::default()
18769 },
18770 cx,
18771 );
18772 }
18773
18774 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18775 let use_autoclose = this.use_autoclose;
18776 let use_auto_surround = this.use_auto_surround;
18777 this.set_use_autoclose(false);
18778 this.set_use_auto_surround(false);
18779 this.handle_input(text, window, cx);
18780 this.set_use_autoclose(use_autoclose);
18781 this.set_use_auto_surround(use_auto_surround);
18782
18783 if let Some(new_selected_range) = new_selected_range_utf16 {
18784 let snapshot = this.buffer.read(cx).read(cx);
18785 let new_selected_ranges = marked_ranges
18786 .into_iter()
18787 .map(|marked_range| {
18788 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18789 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18790 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18791 snapshot.clip_offset_utf16(new_start, Bias::Left)
18792 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18793 })
18794 .collect::<Vec<_>>();
18795
18796 drop(snapshot);
18797 this.change_selections(None, window, cx, |selections| {
18798 selections.select_ranges(new_selected_ranges)
18799 });
18800 }
18801 });
18802
18803 self.ime_transaction = self.ime_transaction.or(transaction);
18804 if let Some(transaction) = self.ime_transaction {
18805 self.buffer.update(cx, |buffer, cx| {
18806 buffer.group_until_transaction(transaction, cx);
18807 });
18808 }
18809
18810 if self.text_highlights::<InputComposition>(cx).is_none() {
18811 self.ime_transaction.take();
18812 }
18813 }
18814
18815 fn bounds_for_range(
18816 &mut self,
18817 range_utf16: Range<usize>,
18818 element_bounds: gpui::Bounds<Pixels>,
18819 window: &mut Window,
18820 cx: &mut Context<Self>,
18821 ) -> Option<gpui::Bounds<Pixels>> {
18822 let text_layout_details = self.text_layout_details(window);
18823 let gpui::Size {
18824 width: em_width,
18825 height: line_height,
18826 } = self.character_size(window);
18827
18828 let snapshot = self.snapshot(window, cx);
18829 let scroll_position = snapshot.scroll_position();
18830 let scroll_left = scroll_position.x * em_width;
18831
18832 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18833 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18834 + self.gutter_dimensions.width
18835 + self.gutter_dimensions.margin;
18836 let y = line_height * (start.row().as_f32() - scroll_position.y);
18837
18838 Some(Bounds {
18839 origin: element_bounds.origin + point(x, y),
18840 size: size(em_width, line_height),
18841 })
18842 }
18843
18844 fn character_index_for_point(
18845 &mut self,
18846 point: gpui::Point<Pixels>,
18847 _window: &mut Window,
18848 _cx: &mut Context<Self>,
18849 ) -> Option<usize> {
18850 let position_map = self.last_position_map.as_ref()?;
18851 if !position_map.text_hitbox.contains(&point) {
18852 return None;
18853 }
18854 let display_point = position_map.point_for_position(point).previous_valid;
18855 let anchor = position_map
18856 .snapshot
18857 .display_point_to_anchor(display_point, Bias::Left);
18858 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18859 Some(utf16_offset.0)
18860 }
18861}
18862
18863trait SelectionExt {
18864 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18865 fn spanned_rows(
18866 &self,
18867 include_end_if_at_line_start: bool,
18868 map: &DisplaySnapshot,
18869 ) -> Range<MultiBufferRow>;
18870}
18871
18872impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18873 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18874 let start = self
18875 .start
18876 .to_point(&map.buffer_snapshot)
18877 .to_display_point(map);
18878 let end = self
18879 .end
18880 .to_point(&map.buffer_snapshot)
18881 .to_display_point(map);
18882 if self.reversed {
18883 end..start
18884 } else {
18885 start..end
18886 }
18887 }
18888
18889 fn spanned_rows(
18890 &self,
18891 include_end_if_at_line_start: bool,
18892 map: &DisplaySnapshot,
18893 ) -> Range<MultiBufferRow> {
18894 let start = self.start.to_point(&map.buffer_snapshot);
18895 let mut end = self.end.to_point(&map.buffer_snapshot);
18896 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18897 end.row -= 1;
18898 }
18899
18900 let buffer_start = map.prev_line_boundary(start).0;
18901 let buffer_end = map.next_line_boundary(end).0;
18902 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18903 }
18904}
18905
18906impl<T: InvalidationRegion> InvalidationStack<T> {
18907 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18908 where
18909 S: Clone + ToOffset,
18910 {
18911 while let Some(region) = self.last() {
18912 let all_selections_inside_invalidation_ranges =
18913 if selections.len() == region.ranges().len() {
18914 selections
18915 .iter()
18916 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18917 .all(|(selection, invalidation_range)| {
18918 let head = selection.head().to_offset(buffer);
18919 invalidation_range.start <= head && invalidation_range.end >= head
18920 })
18921 } else {
18922 false
18923 };
18924
18925 if all_selections_inside_invalidation_ranges {
18926 break;
18927 } else {
18928 self.pop();
18929 }
18930 }
18931 }
18932}
18933
18934impl<T> Default for InvalidationStack<T> {
18935 fn default() -> Self {
18936 Self(Default::default())
18937 }
18938}
18939
18940impl<T> Deref for InvalidationStack<T> {
18941 type Target = Vec<T>;
18942
18943 fn deref(&self) -> &Self::Target {
18944 &self.0
18945 }
18946}
18947
18948impl<T> DerefMut for InvalidationStack<T> {
18949 fn deref_mut(&mut self) -> &mut Self::Target {
18950 &mut self.0
18951 }
18952}
18953
18954impl InvalidationRegion for SnippetState {
18955 fn ranges(&self) -> &[Range<Anchor>] {
18956 &self.ranges[self.active_index]
18957 }
18958}
18959
18960pub fn diagnostic_block_renderer(
18961 diagnostic: Diagnostic,
18962 max_message_rows: Option<u8>,
18963 allow_closing: bool,
18964) -> RenderBlock {
18965 let (text_without_backticks, code_ranges) =
18966 highlight_diagnostic_message(&diagnostic, max_message_rows);
18967
18968 Arc::new(move |cx: &mut BlockContext| {
18969 let group_id: SharedString = cx.block_id.to_string().into();
18970
18971 let mut text_style = cx.window.text_style().clone();
18972 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18973 let theme_settings = ThemeSettings::get_global(cx);
18974 text_style.font_family = theme_settings.buffer_font.family.clone();
18975 text_style.font_style = theme_settings.buffer_font.style;
18976 text_style.font_features = theme_settings.buffer_font.features.clone();
18977 text_style.font_weight = theme_settings.buffer_font.weight;
18978
18979 let multi_line_diagnostic = diagnostic.message.contains('\n');
18980
18981 let buttons = |diagnostic: &Diagnostic| {
18982 if multi_line_diagnostic {
18983 v_flex()
18984 } else {
18985 h_flex()
18986 }
18987 .when(allow_closing, |div| {
18988 div.children(diagnostic.is_primary.then(|| {
18989 IconButton::new("close-block", IconName::XCircle)
18990 .icon_color(Color::Muted)
18991 .size(ButtonSize::Compact)
18992 .style(ButtonStyle::Transparent)
18993 .visible_on_hover(group_id.clone())
18994 .on_click(move |_click, window, cx| {
18995 window.dispatch_action(Box::new(Cancel), cx)
18996 })
18997 .tooltip(|window, cx| {
18998 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
18999 })
19000 }))
19001 })
19002 .child(
19003 IconButton::new("copy-block", IconName::Copy)
19004 .icon_color(Color::Muted)
19005 .size(ButtonSize::Compact)
19006 .style(ButtonStyle::Transparent)
19007 .visible_on_hover(group_id.clone())
19008 .on_click({
19009 let message = diagnostic.message.clone();
19010 move |_click, _, cx| {
19011 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19012 }
19013 })
19014 .tooltip(Tooltip::text("Copy diagnostic message")),
19015 )
19016 };
19017
19018 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19019 AvailableSpace::min_size(),
19020 cx.window,
19021 cx.app,
19022 );
19023
19024 h_flex()
19025 .id(cx.block_id)
19026 .group(group_id.clone())
19027 .relative()
19028 .size_full()
19029 .block_mouse_down()
19030 .pl(cx.gutter_dimensions.width)
19031 .w(cx.max_width - cx.gutter_dimensions.full_width())
19032 .child(
19033 div()
19034 .flex()
19035 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19036 .flex_shrink(),
19037 )
19038 .child(buttons(&diagnostic))
19039 .child(div().flex().flex_shrink_0().child(
19040 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19041 &text_style,
19042 code_ranges.iter().map(|range| {
19043 (
19044 range.clone(),
19045 HighlightStyle {
19046 font_weight: Some(FontWeight::BOLD),
19047 ..Default::default()
19048 },
19049 )
19050 }),
19051 ),
19052 ))
19053 .into_any_element()
19054 })
19055}
19056
19057fn inline_completion_edit_text(
19058 current_snapshot: &BufferSnapshot,
19059 edits: &[(Range<Anchor>, String)],
19060 edit_preview: &EditPreview,
19061 include_deletions: bool,
19062 cx: &App,
19063) -> HighlightedText {
19064 let edits = edits
19065 .iter()
19066 .map(|(anchor, text)| {
19067 (
19068 anchor.start.text_anchor..anchor.end.text_anchor,
19069 text.clone(),
19070 )
19071 })
19072 .collect::<Vec<_>>();
19073
19074 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19075}
19076
19077pub fn highlight_diagnostic_message(
19078 diagnostic: &Diagnostic,
19079 mut max_message_rows: Option<u8>,
19080) -> (SharedString, Vec<Range<usize>>) {
19081 let mut text_without_backticks = String::new();
19082 let mut code_ranges = Vec::new();
19083
19084 if let Some(source) = &diagnostic.source {
19085 text_without_backticks.push_str(source);
19086 code_ranges.push(0..source.len());
19087 text_without_backticks.push_str(": ");
19088 }
19089
19090 let mut prev_offset = 0;
19091 let mut in_code_block = false;
19092 let has_row_limit = max_message_rows.is_some();
19093 let mut newline_indices = diagnostic
19094 .message
19095 .match_indices('\n')
19096 .filter(|_| has_row_limit)
19097 .map(|(ix, _)| ix)
19098 .fuse()
19099 .peekable();
19100
19101 for (quote_ix, _) in diagnostic
19102 .message
19103 .match_indices('`')
19104 .chain([(diagnostic.message.len(), "")])
19105 {
19106 let mut first_newline_ix = None;
19107 let mut last_newline_ix = None;
19108 while let Some(newline_ix) = newline_indices.peek() {
19109 if *newline_ix < quote_ix {
19110 if first_newline_ix.is_none() {
19111 first_newline_ix = Some(*newline_ix);
19112 }
19113 last_newline_ix = Some(*newline_ix);
19114
19115 if let Some(rows_left) = &mut max_message_rows {
19116 if *rows_left == 0 {
19117 break;
19118 } else {
19119 *rows_left -= 1;
19120 }
19121 }
19122 let _ = newline_indices.next();
19123 } else {
19124 break;
19125 }
19126 }
19127 let prev_len = text_without_backticks.len();
19128 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19129 text_without_backticks.push_str(new_text);
19130 if in_code_block {
19131 code_ranges.push(prev_len..text_without_backticks.len());
19132 }
19133 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19134 in_code_block = !in_code_block;
19135 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19136 text_without_backticks.push_str("...");
19137 break;
19138 }
19139 }
19140
19141 (text_without_backticks.into(), code_ranges)
19142}
19143
19144fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19145 match severity {
19146 DiagnosticSeverity::ERROR => colors.error,
19147 DiagnosticSeverity::WARNING => colors.warning,
19148 DiagnosticSeverity::INFORMATION => colors.info,
19149 DiagnosticSeverity::HINT => colors.info,
19150 _ => colors.ignored,
19151 }
19152}
19153
19154pub fn styled_runs_for_code_label<'a>(
19155 label: &'a CodeLabel,
19156 syntax_theme: &'a theme::SyntaxTheme,
19157) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19158 let fade_out = HighlightStyle {
19159 fade_out: Some(0.35),
19160 ..Default::default()
19161 };
19162
19163 let mut prev_end = label.filter_range.end;
19164 label
19165 .runs
19166 .iter()
19167 .enumerate()
19168 .flat_map(move |(ix, (range, highlight_id))| {
19169 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19170 style
19171 } else {
19172 return Default::default();
19173 };
19174 let mut muted_style = style;
19175 muted_style.highlight(fade_out);
19176
19177 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19178 if range.start >= label.filter_range.end {
19179 if range.start > prev_end {
19180 runs.push((prev_end..range.start, fade_out));
19181 }
19182 runs.push((range.clone(), muted_style));
19183 } else if range.end <= label.filter_range.end {
19184 runs.push((range.clone(), style));
19185 } else {
19186 runs.push((range.start..label.filter_range.end, style));
19187 runs.push((label.filter_range.end..range.end, muted_style));
19188 }
19189 prev_end = cmp::max(prev_end, range.end);
19190
19191 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19192 runs.push((prev_end..label.text.len(), fade_out));
19193 }
19194
19195 runs
19196 })
19197}
19198
19199pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19200 let mut prev_index = 0;
19201 let mut prev_codepoint: Option<char> = None;
19202 text.char_indices()
19203 .chain([(text.len(), '\0')])
19204 .filter_map(move |(index, codepoint)| {
19205 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19206 let is_boundary = index == text.len()
19207 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19208 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19209 if is_boundary {
19210 let chunk = &text[prev_index..index];
19211 prev_index = index;
19212 Some(chunk)
19213 } else {
19214 None
19215 }
19216 })
19217}
19218
19219pub trait RangeToAnchorExt: Sized {
19220 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19221
19222 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19223 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19224 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19225 }
19226}
19227
19228impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19229 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19230 let start_offset = self.start.to_offset(snapshot);
19231 let end_offset = self.end.to_offset(snapshot);
19232 if start_offset == end_offset {
19233 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19234 } else {
19235 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19236 }
19237 }
19238}
19239
19240pub trait RowExt {
19241 fn as_f32(&self) -> f32;
19242
19243 fn next_row(&self) -> Self;
19244
19245 fn previous_row(&self) -> Self;
19246
19247 fn minus(&self, other: Self) -> u32;
19248}
19249
19250impl RowExt for DisplayRow {
19251 fn as_f32(&self) -> f32 {
19252 self.0 as f32
19253 }
19254
19255 fn next_row(&self) -> Self {
19256 Self(self.0 + 1)
19257 }
19258
19259 fn previous_row(&self) -> Self {
19260 Self(self.0.saturating_sub(1))
19261 }
19262
19263 fn minus(&self, other: Self) -> u32 {
19264 self.0 - other.0
19265 }
19266}
19267
19268impl RowExt for MultiBufferRow {
19269 fn as_f32(&self) -> f32 {
19270 self.0 as f32
19271 }
19272
19273 fn next_row(&self) -> Self {
19274 Self(self.0 + 1)
19275 }
19276
19277 fn previous_row(&self) -> Self {
19278 Self(self.0.saturating_sub(1))
19279 }
19280
19281 fn minus(&self, other: Self) -> u32 {
19282 self.0 - other.0
19283 }
19284}
19285
19286trait RowRangeExt {
19287 type Row;
19288
19289 fn len(&self) -> usize;
19290
19291 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19292}
19293
19294impl RowRangeExt for Range<MultiBufferRow> {
19295 type Row = MultiBufferRow;
19296
19297 fn len(&self) -> usize {
19298 (self.end.0 - self.start.0) as usize
19299 }
19300
19301 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19302 (self.start.0..self.end.0).map(MultiBufferRow)
19303 }
19304}
19305
19306impl RowRangeExt for Range<DisplayRow> {
19307 type Row = DisplayRow;
19308
19309 fn len(&self) -> usize {
19310 (self.end.0 - self.start.0) as usize
19311 }
19312
19313 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19314 (self.start.0..self.end.0).map(DisplayRow)
19315 }
19316}
19317
19318/// If select range has more than one line, we
19319/// just point the cursor to range.start.
19320fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19321 if range.start.row == range.end.row {
19322 range
19323 } else {
19324 range.start..range.start
19325 }
19326}
19327pub struct KillRing(ClipboardItem);
19328impl Global for KillRing {}
19329
19330const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19331
19332struct BreakpointPromptEditor {
19333 pub(crate) prompt: Entity<Editor>,
19334 editor: WeakEntity<Editor>,
19335 breakpoint_anchor: Anchor,
19336 kind: BreakpointKind,
19337 block_ids: HashSet<CustomBlockId>,
19338 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19339 _subscriptions: Vec<Subscription>,
19340}
19341
19342impl BreakpointPromptEditor {
19343 const MAX_LINES: u8 = 4;
19344
19345 fn new(
19346 editor: WeakEntity<Editor>,
19347 breakpoint_anchor: Anchor,
19348 kind: BreakpointKind,
19349 window: &mut Window,
19350 cx: &mut Context<Self>,
19351 ) -> Self {
19352 let buffer = cx.new(|cx| {
19353 Buffer::local(
19354 kind.log_message()
19355 .map(|msg| msg.to_string())
19356 .unwrap_or_default(),
19357 cx,
19358 )
19359 });
19360 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19361
19362 let prompt = cx.new(|cx| {
19363 let mut prompt = Editor::new(
19364 EditorMode::AutoHeight {
19365 max_lines: Self::MAX_LINES as usize,
19366 },
19367 buffer,
19368 None,
19369 window,
19370 cx,
19371 );
19372 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19373 prompt.set_show_cursor_when_unfocused(false, cx);
19374 prompt.set_placeholder_text(
19375 "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19376 cx,
19377 );
19378
19379 prompt
19380 });
19381
19382 Self {
19383 prompt,
19384 editor,
19385 breakpoint_anchor,
19386 kind,
19387 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19388 block_ids: Default::default(),
19389 _subscriptions: vec![],
19390 }
19391 }
19392
19393 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19394 self.block_ids.extend(block_ids)
19395 }
19396
19397 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19398 if let Some(editor) = self.editor.upgrade() {
19399 let log_message = self
19400 .prompt
19401 .read(cx)
19402 .buffer
19403 .read(cx)
19404 .as_singleton()
19405 .expect("A multi buffer in breakpoint prompt isn't possible")
19406 .read(cx)
19407 .as_rope()
19408 .to_string();
19409
19410 editor.update(cx, |editor, cx| {
19411 editor.edit_breakpoint_at_anchor(
19412 self.breakpoint_anchor,
19413 self.kind.clone(),
19414 BreakpointEditAction::EditLogMessage(log_message.into()),
19415 cx,
19416 );
19417
19418 editor.remove_blocks(self.block_ids.clone(), None, cx);
19419 cx.focus_self(window);
19420 });
19421 }
19422 }
19423
19424 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19425 self.editor
19426 .update(cx, |editor, cx| {
19427 editor.remove_blocks(self.block_ids.clone(), None, cx);
19428 window.focus(&editor.focus_handle);
19429 })
19430 .log_err();
19431 }
19432
19433 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19434 let settings = ThemeSettings::get_global(cx);
19435 let text_style = TextStyle {
19436 color: if self.prompt.read(cx).read_only(cx) {
19437 cx.theme().colors().text_disabled
19438 } else {
19439 cx.theme().colors().text
19440 },
19441 font_family: settings.buffer_font.family.clone(),
19442 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19443 font_size: settings.buffer_font_size(cx).into(),
19444 font_weight: settings.buffer_font.weight,
19445 line_height: relative(settings.buffer_line_height.value()),
19446 ..Default::default()
19447 };
19448 EditorElement::new(
19449 &self.prompt,
19450 EditorStyle {
19451 background: cx.theme().colors().editor_background,
19452 local_player: cx.theme().players().local(),
19453 text: text_style,
19454 ..Default::default()
19455 },
19456 )
19457 }
19458}
19459
19460impl Render for BreakpointPromptEditor {
19461 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19462 let gutter_dimensions = *self.gutter_dimensions.lock();
19463 h_flex()
19464 .key_context("Editor")
19465 .bg(cx.theme().colors().editor_background)
19466 .border_y_1()
19467 .border_color(cx.theme().status().info_border)
19468 .size_full()
19469 .py(window.line_height() / 2.5)
19470 .on_action(cx.listener(Self::confirm))
19471 .on_action(cx.listener(Self::cancel))
19472 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19473 .child(div().flex_1().child(self.render_prompt_editor(cx)))
19474 }
19475}
19476
19477impl Focusable for BreakpointPromptEditor {
19478 fn focus_handle(&self, cx: &App) -> FocusHandle {
19479 self.prompt.focus_handle(cx)
19480 }
19481}
19482
19483fn all_edits_insertions_or_deletions(
19484 edits: &Vec<(Range<Anchor>, String)>,
19485 snapshot: &MultiBufferSnapshot,
19486) -> bool {
19487 let mut all_insertions = true;
19488 let mut all_deletions = true;
19489
19490 for (range, new_text) in edits.iter() {
19491 let range_is_empty = range.to_offset(&snapshot).is_empty();
19492 let text_is_empty = new_text.is_empty();
19493
19494 if range_is_empty != text_is_empty {
19495 if range_is_empty {
19496 all_deletions = false;
19497 } else {
19498 all_insertions = false;
19499 }
19500 } else {
19501 return false;
19502 }
19503
19504 if !all_insertions && !all_deletions {
19505 return false;
19506 }
19507 }
19508 all_insertions || all_deletions
19509}
19510
19511struct MissingEditPredictionKeybindingTooltip;
19512
19513impl Render for MissingEditPredictionKeybindingTooltip {
19514 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
19515 ui::tooltip_container(window, cx, |container, _, cx| {
19516 container
19517 .flex_shrink_0()
19518 .max_w_80()
19519 .min_h(rems_from_px(124.))
19520 .justify_between()
19521 .child(
19522 v_flex()
19523 .flex_1()
19524 .text_ui_sm(cx)
19525 .child(Label::new("Conflict with Accept Keybinding"))
19526 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19527 )
19528 .child(
19529 h_flex()
19530 .pb_1()
19531 .gap_1()
19532 .items_end()
19533 .w_full()
19534 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19535 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19536 }))
19537 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19538 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19539 })),
19540 )
19541 })
19542 }
19543}
19544
19545#[derive(Debug, Clone, Copy, PartialEq)]
19546pub struct LineHighlight {
19547 pub background: Background,
19548 pub border: Option<gpui::Hsla>,
19549}
19550
19551impl From<Hsla> for LineHighlight {
19552 fn from(hsla: Hsla) -> Self {
19553 Self {
19554 background: hsla.into(),
19555 border: None,
19556 }
19557 }
19558}
19559
19560impl From<Background> for LineHighlight {
19561 fn from(background: Background) -> Self {
19562 Self {
19563 background,
19564 border: None,
19565 }
19566 }
19567}