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