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 if buffer.read(cx).file().is_none() {
6056 continue;
6057 }
6058 let breakpoints = breakpoint_store.read(cx).breakpoints(
6059 &buffer,
6060 Some(info.range.context.start..info.range.context.end),
6061 info.buffer.clone(),
6062 cx,
6063 );
6064
6065 // To translate a breakpoint's position within a singular buffer to a multi buffer
6066 // position we need to know it's excerpt starting location, it's position within
6067 // the singular buffer, and if that position is within the excerpt's range.
6068 let excerpt_head = excerpt_ranges
6069 .start
6070 .to_display_point(&snapshot.display_snapshot);
6071
6072 let buffer_start = info
6073 .buffer
6074 .summary_for_anchor::<Point>(&info.range.context.start);
6075
6076 for (anchor, breakpoint) in breakpoints {
6077 let as_row = info.buffer.summary_for_anchor::<Point>(&anchor).row;
6078 let delta = as_row - buffer_start.row;
6079
6080 let position = excerpt_head + DisplayPoint::new(DisplayRow(delta), 0);
6081
6082 let anchor = snapshot.display_point_to_anchor(position, Bias::Left);
6083
6084 breakpoint_display_points.insert(position.row(), (anchor, breakpoint.clone()));
6085 }
6086 }
6087
6088 breakpoint_display_points
6089 }
6090
6091 fn breakpoint_context_menu(
6092 &self,
6093 anchor: Anchor,
6094 kind: Arc<BreakpointKind>,
6095 window: &mut Window,
6096 cx: &mut Context<Self>,
6097 ) -> Entity<ui::ContextMenu> {
6098 let weak_editor = cx.weak_entity();
6099 let focus_handle = self.focus_handle(cx);
6100
6101 let second_entry_msg = if kind.log_message().is_some() {
6102 "Edit Log Breakpoint"
6103 } else {
6104 "Add Log Breakpoint"
6105 };
6106
6107 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6108 menu.on_blur_subscription(Subscription::new(|| {}))
6109 .context(focus_handle)
6110 .entry("Toggle Breakpoint", None, {
6111 let weak_editor = weak_editor.clone();
6112 move |_window, cx| {
6113 weak_editor
6114 .update(cx, |this, cx| {
6115 this.edit_breakpoint_at_anchor(
6116 anchor,
6117 BreakpointKind::Standard,
6118 BreakpointEditAction::Toggle,
6119 cx,
6120 );
6121 })
6122 .log_err();
6123 }
6124 })
6125 .entry(second_entry_msg, None, move |window, cx| {
6126 weak_editor
6127 .update(cx, |this, cx| {
6128 this.add_edit_breakpoint_block(anchor, kind.as_ref(), window, cx);
6129 })
6130 .log_err();
6131 })
6132 })
6133 }
6134
6135 fn render_breakpoint(
6136 &self,
6137 position: Anchor,
6138 row: DisplayRow,
6139 kind: &BreakpointKind,
6140 cx: &mut Context<Self>,
6141 ) -> IconButton {
6142 let color = if self
6143 .gutter_breakpoint_indicator
6144 .is_some_and(|gutter_bp| gutter_bp.row() == row)
6145 {
6146 Color::Hint
6147 } else {
6148 Color::Debugger
6149 };
6150
6151 let icon = match &kind {
6152 BreakpointKind::Standard => ui::IconName::DebugBreakpoint,
6153 BreakpointKind::Log(_) => ui::IconName::DebugLogBreakpoint,
6154 };
6155 let arc_kind = Arc::new(kind.clone());
6156 let arc_kind2 = arc_kind.clone();
6157
6158 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6159 .icon_size(IconSize::XSmall)
6160 .size(ui::ButtonSize::None)
6161 .icon_color(color)
6162 .style(ButtonStyle::Transparent)
6163 .on_click(cx.listener(move |editor, _e, window, cx| {
6164 window.focus(&editor.focus_handle(cx));
6165 editor.edit_breakpoint_at_anchor(
6166 position,
6167 arc_kind.as_ref().clone(),
6168 BreakpointEditAction::Toggle,
6169 cx,
6170 );
6171 }))
6172 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6173 editor.set_breakpoint_context_menu(
6174 row,
6175 Some(position),
6176 arc_kind2.clone(),
6177 event.down.position,
6178 window,
6179 cx,
6180 );
6181 }))
6182 }
6183
6184 fn build_tasks_context(
6185 project: &Entity<Project>,
6186 buffer: &Entity<Buffer>,
6187 buffer_row: u32,
6188 tasks: &Arc<RunnableTasks>,
6189 cx: &mut Context<Self>,
6190 ) -> Task<Option<task::TaskContext>> {
6191 let position = Point::new(buffer_row, tasks.column);
6192 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6193 let location = Location {
6194 buffer: buffer.clone(),
6195 range: range_start..range_start,
6196 };
6197 // Fill in the environmental variables from the tree-sitter captures
6198 let mut captured_task_variables = TaskVariables::default();
6199 for (capture_name, value) in tasks.extra_variables.clone() {
6200 captured_task_variables.insert(
6201 task::VariableName::Custom(capture_name.into()),
6202 value.clone(),
6203 );
6204 }
6205 project.update(cx, |project, cx| {
6206 project.task_store().update(cx, |task_store, cx| {
6207 task_store.task_context_for_location(captured_task_variables, location, cx)
6208 })
6209 })
6210 }
6211
6212 pub fn spawn_nearest_task(
6213 &mut self,
6214 action: &SpawnNearestTask,
6215 window: &mut Window,
6216 cx: &mut Context<Self>,
6217 ) {
6218 let Some((workspace, _)) = self.workspace.clone() else {
6219 return;
6220 };
6221 let Some(project) = self.project.clone() else {
6222 return;
6223 };
6224
6225 // Try to find a closest, enclosing node using tree-sitter that has a
6226 // task
6227 let Some((buffer, buffer_row, tasks)) = self
6228 .find_enclosing_node_task(cx)
6229 // Or find the task that's closest in row-distance.
6230 .or_else(|| self.find_closest_task(cx))
6231 else {
6232 return;
6233 };
6234
6235 let reveal_strategy = action.reveal;
6236 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6237 cx.spawn_in(window, async move |_, cx| {
6238 let context = task_context.await?;
6239 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6240
6241 let resolved = resolved_task.resolved.as_mut()?;
6242 resolved.reveal = reveal_strategy;
6243
6244 workspace
6245 .update(cx, |workspace, cx| {
6246 workspace::tasks::schedule_resolved_task(
6247 workspace,
6248 task_source_kind,
6249 resolved_task,
6250 false,
6251 cx,
6252 );
6253 })
6254 .ok()
6255 })
6256 .detach();
6257 }
6258
6259 fn find_closest_task(
6260 &mut self,
6261 cx: &mut Context<Self>,
6262 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6263 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6264
6265 let ((buffer_id, row), tasks) = self
6266 .tasks
6267 .iter()
6268 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6269
6270 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6271 let tasks = Arc::new(tasks.to_owned());
6272 Some((buffer, *row, tasks))
6273 }
6274
6275 fn find_enclosing_node_task(
6276 &mut self,
6277 cx: &mut Context<Self>,
6278 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6279 let snapshot = self.buffer.read(cx).snapshot(cx);
6280 let offset = self.selections.newest::<usize>(cx).head();
6281 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6282 let buffer_id = excerpt.buffer().remote_id();
6283
6284 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6285 let mut cursor = layer.node().walk();
6286
6287 while cursor.goto_first_child_for_byte(offset).is_some() {
6288 if cursor.node().end_byte() == offset {
6289 cursor.goto_next_sibling();
6290 }
6291 }
6292
6293 // Ascend to the smallest ancestor that contains the range and has a task.
6294 loop {
6295 let node = cursor.node();
6296 let node_range = node.byte_range();
6297 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6298
6299 // Check if this node contains our offset
6300 if node_range.start <= offset && node_range.end >= offset {
6301 // If it contains offset, check for task
6302 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6303 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6304 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6305 }
6306 }
6307
6308 if !cursor.goto_parent() {
6309 break;
6310 }
6311 }
6312 None
6313 }
6314
6315 fn render_run_indicator(
6316 &self,
6317 _style: &EditorStyle,
6318 is_active: bool,
6319 row: DisplayRow,
6320 breakpoint: Option<(Anchor, Breakpoint)>,
6321 cx: &mut Context<Self>,
6322 ) -> IconButton {
6323 let color = Color::Muted;
6324
6325 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6326 let bp_kind = Arc::new(
6327 breakpoint
6328 .map(|(_, bp)| bp.kind)
6329 .unwrap_or(BreakpointKind::Standard),
6330 );
6331
6332 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6333 .shape(ui::IconButtonShape::Square)
6334 .icon_size(IconSize::XSmall)
6335 .icon_color(color)
6336 .toggle_state(is_active)
6337 .on_click(cx.listener(move |editor, _e, window, cx| {
6338 window.focus(&editor.focus_handle(cx));
6339 editor.toggle_code_actions(
6340 &ToggleCodeActions {
6341 deployed_from_indicator: Some(row),
6342 },
6343 window,
6344 cx,
6345 );
6346 }))
6347 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6348 editor.set_breakpoint_context_menu(
6349 row,
6350 position,
6351 bp_kind.clone(),
6352 event.down.position,
6353 window,
6354 cx,
6355 );
6356 }))
6357 }
6358
6359 pub fn context_menu_visible(&self) -> bool {
6360 !self.edit_prediction_preview_is_active()
6361 && self
6362 .context_menu
6363 .borrow()
6364 .as_ref()
6365 .map_or(false, |menu| menu.visible())
6366 }
6367
6368 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6369 self.context_menu
6370 .borrow()
6371 .as_ref()
6372 .map(|menu| menu.origin())
6373 }
6374
6375 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6376 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6377
6378 fn render_edit_prediction_popover(
6379 &mut self,
6380 text_bounds: &Bounds<Pixels>,
6381 content_origin: gpui::Point<Pixels>,
6382 editor_snapshot: &EditorSnapshot,
6383 visible_row_range: Range<DisplayRow>,
6384 scroll_top: f32,
6385 scroll_bottom: f32,
6386 line_layouts: &[LineWithInvisibles],
6387 line_height: Pixels,
6388 scroll_pixel_position: gpui::Point<Pixels>,
6389 newest_selection_head: Option<DisplayPoint>,
6390 editor_width: Pixels,
6391 style: &EditorStyle,
6392 window: &mut Window,
6393 cx: &mut App,
6394 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6395 let active_inline_completion = self.active_inline_completion.as_ref()?;
6396
6397 if self.edit_prediction_visible_in_cursor_popover(true) {
6398 return None;
6399 }
6400
6401 match &active_inline_completion.completion {
6402 InlineCompletion::Move { target, .. } => {
6403 let target_display_point = target.to_display_point(editor_snapshot);
6404
6405 if self.edit_prediction_requires_modifier() {
6406 if !self.edit_prediction_preview_is_active() {
6407 return None;
6408 }
6409
6410 self.render_edit_prediction_modifier_jump_popover(
6411 text_bounds,
6412 content_origin,
6413 visible_row_range,
6414 line_layouts,
6415 line_height,
6416 scroll_pixel_position,
6417 newest_selection_head,
6418 target_display_point,
6419 window,
6420 cx,
6421 )
6422 } else {
6423 self.render_edit_prediction_eager_jump_popover(
6424 text_bounds,
6425 content_origin,
6426 editor_snapshot,
6427 visible_row_range,
6428 scroll_top,
6429 scroll_bottom,
6430 line_height,
6431 scroll_pixel_position,
6432 target_display_point,
6433 editor_width,
6434 window,
6435 cx,
6436 )
6437 }
6438 }
6439 InlineCompletion::Edit {
6440 display_mode: EditDisplayMode::Inline,
6441 ..
6442 } => None,
6443 InlineCompletion::Edit {
6444 display_mode: EditDisplayMode::TabAccept,
6445 edits,
6446 ..
6447 } => {
6448 let range = &edits.first()?.0;
6449 let target_display_point = range.end.to_display_point(editor_snapshot);
6450
6451 self.render_edit_prediction_end_of_line_popover(
6452 "Accept",
6453 editor_snapshot,
6454 visible_row_range,
6455 target_display_point,
6456 line_height,
6457 scroll_pixel_position,
6458 content_origin,
6459 editor_width,
6460 window,
6461 cx,
6462 )
6463 }
6464 InlineCompletion::Edit {
6465 edits,
6466 edit_preview,
6467 display_mode: EditDisplayMode::DiffPopover,
6468 snapshot,
6469 } => self.render_edit_prediction_diff_popover(
6470 text_bounds,
6471 content_origin,
6472 editor_snapshot,
6473 visible_row_range,
6474 line_layouts,
6475 line_height,
6476 scroll_pixel_position,
6477 newest_selection_head,
6478 editor_width,
6479 style,
6480 edits,
6481 edit_preview,
6482 snapshot,
6483 window,
6484 cx,
6485 ),
6486 }
6487 }
6488
6489 fn render_edit_prediction_modifier_jump_popover(
6490 &mut self,
6491 text_bounds: &Bounds<Pixels>,
6492 content_origin: gpui::Point<Pixels>,
6493 visible_row_range: Range<DisplayRow>,
6494 line_layouts: &[LineWithInvisibles],
6495 line_height: Pixels,
6496 scroll_pixel_position: gpui::Point<Pixels>,
6497 newest_selection_head: Option<DisplayPoint>,
6498 target_display_point: DisplayPoint,
6499 window: &mut Window,
6500 cx: &mut App,
6501 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6502 let scrolled_content_origin =
6503 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
6504
6505 const SCROLL_PADDING_Y: Pixels = px(12.);
6506
6507 if target_display_point.row() < visible_row_range.start {
6508 return self.render_edit_prediction_scroll_popover(
6509 |_| SCROLL_PADDING_Y,
6510 IconName::ArrowUp,
6511 visible_row_range,
6512 line_layouts,
6513 newest_selection_head,
6514 scrolled_content_origin,
6515 window,
6516 cx,
6517 );
6518 } else if target_display_point.row() >= visible_row_range.end {
6519 return self.render_edit_prediction_scroll_popover(
6520 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
6521 IconName::ArrowDown,
6522 visible_row_range,
6523 line_layouts,
6524 newest_selection_head,
6525 scrolled_content_origin,
6526 window,
6527 cx,
6528 );
6529 }
6530
6531 const POLE_WIDTH: Pixels = px(2.);
6532
6533 let line_layout =
6534 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
6535 let target_column = target_display_point.column() as usize;
6536
6537 let target_x = line_layout.x_for_index(target_column);
6538 let target_y =
6539 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
6540
6541 let flag_on_right = target_x < text_bounds.size.width / 2.;
6542
6543 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
6544 border_color.l += 0.001;
6545
6546 let mut element = v_flex()
6547 .items_end()
6548 .when(flag_on_right, |el| el.items_start())
6549 .child(if flag_on_right {
6550 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6551 .rounded_bl(px(0.))
6552 .rounded_tl(px(0.))
6553 .border_l_2()
6554 .border_color(border_color)
6555 } else {
6556 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
6557 .rounded_br(px(0.))
6558 .rounded_tr(px(0.))
6559 .border_r_2()
6560 .border_color(border_color)
6561 })
6562 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
6563 .into_any();
6564
6565 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6566
6567 let mut origin = scrolled_content_origin + point(target_x, target_y)
6568 - point(
6569 if flag_on_right {
6570 POLE_WIDTH
6571 } else {
6572 size.width - POLE_WIDTH
6573 },
6574 size.height - line_height,
6575 );
6576
6577 origin.x = origin.x.max(content_origin.x);
6578
6579 element.prepaint_at(origin, window, cx);
6580
6581 Some((element, origin))
6582 }
6583
6584 fn render_edit_prediction_scroll_popover(
6585 &mut self,
6586 to_y: impl Fn(Size<Pixels>) -> Pixels,
6587 scroll_icon: IconName,
6588 visible_row_range: Range<DisplayRow>,
6589 line_layouts: &[LineWithInvisibles],
6590 newest_selection_head: Option<DisplayPoint>,
6591 scrolled_content_origin: gpui::Point<Pixels>,
6592 window: &mut Window,
6593 cx: &mut App,
6594 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6595 let mut element = self
6596 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
6597 .into_any();
6598
6599 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6600
6601 let cursor = newest_selection_head?;
6602 let cursor_row_layout =
6603 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
6604 let cursor_column = cursor.column() as usize;
6605
6606 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
6607
6608 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
6609
6610 element.prepaint_at(origin, window, cx);
6611 Some((element, origin))
6612 }
6613
6614 fn render_edit_prediction_eager_jump_popover(
6615 &mut self,
6616 text_bounds: &Bounds<Pixels>,
6617 content_origin: gpui::Point<Pixels>,
6618 editor_snapshot: &EditorSnapshot,
6619 visible_row_range: Range<DisplayRow>,
6620 scroll_top: f32,
6621 scroll_bottom: f32,
6622 line_height: Pixels,
6623 scroll_pixel_position: gpui::Point<Pixels>,
6624 target_display_point: DisplayPoint,
6625 editor_width: Pixels,
6626 window: &mut Window,
6627 cx: &mut App,
6628 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6629 if target_display_point.row().as_f32() < scroll_top {
6630 let mut element = self
6631 .render_edit_prediction_line_popover(
6632 "Jump to Edit",
6633 Some(IconName::ArrowUp),
6634 window,
6635 cx,
6636 )?
6637 .into_any();
6638
6639 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6640 let offset = point(
6641 (text_bounds.size.width - size.width) / 2.,
6642 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6643 );
6644
6645 let origin = text_bounds.origin + offset;
6646 element.prepaint_at(origin, window, cx);
6647 Some((element, origin))
6648 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
6649 let mut element = self
6650 .render_edit_prediction_line_popover(
6651 "Jump to Edit",
6652 Some(IconName::ArrowDown),
6653 window,
6654 cx,
6655 )?
6656 .into_any();
6657
6658 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6659 let offset = point(
6660 (text_bounds.size.width - size.width) / 2.,
6661 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
6662 );
6663
6664 let origin = text_bounds.origin + offset;
6665 element.prepaint_at(origin, window, cx);
6666 Some((element, origin))
6667 } else {
6668 self.render_edit_prediction_end_of_line_popover(
6669 "Jump to Edit",
6670 editor_snapshot,
6671 visible_row_range,
6672 target_display_point,
6673 line_height,
6674 scroll_pixel_position,
6675 content_origin,
6676 editor_width,
6677 window,
6678 cx,
6679 )
6680 }
6681 }
6682
6683 fn render_edit_prediction_end_of_line_popover(
6684 self: &mut Editor,
6685 label: &'static str,
6686 editor_snapshot: &EditorSnapshot,
6687 visible_row_range: Range<DisplayRow>,
6688 target_display_point: DisplayPoint,
6689 line_height: Pixels,
6690 scroll_pixel_position: gpui::Point<Pixels>,
6691 content_origin: gpui::Point<Pixels>,
6692 editor_width: Pixels,
6693 window: &mut Window,
6694 cx: &mut App,
6695 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6696 let target_line_end = DisplayPoint::new(
6697 target_display_point.row(),
6698 editor_snapshot.line_len(target_display_point.row()),
6699 );
6700
6701 let mut element = self
6702 .render_edit_prediction_line_popover(label, None, window, cx)?
6703 .into_any();
6704
6705 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6706
6707 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
6708
6709 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
6710 let mut origin = start_point
6711 + line_origin
6712 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
6713 origin.x = origin.x.max(content_origin.x);
6714
6715 let max_x = content_origin.x + editor_width - size.width;
6716
6717 if origin.x > max_x {
6718 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
6719
6720 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
6721 origin.y += offset;
6722 IconName::ArrowUp
6723 } else {
6724 origin.y -= offset;
6725 IconName::ArrowDown
6726 };
6727
6728 element = self
6729 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
6730 .into_any();
6731
6732 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6733
6734 origin.x = content_origin.x + editor_width - size.width - px(2.);
6735 }
6736
6737 element.prepaint_at(origin, window, cx);
6738 Some((element, origin))
6739 }
6740
6741 fn render_edit_prediction_diff_popover(
6742 self: &Editor,
6743 text_bounds: &Bounds<Pixels>,
6744 content_origin: gpui::Point<Pixels>,
6745 editor_snapshot: &EditorSnapshot,
6746 visible_row_range: Range<DisplayRow>,
6747 line_layouts: &[LineWithInvisibles],
6748 line_height: Pixels,
6749 scroll_pixel_position: gpui::Point<Pixels>,
6750 newest_selection_head: Option<DisplayPoint>,
6751 editor_width: Pixels,
6752 style: &EditorStyle,
6753 edits: &Vec<(Range<Anchor>, String)>,
6754 edit_preview: &Option<language::EditPreview>,
6755 snapshot: &language::BufferSnapshot,
6756 window: &mut Window,
6757 cx: &mut App,
6758 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6759 let edit_start = edits
6760 .first()
6761 .unwrap()
6762 .0
6763 .start
6764 .to_display_point(editor_snapshot);
6765 let edit_end = edits
6766 .last()
6767 .unwrap()
6768 .0
6769 .end
6770 .to_display_point(editor_snapshot);
6771
6772 let is_visible = visible_row_range.contains(&edit_start.row())
6773 || visible_row_range.contains(&edit_end.row());
6774 if !is_visible {
6775 return None;
6776 }
6777
6778 let highlighted_edits =
6779 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
6780
6781 let styled_text = highlighted_edits.to_styled_text(&style.text);
6782 let line_count = highlighted_edits.text.lines().count();
6783
6784 const BORDER_WIDTH: Pixels = px(1.);
6785
6786 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6787 let has_keybind = keybind.is_some();
6788
6789 let mut element = h_flex()
6790 .items_start()
6791 .child(
6792 h_flex()
6793 .bg(cx.theme().colors().editor_background)
6794 .border(BORDER_WIDTH)
6795 .shadow_sm()
6796 .border_color(cx.theme().colors().border)
6797 .rounded_l_lg()
6798 .when(line_count > 1, |el| el.rounded_br_lg())
6799 .pr_1()
6800 .child(styled_text),
6801 )
6802 .child(
6803 h_flex()
6804 .h(line_height + BORDER_WIDTH * px(2.))
6805 .px_1p5()
6806 .gap_1()
6807 // Workaround: For some reason, there's a gap if we don't do this
6808 .ml(-BORDER_WIDTH)
6809 .shadow(smallvec![gpui::BoxShadow {
6810 color: gpui::black().opacity(0.05),
6811 offset: point(px(1.), px(1.)),
6812 blur_radius: px(2.),
6813 spread_radius: px(0.),
6814 }])
6815 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
6816 .border(BORDER_WIDTH)
6817 .border_color(cx.theme().colors().border)
6818 .rounded_r_lg()
6819 .id("edit_prediction_diff_popover_keybind")
6820 .when(!has_keybind, |el| {
6821 let status_colors = cx.theme().status();
6822
6823 el.bg(status_colors.error_background)
6824 .border_color(status_colors.error.opacity(0.6))
6825 .child(Icon::new(IconName::Info).color(Color::Error))
6826 .cursor_default()
6827 .hoverable_tooltip(move |_window, cx| {
6828 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
6829 })
6830 })
6831 .children(keybind),
6832 )
6833 .into_any();
6834
6835 let longest_row =
6836 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
6837 let longest_line_width = if visible_row_range.contains(&longest_row) {
6838 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
6839 } else {
6840 layout_line(
6841 longest_row,
6842 editor_snapshot,
6843 style,
6844 editor_width,
6845 |_| false,
6846 window,
6847 cx,
6848 )
6849 .width
6850 };
6851
6852 let viewport_bounds =
6853 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
6854 right: -EditorElement::SCROLLBAR_WIDTH,
6855 ..Default::default()
6856 });
6857
6858 let x_after_longest =
6859 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
6860 - scroll_pixel_position.x;
6861
6862 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
6863
6864 // Fully visible if it can be displayed within the window (allow overlapping other
6865 // panes). However, this is only allowed if the popover starts within text_bounds.
6866 let can_position_to_the_right = x_after_longest < text_bounds.right()
6867 && x_after_longest + element_bounds.width < viewport_bounds.right();
6868
6869 let mut origin = if can_position_to_the_right {
6870 point(
6871 x_after_longest,
6872 text_bounds.origin.y + edit_start.row().as_f32() * line_height
6873 - scroll_pixel_position.y,
6874 )
6875 } else {
6876 let cursor_row = newest_selection_head.map(|head| head.row());
6877 let above_edit = edit_start
6878 .row()
6879 .0
6880 .checked_sub(line_count as u32)
6881 .map(DisplayRow);
6882 let below_edit = Some(edit_end.row() + 1);
6883 let above_cursor =
6884 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
6885 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
6886
6887 // Place the edit popover adjacent to the edit if there is a location
6888 // available that is onscreen and does not obscure the cursor. Otherwise,
6889 // place it adjacent to the cursor.
6890 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
6891 .into_iter()
6892 .flatten()
6893 .find(|&start_row| {
6894 let end_row = start_row + line_count as u32;
6895 visible_row_range.contains(&start_row)
6896 && visible_row_range.contains(&end_row)
6897 && cursor_row.map_or(true, |cursor_row| {
6898 !((start_row..end_row).contains(&cursor_row))
6899 })
6900 })?;
6901
6902 content_origin
6903 + point(
6904 -scroll_pixel_position.x,
6905 row_target.as_f32() * line_height - scroll_pixel_position.y,
6906 )
6907 };
6908
6909 origin.x -= BORDER_WIDTH;
6910
6911 window.defer_draw(element, origin, 1);
6912
6913 // Do not return an element, since it will already be drawn due to defer_draw.
6914 None
6915 }
6916
6917 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
6918 px(30.)
6919 }
6920
6921 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
6922 if self.read_only(cx) {
6923 cx.theme().players().read_only()
6924 } else {
6925 self.style.as_ref().unwrap().local_player
6926 }
6927 }
6928
6929 fn render_edit_prediction_accept_keybind(
6930 &self,
6931 window: &mut Window,
6932 cx: &App,
6933 ) -> Option<AnyElement> {
6934 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
6935 let accept_keystroke = accept_binding.keystroke()?;
6936
6937 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
6938
6939 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
6940 Color::Accent
6941 } else {
6942 Color::Muted
6943 };
6944
6945 h_flex()
6946 .px_0p5()
6947 .when(is_platform_style_mac, |parent| parent.gap_0p5())
6948 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
6949 .text_size(TextSize::XSmall.rems(cx))
6950 .child(h_flex().children(ui::render_modifiers(
6951 &accept_keystroke.modifiers,
6952 PlatformStyle::platform(),
6953 Some(modifiers_color),
6954 Some(IconSize::XSmall.rems().into()),
6955 true,
6956 )))
6957 .when(is_platform_style_mac, |parent| {
6958 parent.child(accept_keystroke.key.clone())
6959 })
6960 .when(!is_platform_style_mac, |parent| {
6961 parent.child(
6962 Key::new(
6963 util::capitalize(&accept_keystroke.key),
6964 Some(Color::Default),
6965 )
6966 .size(Some(IconSize::XSmall.rems().into())),
6967 )
6968 })
6969 .into_any()
6970 .into()
6971 }
6972
6973 fn render_edit_prediction_line_popover(
6974 &self,
6975 label: impl Into<SharedString>,
6976 icon: Option<IconName>,
6977 window: &mut Window,
6978 cx: &App,
6979 ) -> Option<Stateful<Div>> {
6980 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
6981
6982 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
6983 let has_keybind = keybind.is_some();
6984
6985 let result = h_flex()
6986 .id("ep-line-popover")
6987 .py_0p5()
6988 .pl_1()
6989 .pr(padding_right)
6990 .gap_1()
6991 .rounded_md()
6992 .border_1()
6993 .bg(Self::edit_prediction_line_popover_bg_color(cx))
6994 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
6995 .shadow_sm()
6996 .when(!has_keybind, |el| {
6997 let status_colors = cx.theme().status();
6998
6999 el.bg(status_colors.error_background)
7000 .border_color(status_colors.error.opacity(0.6))
7001 .pl_2()
7002 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7003 .cursor_default()
7004 .hoverable_tooltip(move |_window, cx| {
7005 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7006 })
7007 })
7008 .children(keybind)
7009 .child(
7010 Label::new(label)
7011 .size(LabelSize::Small)
7012 .when(!has_keybind, |el| {
7013 el.color(cx.theme().status().error.into()).strikethrough()
7014 }),
7015 )
7016 .when(!has_keybind, |el| {
7017 el.child(
7018 h_flex().ml_1().child(
7019 Icon::new(IconName::Info)
7020 .size(IconSize::Small)
7021 .color(cx.theme().status().error.into()),
7022 ),
7023 )
7024 })
7025 .when_some(icon, |element, icon| {
7026 element.child(
7027 div()
7028 .mt(px(1.5))
7029 .child(Icon::new(icon).size(IconSize::Small)),
7030 )
7031 });
7032
7033 Some(result)
7034 }
7035
7036 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7037 let accent_color = cx.theme().colors().text_accent;
7038 let editor_bg_color = cx.theme().colors().editor_background;
7039 editor_bg_color.blend(accent_color.opacity(0.1))
7040 }
7041
7042 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7043 let accent_color = cx.theme().colors().text_accent;
7044 let editor_bg_color = cx.theme().colors().editor_background;
7045 editor_bg_color.blend(accent_color.opacity(0.6))
7046 }
7047
7048 fn render_edit_prediction_cursor_popover(
7049 &self,
7050 min_width: Pixels,
7051 max_width: Pixels,
7052 cursor_point: Point,
7053 style: &EditorStyle,
7054 accept_keystroke: Option<&gpui::Keystroke>,
7055 _window: &Window,
7056 cx: &mut Context<Editor>,
7057 ) -> Option<AnyElement> {
7058 let provider = self.edit_prediction_provider.as_ref()?;
7059
7060 if provider.provider.needs_terms_acceptance(cx) {
7061 return Some(
7062 h_flex()
7063 .min_w(min_width)
7064 .flex_1()
7065 .px_2()
7066 .py_1()
7067 .gap_3()
7068 .elevation_2(cx)
7069 .hover(|style| style.bg(cx.theme().colors().element_hover))
7070 .id("accept-terms")
7071 .cursor_pointer()
7072 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7073 .on_click(cx.listener(|this, _event, window, cx| {
7074 cx.stop_propagation();
7075 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7076 window.dispatch_action(
7077 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7078 cx,
7079 );
7080 }))
7081 .child(
7082 h_flex()
7083 .flex_1()
7084 .gap_2()
7085 .child(Icon::new(IconName::ZedPredict))
7086 .child(Label::new("Accept Terms of Service"))
7087 .child(div().w_full())
7088 .child(
7089 Icon::new(IconName::ArrowUpRight)
7090 .color(Color::Muted)
7091 .size(IconSize::Small),
7092 )
7093 .into_any_element(),
7094 )
7095 .into_any(),
7096 );
7097 }
7098
7099 let is_refreshing = provider.provider.is_refreshing(cx);
7100
7101 fn pending_completion_container() -> Div {
7102 h_flex()
7103 .h_full()
7104 .flex_1()
7105 .gap_2()
7106 .child(Icon::new(IconName::ZedPredict))
7107 }
7108
7109 let completion = match &self.active_inline_completion {
7110 Some(prediction) => {
7111 if !self.has_visible_completions_menu() {
7112 const RADIUS: Pixels = px(6.);
7113 const BORDER_WIDTH: Pixels = px(1.);
7114
7115 return Some(
7116 h_flex()
7117 .elevation_2(cx)
7118 .border(BORDER_WIDTH)
7119 .border_color(cx.theme().colors().border)
7120 .when(accept_keystroke.is_none(), |el| {
7121 el.border_color(cx.theme().status().error)
7122 })
7123 .rounded(RADIUS)
7124 .rounded_tl(px(0.))
7125 .overflow_hidden()
7126 .child(div().px_1p5().child(match &prediction.completion {
7127 InlineCompletion::Move { target, snapshot } => {
7128 use text::ToPoint as _;
7129 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7130 {
7131 Icon::new(IconName::ZedPredictDown)
7132 } else {
7133 Icon::new(IconName::ZedPredictUp)
7134 }
7135 }
7136 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7137 }))
7138 .child(
7139 h_flex()
7140 .gap_1()
7141 .py_1()
7142 .px_2()
7143 .rounded_r(RADIUS - BORDER_WIDTH)
7144 .border_l_1()
7145 .border_color(cx.theme().colors().border)
7146 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7147 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7148 el.child(
7149 Label::new("Hold")
7150 .size(LabelSize::Small)
7151 .when(accept_keystroke.is_none(), |el| {
7152 el.strikethrough()
7153 })
7154 .line_height_style(LineHeightStyle::UiLabel),
7155 )
7156 })
7157 .id("edit_prediction_cursor_popover_keybind")
7158 .when(accept_keystroke.is_none(), |el| {
7159 let status_colors = cx.theme().status();
7160
7161 el.bg(status_colors.error_background)
7162 .border_color(status_colors.error.opacity(0.6))
7163 .child(Icon::new(IconName::Info).color(Color::Error))
7164 .cursor_default()
7165 .hoverable_tooltip(move |_window, cx| {
7166 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7167 .into()
7168 })
7169 })
7170 .when_some(
7171 accept_keystroke.as_ref(),
7172 |el, accept_keystroke| {
7173 el.child(h_flex().children(ui::render_modifiers(
7174 &accept_keystroke.modifiers,
7175 PlatformStyle::platform(),
7176 Some(Color::Default),
7177 Some(IconSize::XSmall.rems().into()),
7178 false,
7179 )))
7180 },
7181 ),
7182 )
7183 .into_any(),
7184 );
7185 }
7186
7187 self.render_edit_prediction_cursor_popover_preview(
7188 prediction,
7189 cursor_point,
7190 style,
7191 cx,
7192 )?
7193 }
7194
7195 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7196 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7197 stale_completion,
7198 cursor_point,
7199 style,
7200 cx,
7201 )?,
7202
7203 None => {
7204 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7205 }
7206 },
7207
7208 None => pending_completion_container().child(Label::new("No Prediction")),
7209 };
7210
7211 let completion = if is_refreshing {
7212 completion
7213 .with_animation(
7214 "loading-completion",
7215 Animation::new(Duration::from_secs(2))
7216 .repeat()
7217 .with_easing(pulsating_between(0.4, 0.8)),
7218 |label, delta| label.opacity(delta),
7219 )
7220 .into_any_element()
7221 } else {
7222 completion.into_any_element()
7223 };
7224
7225 let has_completion = self.active_inline_completion.is_some();
7226
7227 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7228 Some(
7229 h_flex()
7230 .min_w(min_width)
7231 .max_w(max_width)
7232 .flex_1()
7233 .elevation_2(cx)
7234 .border_color(cx.theme().colors().border)
7235 .child(
7236 div()
7237 .flex_1()
7238 .py_1()
7239 .px_2()
7240 .overflow_hidden()
7241 .child(completion),
7242 )
7243 .when_some(accept_keystroke, |el, accept_keystroke| {
7244 if !accept_keystroke.modifiers.modified() {
7245 return el;
7246 }
7247
7248 el.child(
7249 h_flex()
7250 .h_full()
7251 .border_l_1()
7252 .rounded_r_lg()
7253 .border_color(cx.theme().colors().border)
7254 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7255 .gap_1()
7256 .py_1()
7257 .px_2()
7258 .child(
7259 h_flex()
7260 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7261 .when(is_platform_style_mac, |parent| parent.gap_1())
7262 .child(h_flex().children(ui::render_modifiers(
7263 &accept_keystroke.modifiers,
7264 PlatformStyle::platform(),
7265 Some(if !has_completion {
7266 Color::Muted
7267 } else {
7268 Color::Default
7269 }),
7270 None,
7271 false,
7272 ))),
7273 )
7274 .child(Label::new("Preview").into_any_element())
7275 .opacity(if has_completion { 1.0 } else { 0.4 }),
7276 )
7277 })
7278 .into_any(),
7279 )
7280 }
7281
7282 fn render_edit_prediction_cursor_popover_preview(
7283 &self,
7284 completion: &InlineCompletionState,
7285 cursor_point: Point,
7286 style: &EditorStyle,
7287 cx: &mut Context<Editor>,
7288 ) -> Option<Div> {
7289 use text::ToPoint as _;
7290
7291 fn render_relative_row_jump(
7292 prefix: impl Into<String>,
7293 current_row: u32,
7294 target_row: u32,
7295 ) -> Div {
7296 let (row_diff, arrow) = if target_row < current_row {
7297 (current_row - target_row, IconName::ArrowUp)
7298 } else {
7299 (target_row - current_row, IconName::ArrowDown)
7300 };
7301
7302 h_flex()
7303 .child(
7304 Label::new(format!("{}{}", prefix.into(), row_diff))
7305 .color(Color::Muted)
7306 .size(LabelSize::Small),
7307 )
7308 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7309 }
7310
7311 match &completion.completion {
7312 InlineCompletion::Move {
7313 target, snapshot, ..
7314 } => Some(
7315 h_flex()
7316 .px_2()
7317 .gap_2()
7318 .flex_1()
7319 .child(
7320 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7321 Icon::new(IconName::ZedPredictDown)
7322 } else {
7323 Icon::new(IconName::ZedPredictUp)
7324 },
7325 )
7326 .child(Label::new("Jump to Edit")),
7327 ),
7328
7329 InlineCompletion::Edit {
7330 edits,
7331 edit_preview,
7332 snapshot,
7333 display_mode: _,
7334 } => {
7335 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7336
7337 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7338 &snapshot,
7339 &edits,
7340 edit_preview.as_ref()?,
7341 true,
7342 cx,
7343 )
7344 .first_line_preview();
7345
7346 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7347 .with_default_highlights(&style.text, highlighted_edits.highlights);
7348
7349 let preview = h_flex()
7350 .gap_1()
7351 .min_w_16()
7352 .child(styled_text)
7353 .when(has_more_lines, |parent| parent.child("…"));
7354
7355 let left = if first_edit_row != cursor_point.row {
7356 render_relative_row_jump("", cursor_point.row, first_edit_row)
7357 .into_any_element()
7358 } else {
7359 Icon::new(IconName::ZedPredict).into_any_element()
7360 };
7361
7362 Some(
7363 h_flex()
7364 .h_full()
7365 .flex_1()
7366 .gap_2()
7367 .pr_1()
7368 .overflow_x_hidden()
7369 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7370 .child(left)
7371 .child(preview),
7372 )
7373 }
7374 }
7375 }
7376
7377 fn render_context_menu(
7378 &self,
7379 style: &EditorStyle,
7380 max_height_in_lines: u32,
7381 y_flipped: bool,
7382 window: &mut Window,
7383 cx: &mut Context<Editor>,
7384 ) -> Option<AnyElement> {
7385 let menu = self.context_menu.borrow();
7386 let menu = menu.as_ref()?;
7387 if !menu.visible() {
7388 return None;
7389 };
7390 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
7391 }
7392
7393 fn render_context_menu_aside(
7394 &mut self,
7395 max_size: Size<Pixels>,
7396 window: &mut Window,
7397 cx: &mut Context<Editor>,
7398 ) -> Option<AnyElement> {
7399 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7400 if menu.visible() {
7401 menu.render_aside(self, max_size, window, cx)
7402 } else {
7403 None
7404 }
7405 })
7406 }
7407
7408 fn hide_context_menu(
7409 &mut self,
7410 window: &mut Window,
7411 cx: &mut Context<Self>,
7412 ) -> Option<CodeContextMenu> {
7413 cx.notify();
7414 self.completion_tasks.clear();
7415 let context_menu = self.context_menu.borrow_mut().take();
7416 self.stale_inline_completion_in_menu.take();
7417 self.update_visible_inline_completion(window, cx);
7418 context_menu
7419 }
7420
7421 fn show_snippet_choices(
7422 &mut self,
7423 choices: &Vec<String>,
7424 selection: Range<Anchor>,
7425 cx: &mut Context<Self>,
7426 ) {
7427 if selection.start.buffer_id.is_none() {
7428 return;
7429 }
7430 let buffer_id = selection.start.buffer_id.unwrap();
7431 let buffer = self.buffer().read(cx).buffer(buffer_id);
7432 let id = post_inc(&mut self.next_completion_id);
7433
7434 if let Some(buffer) = buffer {
7435 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
7436 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
7437 ));
7438 }
7439 }
7440
7441 pub fn insert_snippet(
7442 &mut self,
7443 insertion_ranges: &[Range<usize>],
7444 snippet: Snippet,
7445 window: &mut Window,
7446 cx: &mut Context<Self>,
7447 ) -> Result<()> {
7448 struct Tabstop<T> {
7449 is_end_tabstop: bool,
7450 ranges: Vec<Range<T>>,
7451 choices: Option<Vec<String>>,
7452 }
7453
7454 let tabstops = self.buffer.update(cx, |buffer, cx| {
7455 let snippet_text: Arc<str> = snippet.text.clone().into();
7456 buffer.edit(
7457 insertion_ranges
7458 .iter()
7459 .cloned()
7460 .map(|range| (range, snippet_text.clone())),
7461 Some(AutoindentMode::EachLine),
7462 cx,
7463 );
7464
7465 let snapshot = &*buffer.read(cx);
7466 let snippet = &snippet;
7467 snippet
7468 .tabstops
7469 .iter()
7470 .map(|tabstop| {
7471 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
7472 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
7473 });
7474 let mut tabstop_ranges = tabstop
7475 .ranges
7476 .iter()
7477 .flat_map(|tabstop_range| {
7478 let mut delta = 0_isize;
7479 insertion_ranges.iter().map(move |insertion_range| {
7480 let insertion_start = insertion_range.start as isize + delta;
7481 delta +=
7482 snippet.text.len() as isize - insertion_range.len() as isize;
7483
7484 let start = ((insertion_start + tabstop_range.start) as usize)
7485 .min(snapshot.len());
7486 let end = ((insertion_start + tabstop_range.end) as usize)
7487 .min(snapshot.len());
7488 snapshot.anchor_before(start)..snapshot.anchor_after(end)
7489 })
7490 })
7491 .collect::<Vec<_>>();
7492 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
7493
7494 Tabstop {
7495 is_end_tabstop,
7496 ranges: tabstop_ranges,
7497 choices: tabstop.choices.clone(),
7498 }
7499 })
7500 .collect::<Vec<_>>()
7501 });
7502 if let Some(tabstop) = tabstops.first() {
7503 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7504 s.select_ranges(tabstop.ranges.iter().cloned());
7505 });
7506
7507 if let Some(choices) = &tabstop.choices {
7508 if let Some(selection) = tabstop.ranges.first() {
7509 self.show_snippet_choices(choices, selection.clone(), cx)
7510 }
7511 }
7512
7513 // If we're already at the last tabstop and it's at the end of the snippet,
7514 // we're done, we don't need to keep the state around.
7515 if !tabstop.is_end_tabstop {
7516 let choices = tabstops
7517 .iter()
7518 .map(|tabstop| tabstop.choices.clone())
7519 .collect();
7520
7521 let ranges = tabstops
7522 .into_iter()
7523 .map(|tabstop| tabstop.ranges)
7524 .collect::<Vec<_>>();
7525
7526 self.snippet_stack.push(SnippetState {
7527 active_index: 0,
7528 ranges,
7529 choices,
7530 });
7531 }
7532
7533 // Check whether the just-entered snippet ends with an auto-closable bracket.
7534 if self.autoclose_regions.is_empty() {
7535 let snapshot = self.buffer.read(cx).snapshot(cx);
7536 for selection in &mut self.selections.all::<Point>(cx) {
7537 let selection_head = selection.head();
7538 let Some(scope) = snapshot.language_scope_at(selection_head) else {
7539 continue;
7540 };
7541
7542 let mut bracket_pair = None;
7543 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
7544 let prev_chars = snapshot
7545 .reversed_chars_at(selection_head)
7546 .collect::<String>();
7547 for (pair, enabled) in scope.brackets() {
7548 if enabled
7549 && pair.close
7550 && prev_chars.starts_with(pair.start.as_str())
7551 && next_chars.starts_with(pair.end.as_str())
7552 {
7553 bracket_pair = Some(pair.clone());
7554 break;
7555 }
7556 }
7557 if let Some(pair) = bracket_pair {
7558 let start = snapshot.anchor_after(selection_head);
7559 let end = snapshot.anchor_after(selection_head);
7560 self.autoclose_regions.push(AutocloseRegion {
7561 selection_id: selection.id,
7562 range: start..end,
7563 pair,
7564 });
7565 }
7566 }
7567 }
7568 }
7569 Ok(())
7570 }
7571
7572 pub fn move_to_next_snippet_tabstop(
7573 &mut self,
7574 window: &mut Window,
7575 cx: &mut Context<Self>,
7576 ) -> bool {
7577 self.move_to_snippet_tabstop(Bias::Right, window, cx)
7578 }
7579
7580 pub fn move_to_prev_snippet_tabstop(
7581 &mut self,
7582 window: &mut Window,
7583 cx: &mut Context<Self>,
7584 ) -> bool {
7585 self.move_to_snippet_tabstop(Bias::Left, window, cx)
7586 }
7587
7588 pub fn move_to_snippet_tabstop(
7589 &mut self,
7590 bias: Bias,
7591 window: &mut Window,
7592 cx: &mut Context<Self>,
7593 ) -> bool {
7594 if let Some(mut snippet) = self.snippet_stack.pop() {
7595 match bias {
7596 Bias::Left => {
7597 if snippet.active_index > 0 {
7598 snippet.active_index -= 1;
7599 } else {
7600 self.snippet_stack.push(snippet);
7601 return false;
7602 }
7603 }
7604 Bias::Right => {
7605 if snippet.active_index + 1 < snippet.ranges.len() {
7606 snippet.active_index += 1;
7607 } else {
7608 self.snippet_stack.push(snippet);
7609 return false;
7610 }
7611 }
7612 }
7613 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
7614 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7615 s.select_anchor_ranges(current_ranges.iter().cloned())
7616 });
7617
7618 if let Some(choices) = &snippet.choices[snippet.active_index] {
7619 if let Some(selection) = current_ranges.first() {
7620 self.show_snippet_choices(&choices, selection.clone(), cx);
7621 }
7622 }
7623
7624 // If snippet state is not at the last tabstop, push it back on the stack
7625 if snippet.active_index + 1 < snippet.ranges.len() {
7626 self.snippet_stack.push(snippet);
7627 }
7628 return true;
7629 }
7630 }
7631
7632 false
7633 }
7634
7635 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
7636 self.transact(window, cx, |this, window, cx| {
7637 this.select_all(&SelectAll, window, cx);
7638 this.insert("", window, cx);
7639 });
7640 }
7641
7642 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
7643 self.transact(window, cx, |this, window, cx| {
7644 this.select_autoclose_pair(window, cx);
7645 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
7646 if !this.linked_edit_ranges.is_empty() {
7647 let selections = this.selections.all::<MultiBufferPoint>(cx);
7648 let snapshot = this.buffer.read(cx).snapshot(cx);
7649
7650 for selection in selections.iter() {
7651 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
7652 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
7653 if selection_start.buffer_id != selection_end.buffer_id {
7654 continue;
7655 }
7656 if let Some(ranges) =
7657 this.linked_editing_ranges_for(selection_start..selection_end, cx)
7658 {
7659 for (buffer, entries) in ranges {
7660 linked_ranges.entry(buffer).or_default().extend(entries);
7661 }
7662 }
7663 }
7664 }
7665
7666 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7667 if !this.selections.line_mode {
7668 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
7669 for selection in &mut selections {
7670 if selection.is_empty() {
7671 let old_head = selection.head();
7672 let mut new_head =
7673 movement::left(&display_map, old_head.to_display_point(&display_map))
7674 .to_point(&display_map);
7675 if let Some((buffer, line_buffer_range)) = display_map
7676 .buffer_snapshot
7677 .buffer_line_for_row(MultiBufferRow(old_head.row))
7678 {
7679 let indent_size =
7680 buffer.indent_size_for_line(line_buffer_range.start.row);
7681 let indent_len = match indent_size.kind {
7682 IndentKind::Space => {
7683 buffer.settings_at(line_buffer_range.start, cx).tab_size
7684 }
7685 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
7686 };
7687 if old_head.column <= indent_size.len && old_head.column > 0 {
7688 let indent_len = indent_len.get();
7689 new_head = cmp::min(
7690 new_head,
7691 MultiBufferPoint::new(
7692 old_head.row,
7693 ((old_head.column - 1) / indent_len) * indent_len,
7694 ),
7695 );
7696 }
7697 }
7698
7699 selection.set_head(new_head, SelectionGoal::None);
7700 }
7701 }
7702 }
7703
7704 this.signature_help_state.set_backspace_pressed(true);
7705 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7706 s.select(selections)
7707 });
7708 this.insert("", window, cx);
7709 let empty_str: Arc<str> = Arc::from("");
7710 for (buffer, edits) in linked_ranges {
7711 let snapshot = buffer.read(cx).snapshot();
7712 use text::ToPoint as TP;
7713
7714 let edits = edits
7715 .into_iter()
7716 .map(|range| {
7717 let end_point = TP::to_point(&range.end, &snapshot);
7718 let mut start_point = TP::to_point(&range.start, &snapshot);
7719
7720 if end_point == start_point {
7721 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
7722 .saturating_sub(1);
7723 start_point =
7724 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
7725 };
7726
7727 (start_point..end_point, empty_str.clone())
7728 })
7729 .sorted_by_key(|(range, _)| range.start)
7730 .collect::<Vec<_>>();
7731 buffer.update(cx, |this, cx| {
7732 this.edit(edits, None, cx);
7733 })
7734 }
7735 this.refresh_inline_completion(true, false, window, cx);
7736 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
7737 });
7738 }
7739
7740 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
7741 self.transact(window, cx, |this, window, cx| {
7742 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7743 let line_mode = s.line_mode;
7744 s.move_with(|map, selection| {
7745 if selection.is_empty() && !line_mode {
7746 let cursor = movement::right(map, selection.head());
7747 selection.end = cursor;
7748 selection.reversed = true;
7749 selection.goal = SelectionGoal::None;
7750 }
7751 })
7752 });
7753 this.insert("", window, cx);
7754 this.refresh_inline_completion(true, false, window, cx);
7755 });
7756 }
7757
7758 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
7759 if self.move_to_prev_snippet_tabstop(window, cx) {
7760 return;
7761 }
7762
7763 self.outdent(&Outdent, window, cx);
7764 }
7765
7766 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
7767 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
7768 return;
7769 }
7770
7771 let mut selections = self.selections.all_adjusted(cx);
7772 let buffer = self.buffer.read(cx);
7773 let snapshot = buffer.snapshot(cx);
7774 let rows_iter = selections.iter().map(|s| s.head().row);
7775 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
7776
7777 let mut edits = Vec::new();
7778 let mut prev_edited_row = 0;
7779 let mut row_delta = 0;
7780 for selection in &mut selections {
7781 if selection.start.row != prev_edited_row {
7782 row_delta = 0;
7783 }
7784 prev_edited_row = selection.end.row;
7785
7786 // If the selection is non-empty, then increase the indentation of the selected lines.
7787 if !selection.is_empty() {
7788 row_delta =
7789 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7790 continue;
7791 }
7792
7793 // If the selection is empty and the cursor is in the leading whitespace before the
7794 // suggested indentation, then auto-indent the line.
7795 let cursor = selection.head();
7796 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
7797 if let Some(suggested_indent) =
7798 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
7799 {
7800 if cursor.column < suggested_indent.len
7801 && cursor.column <= current_indent.len
7802 && current_indent.len <= suggested_indent.len
7803 {
7804 selection.start = Point::new(cursor.row, suggested_indent.len);
7805 selection.end = selection.start;
7806 if row_delta == 0 {
7807 edits.extend(Buffer::edit_for_indent_size_adjustment(
7808 cursor.row,
7809 current_indent,
7810 suggested_indent,
7811 ));
7812 row_delta = suggested_indent.len - current_indent.len;
7813 }
7814 continue;
7815 }
7816 }
7817
7818 // Otherwise, insert a hard or soft tab.
7819 let settings = buffer.language_settings_at(cursor, cx);
7820 let tab_size = if settings.hard_tabs {
7821 IndentSize::tab()
7822 } else {
7823 let tab_size = settings.tab_size.get();
7824 let char_column = snapshot
7825 .text_for_range(Point::new(cursor.row, 0)..cursor)
7826 .flat_map(str::chars)
7827 .count()
7828 + row_delta as usize;
7829 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
7830 IndentSize::spaces(chars_to_next_tab_stop)
7831 };
7832 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
7833 selection.end = selection.start;
7834 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
7835 row_delta += tab_size.len;
7836 }
7837
7838 self.transact(window, cx, |this, window, cx| {
7839 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7840 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7841 s.select(selections)
7842 });
7843 this.refresh_inline_completion(true, false, window, cx);
7844 });
7845 }
7846
7847 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
7848 if self.read_only(cx) {
7849 return;
7850 }
7851 let mut selections = self.selections.all::<Point>(cx);
7852 let mut prev_edited_row = 0;
7853 let mut row_delta = 0;
7854 let mut edits = Vec::new();
7855 let buffer = self.buffer.read(cx);
7856 let snapshot = buffer.snapshot(cx);
7857 for selection in &mut selections {
7858 if selection.start.row != prev_edited_row {
7859 row_delta = 0;
7860 }
7861 prev_edited_row = selection.end.row;
7862
7863 row_delta =
7864 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
7865 }
7866
7867 self.transact(window, cx, |this, window, cx| {
7868 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
7869 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7870 s.select(selections)
7871 });
7872 });
7873 }
7874
7875 fn indent_selection(
7876 buffer: &MultiBuffer,
7877 snapshot: &MultiBufferSnapshot,
7878 selection: &mut Selection<Point>,
7879 edits: &mut Vec<(Range<Point>, String)>,
7880 delta_for_start_row: u32,
7881 cx: &App,
7882 ) -> u32 {
7883 let settings = buffer.language_settings_at(selection.start, cx);
7884 let tab_size = settings.tab_size.get();
7885 let indent_kind = if settings.hard_tabs {
7886 IndentKind::Tab
7887 } else {
7888 IndentKind::Space
7889 };
7890 let mut start_row = selection.start.row;
7891 let mut end_row = selection.end.row + 1;
7892
7893 // If a selection ends at the beginning of a line, don't indent
7894 // that last line.
7895 if selection.end.column == 0 && selection.end.row > selection.start.row {
7896 end_row -= 1;
7897 }
7898
7899 // Avoid re-indenting a row that has already been indented by a
7900 // previous selection, but still update this selection's column
7901 // to reflect that indentation.
7902 if delta_for_start_row > 0 {
7903 start_row += 1;
7904 selection.start.column += delta_for_start_row;
7905 if selection.end.row == selection.start.row {
7906 selection.end.column += delta_for_start_row;
7907 }
7908 }
7909
7910 let mut delta_for_end_row = 0;
7911 let has_multiple_rows = start_row + 1 != end_row;
7912 for row in start_row..end_row {
7913 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
7914 let indent_delta = match (current_indent.kind, indent_kind) {
7915 (IndentKind::Space, IndentKind::Space) => {
7916 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
7917 IndentSize::spaces(columns_to_next_tab_stop)
7918 }
7919 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
7920 (_, IndentKind::Tab) => IndentSize::tab(),
7921 };
7922
7923 let start = if has_multiple_rows || current_indent.len < selection.start.column {
7924 0
7925 } else {
7926 selection.start.column
7927 };
7928 let row_start = Point::new(row, start);
7929 edits.push((
7930 row_start..row_start,
7931 indent_delta.chars().collect::<String>(),
7932 ));
7933
7934 // Update this selection's endpoints to reflect the indentation.
7935 if row == selection.start.row {
7936 selection.start.column += indent_delta.len;
7937 }
7938 if row == selection.end.row {
7939 selection.end.column += indent_delta.len;
7940 delta_for_end_row = indent_delta.len;
7941 }
7942 }
7943
7944 if selection.start.row == selection.end.row {
7945 delta_for_start_row + delta_for_end_row
7946 } else {
7947 delta_for_end_row
7948 }
7949 }
7950
7951 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
7952 if self.read_only(cx) {
7953 return;
7954 }
7955 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7956 let selections = self.selections.all::<Point>(cx);
7957 let mut deletion_ranges = Vec::new();
7958 let mut last_outdent = None;
7959 {
7960 let buffer = self.buffer.read(cx);
7961 let snapshot = buffer.snapshot(cx);
7962 for selection in &selections {
7963 let settings = buffer.language_settings_at(selection.start, cx);
7964 let tab_size = settings.tab_size.get();
7965 let mut rows = selection.spanned_rows(false, &display_map);
7966
7967 // Avoid re-outdenting a row that has already been outdented by a
7968 // previous selection.
7969 if let Some(last_row) = last_outdent {
7970 if last_row == rows.start {
7971 rows.start = rows.start.next_row();
7972 }
7973 }
7974 let has_multiple_rows = rows.len() > 1;
7975 for row in rows.iter_rows() {
7976 let indent_size = snapshot.indent_size_for_line(row);
7977 if indent_size.len > 0 {
7978 let deletion_len = match indent_size.kind {
7979 IndentKind::Space => {
7980 let columns_to_prev_tab_stop = indent_size.len % tab_size;
7981 if columns_to_prev_tab_stop == 0 {
7982 tab_size
7983 } else {
7984 columns_to_prev_tab_stop
7985 }
7986 }
7987 IndentKind::Tab => 1,
7988 };
7989 let start = if has_multiple_rows
7990 || deletion_len > selection.start.column
7991 || indent_size.len < selection.start.column
7992 {
7993 0
7994 } else {
7995 selection.start.column - deletion_len
7996 };
7997 deletion_ranges.push(
7998 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
7999 );
8000 last_outdent = Some(row);
8001 }
8002 }
8003 }
8004 }
8005
8006 self.transact(window, cx, |this, window, cx| {
8007 this.buffer.update(cx, |buffer, cx| {
8008 let empty_str: Arc<str> = Arc::default();
8009 buffer.edit(
8010 deletion_ranges
8011 .into_iter()
8012 .map(|range| (range, empty_str.clone())),
8013 None,
8014 cx,
8015 );
8016 });
8017 let selections = this.selections.all::<usize>(cx);
8018 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8019 s.select(selections)
8020 });
8021 });
8022 }
8023
8024 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8025 if self.read_only(cx) {
8026 return;
8027 }
8028 let selections = self
8029 .selections
8030 .all::<usize>(cx)
8031 .into_iter()
8032 .map(|s| s.range());
8033
8034 self.transact(window, cx, |this, window, cx| {
8035 this.buffer.update(cx, |buffer, cx| {
8036 buffer.autoindent_ranges(selections, cx);
8037 });
8038 let selections = this.selections.all::<usize>(cx);
8039 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8040 s.select(selections)
8041 });
8042 });
8043 }
8044
8045 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8046 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8047 let selections = self.selections.all::<Point>(cx);
8048
8049 let mut new_cursors = Vec::new();
8050 let mut edit_ranges = Vec::new();
8051 let mut selections = selections.iter().peekable();
8052 while let Some(selection) = selections.next() {
8053 let mut rows = selection.spanned_rows(false, &display_map);
8054 let goal_display_column = selection.head().to_display_point(&display_map).column();
8055
8056 // Accumulate contiguous regions of rows that we want to delete.
8057 while let Some(next_selection) = selections.peek() {
8058 let next_rows = next_selection.spanned_rows(false, &display_map);
8059 if next_rows.start <= rows.end {
8060 rows.end = next_rows.end;
8061 selections.next().unwrap();
8062 } else {
8063 break;
8064 }
8065 }
8066
8067 let buffer = &display_map.buffer_snapshot;
8068 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8069 let edit_end;
8070 let cursor_buffer_row;
8071 if buffer.max_point().row >= rows.end.0 {
8072 // If there's a line after the range, delete the \n from the end of the row range
8073 // and position the cursor on the next line.
8074 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8075 cursor_buffer_row = rows.end;
8076 } else {
8077 // If there isn't a line after the range, delete the \n from the line before the
8078 // start of the row range and position the cursor there.
8079 edit_start = edit_start.saturating_sub(1);
8080 edit_end = buffer.len();
8081 cursor_buffer_row = rows.start.previous_row();
8082 }
8083
8084 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8085 *cursor.column_mut() =
8086 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8087
8088 new_cursors.push((
8089 selection.id,
8090 buffer.anchor_after(cursor.to_point(&display_map)),
8091 ));
8092 edit_ranges.push(edit_start..edit_end);
8093 }
8094
8095 self.transact(window, cx, |this, window, cx| {
8096 let buffer = this.buffer.update(cx, |buffer, cx| {
8097 let empty_str: Arc<str> = Arc::default();
8098 buffer.edit(
8099 edit_ranges
8100 .into_iter()
8101 .map(|range| (range, empty_str.clone())),
8102 None,
8103 cx,
8104 );
8105 buffer.snapshot(cx)
8106 });
8107 let new_selections = new_cursors
8108 .into_iter()
8109 .map(|(id, cursor)| {
8110 let cursor = cursor.to_point(&buffer);
8111 Selection {
8112 id,
8113 start: cursor,
8114 end: cursor,
8115 reversed: false,
8116 goal: SelectionGoal::None,
8117 }
8118 })
8119 .collect();
8120
8121 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8122 s.select(new_selections);
8123 });
8124 });
8125 }
8126
8127 pub fn join_lines_impl(
8128 &mut self,
8129 insert_whitespace: bool,
8130 window: &mut Window,
8131 cx: &mut Context<Self>,
8132 ) {
8133 if self.read_only(cx) {
8134 return;
8135 }
8136 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8137 for selection in self.selections.all::<Point>(cx) {
8138 let start = MultiBufferRow(selection.start.row);
8139 // Treat single line selections as if they include the next line. Otherwise this action
8140 // would do nothing for single line selections individual cursors.
8141 let end = if selection.start.row == selection.end.row {
8142 MultiBufferRow(selection.start.row + 1)
8143 } else {
8144 MultiBufferRow(selection.end.row)
8145 };
8146
8147 if let Some(last_row_range) = row_ranges.last_mut() {
8148 if start <= last_row_range.end {
8149 last_row_range.end = end;
8150 continue;
8151 }
8152 }
8153 row_ranges.push(start..end);
8154 }
8155
8156 let snapshot = self.buffer.read(cx).snapshot(cx);
8157 let mut cursor_positions = Vec::new();
8158 for row_range in &row_ranges {
8159 let anchor = snapshot.anchor_before(Point::new(
8160 row_range.end.previous_row().0,
8161 snapshot.line_len(row_range.end.previous_row()),
8162 ));
8163 cursor_positions.push(anchor..anchor);
8164 }
8165
8166 self.transact(window, cx, |this, window, cx| {
8167 for row_range in row_ranges.into_iter().rev() {
8168 for row in row_range.iter_rows().rev() {
8169 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8170 let next_line_row = row.next_row();
8171 let indent = snapshot.indent_size_for_line(next_line_row);
8172 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8173
8174 let replace =
8175 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8176 " "
8177 } else {
8178 ""
8179 };
8180
8181 this.buffer.update(cx, |buffer, cx| {
8182 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8183 });
8184 }
8185 }
8186
8187 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8188 s.select_anchor_ranges(cursor_positions)
8189 });
8190 });
8191 }
8192
8193 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8194 self.join_lines_impl(true, window, cx);
8195 }
8196
8197 pub fn sort_lines_case_sensitive(
8198 &mut self,
8199 _: &SortLinesCaseSensitive,
8200 window: &mut Window,
8201 cx: &mut Context<Self>,
8202 ) {
8203 self.manipulate_lines(window, cx, |lines| lines.sort())
8204 }
8205
8206 pub fn sort_lines_case_insensitive(
8207 &mut self,
8208 _: &SortLinesCaseInsensitive,
8209 window: &mut Window,
8210 cx: &mut Context<Self>,
8211 ) {
8212 self.manipulate_lines(window, cx, |lines| {
8213 lines.sort_by_key(|line| line.to_lowercase())
8214 })
8215 }
8216
8217 pub fn unique_lines_case_insensitive(
8218 &mut self,
8219 _: &UniqueLinesCaseInsensitive,
8220 window: &mut Window,
8221 cx: &mut Context<Self>,
8222 ) {
8223 self.manipulate_lines(window, cx, |lines| {
8224 let mut seen = HashSet::default();
8225 lines.retain(|line| seen.insert(line.to_lowercase()));
8226 })
8227 }
8228
8229 pub fn unique_lines_case_sensitive(
8230 &mut self,
8231 _: &UniqueLinesCaseSensitive,
8232 window: &mut Window,
8233 cx: &mut Context<Self>,
8234 ) {
8235 self.manipulate_lines(window, cx, |lines| {
8236 let mut seen = HashSet::default();
8237 lines.retain(|line| seen.insert(*line));
8238 })
8239 }
8240
8241 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8242 let Some(project) = self.project.clone() else {
8243 return;
8244 };
8245 self.reload(project, window, cx)
8246 .detach_and_notify_err(window, cx);
8247 }
8248
8249 pub fn restore_file(
8250 &mut self,
8251 _: &::git::RestoreFile,
8252 window: &mut Window,
8253 cx: &mut Context<Self>,
8254 ) {
8255 let mut buffer_ids = HashSet::default();
8256 let snapshot = self.buffer().read(cx).snapshot(cx);
8257 for selection in self.selections.all::<usize>(cx) {
8258 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8259 }
8260
8261 let buffer = self.buffer().read(cx);
8262 let ranges = buffer_ids
8263 .into_iter()
8264 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8265 .collect::<Vec<_>>();
8266
8267 self.restore_hunks_in_ranges(ranges, window, cx);
8268 }
8269
8270 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8271 let selections = self
8272 .selections
8273 .all(cx)
8274 .into_iter()
8275 .map(|s| s.range())
8276 .collect();
8277 self.restore_hunks_in_ranges(selections, window, cx);
8278 }
8279
8280 fn restore_hunks_in_ranges(
8281 &mut self,
8282 ranges: Vec<Range<Point>>,
8283 window: &mut Window,
8284 cx: &mut Context<Editor>,
8285 ) {
8286 let mut revert_changes = HashMap::default();
8287 let chunk_by = self
8288 .snapshot(window, cx)
8289 .hunks_for_ranges(ranges)
8290 .into_iter()
8291 .chunk_by(|hunk| hunk.buffer_id);
8292 for (buffer_id, hunks) in &chunk_by {
8293 let hunks = hunks.collect::<Vec<_>>();
8294 for hunk in &hunks {
8295 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8296 }
8297 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8298 }
8299 drop(chunk_by);
8300 if !revert_changes.is_empty() {
8301 self.transact(window, cx, |editor, window, cx| {
8302 editor.restore(revert_changes, window, cx);
8303 });
8304 }
8305 }
8306
8307 pub fn open_active_item_in_terminal(
8308 &mut self,
8309 _: &OpenInTerminal,
8310 window: &mut Window,
8311 cx: &mut Context<Self>,
8312 ) {
8313 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8314 let project_path = buffer.read(cx).project_path(cx)?;
8315 let project = self.project.as_ref()?.read(cx);
8316 let entry = project.entry_for_path(&project_path, cx)?;
8317 let parent = match &entry.canonical_path {
8318 Some(canonical_path) => canonical_path.to_path_buf(),
8319 None => project.absolute_path(&project_path, cx)?,
8320 }
8321 .parent()?
8322 .to_path_buf();
8323 Some(parent)
8324 }) {
8325 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8326 }
8327 }
8328
8329 fn set_breakpoint_context_menu(
8330 &mut self,
8331 row: DisplayRow,
8332 position: Option<Anchor>,
8333 kind: Arc<BreakpointKind>,
8334 clicked_point: gpui::Point<Pixels>,
8335 window: &mut Window,
8336 cx: &mut Context<Self>,
8337 ) {
8338 if !cx.has_flag::<Debugger>() {
8339 return;
8340 }
8341 let source = self
8342 .buffer
8343 .read(cx)
8344 .snapshot(cx)
8345 .anchor_before(Point::new(row.0, 0u32));
8346
8347 let context_menu =
8348 self.breakpoint_context_menu(position.unwrap_or(source), kind, window, cx);
8349
8350 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8351 self,
8352 source,
8353 clicked_point,
8354 context_menu,
8355 window,
8356 cx,
8357 );
8358 }
8359
8360 fn add_edit_breakpoint_block(
8361 &mut self,
8362 anchor: Anchor,
8363 kind: &BreakpointKind,
8364 window: &mut Window,
8365 cx: &mut Context<Self>,
8366 ) {
8367 let weak_editor = cx.weak_entity();
8368 let bp_prompt =
8369 cx.new(|cx| BreakpointPromptEditor::new(weak_editor, anchor, kind.clone(), window, cx));
8370
8371 let height = bp_prompt.update(cx, |this, cx| {
8372 this.prompt
8373 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8374 });
8375 let cloned_prompt = bp_prompt.clone();
8376 let blocks = vec![BlockProperties {
8377 style: BlockStyle::Sticky,
8378 placement: BlockPlacement::Above(anchor),
8379 height,
8380 render: Arc::new(move |cx| {
8381 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8382 cloned_prompt.clone().into_any_element()
8383 }),
8384 priority: 0,
8385 }];
8386
8387 let focus_handle = bp_prompt.focus_handle(cx);
8388 window.focus(&focus_handle);
8389
8390 let block_ids = self.insert_blocks(blocks, None, cx);
8391 bp_prompt.update(cx, |prompt, _| {
8392 prompt.add_block_ids(block_ids);
8393 });
8394 }
8395
8396 pub(crate) fn breakpoint_at_cursor_head(
8397 &self,
8398 window: &mut Window,
8399 cx: &mut Context<Self>,
8400 ) -> Option<(Anchor, Breakpoint)> {
8401 let cursor_position: Point = self.selections.newest(cx).head();
8402 let snapshot = self.snapshot(window, cx);
8403 // We Set the column position to zero so this function interacts correctly
8404 // between calls by clicking on the gutter & using an action to toggle a
8405 // breakpoint. Otherwise, toggling a breakpoint through an action wouldn't
8406 // untoggle a breakpoint that was added through clicking on the gutter
8407 let cursor_position = snapshot
8408 .display_snapshot
8409 .buffer_snapshot
8410 .anchor_before(Point::new(cursor_position.row, 0));
8411
8412 let project = self.project.clone();
8413
8414 let buffer_id = cursor_position.text_anchor.buffer_id?;
8415 let enclosing_excerpt = snapshot
8416 .buffer_snapshot
8417 .excerpt_ids_for_range(cursor_position..cursor_position)
8418 .next()?;
8419 let buffer = project?.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
8420 let buffer_snapshot = buffer.read(cx).snapshot();
8421
8422 let row = buffer_snapshot
8423 .summary_for_anchor::<text::PointUtf16>(&cursor_position.text_anchor)
8424 .row;
8425
8426 let bp = self
8427 .breakpoint_store
8428 .as_ref()?
8429 .read_with(cx, |breakpoint_store, cx| {
8430 breakpoint_store
8431 .breakpoints(
8432 &buffer,
8433 Some(cursor_position.text_anchor..(text::Anchor::MAX)),
8434 buffer_snapshot.clone(),
8435 cx,
8436 )
8437 .next()
8438 .and_then(move |(anchor, bp)| {
8439 let breakpoint_row = buffer_snapshot
8440 .summary_for_anchor::<text::PointUtf16>(anchor)
8441 .row;
8442
8443 if breakpoint_row == row {
8444 snapshot
8445 .buffer_snapshot
8446 .anchor_in_excerpt(enclosing_excerpt, *anchor)
8447 .map(|anchor| (anchor, bp.clone()))
8448 } else {
8449 None
8450 }
8451 })
8452 });
8453 bp
8454 }
8455
8456 pub fn edit_log_breakpoint(
8457 &mut self,
8458 _: &EditLogBreakpoint,
8459 window: &mut Window,
8460 cx: &mut Context<Self>,
8461 ) {
8462 let (anchor, bp) = self
8463 .breakpoint_at_cursor_head(window, cx)
8464 .unwrap_or_else(|| {
8465 let cursor_position: Point = self.selections.newest(cx).head();
8466
8467 let breakpoint_position = self
8468 .snapshot(window, cx)
8469 .display_snapshot
8470 .buffer_snapshot
8471 .anchor_before(Point::new(cursor_position.row, 0));
8472
8473 (
8474 breakpoint_position,
8475 Breakpoint {
8476 kind: BreakpointKind::Standard,
8477 },
8478 )
8479 });
8480
8481 self.add_edit_breakpoint_block(anchor, &bp.kind, window, cx);
8482 }
8483
8484 pub fn toggle_breakpoint(
8485 &mut self,
8486 _: &crate::actions::ToggleBreakpoint,
8487 window: &mut Window,
8488 cx: &mut Context<Self>,
8489 ) {
8490 let edit_action = BreakpointEditAction::Toggle;
8491
8492 if let Some((anchor, breakpoint)) = self.breakpoint_at_cursor_head(window, cx) {
8493 self.edit_breakpoint_at_anchor(anchor, breakpoint.kind, edit_action, cx);
8494 } else {
8495 let cursor_position: Point = self.selections.newest(cx).head();
8496
8497 let breakpoint_position = self
8498 .snapshot(window, cx)
8499 .display_snapshot
8500 .buffer_snapshot
8501 .anchor_before(Point::new(cursor_position.row, 0));
8502
8503 self.edit_breakpoint_at_anchor(
8504 breakpoint_position,
8505 BreakpointKind::Standard,
8506 edit_action,
8507 cx,
8508 );
8509 }
8510 }
8511
8512 pub fn edit_breakpoint_at_anchor(
8513 &mut self,
8514 breakpoint_position: Anchor,
8515 kind: BreakpointKind,
8516 edit_action: BreakpointEditAction,
8517 cx: &mut Context<Self>,
8518 ) {
8519 let Some(breakpoint_store) = &self.breakpoint_store else {
8520 return;
8521 };
8522
8523 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
8524 if breakpoint_position == Anchor::min() {
8525 self.buffer()
8526 .read(cx)
8527 .excerpt_buffer_ids()
8528 .into_iter()
8529 .next()
8530 } else {
8531 None
8532 }
8533 }) else {
8534 return;
8535 };
8536
8537 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
8538 return;
8539 };
8540
8541 breakpoint_store.update(cx, |breakpoint_store, cx| {
8542 breakpoint_store.toggle_breakpoint(
8543 buffer,
8544 (breakpoint_position.text_anchor, Breakpoint { kind }),
8545 edit_action,
8546 cx,
8547 );
8548 });
8549
8550 cx.notify();
8551 }
8552
8553 #[cfg(any(test, feature = "test-support"))]
8554 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
8555 self.breakpoint_store.clone()
8556 }
8557
8558 pub fn prepare_restore_change(
8559 &self,
8560 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
8561 hunk: &MultiBufferDiffHunk,
8562 cx: &mut App,
8563 ) -> Option<()> {
8564 if hunk.is_created_file() {
8565 return None;
8566 }
8567 let buffer = self.buffer.read(cx);
8568 let diff = buffer.diff_for(hunk.buffer_id)?;
8569 let buffer = buffer.buffer(hunk.buffer_id)?;
8570 let buffer = buffer.read(cx);
8571 let original_text = diff
8572 .read(cx)
8573 .base_text()
8574 .as_rope()
8575 .slice(hunk.diff_base_byte_range.clone());
8576 let buffer_snapshot = buffer.snapshot();
8577 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
8578 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
8579 probe
8580 .0
8581 .start
8582 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
8583 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
8584 }) {
8585 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
8586 Some(())
8587 } else {
8588 None
8589 }
8590 }
8591
8592 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
8593 self.manipulate_lines(window, cx, |lines| lines.reverse())
8594 }
8595
8596 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
8597 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
8598 }
8599
8600 fn manipulate_lines<Fn>(
8601 &mut self,
8602 window: &mut Window,
8603 cx: &mut Context<Self>,
8604 mut callback: Fn,
8605 ) where
8606 Fn: FnMut(&mut Vec<&str>),
8607 {
8608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8609 let buffer = self.buffer.read(cx).snapshot(cx);
8610
8611 let mut edits = Vec::new();
8612
8613 let selections = self.selections.all::<Point>(cx);
8614 let mut selections = selections.iter().peekable();
8615 let mut contiguous_row_selections = Vec::new();
8616 let mut new_selections = Vec::new();
8617 let mut added_lines = 0;
8618 let mut removed_lines = 0;
8619
8620 while let Some(selection) = selections.next() {
8621 let (start_row, end_row) = consume_contiguous_rows(
8622 &mut contiguous_row_selections,
8623 selection,
8624 &display_map,
8625 &mut selections,
8626 );
8627
8628 let start_point = Point::new(start_row.0, 0);
8629 let end_point = Point::new(
8630 end_row.previous_row().0,
8631 buffer.line_len(end_row.previous_row()),
8632 );
8633 let text = buffer
8634 .text_for_range(start_point..end_point)
8635 .collect::<String>();
8636
8637 let mut lines = text.split('\n').collect_vec();
8638
8639 let lines_before = lines.len();
8640 callback(&mut lines);
8641 let lines_after = lines.len();
8642
8643 edits.push((start_point..end_point, lines.join("\n")));
8644
8645 // Selections must change based on added and removed line count
8646 let start_row =
8647 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
8648 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
8649 new_selections.push(Selection {
8650 id: selection.id,
8651 start: start_row,
8652 end: end_row,
8653 goal: SelectionGoal::None,
8654 reversed: selection.reversed,
8655 });
8656
8657 if lines_after > lines_before {
8658 added_lines += lines_after - lines_before;
8659 } else if lines_before > lines_after {
8660 removed_lines += lines_before - lines_after;
8661 }
8662 }
8663
8664 self.transact(window, cx, |this, window, cx| {
8665 let buffer = this.buffer.update(cx, |buffer, cx| {
8666 buffer.edit(edits, None, cx);
8667 buffer.snapshot(cx)
8668 });
8669
8670 // Recalculate offsets on newly edited buffer
8671 let new_selections = new_selections
8672 .iter()
8673 .map(|s| {
8674 let start_point = Point::new(s.start.0, 0);
8675 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
8676 Selection {
8677 id: s.id,
8678 start: buffer.point_to_offset(start_point),
8679 end: buffer.point_to_offset(end_point),
8680 goal: s.goal,
8681 reversed: s.reversed,
8682 }
8683 })
8684 .collect();
8685
8686 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8687 s.select(new_selections);
8688 });
8689
8690 this.request_autoscroll(Autoscroll::fit(), cx);
8691 });
8692 }
8693
8694 pub fn convert_to_upper_case(
8695 &mut self,
8696 _: &ConvertToUpperCase,
8697 window: &mut Window,
8698 cx: &mut Context<Self>,
8699 ) {
8700 self.manipulate_text(window, cx, |text| text.to_uppercase())
8701 }
8702
8703 pub fn convert_to_lower_case(
8704 &mut self,
8705 _: &ConvertToLowerCase,
8706 window: &mut Window,
8707 cx: &mut Context<Self>,
8708 ) {
8709 self.manipulate_text(window, cx, |text| text.to_lowercase())
8710 }
8711
8712 pub fn convert_to_title_case(
8713 &mut self,
8714 _: &ConvertToTitleCase,
8715 window: &mut Window,
8716 cx: &mut Context<Self>,
8717 ) {
8718 self.manipulate_text(window, cx, |text| {
8719 text.split('\n')
8720 .map(|line| line.to_case(Case::Title))
8721 .join("\n")
8722 })
8723 }
8724
8725 pub fn convert_to_snake_case(
8726 &mut self,
8727 _: &ConvertToSnakeCase,
8728 window: &mut Window,
8729 cx: &mut Context<Self>,
8730 ) {
8731 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
8732 }
8733
8734 pub fn convert_to_kebab_case(
8735 &mut self,
8736 _: &ConvertToKebabCase,
8737 window: &mut Window,
8738 cx: &mut Context<Self>,
8739 ) {
8740 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
8741 }
8742
8743 pub fn convert_to_upper_camel_case(
8744 &mut self,
8745 _: &ConvertToUpperCamelCase,
8746 window: &mut Window,
8747 cx: &mut Context<Self>,
8748 ) {
8749 self.manipulate_text(window, cx, |text| {
8750 text.split('\n')
8751 .map(|line| line.to_case(Case::UpperCamel))
8752 .join("\n")
8753 })
8754 }
8755
8756 pub fn convert_to_lower_camel_case(
8757 &mut self,
8758 _: &ConvertToLowerCamelCase,
8759 window: &mut Window,
8760 cx: &mut Context<Self>,
8761 ) {
8762 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
8763 }
8764
8765 pub fn convert_to_opposite_case(
8766 &mut self,
8767 _: &ConvertToOppositeCase,
8768 window: &mut Window,
8769 cx: &mut Context<Self>,
8770 ) {
8771 self.manipulate_text(window, cx, |text| {
8772 text.chars()
8773 .fold(String::with_capacity(text.len()), |mut t, c| {
8774 if c.is_uppercase() {
8775 t.extend(c.to_lowercase());
8776 } else {
8777 t.extend(c.to_uppercase());
8778 }
8779 t
8780 })
8781 })
8782 }
8783
8784 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
8785 where
8786 Fn: FnMut(&str) -> String,
8787 {
8788 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8789 let buffer = self.buffer.read(cx).snapshot(cx);
8790
8791 let mut new_selections = Vec::new();
8792 let mut edits = Vec::new();
8793 let mut selection_adjustment = 0i32;
8794
8795 for selection in self.selections.all::<usize>(cx) {
8796 let selection_is_empty = selection.is_empty();
8797
8798 let (start, end) = if selection_is_empty {
8799 let word_range = movement::surrounding_word(
8800 &display_map,
8801 selection.start.to_display_point(&display_map),
8802 );
8803 let start = word_range.start.to_offset(&display_map, Bias::Left);
8804 let end = word_range.end.to_offset(&display_map, Bias::Left);
8805 (start, end)
8806 } else {
8807 (selection.start, selection.end)
8808 };
8809
8810 let text = buffer.text_for_range(start..end).collect::<String>();
8811 let old_length = text.len() as i32;
8812 let text = callback(&text);
8813
8814 new_selections.push(Selection {
8815 start: (start as i32 - selection_adjustment) as usize,
8816 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
8817 goal: SelectionGoal::None,
8818 ..selection
8819 });
8820
8821 selection_adjustment += old_length - text.len() as i32;
8822
8823 edits.push((start..end, text));
8824 }
8825
8826 self.transact(window, cx, |this, window, cx| {
8827 this.buffer.update(cx, |buffer, cx| {
8828 buffer.edit(edits, None, cx);
8829 });
8830
8831 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8832 s.select(new_selections);
8833 });
8834
8835 this.request_autoscroll(Autoscroll::fit(), cx);
8836 });
8837 }
8838
8839 pub fn duplicate(
8840 &mut self,
8841 upwards: bool,
8842 whole_lines: bool,
8843 window: &mut Window,
8844 cx: &mut Context<Self>,
8845 ) {
8846 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8847 let buffer = &display_map.buffer_snapshot;
8848 let selections = self.selections.all::<Point>(cx);
8849
8850 let mut edits = Vec::new();
8851 let mut selections_iter = selections.iter().peekable();
8852 while let Some(selection) = selections_iter.next() {
8853 let mut rows = selection.spanned_rows(false, &display_map);
8854 // duplicate line-wise
8855 if whole_lines || selection.start == selection.end {
8856 // Avoid duplicating the same lines twice.
8857 while let Some(next_selection) = selections_iter.peek() {
8858 let next_rows = next_selection.spanned_rows(false, &display_map);
8859 if next_rows.start < rows.end {
8860 rows.end = next_rows.end;
8861 selections_iter.next().unwrap();
8862 } else {
8863 break;
8864 }
8865 }
8866
8867 // Copy the text from the selected row region and splice it either at the start
8868 // or end of the region.
8869 let start = Point::new(rows.start.0, 0);
8870 let end = Point::new(
8871 rows.end.previous_row().0,
8872 buffer.line_len(rows.end.previous_row()),
8873 );
8874 let text = buffer
8875 .text_for_range(start..end)
8876 .chain(Some("\n"))
8877 .collect::<String>();
8878 let insert_location = if upwards {
8879 Point::new(rows.end.0, 0)
8880 } else {
8881 start
8882 };
8883 edits.push((insert_location..insert_location, text));
8884 } else {
8885 // duplicate character-wise
8886 let start = selection.start;
8887 let end = selection.end;
8888 let text = buffer.text_for_range(start..end).collect::<String>();
8889 edits.push((selection.end..selection.end, text));
8890 }
8891 }
8892
8893 self.transact(window, cx, |this, _, cx| {
8894 this.buffer.update(cx, |buffer, cx| {
8895 buffer.edit(edits, None, cx);
8896 });
8897
8898 this.request_autoscroll(Autoscroll::fit(), cx);
8899 });
8900 }
8901
8902 pub fn duplicate_line_up(
8903 &mut self,
8904 _: &DuplicateLineUp,
8905 window: &mut Window,
8906 cx: &mut Context<Self>,
8907 ) {
8908 self.duplicate(true, true, window, cx);
8909 }
8910
8911 pub fn duplicate_line_down(
8912 &mut self,
8913 _: &DuplicateLineDown,
8914 window: &mut Window,
8915 cx: &mut Context<Self>,
8916 ) {
8917 self.duplicate(false, true, window, cx);
8918 }
8919
8920 pub fn duplicate_selection(
8921 &mut self,
8922 _: &DuplicateSelection,
8923 window: &mut Window,
8924 cx: &mut Context<Self>,
8925 ) {
8926 self.duplicate(false, false, window, cx);
8927 }
8928
8929 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
8930 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8931 let buffer = self.buffer.read(cx).snapshot(cx);
8932
8933 let mut edits = Vec::new();
8934 let mut unfold_ranges = Vec::new();
8935 let mut refold_creases = Vec::new();
8936
8937 let selections = self.selections.all::<Point>(cx);
8938 let mut selections = selections.iter().peekable();
8939 let mut contiguous_row_selections = Vec::new();
8940 let mut new_selections = Vec::new();
8941
8942 while let Some(selection) = selections.next() {
8943 // Find all the selections that span a contiguous row range
8944 let (start_row, end_row) = consume_contiguous_rows(
8945 &mut contiguous_row_selections,
8946 selection,
8947 &display_map,
8948 &mut selections,
8949 );
8950
8951 // Move the text spanned by the row range to be before the line preceding the row range
8952 if start_row.0 > 0 {
8953 let range_to_move = Point::new(
8954 start_row.previous_row().0,
8955 buffer.line_len(start_row.previous_row()),
8956 )
8957 ..Point::new(
8958 end_row.previous_row().0,
8959 buffer.line_len(end_row.previous_row()),
8960 );
8961 let insertion_point = display_map
8962 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
8963 .0;
8964
8965 // Don't move lines across excerpts
8966 if buffer
8967 .excerpt_containing(insertion_point..range_to_move.end)
8968 .is_some()
8969 {
8970 let text = buffer
8971 .text_for_range(range_to_move.clone())
8972 .flat_map(|s| s.chars())
8973 .skip(1)
8974 .chain(['\n'])
8975 .collect::<String>();
8976
8977 edits.push((
8978 buffer.anchor_after(range_to_move.start)
8979 ..buffer.anchor_before(range_to_move.end),
8980 String::new(),
8981 ));
8982 let insertion_anchor = buffer.anchor_after(insertion_point);
8983 edits.push((insertion_anchor..insertion_anchor, text));
8984
8985 let row_delta = range_to_move.start.row - insertion_point.row + 1;
8986
8987 // Move selections up
8988 new_selections.extend(contiguous_row_selections.drain(..).map(
8989 |mut selection| {
8990 selection.start.row -= row_delta;
8991 selection.end.row -= row_delta;
8992 selection
8993 },
8994 ));
8995
8996 // Move folds up
8997 unfold_ranges.push(range_to_move.clone());
8998 for fold in display_map.folds_in_range(
8999 buffer.anchor_before(range_to_move.start)
9000 ..buffer.anchor_after(range_to_move.end),
9001 ) {
9002 let mut start = fold.range.start.to_point(&buffer);
9003 let mut end = fold.range.end.to_point(&buffer);
9004 start.row -= row_delta;
9005 end.row -= row_delta;
9006 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9007 }
9008 }
9009 }
9010
9011 // If we didn't move line(s), preserve the existing selections
9012 new_selections.append(&mut contiguous_row_selections);
9013 }
9014
9015 self.transact(window, cx, |this, window, cx| {
9016 this.unfold_ranges(&unfold_ranges, true, true, cx);
9017 this.buffer.update(cx, |buffer, cx| {
9018 for (range, text) in edits {
9019 buffer.edit([(range, text)], None, cx);
9020 }
9021 });
9022 this.fold_creases(refold_creases, true, window, cx);
9023 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9024 s.select(new_selections);
9025 })
9026 });
9027 }
9028
9029 pub fn move_line_down(
9030 &mut self,
9031 _: &MoveLineDown,
9032 window: &mut Window,
9033 cx: &mut Context<Self>,
9034 ) {
9035 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9036 let buffer = self.buffer.read(cx).snapshot(cx);
9037
9038 let mut edits = Vec::new();
9039 let mut unfold_ranges = Vec::new();
9040 let mut refold_creases = Vec::new();
9041
9042 let selections = self.selections.all::<Point>(cx);
9043 let mut selections = selections.iter().peekable();
9044 let mut contiguous_row_selections = Vec::new();
9045 let mut new_selections = Vec::new();
9046
9047 while let Some(selection) = selections.next() {
9048 // Find all the selections that span a contiguous row range
9049 let (start_row, end_row) = consume_contiguous_rows(
9050 &mut contiguous_row_selections,
9051 selection,
9052 &display_map,
9053 &mut selections,
9054 );
9055
9056 // Move the text spanned by the row range to be after the last line of the row range
9057 if end_row.0 <= buffer.max_point().row {
9058 let range_to_move =
9059 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9060 let insertion_point = display_map
9061 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9062 .0;
9063
9064 // Don't move lines across excerpt boundaries
9065 if buffer
9066 .excerpt_containing(range_to_move.start..insertion_point)
9067 .is_some()
9068 {
9069 let mut text = String::from("\n");
9070 text.extend(buffer.text_for_range(range_to_move.clone()));
9071 text.pop(); // Drop trailing newline
9072 edits.push((
9073 buffer.anchor_after(range_to_move.start)
9074 ..buffer.anchor_before(range_to_move.end),
9075 String::new(),
9076 ));
9077 let insertion_anchor = buffer.anchor_after(insertion_point);
9078 edits.push((insertion_anchor..insertion_anchor, text));
9079
9080 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9081
9082 // Move selections down
9083 new_selections.extend(contiguous_row_selections.drain(..).map(
9084 |mut selection| {
9085 selection.start.row += row_delta;
9086 selection.end.row += row_delta;
9087 selection
9088 },
9089 ));
9090
9091 // Move folds down
9092 unfold_ranges.push(range_to_move.clone());
9093 for fold in display_map.folds_in_range(
9094 buffer.anchor_before(range_to_move.start)
9095 ..buffer.anchor_after(range_to_move.end),
9096 ) {
9097 let mut start = fold.range.start.to_point(&buffer);
9098 let mut end = fold.range.end.to_point(&buffer);
9099 start.row += row_delta;
9100 end.row += row_delta;
9101 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9102 }
9103 }
9104 }
9105
9106 // If we didn't move line(s), preserve the existing selections
9107 new_selections.append(&mut contiguous_row_selections);
9108 }
9109
9110 self.transact(window, cx, |this, window, cx| {
9111 this.unfold_ranges(&unfold_ranges, true, true, cx);
9112 this.buffer.update(cx, |buffer, cx| {
9113 for (range, text) in edits {
9114 buffer.edit([(range, text)], None, cx);
9115 }
9116 });
9117 this.fold_creases(refold_creases, true, window, cx);
9118 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9119 s.select(new_selections)
9120 });
9121 });
9122 }
9123
9124 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9125 let text_layout_details = &self.text_layout_details(window);
9126 self.transact(window, cx, |this, window, cx| {
9127 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9128 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9129 let line_mode = s.line_mode;
9130 s.move_with(|display_map, selection| {
9131 if !selection.is_empty() || line_mode {
9132 return;
9133 }
9134
9135 let mut head = selection.head();
9136 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9137 if head.column() == display_map.line_len(head.row()) {
9138 transpose_offset = display_map
9139 .buffer_snapshot
9140 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9141 }
9142
9143 if transpose_offset == 0 {
9144 return;
9145 }
9146
9147 *head.column_mut() += 1;
9148 head = display_map.clip_point(head, Bias::Right);
9149 let goal = SelectionGoal::HorizontalPosition(
9150 display_map
9151 .x_for_display_point(head, text_layout_details)
9152 .into(),
9153 );
9154 selection.collapse_to(head, goal);
9155
9156 let transpose_start = display_map
9157 .buffer_snapshot
9158 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9159 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9160 let transpose_end = display_map
9161 .buffer_snapshot
9162 .clip_offset(transpose_offset + 1, Bias::Right);
9163 if let Some(ch) =
9164 display_map.buffer_snapshot.chars_at(transpose_start).next()
9165 {
9166 edits.push((transpose_start..transpose_offset, String::new()));
9167 edits.push((transpose_end..transpose_end, ch.to_string()));
9168 }
9169 }
9170 });
9171 edits
9172 });
9173 this.buffer
9174 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9175 let selections = this.selections.all::<usize>(cx);
9176 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9177 s.select(selections);
9178 });
9179 });
9180 }
9181
9182 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9183 self.rewrap_impl(RewrapOptions::default(), cx)
9184 }
9185
9186 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9187 let buffer = self.buffer.read(cx).snapshot(cx);
9188 let selections = self.selections.all::<Point>(cx);
9189 let mut selections = selections.iter().peekable();
9190
9191 let mut edits = Vec::new();
9192 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9193
9194 while let Some(selection) = selections.next() {
9195 let mut start_row = selection.start.row;
9196 let mut end_row = selection.end.row;
9197
9198 // Skip selections that overlap with a range that has already been rewrapped.
9199 let selection_range = start_row..end_row;
9200 if rewrapped_row_ranges
9201 .iter()
9202 .any(|range| range.overlaps(&selection_range))
9203 {
9204 continue;
9205 }
9206
9207 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9208
9209 // Since not all lines in the selection may be at the same indent
9210 // level, choose the indent size that is the most common between all
9211 // of the lines.
9212 //
9213 // If there is a tie, we use the deepest indent.
9214 let (indent_size, indent_end) = {
9215 let mut indent_size_occurrences = HashMap::default();
9216 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9217
9218 for row in start_row..=end_row {
9219 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9220 rows_by_indent_size.entry(indent).or_default().push(row);
9221 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9222 }
9223
9224 let indent_size = indent_size_occurrences
9225 .into_iter()
9226 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9227 .map(|(indent, _)| indent)
9228 .unwrap_or_default();
9229 let row = rows_by_indent_size[&indent_size][0];
9230 let indent_end = Point::new(row, indent_size.len);
9231
9232 (indent_size, indent_end)
9233 };
9234
9235 let mut line_prefix = indent_size.chars().collect::<String>();
9236
9237 let mut inside_comment = false;
9238 if let Some(comment_prefix) =
9239 buffer
9240 .language_scope_at(selection.head())
9241 .and_then(|language| {
9242 language
9243 .line_comment_prefixes()
9244 .iter()
9245 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9246 .cloned()
9247 })
9248 {
9249 line_prefix.push_str(&comment_prefix);
9250 inside_comment = true;
9251 }
9252
9253 let language_settings = buffer.language_settings_at(selection.head(), cx);
9254 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9255 RewrapBehavior::InComments => inside_comment,
9256 RewrapBehavior::InSelections => !selection.is_empty(),
9257 RewrapBehavior::Anywhere => true,
9258 };
9259
9260 let should_rewrap = options.override_language_settings
9261 || allow_rewrap_based_on_language
9262 || self.hard_wrap.is_some();
9263 if !should_rewrap {
9264 continue;
9265 }
9266
9267 if selection.is_empty() {
9268 'expand_upwards: while start_row > 0 {
9269 let prev_row = start_row - 1;
9270 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
9271 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
9272 {
9273 start_row = prev_row;
9274 } else {
9275 break 'expand_upwards;
9276 }
9277 }
9278
9279 'expand_downwards: while end_row < buffer.max_point().row {
9280 let next_row = end_row + 1;
9281 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
9282 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
9283 {
9284 end_row = next_row;
9285 } else {
9286 break 'expand_downwards;
9287 }
9288 }
9289 }
9290
9291 let start = Point::new(start_row, 0);
9292 let start_offset = start.to_offset(&buffer);
9293 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
9294 let selection_text = buffer.text_for_range(start..end).collect::<String>();
9295 let Some(lines_without_prefixes) = selection_text
9296 .lines()
9297 .map(|line| {
9298 line.strip_prefix(&line_prefix)
9299 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
9300 .ok_or_else(|| {
9301 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
9302 })
9303 })
9304 .collect::<Result<Vec<_>, _>>()
9305 .log_err()
9306 else {
9307 continue;
9308 };
9309
9310 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
9311 buffer
9312 .language_settings_at(Point::new(start_row, 0), cx)
9313 .preferred_line_length as usize
9314 });
9315 let wrapped_text = wrap_with_prefix(
9316 line_prefix,
9317 lines_without_prefixes.join("\n"),
9318 wrap_column,
9319 tab_size,
9320 options.preserve_existing_whitespace,
9321 );
9322
9323 // TODO: should always use char-based diff while still supporting cursor behavior that
9324 // matches vim.
9325 let mut diff_options = DiffOptions::default();
9326 if options.override_language_settings {
9327 diff_options.max_word_diff_len = 0;
9328 diff_options.max_word_diff_line_count = 0;
9329 } else {
9330 diff_options.max_word_diff_len = usize::MAX;
9331 diff_options.max_word_diff_line_count = usize::MAX;
9332 }
9333
9334 for (old_range, new_text) in
9335 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
9336 {
9337 let edit_start = buffer.anchor_after(start_offset + old_range.start);
9338 let edit_end = buffer.anchor_after(start_offset + old_range.end);
9339 edits.push((edit_start..edit_end, new_text));
9340 }
9341
9342 rewrapped_row_ranges.push(start_row..=end_row);
9343 }
9344
9345 self.buffer
9346 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9347 }
9348
9349 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
9350 let mut text = String::new();
9351 let buffer = self.buffer.read(cx).snapshot(cx);
9352 let mut selections = self.selections.all::<Point>(cx);
9353 let mut clipboard_selections = Vec::with_capacity(selections.len());
9354 {
9355 let max_point = buffer.max_point();
9356 let mut is_first = true;
9357 for selection in &mut selections {
9358 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9359 if is_entire_line {
9360 selection.start = Point::new(selection.start.row, 0);
9361 if !selection.is_empty() && selection.end.column == 0 {
9362 selection.end = cmp::min(max_point, selection.end);
9363 } else {
9364 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
9365 }
9366 selection.goal = SelectionGoal::None;
9367 }
9368 if is_first {
9369 is_first = false;
9370 } else {
9371 text += "\n";
9372 }
9373 let mut len = 0;
9374 for chunk in buffer.text_for_range(selection.start..selection.end) {
9375 text.push_str(chunk);
9376 len += chunk.len();
9377 }
9378 clipboard_selections.push(ClipboardSelection {
9379 len,
9380 is_entire_line,
9381 first_line_indent: buffer
9382 .indent_size_for_line(MultiBufferRow(selection.start.row))
9383 .len,
9384 });
9385 }
9386 }
9387
9388 self.transact(window, cx, |this, window, cx| {
9389 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9390 s.select(selections);
9391 });
9392 this.insert("", window, cx);
9393 });
9394 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
9395 }
9396
9397 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
9398 let item = self.cut_common(window, cx);
9399 cx.write_to_clipboard(item);
9400 }
9401
9402 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
9403 self.change_selections(None, window, cx, |s| {
9404 s.move_with(|snapshot, sel| {
9405 if sel.is_empty() {
9406 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
9407 }
9408 });
9409 });
9410 let item = self.cut_common(window, cx);
9411 cx.set_global(KillRing(item))
9412 }
9413
9414 pub fn kill_ring_yank(
9415 &mut self,
9416 _: &KillRingYank,
9417 window: &mut Window,
9418 cx: &mut Context<Self>,
9419 ) {
9420 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
9421 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
9422 (kill_ring.text().to_string(), kill_ring.metadata_json())
9423 } else {
9424 return;
9425 }
9426 } else {
9427 return;
9428 };
9429 self.do_paste(&text, metadata, false, window, cx);
9430 }
9431
9432 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
9433 let selections = self.selections.all::<Point>(cx);
9434 let buffer = self.buffer.read(cx).read(cx);
9435 let mut text = String::new();
9436
9437 let mut clipboard_selections = Vec::with_capacity(selections.len());
9438 {
9439 let max_point = buffer.max_point();
9440 let mut is_first = true;
9441 for selection in selections.iter() {
9442 let mut start = selection.start;
9443 let mut end = selection.end;
9444 let is_entire_line = selection.is_empty() || self.selections.line_mode;
9445 if is_entire_line {
9446 start = Point::new(start.row, 0);
9447 end = cmp::min(max_point, Point::new(end.row + 1, 0));
9448 }
9449 if is_first {
9450 is_first = false;
9451 } else {
9452 text += "\n";
9453 }
9454 let mut len = 0;
9455 for chunk in buffer.text_for_range(start..end) {
9456 text.push_str(chunk);
9457 len += chunk.len();
9458 }
9459 clipboard_selections.push(ClipboardSelection {
9460 len,
9461 is_entire_line,
9462 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
9463 });
9464 }
9465 }
9466
9467 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
9468 text,
9469 clipboard_selections,
9470 ));
9471 }
9472
9473 pub fn do_paste(
9474 &mut self,
9475 text: &String,
9476 clipboard_selections: Option<Vec<ClipboardSelection>>,
9477 handle_entire_lines: bool,
9478 window: &mut Window,
9479 cx: &mut Context<Self>,
9480 ) {
9481 if self.read_only(cx) {
9482 return;
9483 }
9484
9485 let clipboard_text = Cow::Borrowed(text);
9486
9487 self.transact(window, cx, |this, window, cx| {
9488 if let Some(mut clipboard_selections) = clipboard_selections {
9489 let old_selections = this.selections.all::<usize>(cx);
9490 let all_selections_were_entire_line =
9491 clipboard_selections.iter().all(|s| s.is_entire_line);
9492 let first_selection_indent_column =
9493 clipboard_selections.first().map(|s| s.first_line_indent);
9494 if clipboard_selections.len() != old_selections.len() {
9495 clipboard_selections.drain(..);
9496 }
9497 let cursor_offset = this.selections.last::<usize>(cx).head();
9498 let mut auto_indent_on_paste = true;
9499
9500 this.buffer.update(cx, |buffer, cx| {
9501 let snapshot = buffer.read(cx);
9502 auto_indent_on_paste = snapshot
9503 .language_settings_at(cursor_offset, cx)
9504 .auto_indent_on_paste;
9505
9506 let mut start_offset = 0;
9507 let mut edits = Vec::new();
9508 let mut original_indent_columns = Vec::new();
9509 for (ix, selection) in old_selections.iter().enumerate() {
9510 let to_insert;
9511 let entire_line;
9512 let original_indent_column;
9513 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
9514 let end_offset = start_offset + clipboard_selection.len;
9515 to_insert = &clipboard_text[start_offset..end_offset];
9516 entire_line = clipboard_selection.is_entire_line;
9517 start_offset = end_offset + 1;
9518 original_indent_column = Some(clipboard_selection.first_line_indent);
9519 } else {
9520 to_insert = clipboard_text.as_str();
9521 entire_line = all_selections_were_entire_line;
9522 original_indent_column = first_selection_indent_column
9523 }
9524
9525 // If the corresponding selection was empty when this slice of the
9526 // clipboard text was written, then the entire line containing the
9527 // selection was copied. If this selection is also currently empty,
9528 // then paste the line before the current line of the buffer.
9529 let range = if selection.is_empty() && handle_entire_lines && entire_line {
9530 let column = selection.start.to_point(&snapshot).column as usize;
9531 let line_start = selection.start - column;
9532 line_start..line_start
9533 } else {
9534 selection.range()
9535 };
9536
9537 edits.push((range, to_insert));
9538 original_indent_columns.push(original_indent_column);
9539 }
9540 drop(snapshot);
9541
9542 buffer.edit(
9543 edits,
9544 if auto_indent_on_paste {
9545 Some(AutoindentMode::Block {
9546 original_indent_columns,
9547 })
9548 } else {
9549 None
9550 },
9551 cx,
9552 );
9553 });
9554
9555 let selections = this.selections.all::<usize>(cx);
9556 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9557 s.select(selections)
9558 });
9559 } else {
9560 this.insert(&clipboard_text, window, cx);
9561 }
9562 });
9563 }
9564
9565 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
9566 if let Some(item) = cx.read_from_clipboard() {
9567 let entries = item.entries();
9568
9569 match entries.first() {
9570 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
9571 // of all the pasted entries.
9572 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
9573 .do_paste(
9574 clipboard_string.text(),
9575 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
9576 true,
9577 window,
9578 cx,
9579 ),
9580 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
9581 }
9582 }
9583 }
9584
9585 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
9586 if self.read_only(cx) {
9587 return;
9588 }
9589
9590 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
9591 if let Some((selections, _)) =
9592 self.selection_history.transaction(transaction_id).cloned()
9593 {
9594 self.change_selections(None, window, cx, |s| {
9595 s.select_anchors(selections.to_vec());
9596 });
9597 } else {
9598 log::error!(
9599 "No entry in selection_history found for undo. \
9600 This may correspond to a bug where undo does not update the selection. \
9601 If this is occurring, please add details to \
9602 https://github.com/zed-industries/zed/issues/22692"
9603 );
9604 }
9605 self.request_autoscroll(Autoscroll::fit(), cx);
9606 self.unmark_text(window, cx);
9607 self.refresh_inline_completion(true, false, window, cx);
9608 cx.emit(EditorEvent::Edited { transaction_id });
9609 cx.emit(EditorEvent::TransactionUndone { transaction_id });
9610 }
9611 }
9612
9613 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
9614 if self.read_only(cx) {
9615 return;
9616 }
9617
9618 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
9619 if let Some((_, Some(selections))) =
9620 self.selection_history.transaction(transaction_id).cloned()
9621 {
9622 self.change_selections(None, window, cx, |s| {
9623 s.select_anchors(selections.to_vec());
9624 });
9625 } else {
9626 log::error!(
9627 "No entry in selection_history found for redo. \
9628 This may correspond to a bug where undo does not update the selection. \
9629 If this is occurring, please add details to \
9630 https://github.com/zed-industries/zed/issues/22692"
9631 );
9632 }
9633 self.request_autoscroll(Autoscroll::fit(), cx);
9634 self.unmark_text(window, cx);
9635 self.refresh_inline_completion(true, false, window, cx);
9636 cx.emit(EditorEvent::Edited { transaction_id });
9637 }
9638 }
9639
9640 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
9641 self.buffer
9642 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
9643 }
9644
9645 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
9646 self.buffer
9647 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
9648 }
9649
9650 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
9651 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9652 let line_mode = s.line_mode;
9653 s.move_with(|map, selection| {
9654 let cursor = if selection.is_empty() && !line_mode {
9655 movement::left(map, selection.start)
9656 } else {
9657 selection.start
9658 };
9659 selection.collapse_to(cursor, SelectionGoal::None);
9660 });
9661 })
9662 }
9663
9664 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
9665 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9666 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
9667 })
9668 }
9669
9670 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
9671 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9672 let line_mode = s.line_mode;
9673 s.move_with(|map, selection| {
9674 let cursor = if selection.is_empty() && !line_mode {
9675 movement::right(map, selection.end)
9676 } else {
9677 selection.end
9678 };
9679 selection.collapse_to(cursor, SelectionGoal::None)
9680 });
9681 })
9682 }
9683
9684 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
9685 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9686 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
9687 })
9688 }
9689
9690 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
9691 if self.take_rename(true, window, cx).is_some() {
9692 return;
9693 }
9694
9695 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9696 cx.propagate();
9697 return;
9698 }
9699
9700 let text_layout_details = &self.text_layout_details(window);
9701 let selection_count = self.selections.count();
9702 let first_selection = self.selections.first_anchor();
9703
9704 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9705 let line_mode = s.line_mode;
9706 s.move_with(|map, selection| {
9707 if !selection.is_empty() && !line_mode {
9708 selection.goal = SelectionGoal::None;
9709 }
9710 let (cursor, goal) = movement::up(
9711 map,
9712 selection.start,
9713 selection.goal,
9714 false,
9715 text_layout_details,
9716 );
9717 selection.collapse_to(cursor, goal);
9718 });
9719 });
9720
9721 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9722 {
9723 cx.propagate();
9724 }
9725 }
9726
9727 pub fn move_up_by_lines(
9728 &mut self,
9729 action: &MoveUpByLines,
9730 window: &mut Window,
9731 cx: &mut Context<Self>,
9732 ) {
9733 if self.take_rename(true, window, cx).is_some() {
9734 return;
9735 }
9736
9737 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9738 cx.propagate();
9739 return;
9740 }
9741
9742 let text_layout_details = &self.text_layout_details(window);
9743
9744 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9745 let line_mode = s.line_mode;
9746 s.move_with(|map, selection| {
9747 if !selection.is_empty() && !line_mode {
9748 selection.goal = SelectionGoal::None;
9749 }
9750 let (cursor, goal) = movement::up_by_rows(
9751 map,
9752 selection.start,
9753 action.lines,
9754 selection.goal,
9755 false,
9756 text_layout_details,
9757 );
9758 selection.collapse_to(cursor, goal);
9759 });
9760 })
9761 }
9762
9763 pub fn move_down_by_lines(
9764 &mut self,
9765 action: &MoveDownByLines,
9766 window: &mut Window,
9767 cx: &mut Context<Self>,
9768 ) {
9769 if self.take_rename(true, window, cx).is_some() {
9770 return;
9771 }
9772
9773 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9774 cx.propagate();
9775 return;
9776 }
9777
9778 let text_layout_details = &self.text_layout_details(window);
9779
9780 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9781 let line_mode = s.line_mode;
9782 s.move_with(|map, selection| {
9783 if !selection.is_empty() && !line_mode {
9784 selection.goal = SelectionGoal::None;
9785 }
9786 let (cursor, goal) = movement::down_by_rows(
9787 map,
9788 selection.start,
9789 action.lines,
9790 selection.goal,
9791 false,
9792 text_layout_details,
9793 );
9794 selection.collapse_to(cursor, goal);
9795 });
9796 })
9797 }
9798
9799 pub fn select_down_by_lines(
9800 &mut self,
9801 action: &SelectDownByLines,
9802 window: &mut Window,
9803 cx: &mut Context<Self>,
9804 ) {
9805 let text_layout_details = &self.text_layout_details(window);
9806 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9807 s.move_heads_with(|map, head, goal| {
9808 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
9809 })
9810 })
9811 }
9812
9813 pub fn select_up_by_lines(
9814 &mut self,
9815 action: &SelectUpByLines,
9816 window: &mut Window,
9817 cx: &mut Context<Self>,
9818 ) {
9819 let text_layout_details = &self.text_layout_details(window);
9820 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9821 s.move_heads_with(|map, head, goal| {
9822 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
9823 })
9824 })
9825 }
9826
9827 pub fn select_page_up(
9828 &mut self,
9829 _: &SelectPageUp,
9830 window: &mut Window,
9831 cx: &mut Context<Self>,
9832 ) {
9833 let Some(row_count) = self.visible_row_count() else {
9834 return;
9835 };
9836
9837 let text_layout_details = &self.text_layout_details(window);
9838
9839 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9840 s.move_heads_with(|map, head, goal| {
9841 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
9842 })
9843 })
9844 }
9845
9846 pub fn move_page_up(
9847 &mut self,
9848 action: &MovePageUp,
9849 window: &mut Window,
9850 cx: &mut Context<Self>,
9851 ) {
9852 if self.take_rename(true, window, cx).is_some() {
9853 return;
9854 }
9855
9856 if self
9857 .context_menu
9858 .borrow_mut()
9859 .as_mut()
9860 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
9861 .unwrap_or(false)
9862 {
9863 return;
9864 }
9865
9866 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9867 cx.propagate();
9868 return;
9869 }
9870
9871 let Some(row_count) = self.visible_row_count() else {
9872 return;
9873 };
9874
9875 let autoscroll = if action.center_cursor {
9876 Autoscroll::center()
9877 } else {
9878 Autoscroll::fit()
9879 };
9880
9881 let text_layout_details = &self.text_layout_details(window);
9882
9883 self.change_selections(Some(autoscroll), window, cx, |s| {
9884 let line_mode = s.line_mode;
9885 s.move_with(|map, selection| {
9886 if !selection.is_empty() && !line_mode {
9887 selection.goal = SelectionGoal::None;
9888 }
9889 let (cursor, goal) = movement::up_by_rows(
9890 map,
9891 selection.end,
9892 row_count,
9893 selection.goal,
9894 false,
9895 text_layout_details,
9896 );
9897 selection.collapse_to(cursor, goal);
9898 });
9899 });
9900 }
9901
9902 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
9903 let text_layout_details = &self.text_layout_details(window);
9904 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9905 s.move_heads_with(|map, head, goal| {
9906 movement::up(map, head, goal, false, text_layout_details)
9907 })
9908 })
9909 }
9910
9911 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
9912 self.take_rename(true, window, cx);
9913
9914 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9915 cx.propagate();
9916 return;
9917 }
9918
9919 let text_layout_details = &self.text_layout_details(window);
9920 let selection_count = self.selections.count();
9921 let first_selection = self.selections.first_anchor();
9922
9923 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9924 let line_mode = s.line_mode;
9925 s.move_with(|map, selection| {
9926 if !selection.is_empty() && !line_mode {
9927 selection.goal = SelectionGoal::None;
9928 }
9929 let (cursor, goal) = movement::down(
9930 map,
9931 selection.end,
9932 selection.goal,
9933 false,
9934 text_layout_details,
9935 );
9936 selection.collapse_to(cursor, goal);
9937 });
9938 });
9939
9940 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
9941 {
9942 cx.propagate();
9943 }
9944 }
9945
9946 pub fn select_page_down(
9947 &mut self,
9948 _: &SelectPageDown,
9949 window: &mut Window,
9950 cx: &mut Context<Self>,
9951 ) {
9952 let Some(row_count) = self.visible_row_count() else {
9953 return;
9954 };
9955
9956 let text_layout_details = &self.text_layout_details(window);
9957
9958 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9959 s.move_heads_with(|map, head, goal| {
9960 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
9961 })
9962 })
9963 }
9964
9965 pub fn move_page_down(
9966 &mut self,
9967 action: &MovePageDown,
9968 window: &mut Window,
9969 cx: &mut Context<Self>,
9970 ) {
9971 if self.take_rename(true, window, cx).is_some() {
9972 return;
9973 }
9974
9975 if self
9976 .context_menu
9977 .borrow_mut()
9978 .as_mut()
9979 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
9980 .unwrap_or(false)
9981 {
9982 return;
9983 }
9984
9985 if matches!(self.mode, EditorMode::SingleLine { .. }) {
9986 cx.propagate();
9987 return;
9988 }
9989
9990 let Some(row_count) = self.visible_row_count() else {
9991 return;
9992 };
9993
9994 let autoscroll = if action.center_cursor {
9995 Autoscroll::center()
9996 } else {
9997 Autoscroll::fit()
9998 };
9999
10000 let text_layout_details = &self.text_layout_details(window);
10001 self.change_selections(Some(autoscroll), window, cx, |s| {
10002 let line_mode = s.line_mode;
10003 s.move_with(|map, selection| {
10004 if !selection.is_empty() && !line_mode {
10005 selection.goal = SelectionGoal::None;
10006 }
10007 let (cursor, goal) = movement::down_by_rows(
10008 map,
10009 selection.end,
10010 row_count,
10011 selection.goal,
10012 false,
10013 text_layout_details,
10014 );
10015 selection.collapse_to(cursor, goal);
10016 });
10017 });
10018 }
10019
10020 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10021 let text_layout_details = &self.text_layout_details(window);
10022 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10023 s.move_heads_with(|map, head, goal| {
10024 movement::down(map, head, goal, false, text_layout_details)
10025 })
10026 });
10027 }
10028
10029 pub fn context_menu_first(
10030 &mut self,
10031 _: &ContextMenuFirst,
10032 _window: &mut Window,
10033 cx: &mut Context<Self>,
10034 ) {
10035 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10036 context_menu.select_first(self.completion_provider.as_deref(), cx);
10037 }
10038 }
10039
10040 pub fn context_menu_prev(
10041 &mut self,
10042 _: &ContextMenuPrevious,
10043 _window: &mut Window,
10044 cx: &mut Context<Self>,
10045 ) {
10046 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10047 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10048 }
10049 }
10050
10051 pub fn context_menu_next(
10052 &mut self,
10053 _: &ContextMenuNext,
10054 _window: &mut Window,
10055 cx: &mut Context<Self>,
10056 ) {
10057 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10058 context_menu.select_next(self.completion_provider.as_deref(), cx);
10059 }
10060 }
10061
10062 pub fn context_menu_last(
10063 &mut self,
10064 _: &ContextMenuLast,
10065 _window: &mut Window,
10066 cx: &mut Context<Self>,
10067 ) {
10068 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10069 context_menu.select_last(self.completion_provider.as_deref(), cx);
10070 }
10071 }
10072
10073 pub fn move_to_previous_word_start(
10074 &mut self,
10075 _: &MoveToPreviousWordStart,
10076 window: &mut Window,
10077 cx: &mut Context<Self>,
10078 ) {
10079 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10080 s.move_cursors_with(|map, head, _| {
10081 (
10082 movement::previous_word_start(map, head),
10083 SelectionGoal::None,
10084 )
10085 });
10086 })
10087 }
10088
10089 pub fn move_to_previous_subword_start(
10090 &mut self,
10091 _: &MoveToPreviousSubwordStart,
10092 window: &mut Window,
10093 cx: &mut Context<Self>,
10094 ) {
10095 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10096 s.move_cursors_with(|map, head, _| {
10097 (
10098 movement::previous_subword_start(map, head),
10099 SelectionGoal::None,
10100 )
10101 });
10102 })
10103 }
10104
10105 pub fn select_to_previous_word_start(
10106 &mut self,
10107 _: &SelectToPreviousWordStart,
10108 window: &mut Window,
10109 cx: &mut Context<Self>,
10110 ) {
10111 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10112 s.move_heads_with(|map, head, _| {
10113 (
10114 movement::previous_word_start(map, head),
10115 SelectionGoal::None,
10116 )
10117 });
10118 })
10119 }
10120
10121 pub fn select_to_previous_subword_start(
10122 &mut self,
10123 _: &SelectToPreviousSubwordStart,
10124 window: &mut Window,
10125 cx: &mut Context<Self>,
10126 ) {
10127 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10128 s.move_heads_with(|map, head, _| {
10129 (
10130 movement::previous_subword_start(map, head),
10131 SelectionGoal::None,
10132 )
10133 });
10134 })
10135 }
10136
10137 pub fn delete_to_previous_word_start(
10138 &mut self,
10139 action: &DeleteToPreviousWordStart,
10140 window: &mut Window,
10141 cx: &mut Context<Self>,
10142 ) {
10143 self.transact(window, cx, |this, window, cx| {
10144 this.select_autoclose_pair(window, cx);
10145 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10146 let line_mode = s.line_mode;
10147 s.move_with(|map, selection| {
10148 if selection.is_empty() && !line_mode {
10149 let cursor = if action.ignore_newlines {
10150 movement::previous_word_start(map, selection.head())
10151 } else {
10152 movement::previous_word_start_or_newline(map, selection.head())
10153 };
10154 selection.set_head(cursor, SelectionGoal::None);
10155 }
10156 });
10157 });
10158 this.insert("", window, cx);
10159 });
10160 }
10161
10162 pub fn delete_to_previous_subword_start(
10163 &mut self,
10164 _: &DeleteToPreviousSubwordStart,
10165 window: &mut Window,
10166 cx: &mut Context<Self>,
10167 ) {
10168 self.transact(window, cx, |this, window, cx| {
10169 this.select_autoclose_pair(window, cx);
10170 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10171 let line_mode = s.line_mode;
10172 s.move_with(|map, selection| {
10173 if selection.is_empty() && !line_mode {
10174 let cursor = movement::previous_subword_start(map, selection.head());
10175 selection.set_head(cursor, SelectionGoal::None);
10176 }
10177 });
10178 });
10179 this.insert("", window, cx);
10180 });
10181 }
10182
10183 pub fn move_to_next_word_end(
10184 &mut self,
10185 _: &MoveToNextWordEnd,
10186 window: &mut Window,
10187 cx: &mut Context<Self>,
10188 ) {
10189 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10190 s.move_cursors_with(|map, head, _| {
10191 (movement::next_word_end(map, head), SelectionGoal::None)
10192 });
10193 })
10194 }
10195
10196 pub fn move_to_next_subword_end(
10197 &mut self,
10198 _: &MoveToNextSubwordEnd,
10199 window: &mut Window,
10200 cx: &mut Context<Self>,
10201 ) {
10202 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10203 s.move_cursors_with(|map, head, _| {
10204 (movement::next_subword_end(map, head), SelectionGoal::None)
10205 });
10206 })
10207 }
10208
10209 pub fn select_to_next_word_end(
10210 &mut self,
10211 _: &SelectToNextWordEnd,
10212 window: &mut Window,
10213 cx: &mut Context<Self>,
10214 ) {
10215 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10216 s.move_heads_with(|map, head, _| {
10217 (movement::next_word_end(map, head), SelectionGoal::None)
10218 });
10219 })
10220 }
10221
10222 pub fn select_to_next_subword_end(
10223 &mut self,
10224 _: &SelectToNextSubwordEnd,
10225 window: &mut Window,
10226 cx: &mut Context<Self>,
10227 ) {
10228 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10229 s.move_heads_with(|map, head, _| {
10230 (movement::next_subword_end(map, head), SelectionGoal::None)
10231 });
10232 })
10233 }
10234
10235 pub fn delete_to_next_word_end(
10236 &mut self,
10237 action: &DeleteToNextWordEnd,
10238 window: &mut Window,
10239 cx: &mut Context<Self>,
10240 ) {
10241 self.transact(window, cx, |this, window, cx| {
10242 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10243 let line_mode = s.line_mode;
10244 s.move_with(|map, selection| {
10245 if selection.is_empty() && !line_mode {
10246 let cursor = if action.ignore_newlines {
10247 movement::next_word_end(map, selection.head())
10248 } else {
10249 movement::next_word_end_or_newline(map, selection.head())
10250 };
10251 selection.set_head(cursor, SelectionGoal::None);
10252 }
10253 });
10254 });
10255 this.insert("", window, cx);
10256 });
10257 }
10258
10259 pub fn delete_to_next_subword_end(
10260 &mut self,
10261 _: &DeleteToNextSubwordEnd,
10262 window: &mut Window,
10263 cx: &mut Context<Self>,
10264 ) {
10265 self.transact(window, cx, |this, window, cx| {
10266 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10267 s.move_with(|map, selection| {
10268 if selection.is_empty() {
10269 let cursor = movement::next_subword_end(map, selection.head());
10270 selection.set_head(cursor, SelectionGoal::None);
10271 }
10272 });
10273 });
10274 this.insert("", window, cx);
10275 });
10276 }
10277
10278 pub fn move_to_beginning_of_line(
10279 &mut self,
10280 action: &MoveToBeginningOfLine,
10281 window: &mut Window,
10282 cx: &mut Context<Self>,
10283 ) {
10284 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10285 s.move_cursors_with(|map, head, _| {
10286 (
10287 movement::indented_line_beginning(
10288 map,
10289 head,
10290 action.stop_at_soft_wraps,
10291 action.stop_at_indent,
10292 ),
10293 SelectionGoal::None,
10294 )
10295 });
10296 })
10297 }
10298
10299 pub fn select_to_beginning_of_line(
10300 &mut self,
10301 action: &SelectToBeginningOfLine,
10302 window: &mut Window,
10303 cx: &mut Context<Self>,
10304 ) {
10305 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10306 s.move_heads_with(|map, head, _| {
10307 (
10308 movement::indented_line_beginning(
10309 map,
10310 head,
10311 action.stop_at_soft_wraps,
10312 action.stop_at_indent,
10313 ),
10314 SelectionGoal::None,
10315 )
10316 });
10317 });
10318 }
10319
10320 pub fn delete_to_beginning_of_line(
10321 &mut self,
10322 action: &DeleteToBeginningOfLine,
10323 window: &mut Window,
10324 cx: &mut Context<Self>,
10325 ) {
10326 self.transact(window, cx, |this, window, cx| {
10327 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10328 s.move_with(|_, selection| {
10329 selection.reversed = true;
10330 });
10331 });
10332
10333 this.select_to_beginning_of_line(
10334 &SelectToBeginningOfLine {
10335 stop_at_soft_wraps: false,
10336 stop_at_indent: action.stop_at_indent,
10337 },
10338 window,
10339 cx,
10340 );
10341 this.backspace(&Backspace, window, cx);
10342 });
10343 }
10344
10345 pub fn move_to_end_of_line(
10346 &mut self,
10347 action: &MoveToEndOfLine,
10348 window: &mut Window,
10349 cx: &mut Context<Self>,
10350 ) {
10351 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10352 s.move_cursors_with(|map, head, _| {
10353 (
10354 movement::line_end(map, head, action.stop_at_soft_wraps),
10355 SelectionGoal::None,
10356 )
10357 });
10358 })
10359 }
10360
10361 pub fn select_to_end_of_line(
10362 &mut self,
10363 action: &SelectToEndOfLine,
10364 window: &mut Window,
10365 cx: &mut Context<Self>,
10366 ) {
10367 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10368 s.move_heads_with(|map, head, _| {
10369 (
10370 movement::line_end(map, head, action.stop_at_soft_wraps),
10371 SelectionGoal::None,
10372 )
10373 });
10374 })
10375 }
10376
10377 pub fn delete_to_end_of_line(
10378 &mut self,
10379 _: &DeleteToEndOfLine,
10380 window: &mut Window,
10381 cx: &mut Context<Self>,
10382 ) {
10383 self.transact(window, cx, |this, window, cx| {
10384 this.select_to_end_of_line(
10385 &SelectToEndOfLine {
10386 stop_at_soft_wraps: false,
10387 },
10388 window,
10389 cx,
10390 );
10391 this.delete(&Delete, window, cx);
10392 });
10393 }
10394
10395 pub fn cut_to_end_of_line(
10396 &mut self,
10397 _: &CutToEndOfLine,
10398 window: &mut Window,
10399 cx: &mut Context<Self>,
10400 ) {
10401 self.transact(window, cx, |this, window, cx| {
10402 this.select_to_end_of_line(
10403 &SelectToEndOfLine {
10404 stop_at_soft_wraps: false,
10405 },
10406 window,
10407 cx,
10408 );
10409 this.cut(&Cut, window, cx);
10410 });
10411 }
10412
10413 pub fn move_to_start_of_paragraph(
10414 &mut self,
10415 _: &MoveToStartOfParagraph,
10416 window: &mut Window,
10417 cx: &mut Context<Self>,
10418 ) {
10419 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10420 cx.propagate();
10421 return;
10422 }
10423
10424 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10425 s.move_with(|map, selection| {
10426 selection.collapse_to(
10427 movement::start_of_paragraph(map, selection.head(), 1),
10428 SelectionGoal::None,
10429 )
10430 });
10431 })
10432 }
10433
10434 pub fn move_to_end_of_paragraph(
10435 &mut self,
10436 _: &MoveToEndOfParagraph,
10437 window: &mut Window,
10438 cx: &mut Context<Self>,
10439 ) {
10440 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10441 cx.propagate();
10442 return;
10443 }
10444
10445 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10446 s.move_with(|map, selection| {
10447 selection.collapse_to(
10448 movement::end_of_paragraph(map, selection.head(), 1),
10449 SelectionGoal::None,
10450 )
10451 });
10452 })
10453 }
10454
10455 pub fn select_to_start_of_paragraph(
10456 &mut self,
10457 _: &SelectToStartOfParagraph,
10458 window: &mut Window,
10459 cx: &mut Context<Self>,
10460 ) {
10461 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10462 cx.propagate();
10463 return;
10464 }
10465
10466 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10467 s.move_heads_with(|map, head, _| {
10468 (
10469 movement::start_of_paragraph(map, head, 1),
10470 SelectionGoal::None,
10471 )
10472 });
10473 })
10474 }
10475
10476 pub fn select_to_end_of_paragraph(
10477 &mut self,
10478 _: &SelectToEndOfParagraph,
10479 window: &mut Window,
10480 cx: &mut Context<Self>,
10481 ) {
10482 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10483 cx.propagate();
10484 return;
10485 }
10486
10487 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10488 s.move_heads_with(|map, head, _| {
10489 (
10490 movement::end_of_paragraph(map, head, 1),
10491 SelectionGoal::None,
10492 )
10493 });
10494 })
10495 }
10496
10497 pub fn move_to_start_of_excerpt(
10498 &mut self,
10499 _: &MoveToStartOfExcerpt,
10500 window: &mut Window,
10501 cx: &mut Context<Self>,
10502 ) {
10503 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10504 cx.propagate();
10505 return;
10506 }
10507
10508 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10509 s.move_with(|map, selection| {
10510 selection.collapse_to(
10511 movement::start_of_excerpt(
10512 map,
10513 selection.head(),
10514 workspace::searchable::Direction::Prev,
10515 ),
10516 SelectionGoal::None,
10517 )
10518 });
10519 })
10520 }
10521
10522 pub fn move_to_start_of_next_excerpt(
10523 &mut self,
10524 _: &MoveToStartOfNextExcerpt,
10525 window: &mut Window,
10526 cx: &mut Context<Self>,
10527 ) {
10528 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10529 cx.propagate();
10530 return;
10531 }
10532
10533 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10534 s.move_with(|map, selection| {
10535 selection.collapse_to(
10536 movement::start_of_excerpt(
10537 map,
10538 selection.head(),
10539 workspace::searchable::Direction::Next,
10540 ),
10541 SelectionGoal::None,
10542 )
10543 });
10544 })
10545 }
10546
10547 pub fn move_to_end_of_excerpt(
10548 &mut self,
10549 _: &MoveToEndOfExcerpt,
10550 window: &mut Window,
10551 cx: &mut Context<Self>,
10552 ) {
10553 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10554 cx.propagate();
10555 return;
10556 }
10557
10558 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10559 s.move_with(|map, selection| {
10560 selection.collapse_to(
10561 movement::end_of_excerpt(
10562 map,
10563 selection.head(),
10564 workspace::searchable::Direction::Next,
10565 ),
10566 SelectionGoal::None,
10567 )
10568 });
10569 })
10570 }
10571
10572 pub fn move_to_end_of_previous_excerpt(
10573 &mut self,
10574 _: &MoveToEndOfPreviousExcerpt,
10575 window: &mut Window,
10576 cx: &mut Context<Self>,
10577 ) {
10578 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10579 cx.propagate();
10580 return;
10581 }
10582
10583 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10584 s.move_with(|map, selection| {
10585 selection.collapse_to(
10586 movement::end_of_excerpt(
10587 map,
10588 selection.head(),
10589 workspace::searchable::Direction::Prev,
10590 ),
10591 SelectionGoal::None,
10592 )
10593 });
10594 })
10595 }
10596
10597 pub fn select_to_start_of_excerpt(
10598 &mut self,
10599 _: &SelectToStartOfExcerpt,
10600 window: &mut Window,
10601 cx: &mut Context<Self>,
10602 ) {
10603 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10604 cx.propagate();
10605 return;
10606 }
10607
10608 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10609 s.move_heads_with(|map, head, _| {
10610 (
10611 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10612 SelectionGoal::None,
10613 )
10614 });
10615 })
10616 }
10617
10618 pub fn select_to_start_of_next_excerpt(
10619 &mut self,
10620 _: &SelectToStartOfNextExcerpt,
10621 window: &mut Window,
10622 cx: &mut Context<Self>,
10623 ) {
10624 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10625 cx.propagate();
10626 return;
10627 }
10628
10629 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10630 s.move_heads_with(|map, head, _| {
10631 (
10632 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
10633 SelectionGoal::None,
10634 )
10635 });
10636 })
10637 }
10638
10639 pub fn select_to_end_of_excerpt(
10640 &mut self,
10641 _: &SelectToEndOfExcerpt,
10642 window: &mut Window,
10643 cx: &mut Context<Self>,
10644 ) {
10645 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10646 cx.propagate();
10647 return;
10648 }
10649
10650 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10651 s.move_heads_with(|map, head, _| {
10652 (
10653 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
10654 SelectionGoal::None,
10655 )
10656 });
10657 })
10658 }
10659
10660 pub fn select_to_end_of_previous_excerpt(
10661 &mut self,
10662 _: &SelectToEndOfPreviousExcerpt,
10663 window: &mut Window,
10664 cx: &mut Context<Self>,
10665 ) {
10666 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10667 cx.propagate();
10668 return;
10669 }
10670
10671 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10672 s.move_heads_with(|map, head, _| {
10673 (
10674 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
10675 SelectionGoal::None,
10676 )
10677 });
10678 })
10679 }
10680
10681 pub fn move_to_beginning(
10682 &mut self,
10683 _: &MoveToBeginning,
10684 window: &mut Window,
10685 cx: &mut Context<Self>,
10686 ) {
10687 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10688 cx.propagate();
10689 return;
10690 }
10691
10692 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10693 s.select_ranges(vec![0..0]);
10694 });
10695 }
10696
10697 pub fn select_to_beginning(
10698 &mut self,
10699 _: &SelectToBeginning,
10700 window: &mut Window,
10701 cx: &mut Context<Self>,
10702 ) {
10703 let mut selection = self.selections.last::<Point>(cx);
10704 selection.set_head(Point::zero(), SelectionGoal::None);
10705
10706 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10707 s.select(vec![selection]);
10708 });
10709 }
10710
10711 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
10712 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10713 cx.propagate();
10714 return;
10715 }
10716
10717 let cursor = self.buffer.read(cx).read(cx).len();
10718 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10719 s.select_ranges(vec![cursor..cursor])
10720 });
10721 }
10722
10723 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
10724 self.nav_history = nav_history;
10725 }
10726
10727 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
10728 self.nav_history.as_ref()
10729 }
10730
10731 fn push_to_nav_history(
10732 &mut self,
10733 cursor_anchor: Anchor,
10734 new_position: Option<Point>,
10735 cx: &mut Context<Self>,
10736 ) {
10737 if let Some(nav_history) = self.nav_history.as_mut() {
10738 let buffer = self.buffer.read(cx).read(cx);
10739 let cursor_position = cursor_anchor.to_point(&buffer);
10740 let scroll_state = self.scroll_manager.anchor();
10741 let scroll_top_row = scroll_state.top_row(&buffer);
10742 drop(buffer);
10743
10744 if let Some(new_position) = new_position {
10745 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
10746 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
10747 return;
10748 }
10749 }
10750
10751 nav_history.push(
10752 Some(NavigationData {
10753 cursor_anchor,
10754 cursor_position,
10755 scroll_anchor: scroll_state,
10756 scroll_top_row,
10757 }),
10758 cx,
10759 );
10760 }
10761 }
10762
10763 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
10764 let buffer = self.buffer.read(cx).snapshot(cx);
10765 let mut selection = self.selections.first::<usize>(cx);
10766 selection.set_head(buffer.len(), SelectionGoal::None);
10767 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10768 s.select(vec![selection]);
10769 });
10770 }
10771
10772 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
10773 let end = self.buffer.read(cx).read(cx).len();
10774 self.change_selections(None, window, cx, |s| {
10775 s.select_ranges(vec![0..end]);
10776 });
10777 }
10778
10779 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
10780 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10781 let mut selections = self.selections.all::<Point>(cx);
10782 let max_point = display_map.buffer_snapshot.max_point();
10783 for selection in &mut selections {
10784 let rows = selection.spanned_rows(true, &display_map);
10785 selection.start = Point::new(rows.start.0, 0);
10786 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
10787 selection.reversed = false;
10788 }
10789 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10790 s.select(selections);
10791 });
10792 }
10793
10794 pub fn split_selection_into_lines(
10795 &mut self,
10796 _: &SplitSelectionIntoLines,
10797 window: &mut Window,
10798 cx: &mut Context<Self>,
10799 ) {
10800 let selections = self
10801 .selections
10802 .all::<Point>(cx)
10803 .into_iter()
10804 .map(|selection| selection.start..selection.end)
10805 .collect::<Vec<_>>();
10806 self.unfold_ranges(&selections, true, true, cx);
10807
10808 let mut new_selection_ranges = Vec::new();
10809 {
10810 let buffer = self.buffer.read(cx).read(cx);
10811 for selection in selections {
10812 for row in selection.start.row..selection.end.row {
10813 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
10814 new_selection_ranges.push(cursor..cursor);
10815 }
10816
10817 let is_multiline_selection = selection.start.row != selection.end.row;
10818 // Don't insert last one if it's a multi-line selection ending at the start of a line,
10819 // so this action feels more ergonomic when paired with other selection operations
10820 let should_skip_last = is_multiline_selection && selection.end.column == 0;
10821 if !should_skip_last {
10822 new_selection_ranges.push(selection.end..selection.end);
10823 }
10824 }
10825 }
10826 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10827 s.select_ranges(new_selection_ranges);
10828 });
10829 }
10830
10831 pub fn add_selection_above(
10832 &mut self,
10833 _: &AddSelectionAbove,
10834 window: &mut Window,
10835 cx: &mut Context<Self>,
10836 ) {
10837 self.add_selection(true, window, cx);
10838 }
10839
10840 pub fn add_selection_below(
10841 &mut self,
10842 _: &AddSelectionBelow,
10843 window: &mut Window,
10844 cx: &mut Context<Self>,
10845 ) {
10846 self.add_selection(false, window, cx);
10847 }
10848
10849 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
10850 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10851 let mut selections = self.selections.all::<Point>(cx);
10852 let text_layout_details = self.text_layout_details(window);
10853 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
10854 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
10855 let range = oldest_selection.display_range(&display_map).sorted();
10856
10857 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
10858 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
10859 let positions = start_x.min(end_x)..start_x.max(end_x);
10860
10861 selections.clear();
10862 let mut stack = Vec::new();
10863 for row in range.start.row().0..=range.end.row().0 {
10864 if let Some(selection) = self.selections.build_columnar_selection(
10865 &display_map,
10866 DisplayRow(row),
10867 &positions,
10868 oldest_selection.reversed,
10869 &text_layout_details,
10870 ) {
10871 stack.push(selection.id);
10872 selections.push(selection);
10873 }
10874 }
10875
10876 if above {
10877 stack.reverse();
10878 }
10879
10880 AddSelectionsState { above, stack }
10881 });
10882
10883 let last_added_selection = *state.stack.last().unwrap();
10884 let mut new_selections = Vec::new();
10885 if above == state.above {
10886 let end_row = if above {
10887 DisplayRow(0)
10888 } else {
10889 display_map.max_point().row()
10890 };
10891
10892 'outer: for selection in selections {
10893 if selection.id == last_added_selection {
10894 let range = selection.display_range(&display_map).sorted();
10895 debug_assert_eq!(range.start.row(), range.end.row());
10896 let mut row = range.start.row();
10897 let positions =
10898 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
10899 px(start)..px(end)
10900 } else {
10901 let start_x =
10902 display_map.x_for_display_point(range.start, &text_layout_details);
10903 let end_x =
10904 display_map.x_for_display_point(range.end, &text_layout_details);
10905 start_x.min(end_x)..start_x.max(end_x)
10906 };
10907
10908 while row != end_row {
10909 if above {
10910 row.0 -= 1;
10911 } else {
10912 row.0 += 1;
10913 }
10914
10915 if let Some(new_selection) = self.selections.build_columnar_selection(
10916 &display_map,
10917 row,
10918 &positions,
10919 selection.reversed,
10920 &text_layout_details,
10921 ) {
10922 state.stack.push(new_selection.id);
10923 if above {
10924 new_selections.push(new_selection);
10925 new_selections.push(selection);
10926 } else {
10927 new_selections.push(selection);
10928 new_selections.push(new_selection);
10929 }
10930
10931 continue 'outer;
10932 }
10933 }
10934 }
10935
10936 new_selections.push(selection);
10937 }
10938 } else {
10939 new_selections = selections;
10940 new_selections.retain(|s| s.id != last_added_selection);
10941 state.stack.pop();
10942 }
10943
10944 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10945 s.select(new_selections);
10946 });
10947 if state.stack.len() > 1 {
10948 self.add_selections_state = Some(state);
10949 }
10950 }
10951
10952 pub fn select_next_match_internal(
10953 &mut self,
10954 display_map: &DisplaySnapshot,
10955 replace_newest: bool,
10956 autoscroll: Option<Autoscroll>,
10957 window: &mut Window,
10958 cx: &mut Context<Self>,
10959 ) -> Result<()> {
10960 fn select_next_match_ranges(
10961 this: &mut Editor,
10962 range: Range<usize>,
10963 replace_newest: bool,
10964 auto_scroll: Option<Autoscroll>,
10965 window: &mut Window,
10966 cx: &mut Context<Editor>,
10967 ) {
10968 this.unfold_ranges(&[range.clone()], false, true, cx);
10969 this.change_selections(auto_scroll, window, cx, |s| {
10970 if replace_newest {
10971 s.delete(s.newest_anchor().id);
10972 }
10973 s.insert_range(range.clone());
10974 });
10975 }
10976
10977 let buffer = &display_map.buffer_snapshot;
10978 let mut selections = self.selections.all::<usize>(cx);
10979 if let Some(mut select_next_state) = self.select_next_state.take() {
10980 let query = &select_next_state.query;
10981 if !select_next_state.done {
10982 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
10983 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
10984 let mut next_selected_range = None;
10985
10986 let bytes_after_last_selection =
10987 buffer.bytes_in_range(last_selection.end..buffer.len());
10988 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
10989 let query_matches = query
10990 .stream_find_iter(bytes_after_last_selection)
10991 .map(|result| (last_selection.end, result))
10992 .chain(
10993 query
10994 .stream_find_iter(bytes_before_first_selection)
10995 .map(|result| (0, result)),
10996 );
10997
10998 for (start_offset, query_match) in query_matches {
10999 let query_match = query_match.unwrap(); // can only fail due to I/O
11000 let offset_range =
11001 start_offset + query_match.start()..start_offset + query_match.end();
11002 let display_range = offset_range.start.to_display_point(display_map)
11003 ..offset_range.end.to_display_point(display_map);
11004
11005 if !select_next_state.wordwise
11006 || (!movement::is_inside_word(display_map, display_range.start)
11007 && !movement::is_inside_word(display_map, display_range.end))
11008 {
11009 // TODO: This is n^2, because we might check all the selections
11010 if !selections
11011 .iter()
11012 .any(|selection| selection.range().overlaps(&offset_range))
11013 {
11014 next_selected_range = Some(offset_range);
11015 break;
11016 }
11017 }
11018 }
11019
11020 if let Some(next_selected_range) = next_selected_range {
11021 select_next_match_ranges(
11022 self,
11023 next_selected_range,
11024 replace_newest,
11025 autoscroll,
11026 window,
11027 cx,
11028 );
11029 } else {
11030 select_next_state.done = true;
11031 }
11032 }
11033
11034 self.select_next_state = Some(select_next_state);
11035 } else {
11036 let mut only_carets = true;
11037 let mut same_text_selected = true;
11038 let mut selected_text = None;
11039
11040 let mut selections_iter = selections.iter().peekable();
11041 while let Some(selection) = selections_iter.next() {
11042 if selection.start != selection.end {
11043 only_carets = false;
11044 }
11045
11046 if same_text_selected {
11047 if selected_text.is_none() {
11048 selected_text =
11049 Some(buffer.text_for_range(selection.range()).collect::<String>());
11050 }
11051
11052 if let Some(next_selection) = selections_iter.peek() {
11053 if next_selection.range().len() == selection.range().len() {
11054 let next_selected_text = buffer
11055 .text_for_range(next_selection.range())
11056 .collect::<String>();
11057 if Some(next_selected_text) != selected_text {
11058 same_text_selected = false;
11059 selected_text = None;
11060 }
11061 } else {
11062 same_text_selected = false;
11063 selected_text = None;
11064 }
11065 }
11066 }
11067 }
11068
11069 if only_carets {
11070 for selection in &mut selections {
11071 let word_range = movement::surrounding_word(
11072 display_map,
11073 selection.start.to_display_point(display_map),
11074 );
11075 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11076 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11077 selection.goal = SelectionGoal::None;
11078 selection.reversed = false;
11079 select_next_match_ranges(
11080 self,
11081 selection.start..selection.end,
11082 replace_newest,
11083 autoscroll,
11084 window,
11085 cx,
11086 );
11087 }
11088
11089 if selections.len() == 1 {
11090 let selection = selections
11091 .last()
11092 .expect("ensured that there's only one selection");
11093 let query = buffer
11094 .text_for_range(selection.start..selection.end)
11095 .collect::<String>();
11096 let is_empty = query.is_empty();
11097 let select_state = SelectNextState {
11098 query: AhoCorasick::new(&[query])?,
11099 wordwise: true,
11100 done: is_empty,
11101 };
11102 self.select_next_state = Some(select_state);
11103 } else {
11104 self.select_next_state = None;
11105 }
11106 } else if let Some(selected_text) = selected_text {
11107 self.select_next_state = Some(SelectNextState {
11108 query: AhoCorasick::new(&[selected_text])?,
11109 wordwise: false,
11110 done: false,
11111 });
11112 self.select_next_match_internal(
11113 display_map,
11114 replace_newest,
11115 autoscroll,
11116 window,
11117 cx,
11118 )?;
11119 }
11120 }
11121 Ok(())
11122 }
11123
11124 pub fn select_all_matches(
11125 &mut self,
11126 _action: &SelectAllMatches,
11127 window: &mut Window,
11128 cx: &mut Context<Self>,
11129 ) -> Result<()> {
11130 self.push_to_selection_history();
11131 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11132
11133 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11134 let Some(select_next_state) = self.select_next_state.as_mut() else {
11135 return Ok(());
11136 };
11137 if select_next_state.done {
11138 return Ok(());
11139 }
11140
11141 let mut new_selections = self.selections.all::<usize>(cx);
11142
11143 let buffer = &display_map.buffer_snapshot;
11144 let query_matches = select_next_state
11145 .query
11146 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11147
11148 for query_match in query_matches {
11149 let query_match = query_match.unwrap(); // can only fail due to I/O
11150 let offset_range = query_match.start()..query_match.end();
11151 let display_range = offset_range.start.to_display_point(&display_map)
11152 ..offset_range.end.to_display_point(&display_map);
11153
11154 if !select_next_state.wordwise
11155 || (!movement::is_inside_word(&display_map, display_range.start)
11156 && !movement::is_inside_word(&display_map, display_range.end))
11157 {
11158 self.selections.change_with(cx, |selections| {
11159 new_selections.push(Selection {
11160 id: selections.new_selection_id(),
11161 start: offset_range.start,
11162 end: offset_range.end,
11163 reversed: false,
11164 goal: SelectionGoal::None,
11165 });
11166 });
11167 }
11168 }
11169
11170 new_selections.sort_by_key(|selection| selection.start);
11171 let mut ix = 0;
11172 while ix + 1 < new_selections.len() {
11173 let current_selection = &new_selections[ix];
11174 let next_selection = &new_selections[ix + 1];
11175 if current_selection.range().overlaps(&next_selection.range()) {
11176 if current_selection.id < next_selection.id {
11177 new_selections.remove(ix + 1);
11178 } else {
11179 new_selections.remove(ix);
11180 }
11181 } else {
11182 ix += 1;
11183 }
11184 }
11185
11186 let reversed = self.selections.oldest::<usize>(cx).reversed;
11187
11188 for selection in new_selections.iter_mut() {
11189 selection.reversed = reversed;
11190 }
11191
11192 select_next_state.done = true;
11193 self.unfold_ranges(
11194 &new_selections
11195 .iter()
11196 .map(|selection| selection.range())
11197 .collect::<Vec<_>>(),
11198 false,
11199 false,
11200 cx,
11201 );
11202 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
11203 selections.select(new_selections)
11204 });
11205
11206 Ok(())
11207 }
11208
11209 pub fn select_next(
11210 &mut self,
11211 action: &SelectNext,
11212 window: &mut Window,
11213 cx: &mut Context<Self>,
11214 ) -> Result<()> {
11215 self.push_to_selection_history();
11216 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11217 self.select_next_match_internal(
11218 &display_map,
11219 action.replace_newest,
11220 Some(Autoscroll::newest()),
11221 window,
11222 cx,
11223 )?;
11224 Ok(())
11225 }
11226
11227 pub fn select_previous(
11228 &mut self,
11229 action: &SelectPrevious,
11230 window: &mut Window,
11231 cx: &mut Context<Self>,
11232 ) -> Result<()> {
11233 self.push_to_selection_history();
11234 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11235 let buffer = &display_map.buffer_snapshot;
11236 let mut selections = self.selections.all::<usize>(cx);
11237 if let Some(mut select_prev_state) = self.select_prev_state.take() {
11238 let query = &select_prev_state.query;
11239 if !select_prev_state.done {
11240 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11241 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11242 let mut next_selected_range = None;
11243 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
11244 let bytes_before_last_selection =
11245 buffer.reversed_bytes_in_range(0..last_selection.start);
11246 let bytes_after_first_selection =
11247 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
11248 let query_matches = query
11249 .stream_find_iter(bytes_before_last_selection)
11250 .map(|result| (last_selection.start, result))
11251 .chain(
11252 query
11253 .stream_find_iter(bytes_after_first_selection)
11254 .map(|result| (buffer.len(), result)),
11255 );
11256 for (end_offset, query_match) in query_matches {
11257 let query_match = query_match.unwrap(); // can only fail due to I/O
11258 let offset_range =
11259 end_offset - query_match.end()..end_offset - query_match.start();
11260 let display_range = offset_range.start.to_display_point(&display_map)
11261 ..offset_range.end.to_display_point(&display_map);
11262
11263 if !select_prev_state.wordwise
11264 || (!movement::is_inside_word(&display_map, display_range.start)
11265 && !movement::is_inside_word(&display_map, display_range.end))
11266 {
11267 next_selected_range = Some(offset_range);
11268 break;
11269 }
11270 }
11271
11272 if let Some(next_selected_range) = next_selected_range {
11273 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
11274 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11275 if action.replace_newest {
11276 s.delete(s.newest_anchor().id);
11277 }
11278 s.insert_range(next_selected_range);
11279 });
11280 } else {
11281 select_prev_state.done = true;
11282 }
11283 }
11284
11285 self.select_prev_state = Some(select_prev_state);
11286 } else {
11287 let mut only_carets = true;
11288 let mut same_text_selected = true;
11289 let mut selected_text = None;
11290
11291 let mut selections_iter = selections.iter().peekable();
11292 while let Some(selection) = selections_iter.next() {
11293 if selection.start != selection.end {
11294 only_carets = false;
11295 }
11296
11297 if same_text_selected {
11298 if selected_text.is_none() {
11299 selected_text =
11300 Some(buffer.text_for_range(selection.range()).collect::<String>());
11301 }
11302
11303 if let Some(next_selection) = selections_iter.peek() {
11304 if next_selection.range().len() == selection.range().len() {
11305 let next_selected_text = buffer
11306 .text_for_range(next_selection.range())
11307 .collect::<String>();
11308 if Some(next_selected_text) != selected_text {
11309 same_text_selected = false;
11310 selected_text = None;
11311 }
11312 } else {
11313 same_text_selected = false;
11314 selected_text = None;
11315 }
11316 }
11317 }
11318 }
11319
11320 if only_carets {
11321 for selection in &mut selections {
11322 let word_range = movement::surrounding_word(
11323 &display_map,
11324 selection.start.to_display_point(&display_map),
11325 );
11326 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
11327 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
11328 selection.goal = SelectionGoal::None;
11329 selection.reversed = false;
11330 }
11331 if selections.len() == 1 {
11332 let selection = selections
11333 .last()
11334 .expect("ensured that there's only one selection");
11335 let query = buffer
11336 .text_for_range(selection.start..selection.end)
11337 .collect::<String>();
11338 let is_empty = query.is_empty();
11339 let select_state = SelectNextState {
11340 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
11341 wordwise: true,
11342 done: is_empty,
11343 };
11344 self.select_prev_state = Some(select_state);
11345 } else {
11346 self.select_prev_state = None;
11347 }
11348
11349 self.unfold_ranges(
11350 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
11351 false,
11352 true,
11353 cx,
11354 );
11355 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
11356 s.select(selections);
11357 });
11358 } else if let Some(selected_text) = selected_text {
11359 self.select_prev_state = Some(SelectNextState {
11360 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
11361 wordwise: false,
11362 done: false,
11363 });
11364 self.select_previous(action, window, cx)?;
11365 }
11366 }
11367 Ok(())
11368 }
11369
11370 pub fn toggle_comments(
11371 &mut self,
11372 action: &ToggleComments,
11373 window: &mut Window,
11374 cx: &mut Context<Self>,
11375 ) {
11376 if self.read_only(cx) {
11377 return;
11378 }
11379 let text_layout_details = &self.text_layout_details(window);
11380 self.transact(window, cx, |this, window, cx| {
11381 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
11382 let mut edits = Vec::new();
11383 let mut selection_edit_ranges = Vec::new();
11384 let mut last_toggled_row = None;
11385 let snapshot = this.buffer.read(cx).read(cx);
11386 let empty_str: Arc<str> = Arc::default();
11387 let mut suffixes_inserted = Vec::new();
11388 let ignore_indent = action.ignore_indent;
11389
11390 fn comment_prefix_range(
11391 snapshot: &MultiBufferSnapshot,
11392 row: MultiBufferRow,
11393 comment_prefix: &str,
11394 comment_prefix_whitespace: &str,
11395 ignore_indent: bool,
11396 ) -> Range<Point> {
11397 let indent_size = if ignore_indent {
11398 0
11399 } else {
11400 snapshot.indent_size_for_line(row).len
11401 };
11402
11403 let start = Point::new(row.0, indent_size);
11404
11405 let mut line_bytes = snapshot
11406 .bytes_in_range(start..snapshot.max_point())
11407 .flatten()
11408 .copied();
11409
11410 // If this line currently begins with the line comment prefix, then record
11411 // the range containing the prefix.
11412 if line_bytes
11413 .by_ref()
11414 .take(comment_prefix.len())
11415 .eq(comment_prefix.bytes())
11416 {
11417 // Include any whitespace that matches the comment prefix.
11418 let matching_whitespace_len = line_bytes
11419 .zip(comment_prefix_whitespace.bytes())
11420 .take_while(|(a, b)| a == b)
11421 .count() as u32;
11422 let end = Point::new(
11423 start.row,
11424 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
11425 );
11426 start..end
11427 } else {
11428 start..start
11429 }
11430 }
11431
11432 fn comment_suffix_range(
11433 snapshot: &MultiBufferSnapshot,
11434 row: MultiBufferRow,
11435 comment_suffix: &str,
11436 comment_suffix_has_leading_space: bool,
11437 ) -> Range<Point> {
11438 let end = Point::new(row.0, snapshot.line_len(row));
11439 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
11440
11441 let mut line_end_bytes = snapshot
11442 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
11443 .flatten()
11444 .copied();
11445
11446 let leading_space_len = if suffix_start_column > 0
11447 && line_end_bytes.next() == Some(b' ')
11448 && comment_suffix_has_leading_space
11449 {
11450 1
11451 } else {
11452 0
11453 };
11454
11455 // If this line currently begins with the line comment prefix, then record
11456 // the range containing the prefix.
11457 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
11458 let start = Point::new(end.row, suffix_start_column - leading_space_len);
11459 start..end
11460 } else {
11461 end..end
11462 }
11463 }
11464
11465 // TODO: Handle selections that cross excerpts
11466 for selection in &mut selections {
11467 let start_column = snapshot
11468 .indent_size_for_line(MultiBufferRow(selection.start.row))
11469 .len;
11470 let language = if let Some(language) =
11471 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
11472 {
11473 language
11474 } else {
11475 continue;
11476 };
11477
11478 selection_edit_ranges.clear();
11479
11480 // If multiple selections contain a given row, avoid processing that
11481 // row more than once.
11482 let mut start_row = MultiBufferRow(selection.start.row);
11483 if last_toggled_row == Some(start_row) {
11484 start_row = start_row.next_row();
11485 }
11486 let end_row =
11487 if selection.end.row > selection.start.row && selection.end.column == 0 {
11488 MultiBufferRow(selection.end.row - 1)
11489 } else {
11490 MultiBufferRow(selection.end.row)
11491 };
11492 last_toggled_row = Some(end_row);
11493
11494 if start_row > end_row {
11495 continue;
11496 }
11497
11498 // If the language has line comments, toggle those.
11499 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
11500
11501 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
11502 if ignore_indent {
11503 full_comment_prefixes = full_comment_prefixes
11504 .into_iter()
11505 .map(|s| Arc::from(s.trim_end()))
11506 .collect();
11507 }
11508
11509 if !full_comment_prefixes.is_empty() {
11510 let first_prefix = full_comment_prefixes
11511 .first()
11512 .expect("prefixes is non-empty");
11513 let prefix_trimmed_lengths = full_comment_prefixes
11514 .iter()
11515 .map(|p| p.trim_end_matches(' ').len())
11516 .collect::<SmallVec<[usize; 4]>>();
11517
11518 let mut all_selection_lines_are_comments = true;
11519
11520 for row in start_row.0..=end_row.0 {
11521 let row = MultiBufferRow(row);
11522 if start_row < end_row && snapshot.is_line_blank(row) {
11523 continue;
11524 }
11525
11526 let prefix_range = full_comment_prefixes
11527 .iter()
11528 .zip(prefix_trimmed_lengths.iter().copied())
11529 .map(|(prefix, trimmed_prefix_len)| {
11530 comment_prefix_range(
11531 snapshot.deref(),
11532 row,
11533 &prefix[..trimmed_prefix_len],
11534 &prefix[trimmed_prefix_len..],
11535 ignore_indent,
11536 )
11537 })
11538 .max_by_key(|range| range.end.column - range.start.column)
11539 .expect("prefixes is non-empty");
11540
11541 if prefix_range.is_empty() {
11542 all_selection_lines_are_comments = false;
11543 }
11544
11545 selection_edit_ranges.push(prefix_range);
11546 }
11547
11548 if all_selection_lines_are_comments {
11549 edits.extend(
11550 selection_edit_ranges
11551 .iter()
11552 .cloned()
11553 .map(|range| (range, empty_str.clone())),
11554 );
11555 } else {
11556 let min_column = selection_edit_ranges
11557 .iter()
11558 .map(|range| range.start.column)
11559 .min()
11560 .unwrap_or(0);
11561 edits.extend(selection_edit_ranges.iter().map(|range| {
11562 let position = Point::new(range.start.row, min_column);
11563 (position..position, first_prefix.clone())
11564 }));
11565 }
11566 } else if let Some((full_comment_prefix, comment_suffix)) =
11567 language.block_comment_delimiters()
11568 {
11569 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
11570 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
11571 let prefix_range = comment_prefix_range(
11572 snapshot.deref(),
11573 start_row,
11574 comment_prefix,
11575 comment_prefix_whitespace,
11576 ignore_indent,
11577 );
11578 let suffix_range = comment_suffix_range(
11579 snapshot.deref(),
11580 end_row,
11581 comment_suffix.trim_start_matches(' '),
11582 comment_suffix.starts_with(' '),
11583 );
11584
11585 if prefix_range.is_empty() || suffix_range.is_empty() {
11586 edits.push((
11587 prefix_range.start..prefix_range.start,
11588 full_comment_prefix.clone(),
11589 ));
11590 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
11591 suffixes_inserted.push((end_row, comment_suffix.len()));
11592 } else {
11593 edits.push((prefix_range, empty_str.clone()));
11594 edits.push((suffix_range, empty_str.clone()));
11595 }
11596 } else {
11597 continue;
11598 }
11599 }
11600
11601 drop(snapshot);
11602 this.buffer.update(cx, |buffer, cx| {
11603 buffer.edit(edits, None, cx);
11604 });
11605
11606 // Adjust selections so that they end before any comment suffixes that
11607 // were inserted.
11608 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
11609 let mut selections = this.selections.all::<Point>(cx);
11610 let snapshot = this.buffer.read(cx).read(cx);
11611 for selection in &mut selections {
11612 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
11613 match row.cmp(&MultiBufferRow(selection.end.row)) {
11614 Ordering::Less => {
11615 suffixes_inserted.next();
11616 continue;
11617 }
11618 Ordering::Greater => break,
11619 Ordering::Equal => {
11620 if selection.end.column == snapshot.line_len(row) {
11621 if selection.is_empty() {
11622 selection.start.column -= suffix_len as u32;
11623 }
11624 selection.end.column -= suffix_len as u32;
11625 }
11626 break;
11627 }
11628 }
11629 }
11630 }
11631
11632 drop(snapshot);
11633 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11634 s.select(selections)
11635 });
11636
11637 let selections = this.selections.all::<Point>(cx);
11638 let selections_on_single_row = selections.windows(2).all(|selections| {
11639 selections[0].start.row == selections[1].start.row
11640 && selections[0].end.row == selections[1].end.row
11641 && selections[0].start.row == selections[0].end.row
11642 });
11643 let selections_selecting = selections
11644 .iter()
11645 .any(|selection| selection.start != selection.end);
11646 let advance_downwards = action.advance_downwards
11647 && selections_on_single_row
11648 && !selections_selecting
11649 && !matches!(this.mode, EditorMode::SingleLine { .. });
11650
11651 if advance_downwards {
11652 let snapshot = this.buffer.read(cx).snapshot(cx);
11653
11654 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11655 s.move_cursors_with(|display_snapshot, display_point, _| {
11656 let mut point = display_point.to_point(display_snapshot);
11657 point.row += 1;
11658 point = snapshot.clip_point(point, Bias::Left);
11659 let display_point = point.to_display_point(display_snapshot);
11660 let goal = SelectionGoal::HorizontalPosition(
11661 display_snapshot
11662 .x_for_display_point(display_point, text_layout_details)
11663 .into(),
11664 );
11665 (display_point, goal)
11666 })
11667 });
11668 }
11669 });
11670 }
11671
11672 pub fn select_enclosing_symbol(
11673 &mut self,
11674 _: &SelectEnclosingSymbol,
11675 window: &mut Window,
11676 cx: &mut Context<Self>,
11677 ) {
11678 let buffer = self.buffer.read(cx).snapshot(cx);
11679 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11680
11681 fn update_selection(
11682 selection: &Selection<usize>,
11683 buffer_snap: &MultiBufferSnapshot,
11684 ) -> Option<Selection<usize>> {
11685 let cursor = selection.head();
11686 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
11687 for symbol in symbols.iter().rev() {
11688 let start = symbol.range.start.to_offset(buffer_snap);
11689 let end = symbol.range.end.to_offset(buffer_snap);
11690 let new_range = start..end;
11691 if start < selection.start || end > selection.end {
11692 return Some(Selection {
11693 id: selection.id,
11694 start: new_range.start,
11695 end: new_range.end,
11696 goal: SelectionGoal::None,
11697 reversed: selection.reversed,
11698 });
11699 }
11700 }
11701 None
11702 }
11703
11704 let mut selected_larger_symbol = false;
11705 let new_selections = old_selections
11706 .iter()
11707 .map(|selection| match update_selection(selection, &buffer) {
11708 Some(new_selection) => {
11709 if new_selection.range() != selection.range() {
11710 selected_larger_symbol = true;
11711 }
11712 new_selection
11713 }
11714 None => selection.clone(),
11715 })
11716 .collect::<Vec<_>>();
11717
11718 if selected_larger_symbol {
11719 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11720 s.select(new_selections);
11721 });
11722 }
11723 }
11724
11725 pub fn select_larger_syntax_node(
11726 &mut self,
11727 _: &SelectLargerSyntaxNode,
11728 window: &mut Window,
11729 cx: &mut Context<Self>,
11730 ) {
11731 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11732 let buffer = self.buffer.read(cx).snapshot(cx);
11733 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
11734
11735 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11736 let mut selected_larger_node = false;
11737 let new_selections = old_selections
11738 .iter()
11739 .map(|selection| {
11740 let old_range = selection.start..selection.end;
11741 let mut new_range = old_range.clone();
11742 let mut new_node = None;
11743 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
11744 {
11745 new_node = Some(node);
11746 new_range = match containing_range {
11747 MultiOrSingleBufferOffsetRange::Single(_) => break,
11748 MultiOrSingleBufferOffsetRange::Multi(range) => range,
11749 };
11750 if !display_map.intersects_fold(new_range.start)
11751 && !display_map.intersects_fold(new_range.end)
11752 {
11753 break;
11754 }
11755 }
11756
11757 if let Some(node) = new_node {
11758 // Log the ancestor, to support using this action as a way to explore TreeSitter
11759 // nodes. Parent and grandparent are also logged because this operation will not
11760 // visit nodes that have the same range as their parent.
11761 log::info!("Node: {node:?}");
11762 let parent = node.parent();
11763 log::info!("Parent: {parent:?}");
11764 let grandparent = parent.and_then(|x| x.parent());
11765 log::info!("Grandparent: {grandparent:?}");
11766 }
11767
11768 selected_larger_node |= new_range != old_range;
11769 Selection {
11770 id: selection.id,
11771 start: new_range.start,
11772 end: new_range.end,
11773 goal: SelectionGoal::None,
11774 reversed: selection.reversed,
11775 }
11776 })
11777 .collect::<Vec<_>>();
11778
11779 if selected_larger_node {
11780 stack.push(old_selections);
11781 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11782 s.select(new_selections);
11783 });
11784 }
11785 self.select_larger_syntax_node_stack = stack;
11786 }
11787
11788 pub fn select_smaller_syntax_node(
11789 &mut self,
11790 _: &SelectSmallerSyntaxNode,
11791 window: &mut Window,
11792 cx: &mut Context<Self>,
11793 ) {
11794 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
11795 if let Some(selections) = stack.pop() {
11796 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11797 s.select(selections.to_vec());
11798 });
11799 }
11800 self.select_larger_syntax_node_stack = stack;
11801 }
11802
11803 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
11804 if !EditorSettings::get_global(cx).gutter.runnables {
11805 self.clear_tasks();
11806 return Task::ready(());
11807 }
11808 let project = self.project.as_ref().map(Entity::downgrade);
11809 cx.spawn_in(window, async move |this, cx| {
11810 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
11811 let Some(project) = project.and_then(|p| p.upgrade()) else {
11812 return;
11813 };
11814 let Ok(display_snapshot) = this.update(cx, |this, cx| {
11815 this.display_map.update(cx, |map, cx| map.snapshot(cx))
11816 }) else {
11817 return;
11818 };
11819
11820 let hide_runnables = project
11821 .update(cx, |project, cx| {
11822 // Do not display any test indicators in non-dev server remote projects.
11823 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
11824 })
11825 .unwrap_or(true);
11826 if hide_runnables {
11827 return;
11828 }
11829 let new_rows =
11830 cx.background_spawn({
11831 let snapshot = display_snapshot.clone();
11832 async move {
11833 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
11834 }
11835 })
11836 .await;
11837
11838 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
11839 this.update(cx, |this, _| {
11840 this.clear_tasks();
11841 for (key, value) in rows {
11842 this.insert_tasks(key, value);
11843 }
11844 })
11845 .ok();
11846 })
11847 }
11848 fn fetch_runnable_ranges(
11849 snapshot: &DisplaySnapshot,
11850 range: Range<Anchor>,
11851 ) -> Vec<language::RunnableRange> {
11852 snapshot.buffer_snapshot.runnable_ranges(range).collect()
11853 }
11854
11855 fn runnable_rows(
11856 project: Entity<Project>,
11857 snapshot: DisplaySnapshot,
11858 runnable_ranges: Vec<RunnableRange>,
11859 mut cx: AsyncWindowContext,
11860 ) -> Vec<((BufferId, u32), RunnableTasks)> {
11861 runnable_ranges
11862 .into_iter()
11863 .filter_map(|mut runnable| {
11864 let tasks = cx
11865 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
11866 .ok()?;
11867 if tasks.is_empty() {
11868 return None;
11869 }
11870
11871 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
11872
11873 let row = snapshot
11874 .buffer_snapshot
11875 .buffer_line_for_row(MultiBufferRow(point.row))?
11876 .1
11877 .start
11878 .row;
11879
11880 let context_range =
11881 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
11882 Some((
11883 (runnable.buffer_id, row),
11884 RunnableTasks {
11885 templates: tasks,
11886 offset: snapshot
11887 .buffer_snapshot
11888 .anchor_before(runnable.run_range.start),
11889 context_range,
11890 column: point.column,
11891 extra_variables: runnable.extra_captures,
11892 },
11893 ))
11894 })
11895 .collect()
11896 }
11897
11898 fn templates_with_tags(
11899 project: &Entity<Project>,
11900 runnable: &mut Runnable,
11901 cx: &mut App,
11902 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
11903 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
11904 let (worktree_id, file) = project
11905 .buffer_for_id(runnable.buffer, cx)
11906 .and_then(|buffer| buffer.read(cx).file())
11907 .map(|file| (file.worktree_id(cx), file.clone()))
11908 .unzip();
11909
11910 (
11911 project.task_store().read(cx).task_inventory().cloned(),
11912 worktree_id,
11913 file,
11914 )
11915 });
11916
11917 let tags = mem::take(&mut runnable.tags);
11918 let mut tags: Vec<_> = tags
11919 .into_iter()
11920 .flat_map(|tag| {
11921 let tag = tag.0.clone();
11922 inventory
11923 .as_ref()
11924 .into_iter()
11925 .flat_map(|inventory| {
11926 inventory.read(cx).list_tasks(
11927 file.clone(),
11928 Some(runnable.language.clone()),
11929 worktree_id,
11930 cx,
11931 )
11932 })
11933 .filter(move |(_, template)| {
11934 template.tags.iter().any(|source_tag| source_tag == &tag)
11935 })
11936 })
11937 .sorted_by_key(|(kind, _)| kind.to_owned())
11938 .collect();
11939 if let Some((leading_tag_source, _)) = tags.first() {
11940 // Strongest source wins; if we have worktree tag binding, prefer that to
11941 // global and language bindings;
11942 // if we have a global binding, prefer that to language binding.
11943 let first_mismatch = tags
11944 .iter()
11945 .position(|(tag_source, _)| tag_source != leading_tag_source);
11946 if let Some(index) = first_mismatch {
11947 tags.truncate(index);
11948 }
11949 }
11950
11951 tags
11952 }
11953
11954 pub fn move_to_enclosing_bracket(
11955 &mut self,
11956 _: &MoveToEnclosingBracket,
11957 window: &mut Window,
11958 cx: &mut Context<Self>,
11959 ) {
11960 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11961 s.move_offsets_with(|snapshot, selection| {
11962 let Some(enclosing_bracket_ranges) =
11963 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
11964 else {
11965 return;
11966 };
11967
11968 let mut best_length = usize::MAX;
11969 let mut best_inside = false;
11970 let mut best_in_bracket_range = false;
11971 let mut best_destination = None;
11972 for (open, close) in enclosing_bracket_ranges {
11973 let close = close.to_inclusive();
11974 let length = close.end() - open.start;
11975 let inside = selection.start >= open.end && selection.end <= *close.start();
11976 let in_bracket_range = open.to_inclusive().contains(&selection.head())
11977 || close.contains(&selection.head());
11978
11979 // If best is next to a bracket and current isn't, skip
11980 if !in_bracket_range && best_in_bracket_range {
11981 continue;
11982 }
11983
11984 // Prefer smaller lengths unless best is inside and current isn't
11985 if length > best_length && (best_inside || !inside) {
11986 continue;
11987 }
11988
11989 best_length = length;
11990 best_inside = inside;
11991 best_in_bracket_range = in_bracket_range;
11992 best_destination = Some(
11993 if close.contains(&selection.start) && close.contains(&selection.end) {
11994 if inside {
11995 open.end
11996 } else {
11997 open.start
11998 }
11999 } else if inside {
12000 *close.start()
12001 } else {
12002 *close.end()
12003 },
12004 );
12005 }
12006
12007 if let Some(destination) = best_destination {
12008 selection.collapse_to(destination, SelectionGoal::None);
12009 }
12010 })
12011 });
12012 }
12013
12014 pub fn undo_selection(
12015 &mut self,
12016 _: &UndoSelection,
12017 window: &mut Window,
12018 cx: &mut Context<Self>,
12019 ) {
12020 self.end_selection(window, cx);
12021 self.selection_history.mode = SelectionHistoryMode::Undoing;
12022 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
12023 self.change_selections(None, window, cx, |s| {
12024 s.select_anchors(entry.selections.to_vec())
12025 });
12026 self.select_next_state = entry.select_next_state;
12027 self.select_prev_state = entry.select_prev_state;
12028 self.add_selections_state = entry.add_selections_state;
12029 self.request_autoscroll(Autoscroll::newest(), cx);
12030 }
12031 self.selection_history.mode = SelectionHistoryMode::Normal;
12032 }
12033
12034 pub fn redo_selection(
12035 &mut self,
12036 _: &RedoSelection,
12037 window: &mut Window,
12038 cx: &mut Context<Self>,
12039 ) {
12040 self.end_selection(window, cx);
12041 self.selection_history.mode = SelectionHistoryMode::Redoing;
12042 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
12043 self.change_selections(None, window, cx, |s| {
12044 s.select_anchors(entry.selections.to_vec())
12045 });
12046 self.select_next_state = entry.select_next_state;
12047 self.select_prev_state = entry.select_prev_state;
12048 self.add_selections_state = entry.add_selections_state;
12049 self.request_autoscroll(Autoscroll::newest(), cx);
12050 }
12051 self.selection_history.mode = SelectionHistoryMode::Normal;
12052 }
12053
12054 pub fn expand_excerpts(
12055 &mut self,
12056 action: &ExpandExcerpts,
12057 _: &mut Window,
12058 cx: &mut Context<Self>,
12059 ) {
12060 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
12061 }
12062
12063 pub fn expand_excerpts_down(
12064 &mut self,
12065 action: &ExpandExcerptsDown,
12066 _: &mut Window,
12067 cx: &mut Context<Self>,
12068 ) {
12069 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
12070 }
12071
12072 pub fn expand_excerpts_up(
12073 &mut self,
12074 action: &ExpandExcerptsUp,
12075 _: &mut Window,
12076 cx: &mut Context<Self>,
12077 ) {
12078 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
12079 }
12080
12081 pub fn expand_excerpts_for_direction(
12082 &mut self,
12083 lines: u32,
12084 direction: ExpandExcerptDirection,
12085
12086 cx: &mut Context<Self>,
12087 ) {
12088 let selections = self.selections.disjoint_anchors();
12089
12090 let lines = if lines == 0 {
12091 EditorSettings::get_global(cx).expand_excerpt_lines
12092 } else {
12093 lines
12094 };
12095
12096 self.buffer.update(cx, |buffer, cx| {
12097 let snapshot = buffer.snapshot(cx);
12098 let mut excerpt_ids = selections
12099 .iter()
12100 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
12101 .collect::<Vec<_>>();
12102 excerpt_ids.sort();
12103 excerpt_ids.dedup();
12104 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
12105 })
12106 }
12107
12108 pub fn expand_excerpt(
12109 &mut self,
12110 excerpt: ExcerptId,
12111 direction: ExpandExcerptDirection,
12112 window: &mut Window,
12113 cx: &mut Context<Self>,
12114 ) {
12115 let current_scroll_position = self.scroll_position(cx);
12116 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
12117 self.buffer.update(cx, |buffer, cx| {
12118 buffer.expand_excerpts([excerpt], lines, direction, cx)
12119 });
12120 if direction == ExpandExcerptDirection::Down {
12121 let new_scroll_position = current_scroll_position + gpui::Point::new(0.0, lines as f32);
12122 self.set_scroll_position(new_scroll_position, window, cx);
12123 }
12124 }
12125
12126 pub fn go_to_singleton_buffer_point(
12127 &mut self,
12128 point: Point,
12129 window: &mut Window,
12130 cx: &mut Context<Self>,
12131 ) {
12132 self.go_to_singleton_buffer_range(point..point, window, cx);
12133 }
12134
12135 pub fn go_to_singleton_buffer_range(
12136 &mut self,
12137 range: Range<Point>,
12138 window: &mut Window,
12139 cx: &mut Context<Self>,
12140 ) {
12141 let multibuffer = self.buffer().read(cx);
12142 let Some(buffer) = multibuffer.as_singleton() else {
12143 return;
12144 };
12145 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
12146 return;
12147 };
12148 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
12149 return;
12150 };
12151 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
12152 s.select_anchor_ranges([start..end])
12153 });
12154 }
12155
12156 fn go_to_diagnostic(
12157 &mut self,
12158 _: &GoToDiagnostic,
12159 window: &mut Window,
12160 cx: &mut Context<Self>,
12161 ) {
12162 self.go_to_diagnostic_impl(Direction::Next, window, cx)
12163 }
12164
12165 fn go_to_prev_diagnostic(
12166 &mut self,
12167 _: &GoToPreviousDiagnostic,
12168 window: &mut Window,
12169 cx: &mut Context<Self>,
12170 ) {
12171 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
12172 }
12173
12174 pub fn go_to_diagnostic_impl(
12175 &mut self,
12176 direction: Direction,
12177 window: &mut Window,
12178 cx: &mut Context<Self>,
12179 ) {
12180 let buffer = self.buffer.read(cx).snapshot(cx);
12181 let selection = self.selections.newest::<usize>(cx);
12182
12183 // If there is an active Diagnostic Popover jump to its diagnostic instead.
12184 if direction == Direction::Next {
12185 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
12186 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
12187 return;
12188 };
12189 self.activate_diagnostics(
12190 buffer_id,
12191 popover.local_diagnostic.diagnostic.group_id,
12192 window,
12193 cx,
12194 );
12195 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
12196 let primary_range_start = active_diagnostics.primary_range.start;
12197 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12198 let mut new_selection = s.newest_anchor().clone();
12199 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
12200 s.select_anchors(vec![new_selection.clone()]);
12201 });
12202 self.refresh_inline_completion(false, true, window, cx);
12203 }
12204 return;
12205 }
12206 }
12207
12208 let active_group_id = self
12209 .active_diagnostics
12210 .as_ref()
12211 .map(|active_group| active_group.group_id);
12212 let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
12213 active_diagnostics
12214 .primary_range
12215 .to_offset(&buffer)
12216 .to_inclusive()
12217 });
12218 let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
12219 if active_primary_range.contains(&selection.head()) {
12220 *active_primary_range.start()
12221 } else {
12222 selection.head()
12223 }
12224 } else {
12225 selection.head()
12226 };
12227
12228 let snapshot = self.snapshot(window, cx);
12229 let primary_diagnostics_before = buffer
12230 .diagnostics_in_range::<usize>(0..search_start)
12231 .filter(|entry| entry.diagnostic.is_primary)
12232 .filter(|entry| entry.range.start != entry.range.end)
12233 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12234 .filter(|entry| !snapshot.intersects_fold(entry.range.start))
12235 .collect::<Vec<_>>();
12236 let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
12237 primary_diagnostics_before
12238 .iter()
12239 .position(|entry| entry.diagnostic.group_id == active_group_id)
12240 });
12241
12242 let primary_diagnostics_after = buffer
12243 .diagnostics_in_range::<usize>(search_start..buffer.len())
12244 .filter(|entry| entry.diagnostic.is_primary)
12245 .filter(|entry| entry.range.start != entry.range.end)
12246 .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
12247 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
12248 .collect::<Vec<_>>();
12249 let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
12250 primary_diagnostics_after
12251 .iter()
12252 .enumerate()
12253 .rev()
12254 .find_map(|(i, entry)| {
12255 if entry.diagnostic.group_id == active_group_id {
12256 Some(i)
12257 } else {
12258 None
12259 }
12260 })
12261 });
12262
12263 let next_primary_diagnostic = match direction {
12264 Direction::Prev => primary_diagnostics_before
12265 .iter()
12266 .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
12267 .rev()
12268 .next(),
12269 Direction::Next => primary_diagnostics_after
12270 .iter()
12271 .skip(
12272 last_same_group_diagnostic_after
12273 .map(|index| index + 1)
12274 .unwrap_or(0),
12275 )
12276 .next(),
12277 };
12278
12279 // Cycle around to the start of the buffer, potentially moving back to the start of
12280 // the currently active diagnostic.
12281 let cycle_around = || match direction {
12282 Direction::Prev => primary_diagnostics_after
12283 .iter()
12284 .rev()
12285 .chain(primary_diagnostics_before.iter().rev())
12286 .next(),
12287 Direction::Next => primary_diagnostics_before
12288 .iter()
12289 .chain(primary_diagnostics_after.iter())
12290 .next(),
12291 };
12292
12293 if let Some((primary_range, group_id)) = next_primary_diagnostic
12294 .or_else(cycle_around)
12295 .map(|entry| (&entry.range, entry.diagnostic.group_id))
12296 {
12297 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
12298 return;
12299 };
12300 self.activate_diagnostics(buffer_id, group_id, window, cx);
12301 if self.active_diagnostics.is_some() {
12302 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12303 s.select(vec![Selection {
12304 id: selection.id,
12305 start: primary_range.start,
12306 end: primary_range.start,
12307 reversed: false,
12308 goal: SelectionGoal::None,
12309 }]);
12310 });
12311 self.refresh_inline_completion(false, true, window, cx);
12312 }
12313 }
12314 }
12315
12316 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
12317 let snapshot = self.snapshot(window, cx);
12318 let selection = self.selections.newest::<Point>(cx);
12319 self.go_to_hunk_before_or_after_position(
12320 &snapshot,
12321 selection.head(),
12322 Direction::Next,
12323 window,
12324 cx,
12325 );
12326 }
12327
12328 fn go_to_hunk_before_or_after_position(
12329 &mut self,
12330 snapshot: &EditorSnapshot,
12331 position: Point,
12332 direction: Direction,
12333 window: &mut Window,
12334 cx: &mut Context<Editor>,
12335 ) {
12336 let row = if direction == Direction::Next {
12337 self.hunk_after_position(snapshot, position)
12338 .map(|hunk| hunk.row_range.start)
12339 } else {
12340 self.hunk_before_position(snapshot, position)
12341 };
12342
12343 if let Some(row) = row {
12344 let destination = Point::new(row.0, 0);
12345 let autoscroll = Autoscroll::center();
12346
12347 self.unfold_ranges(&[destination..destination], false, false, cx);
12348 self.change_selections(Some(autoscroll), window, cx, |s| {
12349 s.select_ranges([destination..destination]);
12350 });
12351 }
12352 }
12353
12354 fn hunk_after_position(
12355 &mut self,
12356 snapshot: &EditorSnapshot,
12357 position: Point,
12358 ) -> Option<MultiBufferDiffHunk> {
12359 snapshot
12360 .buffer_snapshot
12361 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
12362 .find(|hunk| hunk.row_range.start.0 > position.row)
12363 .or_else(|| {
12364 snapshot
12365 .buffer_snapshot
12366 .diff_hunks_in_range(Point::zero()..position)
12367 .find(|hunk| hunk.row_range.end.0 < position.row)
12368 })
12369 }
12370
12371 fn go_to_prev_hunk(
12372 &mut self,
12373 _: &GoToPreviousHunk,
12374 window: &mut Window,
12375 cx: &mut Context<Self>,
12376 ) {
12377 let snapshot = self.snapshot(window, cx);
12378 let selection = self.selections.newest::<Point>(cx);
12379 self.go_to_hunk_before_or_after_position(
12380 &snapshot,
12381 selection.head(),
12382 Direction::Prev,
12383 window,
12384 cx,
12385 );
12386 }
12387
12388 fn hunk_before_position(
12389 &mut self,
12390 snapshot: &EditorSnapshot,
12391 position: Point,
12392 ) -> Option<MultiBufferRow> {
12393 snapshot
12394 .buffer_snapshot
12395 .diff_hunk_before(position)
12396 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
12397 }
12398
12399 fn go_to_line<T: 'static>(
12400 &mut self,
12401 position: Anchor,
12402 highlight_color: Option<Hsla>,
12403 window: &mut Window,
12404 cx: &mut Context<Self>,
12405 ) {
12406 let snapshot = self.snapshot(window, cx).display_snapshot;
12407 let position = position.to_point(&snapshot.buffer_snapshot);
12408 let start = snapshot
12409 .buffer_snapshot
12410 .clip_point(Point::new(position.row, 0), Bias::Left);
12411 let end = start + Point::new(1, 0);
12412 let start = snapshot.buffer_snapshot.anchor_before(start);
12413 let end = snapshot.buffer_snapshot.anchor_before(end);
12414
12415 self.clear_row_highlights::<T>();
12416 self.highlight_rows::<T>(
12417 start..end,
12418 highlight_color
12419 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
12420 true,
12421 cx,
12422 );
12423 self.request_autoscroll(Autoscroll::center(), cx);
12424 }
12425
12426 pub fn go_to_definition(
12427 &mut self,
12428 _: &GoToDefinition,
12429 window: &mut Window,
12430 cx: &mut Context<Self>,
12431 ) -> Task<Result<Navigated>> {
12432 let definition =
12433 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
12434 cx.spawn_in(window, async move |editor, cx| {
12435 if definition.await? == Navigated::Yes {
12436 return Ok(Navigated::Yes);
12437 }
12438 match editor.update_in(cx, |editor, window, cx| {
12439 editor.find_all_references(&FindAllReferences, window, cx)
12440 })? {
12441 Some(references) => references.await,
12442 None => Ok(Navigated::No),
12443 }
12444 })
12445 }
12446
12447 pub fn go_to_declaration(
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, false, window, cx)
12454 }
12455
12456 pub fn go_to_declaration_split(
12457 &mut self,
12458 _: &GoToDeclaration,
12459 window: &mut Window,
12460 cx: &mut Context<Self>,
12461 ) -> Task<Result<Navigated>> {
12462 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
12463 }
12464
12465 pub fn go_to_implementation(
12466 &mut self,
12467 _: &GoToImplementation,
12468 window: &mut Window,
12469 cx: &mut Context<Self>,
12470 ) -> Task<Result<Navigated>> {
12471 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
12472 }
12473
12474 pub fn go_to_implementation_split(
12475 &mut self,
12476 _: &GoToImplementationSplit,
12477 window: &mut Window,
12478 cx: &mut Context<Self>,
12479 ) -> Task<Result<Navigated>> {
12480 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
12481 }
12482
12483 pub fn go_to_type_definition(
12484 &mut self,
12485 _: &GoToTypeDefinition,
12486 window: &mut Window,
12487 cx: &mut Context<Self>,
12488 ) -> Task<Result<Navigated>> {
12489 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
12490 }
12491
12492 pub fn go_to_definition_split(
12493 &mut self,
12494 _: &GoToDefinitionSplit,
12495 window: &mut Window,
12496 cx: &mut Context<Self>,
12497 ) -> Task<Result<Navigated>> {
12498 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
12499 }
12500
12501 pub fn go_to_type_definition_split(
12502 &mut self,
12503 _: &GoToTypeDefinitionSplit,
12504 window: &mut Window,
12505 cx: &mut Context<Self>,
12506 ) -> Task<Result<Navigated>> {
12507 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
12508 }
12509
12510 fn go_to_definition_of_kind(
12511 &mut self,
12512 kind: GotoDefinitionKind,
12513 split: bool,
12514 window: &mut Window,
12515 cx: &mut Context<Self>,
12516 ) -> Task<Result<Navigated>> {
12517 let Some(provider) = self.semantics_provider.clone() else {
12518 return Task::ready(Ok(Navigated::No));
12519 };
12520 let head = self.selections.newest::<usize>(cx).head();
12521 let buffer = self.buffer.read(cx);
12522 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
12523 text_anchor
12524 } else {
12525 return Task::ready(Ok(Navigated::No));
12526 };
12527
12528 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
12529 return Task::ready(Ok(Navigated::No));
12530 };
12531
12532 cx.spawn_in(window, async move |editor, cx| {
12533 let definitions = definitions.await?;
12534 let navigated = editor
12535 .update_in(cx, |editor, window, cx| {
12536 editor.navigate_to_hover_links(
12537 Some(kind),
12538 definitions
12539 .into_iter()
12540 .filter(|location| {
12541 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
12542 })
12543 .map(HoverLink::Text)
12544 .collect::<Vec<_>>(),
12545 split,
12546 window,
12547 cx,
12548 )
12549 })?
12550 .await?;
12551 anyhow::Ok(navigated)
12552 })
12553 }
12554
12555 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
12556 let selection = self.selections.newest_anchor();
12557 let head = selection.head();
12558 let tail = selection.tail();
12559
12560 let Some((buffer, start_position)) =
12561 self.buffer.read(cx).text_anchor_for_position(head, cx)
12562 else {
12563 return;
12564 };
12565
12566 let end_position = if head != tail {
12567 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
12568 return;
12569 };
12570 Some(pos)
12571 } else {
12572 None
12573 };
12574
12575 let url_finder = cx.spawn_in(window, async move |editor, cx| {
12576 let url = if let Some(end_pos) = end_position {
12577 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
12578 } else {
12579 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
12580 };
12581
12582 if let Some(url) = url {
12583 editor.update(cx, |_, cx| {
12584 cx.open_url(&url);
12585 })
12586 } else {
12587 Ok(())
12588 }
12589 });
12590
12591 url_finder.detach();
12592 }
12593
12594 pub fn open_selected_filename(
12595 &mut self,
12596 _: &OpenSelectedFilename,
12597 window: &mut Window,
12598 cx: &mut Context<Self>,
12599 ) {
12600 let Some(workspace) = self.workspace() else {
12601 return;
12602 };
12603
12604 let position = self.selections.newest_anchor().head();
12605
12606 let Some((buffer, buffer_position)) =
12607 self.buffer.read(cx).text_anchor_for_position(position, cx)
12608 else {
12609 return;
12610 };
12611
12612 let project = self.project.clone();
12613
12614 cx.spawn_in(window, async move |_, cx| {
12615 let result = find_file(&buffer, project, buffer_position, cx).await;
12616
12617 if let Some((_, path)) = result {
12618 workspace
12619 .update_in(cx, |workspace, window, cx| {
12620 workspace.open_resolved_path(path, window, cx)
12621 })?
12622 .await?;
12623 }
12624 anyhow::Ok(())
12625 })
12626 .detach();
12627 }
12628
12629 pub(crate) fn navigate_to_hover_links(
12630 &mut self,
12631 kind: Option<GotoDefinitionKind>,
12632 mut definitions: Vec<HoverLink>,
12633 split: bool,
12634 window: &mut Window,
12635 cx: &mut Context<Editor>,
12636 ) -> Task<Result<Navigated>> {
12637 // If there is one definition, just open it directly
12638 if definitions.len() == 1 {
12639 let definition = definitions.pop().unwrap();
12640
12641 enum TargetTaskResult {
12642 Location(Option<Location>),
12643 AlreadyNavigated,
12644 }
12645
12646 let target_task = match definition {
12647 HoverLink::Text(link) => {
12648 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
12649 }
12650 HoverLink::InlayHint(lsp_location, server_id) => {
12651 let computation =
12652 self.compute_target_location(lsp_location, server_id, window, cx);
12653 cx.background_spawn(async move {
12654 let location = computation.await?;
12655 Ok(TargetTaskResult::Location(location))
12656 })
12657 }
12658 HoverLink::Url(url) => {
12659 cx.open_url(&url);
12660 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
12661 }
12662 HoverLink::File(path) => {
12663 if let Some(workspace) = self.workspace() {
12664 cx.spawn_in(window, async move |_, cx| {
12665 workspace
12666 .update_in(cx, |workspace, window, cx| {
12667 workspace.open_resolved_path(path, window, cx)
12668 })?
12669 .await
12670 .map(|_| TargetTaskResult::AlreadyNavigated)
12671 })
12672 } else {
12673 Task::ready(Ok(TargetTaskResult::Location(None)))
12674 }
12675 }
12676 };
12677 cx.spawn_in(window, async move |editor, cx| {
12678 let target = match target_task.await.context("target resolution task")? {
12679 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
12680 TargetTaskResult::Location(None) => return Ok(Navigated::No),
12681 TargetTaskResult::Location(Some(target)) => target,
12682 };
12683
12684 editor.update_in(cx, |editor, window, cx| {
12685 let Some(workspace) = editor.workspace() else {
12686 return Navigated::No;
12687 };
12688 let pane = workspace.read(cx).active_pane().clone();
12689
12690 let range = target.range.to_point(target.buffer.read(cx));
12691 let range = editor.range_for_match(&range);
12692 let range = collapse_multiline_range(range);
12693
12694 if !split
12695 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
12696 {
12697 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
12698 } else {
12699 window.defer(cx, move |window, cx| {
12700 let target_editor: Entity<Self> =
12701 workspace.update(cx, |workspace, cx| {
12702 let pane = if split {
12703 workspace.adjacent_pane(window, cx)
12704 } else {
12705 workspace.active_pane().clone()
12706 };
12707
12708 workspace.open_project_item(
12709 pane,
12710 target.buffer.clone(),
12711 true,
12712 true,
12713 window,
12714 cx,
12715 )
12716 });
12717 target_editor.update(cx, |target_editor, cx| {
12718 // When selecting a definition in a different buffer, disable the nav history
12719 // to avoid creating a history entry at the previous cursor location.
12720 pane.update(cx, |pane, _| pane.disable_history());
12721 target_editor.go_to_singleton_buffer_range(range, window, cx);
12722 pane.update(cx, |pane, _| pane.enable_history());
12723 });
12724 });
12725 }
12726 Navigated::Yes
12727 })
12728 })
12729 } else if !definitions.is_empty() {
12730 cx.spawn_in(window, async move |editor, cx| {
12731 let (title, location_tasks, workspace) = editor
12732 .update_in(cx, |editor, window, cx| {
12733 let tab_kind = match kind {
12734 Some(GotoDefinitionKind::Implementation) => "Implementations",
12735 _ => "Definitions",
12736 };
12737 let title = definitions
12738 .iter()
12739 .find_map(|definition| match definition {
12740 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
12741 let buffer = origin.buffer.read(cx);
12742 format!(
12743 "{} for {}",
12744 tab_kind,
12745 buffer
12746 .text_for_range(origin.range.clone())
12747 .collect::<String>()
12748 )
12749 }),
12750 HoverLink::InlayHint(_, _) => None,
12751 HoverLink::Url(_) => None,
12752 HoverLink::File(_) => None,
12753 })
12754 .unwrap_or(tab_kind.to_string());
12755 let location_tasks = definitions
12756 .into_iter()
12757 .map(|definition| match definition {
12758 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
12759 HoverLink::InlayHint(lsp_location, server_id) => editor
12760 .compute_target_location(lsp_location, server_id, window, cx),
12761 HoverLink::Url(_) => Task::ready(Ok(None)),
12762 HoverLink::File(_) => Task::ready(Ok(None)),
12763 })
12764 .collect::<Vec<_>>();
12765 (title, location_tasks, editor.workspace().clone())
12766 })
12767 .context("location tasks preparation")?;
12768
12769 let locations = future::join_all(location_tasks)
12770 .await
12771 .into_iter()
12772 .filter_map(|location| location.transpose())
12773 .collect::<Result<_>>()
12774 .context("location tasks")?;
12775
12776 let Some(workspace) = workspace else {
12777 return Ok(Navigated::No);
12778 };
12779 let opened = workspace
12780 .update_in(cx, |workspace, window, cx| {
12781 Self::open_locations_in_multibuffer(
12782 workspace,
12783 locations,
12784 title,
12785 split,
12786 MultibufferSelectionMode::First,
12787 window,
12788 cx,
12789 )
12790 })
12791 .ok();
12792
12793 anyhow::Ok(Navigated::from_bool(opened.is_some()))
12794 })
12795 } else {
12796 Task::ready(Ok(Navigated::No))
12797 }
12798 }
12799
12800 fn compute_target_location(
12801 &self,
12802 lsp_location: lsp::Location,
12803 server_id: LanguageServerId,
12804 window: &mut Window,
12805 cx: &mut Context<Self>,
12806 ) -> Task<anyhow::Result<Option<Location>>> {
12807 let Some(project) = self.project.clone() else {
12808 return Task::ready(Ok(None));
12809 };
12810
12811 cx.spawn_in(window, async move |editor, cx| {
12812 let location_task = editor.update(cx, |_, cx| {
12813 project.update(cx, |project, cx| {
12814 let language_server_name = project
12815 .language_server_statuses(cx)
12816 .find(|(id, _)| server_id == *id)
12817 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
12818 language_server_name.map(|language_server_name| {
12819 project.open_local_buffer_via_lsp(
12820 lsp_location.uri.clone(),
12821 server_id,
12822 language_server_name,
12823 cx,
12824 )
12825 })
12826 })
12827 })?;
12828 let location = match location_task {
12829 Some(task) => Some({
12830 let target_buffer_handle = task.await.context("open local buffer")?;
12831 let range = target_buffer_handle.update(cx, |target_buffer, _| {
12832 let target_start = target_buffer
12833 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
12834 let target_end = target_buffer
12835 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
12836 target_buffer.anchor_after(target_start)
12837 ..target_buffer.anchor_before(target_end)
12838 })?;
12839 Location {
12840 buffer: target_buffer_handle,
12841 range,
12842 }
12843 }),
12844 None => None,
12845 };
12846 Ok(location)
12847 })
12848 }
12849
12850 pub fn find_all_references(
12851 &mut self,
12852 _: &FindAllReferences,
12853 window: &mut Window,
12854 cx: &mut Context<Self>,
12855 ) -> Option<Task<Result<Navigated>>> {
12856 let selection = self.selections.newest::<usize>(cx);
12857 let multi_buffer = self.buffer.read(cx);
12858 let head = selection.head();
12859
12860 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12861 let head_anchor = multi_buffer_snapshot.anchor_at(
12862 head,
12863 if head < selection.tail() {
12864 Bias::Right
12865 } else {
12866 Bias::Left
12867 },
12868 );
12869
12870 match self
12871 .find_all_references_task_sources
12872 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12873 {
12874 Ok(_) => {
12875 log::info!(
12876 "Ignoring repeated FindAllReferences invocation with the position of already running task"
12877 );
12878 return None;
12879 }
12880 Err(i) => {
12881 self.find_all_references_task_sources.insert(i, head_anchor);
12882 }
12883 }
12884
12885 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
12886 let workspace = self.workspace()?;
12887 let project = workspace.read(cx).project().clone();
12888 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
12889 Some(cx.spawn_in(window, async move |editor, cx| {
12890 let _cleanup = cx.on_drop(&editor, move |editor, _| {
12891 if let Ok(i) = editor
12892 .find_all_references_task_sources
12893 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
12894 {
12895 editor.find_all_references_task_sources.remove(i);
12896 }
12897 });
12898
12899 let locations = references.await?;
12900 if locations.is_empty() {
12901 return anyhow::Ok(Navigated::No);
12902 }
12903
12904 workspace.update_in(cx, |workspace, window, cx| {
12905 let title = locations
12906 .first()
12907 .as_ref()
12908 .map(|location| {
12909 let buffer = location.buffer.read(cx);
12910 format!(
12911 "References to `{}`",
12912 buffer
12913 .text_for_range(location.range.clone())
12914 .collect::<String>()
12915 )
12916 })
12917 .unwrap();
12918 Self::open_locations_in_multibuffer(
12919 workspace,
12920 locations,
12921 title,
12922 false,
12923 MultibufferSelectionMode::First,
12924 window,
12925 cx,
12926 );
12927 Navigated::Yes
12928 })
12929 }))
12930 }
12931
12932 /// Opens a multibuffer with the given project locations in it
12933 pub fn open_locations_in_multibuffer(
12934 workspace: &mut Workspace,
12935 mut locations: Vec<Location>,
12936 title: String,
12937 split: bool,
12938 multibuffer_selection_mode: MultibufferSelectionMode,
12939 window: &mut Window,
12940 cx: &mut Context<Workspace>,
12941 ) {
12942 // If there are multiple definitions, open them in a multibuffer
12943 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
12944 let mut locations = locations.into_iter().peekable();
12945 let mut ranges = Vec::new();
12946 let capability = workspace.project().read(cx).capability();
12947
12948 let excerpt_buffer = cx.new(|cx| {
12949 let mut multibuffer = MultiBuffer::new(capability);
12950 while let Some(location) = locations.next() {
12951 let buffer = location.buffer.read(cx);
12952 let mut ranges_for_buffer = Vec::new();
12953 let range = location.range.to_offset(buffer);
12954 ranges_for_buffer.push(range.clone());
12955
12956 while let Some(next_location) = locations.peek() {
12957 if next_location.buffer == location.buffer {
12958 ranges_for_buffer.push(next_location.range.to_offset(buffer));
12959 locations.next();
12960 } else {
12961 break;
12962 }
12963 }
12964
12965 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
12966 ranges.extend(multibuffer.push_excerpts_with_context_lines(
12967 location.buffer.clone(),
12968 ranges_for_buffer,
12969 DEFAULT_MULTIBUFFER_CONTEXT,
12970 cx,
12971 ))
12972 }
12973
12974 multibuffer.with_title(title)
12975 });
12976
12977 let editor = cx.new(|cx| {
12978 Editor::for_multibuffer(
12979 excerpt_buffer,
12980 Some(workspace.project().clone()),
12981 window,
12982 cx,
12983 )
12984 });
12985 editor.update(cx, |editor, cx| {
12986 match multibuffer_selection_mode {
12987 MultibufferSelectionMode::First => {
12988 if let Some(first_range) = ranges.first() {
12989 editor.change_selections(None, window, cx, |selections| {
12990 selections.clear_disjoint();
12991 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
12992 });
12993 }
12994 editor.highlight_background::<Self>(
12995 &ranges,
12996 |theme| theme.editor_highlighted_line_background,
12997 cx,
12998 );
12999 }
13000 MultibufferSelectionMode::All => {
13001 editor.change_selections(None, window, cx, |selections| {
13002 selections.clear_disjoint();
13003 selections.select_anchor_ranges(ranges);
13004 });
13005 }
13006 }
13007 editor.register_buffers_with_language_servers(cx);
13008 });
13009
13010 let item = Box::new(editor);
13011 let item_id = item.item_id();
13012
13013 if split {
13014 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
13015 } else {
13016 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
13017 let (preview_item_id, preview_item_idx) =
13018 workspace.active_pane().update(cx, |pane, _| {
13019 (pane.preview_item_id(), pane.preview_item_idx())
13020 });
13021
13022 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
13023
13024 if let Some(preview_item_id) = preview_item_id {
13025 workspace.active_pane().update(cx, |pane, cx| {
13026 pane.remove_item(preview_item_id, false, false, window, cx);
13027 });
13028 }
13029 } else {
13030 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
13031 }
13032 }
13033 workspace.active_pane().update(cx, |pane, cx| {
13034 pane.set_preview_item_id(Some(item_id), cx);
13035 });
13036 }
13037
13038 pub fn rename(
13039 &mut self,
13040 _: &Rename,
13041 window: &mut Window,
13042 cx: &mut Context<Self>,
13043 ) -> Option<Task<Result<()>>> {
13044 use language::ToOffset as _;
13045
13046 let provider = self.semantics_provider.clone()?;
13047 let selection = self.selections.newest_anchor().clone();
13048 let (cursor_buffer, cursor_buffer_position) = self
13049 .buffer
13050 .read(cx)
13051 .text_anchor_for_position(selection.head(), cx)?;
13052 let (tail_buffer, cursor_buffer_position_end) = self
13053 .buffer
13054 .read(cx)
13055 .text_anchor_for_position(selection.tail(), cx)?;
13056 if tail_buffer != cursor_buffer {
13057 return None;
13058 }
13059
13060 let snapshot = cursor_buffer.read(cx).snapshot();
13061 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
13062 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
13063 let prepare_rename = provider
13064 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
13065 .unwrap_or_else(|| Task::ready(Ok(None)));
13066 drop(snapshot);
13067
13068 Some(cx.spawn_in(window, async move |this, cx| {
13069 let rename_range = if let Some(range) = prepare_rename.await? {
13070 Some(range)
13071 } else {
13072 this.update(cx, |this, cx| {
13073 let buffer = this.buffer.read(cx).snapshot(cx);
13074 let mut buffer_highlights = this
13075 .document_highlights_for_position(selection.head(), &buffer)
13076 .filter(|highlight| {
13077 highlight.start.excerpt_id == selection.head().excerpt_id
13078 && highlight.end.excerpt_id == selection.head().excerpt_id
13079 });
13080 buffer_highlights
13081 .next()
13082 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
13083 })?
13084 };
13085 if let Some(rename_range) = rename_range {
13086 this.update_in(cx, |this, window, cx| {
13087 let snapshot = cursor_buffer.read(cx).snapshot();
13088 let rename_buffer_range = rename_range.to_offset(&snapshot);
13089 let cursor_offset_in_rename_range =
13090 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
13091 let cursor_offset_in_rename_range_end =
13092 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
13093
13094 this.take_rename(false, window, cx);
13095 let buffer = this.buffer.read(cx).read(cx);
13096 let cursor_offset = selection.head().to_offset(&buffer);
13097 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
13098 let rename_end = rename_start + rename_buffer_range.len();
13099 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
13100 let mut old_highlight_id = None;
13101 let old_name: Arc<str> = buffer
13102 .chunks(rename_start..rename_end, true)
13103 .map(|chunk| {
13104 if old_highlight_id.is_none() {
13105 old_highlight_id = chunk.syntax_highlight_id;
13106 }
13107 chunk.text
13108 })
13109 .collect::<String>()
13110 .into();
13111
13112 drop(buffer);
13113
13114 // Position the selection in the rename editor so that it matches the current selection.
13115 this.show_local_selections = false;
13116 let rename_editor = cx.new(|cx| {
13117 let mut editor = Editor::single_line(window, cx);
13118 editor.buffer.update(cx, |buffer, cx| {
13119 buffer.edit([(0..0, old_name.clone())], None, cx)
13120 });
13121 let rename_selection_range = match cursor_offset_in_rename_range
13122 .cmp(&cursor_offset_in_rename_range_end)
13123 {
13124 Ordering::Equal => {
13125 editor.select_all(&SelectAll, window, cx);
13126 return editor;
13127 }
13128 Ordering::Less => {
13129 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
13130 }
13131 Ordering::Greater => {
13132 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
13133 }
13134 };
13135 if rename_selection_range.end > old_name.len() {
13136 editor.select_all(&SelectAll, window, cx);
13137 } else {
13138 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13139 s.select_ranges([rename_selection_range]);
13140 });
13141 }
13142 editor
13143 });
13144 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
13145 if e == &EditorEvent::Focused {
13146 cx.emit(EditorEvent::FocusedIn)
13147 }
13148 })
13149 .detach();
13150
13151 let write_highlights =
13152 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
13153 let read_highlights =
13154 this.clear_background_highlights::<DocumentHighlightRead>(cx);
13155 let ranges = write_highlights
13156 .iter()
13157 .flat_map(|(_, ranges)| ranges.iter())
13158 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
13159 .cloned()
13160 .collect();
13161
13162 this.highlight_text::<Rename>(
13163 ranges,
13164 HighlightStyle {
13165 fade_out: Some(0.6),
13166 ..Default::default()
13167 },
13168 cx,
13169 );
13170 let rename_focus_handle = rename_editor.focus_handle(cx);
13171 window.focus(&rename_focus_handle);
13172 let block_id = this.insert_blocks(
13173 [BlockProperties {
13174 style: BlockStyle::Flex,
13175 placement: BlockPlacement::Below(range.start),
13176 height: 1,
13177 render: Arc::new({
13178 let rename_editor = rename_editor.clone();
13179 move |cx: &mut BlockContext| {
13180 let mut text_style = cx.editor_style.text.clone();
13181 if let Some(highlight_style) = old_highlight_id
13182 .and_then(|h| h.style(&cx.editor_style.syntax))
13183 {
13184 text_style = text_style.highlight(highlight_style);
13185 }
13186 div()
13187 .block_mouse_down()
13188 .pl(cx.anchor_x)
13189 .child(EditorElement::new(
13190 &rename_editor,
13191 EditorStyle {
13192 background: cx.theme().system().transparent,
13193 local_player: cx.editor_style.local_player,
13194 text: text_style,
13195 scrollbar_width: cx.editor_style.scrollbar_width,
13196 syntax: cx.editor_style.syntax.clone(),
13197 status: cx.editor_style.status.clone(),
13198 inlay_hints_style: HighlightStyle {
13199 font_weight: Some(FontWeight::BOLD),
13200 ..make_inlay_hints_style(cx.app)
13201 },
13202 inline_completion_styles: make_suggestion_styles(
13203 cx.app,
13204 ),
13205 ..EditorStyle::default()
13206 },
13207 ))
13208 .into_any_element()
13209 }
13210 }),
13211 priority: 0,
13212 }],
13213 Some(Autoscroll::fit()),
13214 cx,
13215 )[0];
13216 this.pending_rename = Some(RenameState {
13217 range,
13218 old_name,
13219 editor: rename_editor,
13220 block_id,
13221 });
13222 })?;
13223 }
13224
13225 Ok(())
13226 }))
13227 }
13228
13229 pub fn confirm_rename(
13230 &mut self,
13231 _: &ConfirmRename,
13232 window: &mut Window,
13233 cx: &mut Context<Self>,
13234 ) -> Option<Task<Result<()>>> {
13235 let rename = self.take_rename(false, window, cx)?;
13236 let workspace = self.workspace()?.downgrade();
13237 let (buffer, start) = self
13238 .buffer
13239 .read(cx)
13240 .text_anchor_for_position(rename.range.start, cx)?;
13241 let (end_buffer, _) = self
13242 .buffer
13243 .read(cx)
13244 .text_anchor_for_position(rename.range.end, cx)?;
13245 if buffer != end_buffer {
13246 return None;
13247 }
13248
13249 let old_name = rename.old_name;
13250 let new_name = rename.editor.read(cx).text(cx);
13251
13252 let rename = self.semantics_provider.as_ref()?.perform_rename(
13253 &buffer,
13254 start,
13255 new_name.clone(),
13256 cx,
13257 )?;
13258
13259 Some(cx.spawn_in(window, async move |editor, cx| {
13260 let project_transaction = rename.await?;
13261 Self::open_project_transaction(
13262 &editor,
13263 workspace,
13264 project_transaction,
13265 format!("Rename: {} → {}", old_name, new_name),
13266 cx,
13267 )
13268 .await?;
13269
13270 editor.update(cx, |editor, cx| {
13271 editor.refresh_document_highlights(cx);
13272 })?;
13273 Ok(())
13274 }))
13275 }
13276
13277 fn take_rename(
13278 &mut self,
13279 moving_cursor: bool,
13280 window: &mut Window,
13281 cx: &mut Context<Self>,
13282 ) -> Option<RenameState> {
13283 let rename = self.pending_rename.take()?;
13284 if rename.editor.focus_handle(cx).is_focused(window) {
13285 window.focus(&self.focus_handle);
13286 }
13287
13288 self.remove_blocks(
13289 [rename.block_id].into_iter().collect(),
13290 Some(Autoscroll::fit()),
13291 cx,
13292 );
13293 self.clear_highlights::<Rename>(cx);
13294 self.show_local_selections = true;
13295
13296 if moving_cursor {
13297 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
13298 editor.selections.newest::<usize>(cx).head()
13299 });
13300
13301 // Update the selection to match the position of the selection inside
13302 // the rename editor.
13303 let snapshot = self.buffer.read(cx).read(cx);
13304 let rename_range = rename.range.to_offset(&snapshot);
13305 let cursor_in_editor = snapshot
13306 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
13307 .min(rename_range.end);
13308 drop(snapshot);
13309
13310 self.change_selections(None, window, cx, |s| {
13311 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
13312 });
13313 } else {
13314 self.refresh_document_highlights(cx);
13315 }
13316
13317 Some(rename)
13318 }
13319
13320 pub fn pending_rename(&self) -> Option<&RenameState> {
13321 self.pending_rename.as_ref()
13322 }
13323
13324 fn format(
13325 &mut self,
13326 _: &Format,
13327 window: &mut Window,
13328 cx: &mut Context<Self>,
13329 ) -> Option<Task<Result<()>>> {
13330 let project = match &self.project {
13331 Some(project) => project.clone(),
13332 None => return None,
13333 };
13334
13335 Some(self.perform_format(
13336 project,
13337 FormatTrigger::Manual,
13338 FormatTarget::Buffers,
13339 window,
13340 cx,
13341 ))
13342 }
13343
13344 fn format_selections(
13345 &mut self,
13346 _: &FormatSelections,
13347 window: &mut Window,
13348 cx: &mut Context<Self>,
13349 ) -> Option<Task<Result<()>>> {
13350 let project = match &self.project {
13351 Some(project) => project.clone(),
13352 None => return None,
13353 };
13354
13355 let ranges = self
13356 .selections
13357 .all_adjusted(cx)
13358 .into_iter()
13359 .map(|selection| selection.range())
13360 .collect_vec();
13361
13362 Some(self.perform_format(
13363 project,
13364 FormatTrigger::Manual,
13365 FormatTarget::Ranges(ranges),
13366 window,
13367 cx,
13368 ))
13369 }
13370
13371 fn perform_format(
13372 &mut self,
13373 project: Entity<Project>,
13374 trigger: FormatTrigger,
13375 target: FormatTarget,
13376 window: &mut Window,
13377 cx: &mut Context<Self>,
13378 ) -> Task<Result<()>> {
13379 let buffer = self.buffer.clone();
13380 let (buffers, target) = match target {
13381 FormatTarget::Buffers => {
13382 let mut buffers = buffer.read(cx).all_buffers();
13383 if trigger == FormatTrigger::Save {
13384 buffers.retain(|buffer| buffer.read(cx).is_dirty());
13385 }
13386 (buffers, LspFormatTarget::Buffers)
13387 }
13388 FormatTarget::Ranges(selection_ranges) => {
13389 let multi_buffer = buffer.read(cx);
13390 let snapshot = multi_buffer.read(cx);
13391 let mut buffers = HashSet::default();
13392 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
13393 BTreeMap::new();
13394 for selection_range in selection_ranges {
13395 for (buffer, buffer_range, _) in
13396 snapshot.range_to_buffer_ranges(selection_range)
13397 {
13398 let buffer_id = buffer.remote_id();
13399 let start = buffer.anchor_before(buffer_range.start);
13400 let end = buffer.anchor_after(buffer_range.end);
13401 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
13402 buffer_id_to_ranges
13403 .entry(buffer_id)
13404 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
13405 .or_insert_with(|| vec![start..end]);
13406 }
13407 }
13408 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
13409 }
13410 };
13411
13412 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
13413 let format = project.update(cx, |project, cx| {
13414 project.format(buffers, target, true, trigger, cx)
13415 });
13416
13417 cx.spawn_in(window, async move |_, cx| {
13418 let transaction = futures::select_biased! {
13419 transaction = format.log_err().fuse() => transaction,
13420 () = timeout => {
13421 log::warn!("timed out waiting for formatting");
13422 None
13423 }
13424 };
13425
13426 buffer
13427 .update(cx, |buffer, cx| {
13428 if let Some(transaction) = transaction {
13429 if !buffer.is_singleton() {
13430 buffer.push_transaction(&transaction.0, cx);
13431 }
13432 }
13433 cx.notify();
13434 })
13435 .ok();
13436
13437 Ok(())
13438 })
13439 }
13440
13441 fn organize_imports(
13442 &mut self,
13443 _: &OrganizeImports,
13444 window: &mut Window,
13445 cx: &mut Context<Self>,
13446 ) -> Option<Task<Result<()>>> {
13447 let project = match &self.project {
13448 Some(project) => project.clone(),
13449 None => return None,
13450 };
13451 Some(self.perform_code_action_kind(
13452 project,
13453 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
13454 window,
13455 cx,
13456 ))
13457 }
13458
13459 fn perform_code_action_kind(
13460 &mut self,
13461 project: Entity<Project>,
13462 kind: CodeActionKind,
13463 window: &mut Window,
13464 cx: &mut Context<Self>,
13465 ) -> Task<Result<()>> {
13466 let buffer = self.buffer.clone();
13467 let buffers = buffer.read(cx).all_buffers();
13468 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
13469 let apply_action = project.update(cx, |project, cx| {
13470 project.apply_code_action_kind(buffers, kind, true, cx)
13471 });
13472 cx.spawn_in(window, async move |_, cx| {
13473 let transaction = futures::select_biased! {
13474 () = timeout => {
13475 log::warn!("timed out waiting for executing code action");
13476 None
13477 }
13478 transaction = apply_action.log_err().fuse() => transaction,
13479 };
13480 buffer
13481 .update(cx, |buffer, cx| {
13482 // check if we need this
13483 if let Some(transaction) = transaction {
13484 if !buffer.is_singleton() {
13485 buffer.push_transaction(&transaction.0, cx);
13486 }
13487 }
13488 cx.notify();
13489 })
13490 .ok();
13491 Ok(())
13492 })
13493 }
13494
13495 fn restart_language_server(
13496 &mut self,
13497 _: &RestartLanguageServer,
13498 _: &mut Window,
13499 cx: &mut Context<Self>,
13500 ) {
13501 if let Some(project) = self.project.clone() {
13502 self.buffer.update(cx, |multi_buffer, cx| {
13503 project.update(cx, |project, cx| {
13504 project.restart_language_servers_for_buffers(
13505 multi_buffer.all_buffers().into_iter().collect(),
13506 cx,
13507 );
13508 });
13509 })
13510 }
13511 }
13512
13513 fn cancel_language_server_work(
13514 workspace: &mut Workspace,
13515 _: &actions::CancelLanguageServerWork,
13516 _: &mut Window,
13517 cx: &mut Context<Workspace>,
13518 ) {
13519 let project = workspace.project();
13520 let buffers = workspace
13521 .active_item(cx)
13522 .and_then(|item| item.act_as::<Editor>(cx))
13523 .map_or(HashSet::default(), |editor| {
13524 editor.read(cx).buffer.read(cx).all_buffers()
13525 });
13526 project.update(cx, |project, cx| {
13527 project.cancel_language_server_work_for_buffers(buffers, cx);
13528 });
13529 }
13530
13531 fn show_character_palette(
13532 &mut self,
13533 _: &ShowCharacterPalette,
13534 window: &mut Window,
13535 _: &mut Context<Self>,
13536 ) {
13537 window.show_character_palette();
13538 }
13539
13540 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
13541 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
13542 let buffer = self.buffer.read(cx).snapshot(cx);
13543 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
13544 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
13545 let is_valid = buffer
13546 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
13547 .any(|entry| {
13548 entry.diagnostic.is_primary
13549 && !entry.range.is_empty()
13550 && entry.range.start == primary_range_start
13551 && entry.diagnostic.message == active_diagnostics.primary_message
13552 });
13553
13554 if is_valid != active_diagnostics.is_valid {
13555 active_diagnostics.is_valid = is_valid;
13556 if is_valid {
13557 let mut new_styles = HashMap::default();
13558 for (block_id, diagnostic) in &active_diagnostics.blocks {
13559 new_styles.insert(
13560 *block_id,
13561 diagnostic_block_renderer(diagnostic.clone(), None, true),
13562 );
13563 }
13564 self.display_map.update(cx, |display_map, _cx| {
13565 display_map.replace_blocks(new_styles);
13566 });
13567 } else {
13568 self.dismiss_diagnostics(cx);
13569 }
13570 }
13571 }
13572 }
13573
13574 fn activate_diagnostics(
13575 &mut self,
13576 buffer_id: BufferId,
13577 group_id: usize,
13578 window: &mut Window,
13579 cx: &mut Context<Self>,
13580 ) {
13581 self.dismiss_diagnostics(cx);
13582 let snapshot = self.snapshot(window, cx);
13583 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
13584 let buffer = self.buffer.read(cx).snapshot(cx);
13585
13586 let mut primary_range = None;
13587 let mut primary_message = None;
13588 let diagnostic_group = buffer
13589 .diagnostic_group(buffer_id, group_id)
13590 .filter_map(|entry| {
13591 let start = entry.range.start;
13592 let end = entry.range.end;
13593 if snapshot.is_line_folded(MultiBufferRow(start.row))
13594 && (start.row == end.row
13595 || snapshot.is_line_folded(MultiBufferRow(end.row)))
13596 {
13597 return None;
13598 }
13599 if entry.diagnostic.is_primary {
13600 primary_range = Some(entry.range.clone());
13601 primary_message = Some(entry.diagnostic.message.clone());
13602 }
13603 Some(entry)
13604 })
13605 .collect::<Vec<_>>();
13606 let primary_range = primary_range?;
13607 let primary_message = primary_message?;
13608
13609 let blocks = display_map
13610 .insert_blocks(
13611 diagnostic_group.iter().map(|entry| {
13612 let diagnostic = entry.diagnostic.clone();
13613 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
13614 BlockProperties {
13615 style: BlockStyle::Fixed,
13616 placement: BlockPlacement::Below(
13617 buffer.anchor_after(entry.range.start),
13618 ),
13619 height: message_height,
13620 render: diagnostic_block_renderer(diagnostic, None, true),
13621 priority: 0,
13622 }
13623 }),
13624 cx,
13625 )
13626 .into_iter()
13627 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
13628 .collect();
13629
13630 Some(ActiveDiagnosticGroup {
13631 primary_range: buffer.anchor_before(primary_range.start)
13632 ..buffer.anchor_after(primary_range.end),
13633 primary_message,
13634 group_id,
13635 blocks,
13636 is_valid: true,
13637 })
13638 });
13639 }
13640
13641 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
13642 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
13643 self.display_map.update(cx, |display_map, cx| {
13644 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
13645 });
13646 cx.notify();
13647 }
13648 }
13649
13650 /// Disable inline diagnostics rendering for this editor.
13651 pub fn disable_inline_diagnostics(&mut self) {
13652 self.inline_diagnostics_enabled = false;
13653 self.inline_diagnostics_update = Task::ready(());
13654 self.inline_diagnostics.clear();
13655 }
13656
13657 pub fn inline_diagnostics_enabled(&self) -> bool {
13658 self.inline_diagnostics_enabled
13659 }
13660
13661 pub fn show_inline_diagnostics(&self) -> bool {
13662 self.show_inline_diagnostics
13663 }
13664
13665 pub fn toggle_inline_diagnostics(
13666 &mut self,
13667 _: &ToggleInlineDiagnostics,
13668 window: &mut Window,
13669 cx: &mut Context<'_, Editor>,
13670 ) {
13671 self.show_inline_diagnostics = !self.show_inline_diagnostics;
13672 self.refresh_inline_diagnostics(false, window, cx);
13673 }
13674
13675 fn refresh_inline_diagnostics(
13676 &mut self,
13677 debounce: bool,
13678 window: &mut Window,
13679 cx: &mut Context<Self>,
13680 ) {
13681 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
13682 self.inline_diagnostics_update = Task::ready(());
13683 self.inline_diagnostics.clear();
13684 return;
13685 }
13686
13687 let debounce_ms = ProjectSettings::get_global(cx)
13688 .diagnostics
13689 .inline
13690 .update_debounce_ms;
13691 let debounce = if debounce && debounce_ms > 0 {
13692 Some(Duration::from_millis(debounce_ms))
13693 } else {
13694 None
13695 };
13696 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
13697 if let Some(debounce) = debounce {
13698 cx.background_executor().timer(debounce).await;
13699 }
13700 let Some(snapshot) = editor
13701 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
13702 .ok()
13703 else {
13704 return;
13705 };
13706
13707 let new_inline_diagnostics = cx
13708 .background_spawn(async move {
13709 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
13710 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
13711 let message = diagnostic_entry
13712 .diagnostic
13713 .message
13714 .split_once('\n')
13715 .map(|(line, _)| line)
13716 .map(SharedString::new)
13717 .unwrap_or_else(|| {
13718 SharedString::from(diagnostic_entry.diagnostic.message)
13719 });
13720 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
13721 let (Ok(i) | Err(i)) = inline_diagnostics
13722 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
13723 inline_diagnostics.insert(
13724 i,
13725 (
13726 start_anchor,
13727 InlineDiagnostic {
13728 message,
13729 group_id: diagnostic_entry.diagnostic.group_id,
13730 start: diagnostic_entry.range.start.to_point(&snapshot),
13731 is_primary: diagnostic_entry.diagnostic.is_primary,
13732 severity: diagnostic_entry.diagnostic.severity,
13733 },
13734 ),
13735 );
13736 }
13737 inline_diagnostics
13738 })
13739 .await;
13740
13741 editor
13742 .update(cx, |editor, cx| {
13743 editor.inline_diagnostics = new_inline_diagnostics;
13744 cx.notify();
13745 })
13746 .ok();
13747 });
13748 }
13749
13750 pub fn set_selections_from_remote(
13751 &mut self,
13752 selections: Vec<Selection<Anchor>>,
13753 pending_selection: Option<Selection<Anchor>>,
13754 window: &mut Window,
13755 cx: &mut Context<Self>,
13756 ) {
13757 let old_cursor_position = self.selections.newest_anchor().head();
13758 self.selections.change_with(cx, |s| {
13759 s.select_anchors(selections);
13760 if let Some(pending_selection) = pending_selection {
13761 s.set_pending(pending_selection, SelectMode::Character);
13762 } else {
13763 s.clear_pending();
13764 }
13765 });
13766 self.selections_did_change(false, &old_cursor_position, true, window, cx);
13767 }
13768
13769 fn push_to_selection_history(&mut self) {
13770 self.selection_history.push(SelectionHistoryEntry {
13771 selections: self.selections.disjoint_anchors(),
13772 select_next_state: self.select_next_state.clone(),
13773 select_prev_state: self.select_prev_state.clone(),
13774 add_selections_state: self.add_selections_state.clone(),
13775 });
13776 }
13777
13778 pub fn transact(
13779 &mut self,
13780 window: &mut Window,
13781 cx: &mut Context<Self>,
13782 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
13783 ) -> Option<TransactionId> {
13784 self.start_transaction_at(Instant::now(), window, cx);
13785 update(self, window, cx);
13786 self.end_transaction_at(Instant::now(), cx)
13787 }
13788
13789 pub fn start_transaction_at(
13790 &mut self,
13791 now: Instant,
13792 window: &mut Window,
13793 cx: &mut Context<Self>,
13794 ) {
13795 self.end_selection(window, cx);
13796 if let Some(tx_id) = self
13797 .buffer
13798 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
13799 {
13800 self.selection_history
13801 .insert_transaction(tx_id, self.selections.disjoint_anchors());
13802 cx.emit(EditorEvent::TransactionBegun {
13803 transaction_id: tx_id,
13804 })
13805 }
13806 }
13807
13808 pub fn end_transaction_at(
13809 &mut self,
13810 now: Instant,
13811 cx: &mut Context<Self>,
13812 ) -> Option<TransactionId> {
13813 if let Some(transaction_id) = self
13814 .buffer
13815 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
13816 {
13817 if let Some((_, end_selections)) =
13818 self.selection_history.transaction_mut(transaction_id)
13819 {
13820 *end_selections = Some(self.selections.disjoint_anchors());
13821 } else {
13822 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
13823 }
13824
13825 cx.emit(EditorEvent::Edited { transaction_id });
13826 Some(transaction_id)
13827 } else {
13828 None
13829 }
13830 }
13831
13832 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
13833 if self.selection_mark_mode {
13834 self.change_selections(None, window, cx, |s| {
13835 s.move_with(|_, sel| {
13836 sel.collapse_to(sel.head(), SelectionGoal::None);
13837 });
13838 })
13839 }
13840 self.selection_mark_mode = true;
13841 cx.notify();
13842 }
13843
13844 pub fn swap_selection_ends(
13845 &mut self,
13846 _: &actions::SwapSelectionEnds,
13847 window: &mut Window,
13848 cx: &mut Context<Self>,
13849 ) {
13850 self.change_selections(None, window, cx, |s| {
13851 s.move_with(|_, sel| {
13852 if sel.start != sel.end {
13853 sel.reversed = !sel.reversed
13854 }
13855 });
13856 });
13857 self.request_autoscroll(Autoscroll::newest(), cx);
13858 cx.notify();
13859 }
13860
13861 pub fn toggle_fold(
13862 &mut self,
13863 _: &actions::ToggleFold,
13864 window: &mut Window,
13865 cx: &mut Context<Self>,
13866 ) {
13867 if self.is_singleton(cx) {
13868 let selection = self.selections.newest::<Point>(cx);
13869
13870 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13871 let range = if selection.is_empty() {
13872 let point = selection.head().to_display_point(&display_map);
13873 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13874 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13875 .to_point(&display_map);
13876 start..end
13877 } else {
13878 selection.range()
13879 };
13880 if display_map.folds_in_range(range).next().is_some() {
13881 self.unfold_lines(&Default::default(), window, cx)
13882 } else {
13883 self.fold(&Default::default(), window, cx)
13884 }
13885 } else {
13886 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13887 let buffer_ids: HashSet<_> = self
13888 .selections
13889 .disjoint_anchor_ranges()
13890 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13891 .collect();
13892
13893 let should_unfold = buffer_ids
13894 .iter()
13895 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
13896
13897 for buffer_id in buffer_ids {
13898 if should_unfold {
13899 self.unfold_buffer(buffer_id, cx);
13900 } else {
13901 self.fold_buffer(buffer_id, cx);
13902 }
13903 }
13904 }
13905 }
13906
13907 pub fn toggle_fold_recursive(
13908 &mut self,
13909 _: &actions::ToggleFoldRecursive,
13910 window: &mut Window,
13911 cx: &mut Context<Self>,
13912 ) {
13913 let selection = self.selections.newest::<Point>(cx);
13914
13915 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13916 let range = if selection.is_empty() {
13917 let point = selection.head().to_display_point(&display_map);
13918 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
13919 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
13920 .to_point(&display_map);
13921 start..end
13922 } else {
13923 selection.range()
13924 };
13925 if display_map.folds_in_range(range).next().is_some() {
13926 self.unfold_recursive(&Default::default(), window, cx)
13927 } else {
13928 self.fold_recursive(&Default::default(), window, cx)
13929 }
13930 }
13931
13932 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
13933 if self.is_singleton(cx) {
13934 let mut to_fold = Vec::new();
13935 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
13936 let selections = self.selections.all_adjusted(cx);
13937
13938 for selection in selections {
13939 let range = selection.range().sorted();
13940 let buffer_start_row = range.start.row;
13941
13942 if range.start.row != range.end.row {
13943 let mut found = false;
13944 let mut row = range.start.row;
13945 while row <= range.end.row {
13946 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
13947 {
13948 found = true;
13949 row = crease.range().end.row + 1;
13950 to_fold.push(crease);
13951 } else {
13952 row += 1
13953 }
13954 }
13955 if found {
13956 continue;
13957 }
13958 }
13959
13960 for row in (0..=range.start.row).rev() {
13961 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
13962 if crease.range().end.row >= buffer_start_row {
13963 to_fold.push(crease);
13964 if row <= range.start.row {
13965 break;
13966 }
13967 }
13968 }
13969 }
13970 }
13971
13972 self.fold_creases(to_fold, true, window, cx);
13973 } else {
13974 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13975 let buffer_ids = self
13976 .selections
13977 .disjoint_anchor_ranges()
13978 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
13979 .collect::<HashSet<_>>();
13980 for buffer_id in buffer_ids {
13981 self.fold_buffer(buffer_id, cx);
13982 }
13983 }
13984 }
13985
13986 fn fold_at_level(
13987 &mut self,
13988 fold_at: &FoldAtLevel,
13989 window: &mut Window,
13990 cx: &mut Context<Self>,
13991 ) {
13992 if !self.buffer.read(cx).is_singleton() {
13993 return;
13994 }
13995
13996 let fold_at_level = fold_at.0;
13997 let snapshot = self.buffer.read(cx).snapshot(cx);
13998 let mut to_fold = Vec::new();
13999 let mut stack = vec![(0, snapshot.max_row().0, 1)];
14000
14001 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
14002 while start_row < end_row {
14003 match self
14004 .snapshot(window, cx)
14005 .crease_for_buffer_row(MultiBufferRow(start_row))
14006 {
14007 Some(crease) => {
14008 let nested_start_row = crease.range().start.row + 1;
14009 let nested_end_row = crease.range().end.row;
14010
14011 if current_level < fold_at_level {
14012 stack.push((nested_start_row, nested_end_row, current_level + 1));
14013 } else if current_level == fold_at_level {
14014 to_fold.push(crease);
14015 }
14016
14017 start_row = nested_end_row + 1;
14018 }
14019 None => start_row += 1,
14020 }
14021 }
14022 }
14023
14024 self.fold_creases(to_fold, true, window, cx);
14025 }
14026
14027 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
14028 if self.buffer.read(cx).is_singleton() {
14029 let mut fold_ranges = Vec::new();
14030 let snapshot = self.buffer.read(cx).snapshot(cx);
14031
14032 for row in 0..snapshot.max_row().0 {
14033 if let Some(foldable_range) = self
14034 .snapshot(window, cx)
14035 .crease_for_buffer_row(MultiBufferRow(row))
14036 {
14037 fold_ranges.push(foldable_range);
14038 }
14039 }
14040
14041 self.fold_creases(fold_ranges, true, window, cx);
14042 } else {
14043 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
14044 editor
14045 .update_in(cx, |editor, _, cx| {
14046 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14047 editor.fold_buffer(buffer_id, cx);
14048 }
14049 })
14050 .ok();
14051 });
14052 }
14053 }
14054
14055 pub fn fold_function_bodies(
14056 &mut self,
14057 _: &actions::FoldFunctionBodies,
14058 window: &mut Window,
14059 cx: &mut Context<Self>,
14060 ) {
14061 let snapshot = self.buffer.read(cx).snapshot(cx);
14062
14063 let ranges = snapshot
14064 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
14065 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
14066 .collect::<Vec<_>>();
14067
14068 let creases = ranges
14069 .into_iter()
14070 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
14071 .collect();
14072
14073 self.fold_creases(creases, true, window, cx);
14074 }
14075
14076 pub fn fold_recursive(
14077 &mut self,
14078 _: &actions::FoldRecursive,
14079 window: &mut Window,
14080 cx: &mut Context<Self>,
14081 ) {
14082 let mut to_fold = Vec::new();
14083 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14084 let selections = self.selections.all_adjusted(cx);
14085
14086 for selection in selections {
14087 let range = selection.range().sorted();
14088 let buffer_start_row = range.start.row;
14089
14090 if range.start.row != range.end.row {
14091 let mut found = false;
14092 for row in range.start.row..=range.end.row {
14093 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14094 found = true;
14095 to_fold.push(crease);
14096 }
14097 }
14098 if found {
14099 continue;
14100 }
14101 }
14102
14103 for row in (0..=range.start.row).rev() {
14104 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
14105 if crease.range().end.row >= buffer_start_row {
14106 to_fold.push(crease);
14107 } else {
14108 break;
14109 }
14110 }
14111 }
14112 }
14113
14114 self.fold_creases(to_fold, true, window, cx);
14115 }
14116
14117 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
14118 let buffer_row = fold_at.buffer_row;
14119 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14120
14121 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
14122 let autoscroll = self
14123 .selections
14124 .all::<Point>(cx)
14125 .iter()
14126 .any(|selection| crease.range().overlaps(&selection.range()));
14127
14128 self.fold_creases(vec![crease], autoscroll, window, cx);
14129 }
14130 }
14131
14132 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
14133 if self.is_singleton(cx) {
14134 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14135 let buffer = &display_map.buffer_snapshot;
14136 let selections = self.selections.all::<Point>(cx);
14137 let ranges = selections
14138 .iter()
14139 .map(|s| {
14140 let range = s.display_range(&display_map).sorted();
14141 let mut start = range.start.to_point(&display_map);
14142 let mut end = range.end.to_point(&display_map);
14143 start.column = 0;
14144 end.column = buffer.line_len(MultiBufferRow(end.row));
14145 start..end
14146 })
14147 .collect::<Vec<_>>();
14148
14149 self.unfold_ranges(&ranges, true, true, cx);
14150 } else {
14151 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14152 let buffer_ids = self
14153 .selections
14154 .disjoint_anchor_ranges()
14155 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14156 .collect::<HashSet<_>>();
14157 for buffer_id in buffer_ids {
14158 self.unfold_buffer(buffer_id, cx);
14159 }
14160 }
14161 }
14162
14163 pub fn unfold_recursive(
14164 &mut self,
14165 _: &UnfoldRecursive,
14166 _window: &mut Window,
14167 cx: &mut Context<Self>,
14168 ) {
14169 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14170 let selections = self.selections.all::<Point>(cx);
14171 let ranges = selections
14172 .iter()
14173 .map(|s| {
14174 let mut range = s.display_range(&display_map).sorted();
14175 *range.start.column_mut() = 0;
14176 *range.end.column_mut() = display_map.line_len(range.end.row());
14177 let start = range.start.to_point(&display_map);
14178 let end = range.end.to_point(&display_map);
14179 start..end
14180 })
14181 .collect::<Vec<_>>();
14182
14183 self.unfold_ranges(&ranges, true, true, cx);
14184 }
14185
14186 pub fn unfold_at(
14187 &mut self,
14188 unfold_at: &UnfoldAt,
14189 _window: &mut Window,
14190 cx: &mut Context<Self>,
14191 ) {
14192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14193
14194 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
14195 ..Point::new(
14196 unfold_at.buffer_row.0,
14197 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
14198 );
14199
14200 let autoscroll = self
14201 .selections
14202 .all::<Point>(cx)
14203 .iter()
14204 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
14205
14206 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
14207 }
14208
14209 pub fn unfold_all(
14210 &mut self,
14211 _: &actions::UnfoldAll,
14212 _window: &mut Window,
14213 cx: &mut Context<Self>,
14214 ) {
14215 if self.buffer.read(cx).is_singleton() {
14216 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14217 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
14218 } else {
14219 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
14220 editor
14221 .update(cx, |editor, cx| {
14222 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
14223 editor.unfold_buffer(buffer_id, cx);
14224 }
14225 })
14226 .ok();
14227 });
14228 }
14229 }
14230
14231 pub fn fold_selected_ranges(
14232 &mut self,
14233 _: &FoldSelectedRanges,
14234 window: &mut Window,
14235 cx: &mut Context<Self>,
14236 ) {
14237 let selections = self.selections.all::<Point>(cx);
14238 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14239 let line_mode = self.selections.line_mode;
14240 let ranges = selections
14241 .into_iter()
14242 .map(|s| {
14243 if line_mode {
14244 let start = Point::new(s.start.row, 0);
14245 let end = Point::new(
14246 s.end.row,
14247 display_map
14248 .buffer_snapshot
14249 .line_len(MultiBufferRow(s.end.row)),
14250 );
14251 Crease::simple(start..end, display_map.fold_placeholder.clone())
14252 } else {
14253 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
14254 }
14255 })
14256 .collect::<Vec<_>>();
14257 self.fold_creases(ranges, true, window, cx);
14258 }
14259
14260 pub fn fold_ranges<T: ToOffset + Clone>(
14261 &mut self,
14262 ranges: Vec<Range<T>>,
14263 auto_scroll: bool,
14264 window: &mut Window,
14265 cx: &mut Context<Self>,
14266 ) {
14267 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14268 let ranges = ranges
14269 .into_iter()
14270 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
14271 .collect::<Vec<_>>();
14272 self.fold_creases(ranges, auto_scroll, window, cx);
14273 }
14274
14275 pub fn fold_creases<T: ToOffset + Clone>(
14276 &mut self,
14277 creases: Vec<Crease<T>>,
14278 auto_scroll: bool,
14279 window: &mut Window,
14280 cx: &mut Context<Self>,
14281 ) {
14282 if creases.is_empty() {
14283 return;
14284 }
14285
14286 let mut buffers_affected = HashSet::default();
14287 let multi_buffer = self.buffer().read(cx);
14288 for crease in &creases {
14289 if let Some((_, buffer, _)) =
14290 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
14291 {
14292 buffers_affected.insert(buffer.read(cx).remote_id());
14293 };
14294 }
14295
14296 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
14297
14298 if auto_scroll {
14299 self.request_autoscroll(Autoscroll::fit(), cx);
14300 }
14301
14302 cx.notify();
14303
14304 if let Some(active_diagnostics) = self.active_diagnostics.take() {
14305 // Clear diagnostics block when folding a range that contains it.
14306 let snapshot = self.snapshot(window, cx);
14307 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
14308 drop(snapshot);
14309 self.active_diagnostics = Some(active_diagnostics);
14310 self.dismiss_diagnostics(cx);
14311 } else {
14312 self.active_diagnostics = Some(active_diagnostics);
14313 }
14314 }
14315
14316 self.scrollbar_marker_state.dirty = true;
14317 }
14318
14319 /// Removes any folds whose ranges intersect any of the given ranges.
14320 pub fn unfold_ranges<T: ToOffset + Clone>(
14321 &mut self,
14322 ranges: &[Range<T>],
14323 inclusive: bool,
14324 auto_scroll: bool,
14325 cx: &mut Context<Self>,
14326 ) {
14327 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14328 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
14329 });
14330 }
14331
14332 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14333 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
14334 return;
14335 }
14336 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14337 self.display_map.update(cx, |display_map, cx| {
14338 display_map.fold_buffers([buffer_id], cx)
14339 });
14340 cx.emit(EditorEvent::BufferFoldToggled {
14341 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
14342 folded: true,
14343 });
14344 cx.notify();
14345 }
14346
14347 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
14348 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
14349 return;
14350 }
14351 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
14352 self.display_map.update(cx, |display_map, cx| {
14353 display_map.unfold_buffers([buffer_id], cx);
14354 });
14355 cx.emit(EditorEvent::BufferFoldToggled {
14356 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
14357 folded: false,
14358 });
14359 cx.notify();
14360 }
14361
14362 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
14363 self.display_map.read(cx).is_buffer_folded(buffer)
14364 }
14365
14366 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
14367 self.display_map.read(cx).folded_buffers()
14368 }
14369
14370 /// Removes any folds with the given ranges.
14371 pub fn remove_folds_with_type<T: ToOffset + Clone>(
14372 &mut self,
14373 ranges: &[Range<T>],
14374 type_id: TypeId,
14375 auto_scroll: bool,
14376 cx: &mut Context<Self>,
14377 ) {
14378 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
14379 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
14380 });
14381 }
14382
14383 fn remove_folds_with<T: ToOffset + Clone>(
14384 &mut self,
14385 ranges: &[Range<T>],
14386 auto_scroll: bool,
14387 cx: &mut Context<Self>,
14388 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
14389 ) {
14390 if ranges.is_empty() {
14391 return;
14392 }
14393
14394 let mut buffers_affected = HashSet::default();
14395 let multi_buffer = self.buffer().read(cx);
14396 for range in ranges {
14397 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
14398 buffers_affected.insert(buffer.read(cx).remote_id());
14399 };
14400 }
14401
14402 self.display_map.update(cx, update);
14403
14404 if auto_scroll {
14405 self.request_autoscroll(Autoscroll::fit(), cx);
14406 }
14407
14408 cx.notify();
14409 self.scrollbar_marker_state.dirty = true;
14410 self.active_indent_guides_state.dirty = true;
14411 }
14412
14413 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
14414 self.display_map.read(cx).fold_placeholder.clone()
14415 }
14416
14417 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
14418 self.buffer.update(cx, |buffer, cx| {
14419 buffer.set_all_diff_hunks_expanded(cx);
14420 });
14421 }
14422
14423 pub fn expand_all_diff_hunks(
14424 &mut self,
14425 _: &ExpandAllDiffHunks,
14426 _window: &mut Window,
14427 cx: &mut Context<Self>,
14428 ) {
14429 self.buffer.update(cx, |buffer, cx| {
14430 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
14431 });
14432 }
14433
14434 pub fn toggle_selected_diff_hunks(
14435 &mut self,
14436 _: &ToggleSelectedDiffHunks,
14437 _window: &mut Window,
14438 cx: &mut Context<Self>,
14439 ) {
14440 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14441 self.toggle_diff_hunks_in_ranges(ranges, cx);
14442 }
14443
14444 pub fn diff_hunks_in_ranges<'a>(
14445 &'a self,
14446 ranges: &'a [Range<Anchor>],
14447 buffer: &'a MultiBufferSnapshot,
14448 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
14449 ranges.iter().flat_map(move |range| {
14450 let end_excerpt_id = range.end.excerpt_id;
14451 let range = range.to_point(buffer);
14452 let mut peek_end = range.end;
14453 if range.end.row < buffer.max_row().0 {
14454 peek_end = Point::new(range.end.row + 1, 0);
14455 }
14456 buffer
14457 .diff_hunks_in_range(range.start..peek_end)
14458 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
14459 })
14460 }
14461
14462 pub fn has_stageable_diff_hunks_in_ranges(
14463 &self,
14464 ranges: &[Range<Anchor>],
14465 snapshot: &MultiBufferSnapshot,
14466 ) -> bool {
14467 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
14468 hunks.any(|hunk| hunk.status().has_secondary_hunk())
14469 }
14470
14471 pub fn toggle_staged_selected_diff_hunks(
14472 &mut self,
14473 _: &::git::ToggleStaged,
14474 _: &mut Window,
14475 cx: &mut Context<Self>,
14476 ) {
14477 let snapshot = self.buffer.read(cx).snapshot(cx);
14478 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14479 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
14480 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14481 }
14482
14483 pub fn stage_and_next(
14484 &mut self,
14485 _: &::git::StageAndNext,
14486 window: &mut Window,
14487 cx: &mut Context<Self>,
14488 ) {
14489 self.do_stage_or_unstage_and_next(true, window, cx);
14490 }
14491
14492 pub fn unstage_and_next(
14493 &mut self,
14494 _: &::git::UnstageAndNext,
14495 window: &mut Window,
14496 cx: &mut Context<Self>,
14497 ) {
14498 self.do_stage_or_unstage_and_next(false, window, cx);
14499 }
14500
14501 pub fn stage_or_unstage_diff_hunks(
14502 &mut self,
14503 stage: bool,
14504 ranges: Vec<Range<Anchor>>,
14505 cx: &mut Context<Self>,
14506 ) {
14507 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
14508 cx.spawn(async move |this, cx| {
14509 task.await?;
14510 this.update(cx, |this, cx| {
14511 let snapshot = this.buffer.read(cx).snapshot(cx);
14512 let chunk_by = this
14513 .diff_hunks_in_ranges(&ranges, &snapshot)
14514 .chunk_by(|hunk| hunk.buffer_id);
14515 for (buffer_id, hunks) in &chunk_by {
14516 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
14517 }
14518 })
14519 })
14520 .detach_and_log_err(cx);
14521 }
14522
14523 fn save_buffers_for_ranges_if_needed(
14524 &mut self,
14525 ranges: &[Range<Anchor>],
14526 cx: &mut Context<'_, Editor>,
14527 ) -> Task<Result<()>> {
14528 let multibuffer = self.buffer.read(cx);
14529 let snapshot = multibuffer.read(cx);
14530 let buffer_ids: HashSet<_> = ranges
14531 .iter()
14532 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
14533 .collect();
14534 drop(snapshot);
14535
14536 let mut buffers = HashSet::default();
14537 for buffer_id in buffer_ids {
14538 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
14539 let buffer = buffer_entity.read(cx);
14540 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
14541 {
14542 buffers.insert(buffer_entity);
14543 }
14544 }
14545 }
14546
14547 if let Some(project) = &self.project {
14548 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
14549 } else {
14550 Task::ready(Ok(()))
14551 }
14552 }
14553
14554 fn do_stage_or_unstage_and_next(
14555 &mut self,
14556 stage: bool,
14557 window: &mut Window,
14558 cx: &mut Context<Self>,
14559 ) {
14560 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
14561
14562 if ranges.iter().any(|range| range.start != range.end) {
14563 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14564 return;
14565 }
14566
14567 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
14568 let snapshot = self.snapshot(window, cx);
14569 let position = self.selections.newest::<Point>(cx).head();
14570 let mut row = snapshot
14571 .buffer_snapshot
14572 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
14573 .find(|hunk| hunk.row_range.start.0 > position.row)
14574 .map(|hunk| hunk.row_range.start);
14575
14576 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
14577 // Outside of the project diff editor, wrap around to the beginning.
14578 if !all_diff_hunks_expanded {
14579 row = row.or_else(|| {
14580 snapshot
14581 .buffer_snapshot
14582 .diff_hunks_in_range(Point::zero()..position)
14583 .find(|hunk| hunk.row_range.end.0 < position.row)
14584 .map(|hunk| hunk.row_range.start)
14585 });
14586 }
14587
14588 if let Some(row) = row {
14589 let destination = Point::new(row.0, 0);
14590 let autoscroll = Autoscroll::center();
14591
14592 self.unfold_ranges(&[destination..destination], false, false, cx);
14593 self.change_selections(Some(autoscroll), window, cx, |s| {
14594 s.select_ranges([destination..destination]);
14595 });
14596 }
14597 }
14598
14599 fn do_stage_or_unstage(
14600 &self,
14601 stage: bool,
14602 buffer_id: BufferId,
14603 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
14604 cx: &mut App,
14605 ) -> Option<()> {
14606 let project = self.project.as_ref()?;
14607 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
14608 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
14609 let buffer_snapshot = buffer.read(cx).snapshot();
14610 let file_exists = buffer_snapshot
14611 .file()
14612 .is_some_and(|file| file.disk_state().exists());
14613 diff.update(cx, |diff, cx| {
14614 diff.stage_or_unstage_hunks(
14615 stage,
14616 &hunks
14617 .map(|hunk| buffer_diff::DiffHunk {
14618 buffer_range: hunk.buffer_range,
14619 diff_base_byte_range: hunk.diff_base_byte_range,
14620 secondary_status: hunk.secondary_status,
14621 range: Point::zero()..Point::zero(), // unused
14622 })
14623 .collect::<Vec<_>>(),
14624 &buffer_snapshot,
14625 file_exists,
14626 cx,
14627 )
14628 });
14629 None
14630 }
14631
14632 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
14633 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
14634 self.buffer
14635 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
14636 }
14637
14638 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
14639 self.buffer.update(cx, |buffer, cx| {
14640 let ranges = vec![Anchor::min()..Anchor::max()];
14641 if !buffer.all_diff_hunks_expanded()
14642 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
14643 {
14644 buffer.collapse_diff_hunks(ranges, cx);
14645 true
14646 } else {
14647 false
14648 }
14649 })
14650 }
14651
14652 fn toggle_diff_hunks_in_ranges(
14653 &mut self,
14654 ranges: Vec<Range<Anchor>>,
14655 cx: &mut Context<'_, Editor>,
14656 ) {
14657 self.buffer.update(cx, |buffer, cx| {
14658 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
14659 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
14660 })
14661 }
14662
14663 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
14664 self.buffer.update(cx, |buffer, cx| {
14665 let snapshot = buffer.snapshot(cx);
14666 let excerpt_id = range.end.excerpt_id;
14667 let point_range = range.to_point(&snapshot);
14668 let expand = !buffer.single_hunk_is_expanded(range, cx);
14669 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
14670 })
14671 }
14672
14673 pub(crate) fn apply_all_diff_hunks(
14674 &mut self,
14675 _: &ApplyAllDiffHunks,
14676 window: &mut Window,
14677 cx: &mut Context<Self>,
14678 ) {
14679 let buffers = self.buffer.read(cx).all_buffers();
14680 for branch_buffer in buffers {
14681 branch_buffer.update(cx, |branch_buffer, cx| {
14682 branch_buffer.merge_into_base(Vec::new(), cx);
14683 });
14684 }
14685
14686 if let Some(project) = self.project.clone() {
14687 self.save(true, project, window, cx).detach_and_log_err(cx);
14688 }
14689 }
14690
14691 pub(crate) fn apply_selected_diff_hunks(
14692 &mut self,
14693 _: &ApplyDiffHunk,
14694 window: &mut Window,
14695 cx: &mut Context<Self>,
14696 ) {
14697 let snapshot = self.snapshot(window, cx);
14698 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
14699 let mut ranges_by_buffer = HashMap::default();
14700 self.transact(window, cx, |editor, _window, cx| {
14701 for hunk in hunks {
14702 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
14703 ranges_by_buffer
14704 .entry(buffer.clone())
14705 .or_insert_with(Vec::new)
14706 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
14707 }
14708 }
14709
14710 for (buffer, ranges) in ranges_by_buffer {
14711 buffer.update(cx, |buffer, cx| {
14712 buffer.merge_into_base(ranges, cx);
14713 });
14714 }
14715 });
14716
14717 if let Some(project) = self.project.clone() {
14718 self.save(true, project, window, cx).detach_and_log_err(cx);
14719 }
14720 }
14721
14722 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
14723 if hovered != self.gutter_hovered {
14724 self.gutter_hovered = hovered;
14725 cx.notify();
14726 }
14727 }
14728
14729 pub fn insert_blocks(
14730 &mut self,
14731 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
14732 autoscroll: Option<Autoscroll>,
14733 cx: &mut Context<Self>,
14734 ) -> Vec<CustomBlockId> {
14735 let blocks = self
14736 .display_map
14737 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
14738 if let Some(autoscroll) = autoscroll {
14739 self.request_autoscroll(autoscroll, cx);
14740 }
14741 cx.notify();
14742 blocks
14743 }
14744
14745 pub fn resize_blocks(
14746 &mut self,
14747 heights: HashMap<CustomBlockId, u32>,
14748 autoscroll: Option<Autoscroll>,
14749 cx: &mut Context<Self>,
14750 ) {
14751 self.display_map
14752 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
14753 if let Some(autoscroll) = autoscroll {
14754 self.request_autoscroll(autoscroll, cx);
14755 }
14756 cx.notify();
14757 }
14758
14759 pub fn replace_blocks(
14760 &mut self,
14761 renderers: HashMap<CustomBlockId, RenderBlock>,
14762 autoscroll: Option<Autoscroll>,
14763 cx: &mut Context<Self>,
14764 ) {
14765 self.display_map
14766 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
14767 if let Some(autoscroll) = autoscroll {
14768 self.request_autoscroll(autoscroll, cx);
14769 }
14770 cx.notify();
14771 }
14772
14773 pub fn remove_blocks(
14774 &mut self,
14775 block_ids: HashSet<CustomBlockId>,
14776 autoscroll: Option<Autoscroll>,
14777 cx: &mut Context<Self>,
14778 ) {
14779 self.display_map.update(cx, |display_map, cx| {
14780 display_map.remove_blocks(block_ids, cx)
14781 });
14782 if let Some(autoscroll) = autoscroll {
14783 self.request_autoscroll(autoscroll, cx);
14784 }
14785 cx.notify();
14786 }
14787
14788 pub fn row_for_block(
14789 &self,
14790 block_id: CustomBlockId,
14791 cx: &mut Context<Self>,
14792 ) -> Option<DisplayRow> {
14793 self.display_map
14794 .update(cx, |map, cx| map.row_for_block(block_id, cx))
14795 }
14796
14797 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
14798 self.focused_block = Some(focused_block);
14799 }
14800
14801 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
14802 self.focused_block.take()
14803 }
14804
14805 pub fn insert_creases(
14806 &mut self,
14807 creases: impl IntoIterator<Item = Crease<Anchor>>,
14808 cx: &mut Context<Self>,
14809 ) -> Vec<CreaseId> {
14810 self.display_map
14811 .update(cx, |map, cx| map.insert_creases(creases, cx))
14812 }
14813
14814 pub fn remove_creases(
14815 &mut self,
14816 ids: impl IntoIterator<Item = CreaseId>,
14817 cx: &mut Context<Self>,
14818 ) {
14819 self.display_map
14820 .update(cx, |map, cx| map.remove_creases(ids, cx));
14821 }
14822
14823 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
14824 self.display_map
14825 .update(cx, |map, cx| map.snapshot(cx))
14826 .longest_row()
14827 }
14828
14829 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
14830 self.display_map
14831 .update(cx, |map, cx| map.snapshot(cx))
14832 .max_point()
14833 }
14834
14835 pub fn text(&self, cx: &App) -> String {
14836 self.buffer.read(cx).read(cx).text()
14837 }
14838
14839 pub fn is_empty(&self, cx: &App) -> bool {
14840 self.buffer.read(cx).read(cx).is_empty()
14841 }
14842
14843 pub fn text_option(&self, cx: &App) -> Option<String> {
14844 let text = self.text(cx);
14845 let text = text.trim();
14846
14847 if text.is_empty() {
14848 return None;
14849 }
14850
14851 Some(text.to_string())
14852 }
14853
14854 pub fn set_text(
14855 &mut self,
14856 text: impl Into<Arc<str>>,
14857 window: &mut Window,
14858 cx: &mut Context<Self>,
14859 ) {
14860 self.transact(window, cx, |this, _, cx| {
14861 this.buffer
14862 .read(cx)
14863 .as_singleton()
14864 .expect("you can only call set_text on editors for singleton buffers")
14865 .update(cx, |buffer, cx| buffer.set_text(text, cx));
14866 });
14867 }
14868
14869 pub fn display_text(&self, cx: &mut App) -> String {
14870 self.display_map
14871 .update(cx, |map, cx| map.snapshot(cx))
14872 .text()
14873 }
14874
14875 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
14876 let mut wrap_guides = smallvec::smallvec![];
14877
14878 if self.show_wrap_guides == Some(false) {
14879 return wrap_guides;
14880 }
14881
14882 let settings = self.buffer.read(cx).language_settings(cx);
14883 if settings.show_wrap_guides {
14884 match self.soft_wrap_mode(cx) {
14885 SoftWrap::Column(soft_wrap) => {
14886 wrap_guides.push((soft_wrap as usize, true));
14887 }
14888 SoftWrap::Bounded(soft_wrap) => {
14889 wrap_guides.push((soft_wrap as usize, true));
14890 }
14891 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
14892 }
14893 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
14894 }
14895
14896 wrap_guides
14897 }
14898
14899 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
14900 let settings = self.buffer.read(cx).language_settings(cx);
14901 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
14902 match mode {
14903 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
14904 SoftWrap::None
14905 }
14906 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
14907 language_settings::SoftWrap::PreferredLineLength => {
14908 SoftWrap::Column(settings.preferred_line_length)
14909 }
14910 language_settings::SoftWrap::Bounded => {
14911 SoftWrap::Bounded(settings.preferred_line_length)
14912 }
14913 }
14914 }
14915
14916 pub fn set_soft_wrap_mode(
14917 &mut self,
14918 mode: language_settings::SoftWrap,
14919
14920 cx: &mut Context<Self>,
14921 ) {
14922 self.soft_wrap_mode_override = Some(mode);
14923 cx.notify();
14924 }
14925
14926 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
14927 self.hard_wrap = hard_wrap;
14928 cx.notify();
14929 }
14930
14931 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
14932 self.text_style_refinement = Some(style);
14933 }
14934
14935 /// called by the Element so we know what style we were most recently rendered with.
14936 pub(crate) fn set_style(
14937 &mut self,
14938 style: EditorStyle,
14939 window: &mut Window,
14940 cx: &mut Context<Self>,
14941 ) {
14942 let rem_size = window.rem_size();
14943 self.display_map.update(cx, |map, cx| {
14944 map.set_font(
14945 style.text.font(),
14946 style.text.font_size.to_pixels(rem_size),
14947 cx,
14948 )
14949 });
14950 self.style = Some(style);
14951 }
14952
14953 pub fn style(&self) -> Option<&EditorStyle> {
14954 self.style.as_ref()
14955 }
14956
14957 // Called by the element. This method is not designed to be called outside of the editor
14958 // element's layout code because it does not notify when rewrapping is computed synchronously.
14959 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
14960 self.display_map
14961 .update(cx, |map, cx| map.set_wrap_width(width, cx))
14962 }
14963
14964 pub fn set_soft_wrap(&mut self) {
14965 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
14966 }
14967
14968 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
14969 if self.soft_wrap_mode_override.is_some() {
14970 self.soft_wrap_mode_override.take();
14971 } else {
14972 let soft_wrap = match self.soft_wrap_mode(cx) {
14973 SoftWrap::GitDiff => return,
14974 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
14975 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
14976 language_settings::SoftWrap::None
14977 }
14978 };
14979 self.soft_wrap_mode_override = Some(soft_wrap);
14980 }
14981 cx.notify();
14982 }
14983
14984 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
14985 let Some(workspace) = self.workspace() else {
14986 return;
14987 };
14988 let fs = workspace.read(cx).app_state().fs.clone();
14989 let current_show = TabBarSettings::get_global(cx).show;
14990 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
14991 setting.show = Some(!current_show);
14992 });
14993 }
14994
14995 pub fn toggle_indent_guides(
14996 &mut self,
14997 _: &ToggleIndentGuides,
14998 _: &mut Window,
14999 cx: &mut Context<Self>,
15000 ) {
15001 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
15002 self.buffer
15003 .read(cx)
15004 .language_settings(cx)
15005 .indent_guides
15006 .enabled
15007 });
15008 self.show_indent_guides = Some(!currently_enabled);
15009 cx.notify();
15010 }
15011
15012 fn should_show_indent_guides(&self) -> Option<bool> {
15013 self.show_indent_guides
15014 }
15015
15016 pub fn toggle_line_numbers(
15017 &mut self,
15018 _: &ToggleLineNumbers,
15019 _: &mut Window,
15020 cx: &mut Context<Self>,
15021 ) {
15022 let mut editor_settings = EditorSettings::get_global(cx).clone();
15023 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
15024 EditorSettings::override_global(editor_settings, cx);
15025 }
15026
15027 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
15028 if let Some(show_line_numbers) = self.show_line_numbers {
15029 return show_line_numbers;
15030 }
15031 EditorSettings::get_global(cx).gutter.line_numbers
15032 }
15033
15034 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
15035 self.use_relative_line_numbers
15036 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
15037 }
15038
15039 pub fn toggle_relative_line_numbers(
15040 &mut self,
15041 _: &ToggleRelativeLineNumbers,
15042 _: &mut Window,
15043 cx: &mut Context<Self>,
15044 ) {
15045 let is_relative = self.should_use_relative_line_numbers(cx);
15046 self.set_relative_line_number(Some(!is_relative), cx)
15047 }
15048
15049 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
15050 self.use_relative_line_numbers = is_relative;
15051 cx.notify();
15052 }
15053
15054 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
15055 self.show_gutter = show_gutter;
15056 cx.notify();
15057 }
15058
15059 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
15060 self.show_scrollbars = show_scrollbars;
15061 cx.notify();
15062 }
15063
15064 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
15065 self.show_line_numbers = Some(show_line_numbers);
15066 cx.notify();
15067 }
15068
15069 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
15070 self.show_git_diff_gutter = Some(show_git_diff_gutter);
15071 cx.notify();
15072 }
15073
15074 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
15075 self.show_code_actions = Some(show_code_actions);
15076 cx.notify();
15077 }
15078
15079 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
15080 self.show_runnables = Some(show_runnables);
15081 cx.notify();
15082 }
15083
15084 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
15085 self.show_breakpoints = Some(show_breakpoints);
15086 cx.notify();
15087 }
15088
15089 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
15090 if self.display_map.read(cx).masked != masked {
15091 self.display_map.update(cx, |map, _| map.masked = masked);
15092 }
15093 cx.notify()
15094 }
15095
15096 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
15097 self.show_wrap_guides = Some(show_wrap_guides);
15098 cx.notify();
15099 }
15100
15101 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
15102 self.show_indent_guides = Some(show_indent_guides);
15103 cx.notify();
15104 }
15105
15106 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
15107 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
15108 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
15109 if let Some(dir) = file.abs_path(cx).parent() {
15110 return Some(dir.to_owned());
15111 }
15112 }
15113
15114 if let Some(project_path) = buffer.read(cx).project_path(cx) {
15115 return Some(project_path.path.to_path_buf());
15116 }
15117 }
15118
15119 None
15120 }
15121
15122 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
15123 self.active_excerpt(cx)?
15124 .1
15125 .read(cx)
15126 .file()
15127 .and_then(|f| f.as_local())
15128 }
15129
15130 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15131 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15132 let buffer = buffer.read(cx);
15133 if let Some(project_path) = buffer.project_path(cx) {
15134 let project = self.project.as_ref()?.read(cx);
15135 project.absolute_path(&project_path, cx)
15136 } else {
15137 buffer
15138 .file()
15139 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
15140 }
15141 })
15142 }
15143
15144 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
15145 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
15146 let project_path = buffer.read(cx).project_path(cx)?;
15147 let project = self.project.as_ref()?.read(cx);
15148 let entry = project.entry_for_path(&project_path, cx)?;
15149 let path = entry.path.to_path_buf();
15150 Some(path)
15151 })
15152 }
15153
15154 pub fn reveal_in_finder(
15155 &mut self,
15156 _: &RevealInFileManager,
15157 _window: &mut Window,
15158 cx: &mut Context<Self>,
15159 ) {
15160 if let Some(target) = self.target_file(cx) {
15161 cx.reveal_path(&target.abs_path(cx));
15162 }
15163 }
15164
15165 pub fn copy_path(
15166 &mut self,
15167 _: &zed_actions::workspace::CopyPath,
15168 _window: &mut Window,
15169 cx: &mut Context<Self>,
15170 ) {
15171 if let Some(path) = self.target_file_abs_path(cx) {
15172 if let Some(path) = path.to_str() {
15173 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15174 }
15175 }
15176 }
15177
15178 pub fn copy_relative_path(
15179 &mut self,
15180 _: &zed_actions::workspace::CopyRelativePath,
15181 _window: &mut Window,
15182 cx: &mut Context<Self>,
15183 ) {
15184 if let Some(path) = self.target_file_path(cx) {
15185 if let Some(path) = path.to_str() {
15186 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
15187 }
15188 }
15189 }
15190
15191 pub fn project_path(&self, cx: &mut Context<Self>) -> Option<ProjectPath> {
15192 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
15193 buffer.read_with(cx, |buffer, cx| buffer.project_path(cx))
15194 } else {
15195 None
15196 }
15197 }
15198
15199 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15200 let _ = maybe!({
15201 let breakpoint_store = self.breakpoint_store.as_ref()?;
15202
15203 let Some((_, _, active_position)) =
15204 breakpoint_store.read(cx).active_position().cloned()
15205 else {
15206 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15207 return None;
15208 };
15209
15210 let snapshot = self
15211 .project
15212 .as_ref()?
15213 .read(cx)
15214 .buffer_for_id(active_position.buffer_id?, cx)?
15215 .read(cx)
15216 .snapshot();
15217
15218 for (id, ExcerptRange { context, .. }) in self
15219 .buffer
15220 .read(cx)
15221 .excerpts_for_buffer(active_position.buffer_id?, cx)
15222 {
15223 if context.start.cmp(&active_position, &snapshot).is_ge()
15224 || context.end.cmp(&active_position, &snapshot).is_lt()
15225 {
15226 continue;
15227 }
15228 let snapshot = self.buffer.read(cx).snapshot(cx);
15229 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
15230
15231 self.clear_row_highlights::<DebugCurrentRowHighlight>();
15232 self.go_to_line::<DebugCurrentRowHighlight>(
15233 multibuffer_anchor,
15234 Some(cx.theme().colors().editor_debugger_active_line_background),
15235 window,
15236 cx,
15237 );
15238
15239 cx.notify();
15240 }
15241
15242 Some(())
15243 });
15244 }
15245
15246 pub fn copy_file_name_without_extension(
15247 &mut self,
15248 _: &CopyFileNameWithoutExtension,
15249 _: &mut Window,
15250 cx: &mut Context<Self>,
15251 ) {
15252 if let Some(file) = self.target_file(cx) {
15253 if let Some(file_stem) = file.path().file_stem() {
15254 if let Some(name) = file_stem.to_str() {
15255 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15256 }
15257 }
15258 }
15259 }
15260
15261 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
15262 if let Some(file) = self.target_file(cx) {
15263 if let Some(file_name) = file.path().file_name() {
15264 if let Some(name) = file_name.to_str() {
15265 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
15266 }
15267 }
15268 }
15269 }
15270
15271 pub fn toggle_git_blame(
15272 &mut self,
15273 _: &::git::Blame,
15274 window: &mut Window,
15275 cx: &mut Context<Self>,
15276 ) {
15277 self.show_git_blame_gutter = !self.show_git_blame_gutter;
15278
15279 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
15280 self.start_git_blame(true, window, cx);
15281 }
15282
15283 cx.notify();
15284 }
15285
15286 pub fn toggle_git_blame_inline(
15287 &mut self,
15288 _: &ToggleGitBlameInline,
15289 window: &mut Window,
15290 cx: &mut Context<Self>,
15291 ) {
15292 self.toggle_git_blame_inline_internal(true, window, cx);
15293 cx.notify();
15294 }
15295
15296 pub fn git_blame_inline_enabled(&self) -> bool {
15297 self.git_blame_inline_enabled
15298 }
15299
15300 pub fn toggle_selection_menu(
15301 &mut self,
15302 _: &ToggleSelectionMenu,
15303 _: &mut Window,
15304 cx: &mut Context<Self>,
15305 ) {
15306 self.show_selection_menu = self
15307 .show_selection_menu
15308 .map(|show_selections_menu| !show_selections_menu)
15309 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
15310
15311 cx.notify();
15312 }
15313
15314 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
15315 self.show_selection_menu
15316 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
15317 }
15318
15319 fn start_git_blame(
15320 &mut self,
15321 user_triggered: bool,
15322 window: &mut Window,
15323 cx: &mut Context<Self>,
15324 ) {
15325 if let Some(project) = self.project.as_ref() {
15326 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
15327 return;
15328 };
15329
15330 if buffer.read(cx).file().is_none() {
15331 return;
15332 }
15333
15334 let focused = self.focus_handle(cx).contains_focused(window, cx);
15335
15336 let project = project.clone();
15337 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
15338 self.blame_subscription =
15339 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
15340 self.blame = Some(blame);
15341 }
15342 }
15343
15344 fn toggle_git_blame_inline_internal(
15345 &mut self,
15346 user_triggered: bool,
15347 window: &mut Window,
15348 cx: &mut Context<Self>,
15349 ) {
15350 if self.git_blame_inline_enabled {
15351 self.git_blame_inline_enabled = false;
15352 self.show_git_blame_inline = false;
15353 self.show_git_blame_inline_delay_task.take();
15354 } else {
15355 self.git_blame_inline_enabled = true;
15356 self.start_git_blame_inline(user_triggered, window, cx);
15357 }
15358
15359 cx.notify();
15360 }
15361
15362 fn start_git_blame_inline(
15363 &mut self,
15364 user_triggered: bool,
15365 window: &mut Window,
15366 cx: &mut Context<Self>,
15367 ) {
15368 self.start_git_blame(user_triggered, window, cx);
15369
15370 if ProjectSettings::get_global(cx)
15371 .git
15372 .inline_blame_delay()
15373 .is_some()
15374 {
15375 self.start_inline_blame_timer(window, cx);
15376 } else {
15377 self.show_git_blame_inline = true
15378 }
15379 }
15380
15381 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
15382 self.blame.as_ref()
15383 }
15384
15385 pub fn show_git_blame_gutter(&self) -> bool {
15386 self.show_git_blame_gutter
15387 }
15388
15389 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
15390 self.show_git_blame_gutter && self.has_blame_entries(cx)
15391 }
15392
15393 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
15394 self.show_git_blame_inline
15395 && (self.focus_handle.is_focused(window)
15396 || self
15397 .git_blame_inline_tooltip
15398 .as_ref()
15399 .and_then(|t| t.upgrade())
15400 .is_some())
15401 && !self.newest_selection_head_on_empty_line(cx)
15402 && self.has_blame_entries(cx)
15403 }
15404
15405 fn has_blame_entries(&self, cx: &App) -> bool {
15406 self.blame()
15407 .map_or(false, |blame| blame.read(cx).has_generated_entries())
15408 }
15409
15410 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
15411 let cursor_anchor = self.selections.newest_anchor().head();
15412
15413 let snapshot = self.buffer.read(cx).snapshot(cx);
15414 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
15415
15416 snapshot.line_len(buffer_row) == 0
15417 }
15418
15419 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
15420 let buffer_and_selection = maybe!({
15421 let selection = self.selections.newest::<Point>(cx);
15422 let selection_range = selection.range();
15423
15424 let multi_buffer = self.buffer().read(cx);
15425 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
15426 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
15427
15428 let (buffer, range, _) = if selection.reversed {
15429 buffer_ranges.first()
15430 } else {
15431 buffer_ranges.last()
15432 }?;
15433
15434 let selection = text::ToPoint::to_point(&range.start, &buffer).row
15435 ..text::ToPoint::to_point(&range.end, &buffer).row;
15436 Some((
15437 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
15438 selection,
15439 ))
15440 });
15441
15442 let Some((buffer, selection)) = buffer_and_selection else {
15443 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
15444 };
15445
15446 let Some(project) = self.project.as_ref() else {
15447 return Task::ready(Err(anyhow!("editor does not have project")));
15448 };
15449
15450 project.update(cx, |project, cx| {
15451 project.get_permalink_to_line(&buffer, selection, cx)
15452 })
15453 }
15454
15455 pub fn copy_permalink_to_line(
15456 &mut self,
15457 _: &CopyPermalinkToLine,
15458 window: &mut Window,
15459 cx: &mut Context<Self>,
15460 ) {
15461 let permalink_task = self.get_permalink_to_line(cx);
15462 let workspace = self.workspace();
15463
15464 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15465 Ok(permalink) => {
15466 cx.update(|_, cx| {
15467 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
15468 })
15469 .ok();
15470 }
15471 Err(err) => {
15472 let message = format!("Failed to copy permalink: {err}");
15473
15474 Err::<(), anyhow::Error>(err).log_err();
15475
15476 if let Some(workspace) = workspace {
15477 workspace
15478 .update_in(cx, |workspace, _, cx| {
15479 struct CopyPermalinkToLine;
15480
15481 workspace.show_toast(
15482 Toast::new(
15483 NotificationId::unique::<CopyPermalinkToLine>(),
15484 message,
15485 ),
15486 cx,
15487 )
15488 })
15489 .ok();
15490 }
15491 }
15492 })
15493 .detach();
15494 }
15495
15496 pub fn copy_file_location(
15497 &mut self,
15498 _: &CopyFileLocation,
15499 _: &mut Window,
15500 cx: &mut Context<Self>,
15501 ) {
15502 let selection = self.selections.newest::<Point>(cx).start.row + 1;
15503 if let Some(file) = self.target_file(cx) {
15504 if let Some(path) = file.path().to_str() {
15505 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
15506 }
15507 }
15508 }
15509
15510 pub fn open_permalink_to_line(
15511 &mut self,
15512 _: &OpenPermalinkToLine,
15513 window: &mut Window,
15514 cx: &mut Context<Self>,
15515 ) {
15516 let permalink_task = self.get_permalink_to_line(cx);
15517 let workspace = self.workspace();
15518
15519 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
15520 Ok(permalink) => {
15521 cx.update(|_, cx| {
15522 cx.open_url(permalink.as_ref());
15523 })
15524 .ok();
15525 }
15526 Err(err) => {
15527 let message = format!("Failed to open permalink: {err}");
15528
15529 Err::<(), anyhow::Error>(err).log_err();
15530
15531 if let Some(workspace) = workspace {
15532 workspace
15533 .update(cx, |workspace, cx| {
15534 struct OpenPermalinkToLine;
15535
15536 workspace.show_toast(
15537 Toast::new(
15538 NotificationId::unique::<OpenPermalinkToLine>(),
15539 message,
15540 ),
15541 cx,
15542 )
15543 })
15544 .ok();
15545 }
15546 }
15547 })
15548 .detach();
15549 }
15550
15551 pub fn insert_uuid_v4(
15552 &mut self,
15553 _: &InsertUuidV4,
15554 window: &mut Window,
15555 cx: &mut Context<Self>,
15556 ) {
15557 self.insert_uuid(UuidVersion::V4, window, cx);
15558 }
15559
15560 pub fn insert_uuid_v7(
15561 &mut self,
15562 _: &InsertUuidV7,
15563 window: &mut Window,
15564 cx: &mut Context<Self>,
15565 ) {
15566 self.insert_uuid(UuidVersion::V7, window, cx);
15567 }
15568
15569 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
15570 self.transact(window, cx, |this, window, cx| {
15571 let edits = this
15572 .selections
15573 .all::<Point>(cx)
15574 .into_iter()
15575 .map(|selection| {
15576 let uuid = match version {
15577 UuidVersion::V4 => uuid::Uuid::new_v4(),
15578 UuidVersion::V7 => uuid::Uuid::now_v7(),
15579 };
15580
15581 (selection.range(), uuid.to_string())
15582 });
15583 this.edit(edits, cx);
15584 this.refresh_inline_completion(true, false, window, cx);
15585 });
15586 }
15587
15588 pub fn open_selections_in_multibuffer(
15589 &mut self,
15590 _: &OpenSelectionsInMultibuffer,
15591 window: &mut Window,
15592 cx: &mut Context<Self>,
15593 ) {
15594 let multibuffer = self.buffer.read(cx);
15595
15596 let Some(buffer) = multibuffer.as_singleton() else {
15597 return;
15598 };
15599
15600 let Some(workspace) = self.workspace() else {
15601 return;
15602 };
15603
15604 let locations = self
15605 .selections
15606 .disjoint_anchors()
15607 .iter()
15608 .map(|range| Location {
15609 buffer: buffer.clone(),
15610 range: range.start.text_anchor..range.end.text_anchor,
15611 })
15612 .collect::<Vec<_>>();
15613
15614 let title = multibuffer.title(cx).to_string();
15615
15616 cx.spawn_in(window, async move |_, cx| {
15617 workspace.update_in(cx, |workspace, window, cx| {
15618 Self::open_locations_in_multibuffer(
15619 workspace,
15620 locations,
15621 format!("Selections for '{title}'"),
15622 false,
15623 MultibufferSelectionMode::All,
15624 window,
15625 cx,
15626 );
15627 })
15628 })
15629 .detach();
15630 }
15631
15632 /// Adds a row highlight for the given range. If a row has multiple highlights, the
15633 /// last highlight added will be used.
15634 ///
15635 /// If the range ends at the beginning of a line, then that line will not be highlighted.
15636 pub fn highlight_rows<T: 'static>(
15637 &mut self,
15638 range: Range<Anchor>,
15639 color: Hsla,
15640 should_autoscroll: bool,
15641 cx: &mut Context<Self>,
15642 ) {
15643 let snapshot = self.buffer().read(cx).snapshot(cx);
15644 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15645 let ix = row_highlights.binary_search_by(|highlight| {
15646 Ordering::Equal
15647 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
15648 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
15649 });
15650
15651 if let Err(mut ix) = ix {
15652 let index = post_inc(&mut self.highlight_order);
15653
15654 // If this range intersects with the preceding highlight, then merge it with
15655 // the preceding highlight. Otherwise insert a new highlight.
15656 let mut merged = false;
15657 if ix > 0 {
15658 let prev_highlight = &mut row_highlights[ix - 1];
15659 if prev_highlight
15660 .range
15661 .end
15662 .cmp(&range.start, &snapshot)
15663 .is_ge()
15664 {
15665 ix -= 1;
15666 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
15667 prev_highlight.range.end = range.end;
15668 }
15669 merged = true;
15670 prev_highlight.index = index;
15671 prev_highlight.color = color;
15672 prev_highlight.should_autoscroll = should_autoscroll;
15673 }
15674 }
15675
15676 if !merged {
15677 row_highlights.insert(
15678 ix,
15679 RowHighlight {
15680 range: range.clone(),
15681 index,
15682 color,
15683 should_autoscroll,
15684 },
15685 );
15686 }
15687
15688 // If any of the following highlights intersect with this one, merge them.
15689 while let Some(next_highlight) = row_highlights.get(ix + 1) {
15690 let highlight = &row_highlights[ix];
15691 if next_highlight
15692 .range
15693 .start
15694 .cmp(&highlight.range.end, &snapshot)
15695 .is_le()
15696 {
15697 if next_highlight
15698 .range
15699 .end
15700 .cmp(&highlight.range.end, &snapshot)
15701 .is_gt()
15702 {
15703 row_highlights[ix].range.end = next_highlight.range.end;
15704 }
15705 row_highlights.remove(ix + 1);
15706 } else {
15707 break;
15708 }
15709 }
15710 }
15711 }
15712
15713 /// Remove any highlighted row ranges of the given type that intersect the
15714 /// given ranges.
15715 pub fn remove_highlighted_rows<T: 'static>(
15716 &mut self,
15717 ranges_to_remove: Vec<Range<Anchor>>,
15718 cx: &mut Context<Self>,
15719 ) {
15720 let snapshot = self.buffer().read(cx).snapshot(cx);
15721 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
15722 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
15723 row_highlights.retain(|highlight| {
15724 while let Some(range_to_remove) = ranges_to_remove.peek() {
15725 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
15726 Ordering::Less | Ordering::Equal => {
15727 ranges_to_remove.next();
15728 }
15729 Ordering::Greater => {
15730 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
15731 Ordering::Less | Ordering::Equal => {
15732 return false;
15733 }
15734 Ordering::Greater => break,
15735 }
15736 }
15737 }
15738 }
15739
15740 true
15741 })
15742 }
15743
15744 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
15745 pub fn clear_row_highlights<T: 'static>(&mut self) {
15746 self.highlighted_rows.remove(&TypeId::of::<T>());
15747 }
15748
15749 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
15750 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
15751 self.highlighted_rows
15752 .get(&TypeId::of::<T>())
15753 .map_or(&[] as &[_], |vec| vec.as_slice())
15754 .iter()
15755 .map(|highlight| (highlight.range.clone(), highlight.color))
15756 }
15757
15758 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
15759 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
15760 /// Allows to ignore certain kinds of highlights.
15761 pub fn highlighted_display_rows(
15762 &self,
15763 window: &mut Window,
15764 cx: &mut App,
15765 ) -> BTreeMap<DisplayRow, LineHighlight> {
15766 let snapshot = self.snapshot(window, cx);
15767 let mut used_highlight_orders = HashMap::default();
15768 self.highlighted_rows
15769 .iter()
15770 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
15771 .fold(
15772 BTreeMap::<DisplayRow, LineHighlight>::new(),
15773 |mut unique_rows, highlight| {
15774 let start = highlight.range.start.to_display_point(&snapshot);
15775 let end = highlight.range.end.to_display_point(&snapshot);
15776 let start_row = start.row().0;
15777 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
15778 && end.column() == 0
15779 {
15780 end.row().0.saturating_sub(1)
15781 } else {
15782 end.row().0
15783 };
15784 for row in start_row..=end_row {
15785 let used_index =
15786 used_highlight_orders.entry(row).or_insert(highlight.index);
15787 if highlight.index >= *used_index {
15788 *used_index = highlight.index;
15789 unique_rows.insert(DisplayRow(row), highlight.color.into());
15790 }
15791 }
15792 unique_rows
15793 },
15794 )
15795 }
15796
15797 pub fn highlighted_display_row_for_autoscroll(
15798 &self,
15799 snapshot: &DisplaySnapshot,
15800 ) -> Option<DisplayRow> {
15801 self.highlighted_rows
15802 .values()
15803 .flat_map(|highlighted_rows| highlighted_rows.iter())
15804 .filter_map(|highlight| {
15805 if highlight.should_autoscroll {
15806 Some(highlight.range.start.to_display_point(snapshot).row())
15807 } else {
15808 None
15809 }
15810 })
15811 .min()
15812 }
15813
15814 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
15815 self.highlight_background::<SearchWithinRange>(
15816 ranges,
15817 |colors| colors.editor_document_highlight_read_background,
15818 cx,
15819 )
15820 }
15821
15822 pub fn set_breadcrumb_header(&mut self, new_header: String) {
15823 self.breadcrumb_header = Some(new_header);
15824 }
15825
15826 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
15827 self.clear_background_highlights::<SearchWithinRange>(cx);
15828 }
15829
15830 pub fn highlight_background<T: 'static>(
15831 &mut self,
15832 ranges: &[Range<Anchor>],
15833 color_fetcher: fn(&ThemeColors) -> Hsla,
15834 cx: &mut Context<Self>,
15835 ) {
15836 self.background_highlights
15837 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15838 self.scrollbar_marker_state.dirty = true;
15839 cx.notify();
15840 }
15841
15842 pub fn clear_background_highlights<T: 'static>(
15843 &mut self,
15844 cx: &mut Context<Self>,
15845 ) -> Option<BackgroundHighlight> {
15846 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
15847 if !text_highlights.1.is_empty() {
15848 self.scrollbar_marker_state.dirty = true;
15849 cx.notify();
15850 }
15851 Some(text_highlights)
15852 }
15853
15854 pub fn highlight_gutter<T: 'static>(
15855 &mut self,
15856 ranges: &[Range<Anchor>],
15857 color_fetcher: fn(&App) -> Hsla,
15858 cx: &mut Context<Self>,
15859 ) {
15860 self.gutter_highlights
15861 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
15862 cx.notify();
15863 }
15864
15865 pub fn clear_gutter_highlights<T: 'static>(
15866 &mut self,
15867 cx: &mut Context<Self>,
15868 ) -> Option<GutterHighlight> {
15869 cx.notify();
15870 self.gutter_highlights.remove(&TypeId::of::<T>())
15871 }
15872
15873 #[cfg(feature = "test-support")]
15874 pub fn all_text_background_highlights(
15875 &self,
15876 window: &mut Window,
15877 cx: &mut Context<Self>,
15878 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15879 let snapshot = self.snapshot(window, cx);
15880 let buffer = &snapshot.buffer_snapshot;
15881 let start = buffer.anchor_before(0);
15882 let end = buffer.anchor_after(buffer.len());
15883 let theme = cx.theme().colors();
15884 self.background_highlights_in_range(start..end, &snapshot, theme)
15885 }
15886
15887 #[cfg(feature = "test-support")]
15888 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
15889 let snapshot = self.buffer().read(cx).snapshot(cx);
15890
15891 let highlights = self
15892 .background_highlights
15893 .get(&TypeId::of::<items::BufferSearchHighlights>());
15894
15895 if let Some((_color, ranges)) = highlights {
15896 ranges
15897 .iter()
15898 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
15899 .collect_vec()
15900 } else {
15901 vec![]
15902 }
15903 }
15904
15905 fn document_highlights_for_position<'a>(
15906 &'a self,
15907 position: Anchor,
15908 buffer: &'a MultiBufferSnapshot,
15909 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
15910 let read_highlights = self
15911 .background_highlights
15912 .get(&TypeId::of::<DocumentHighlightRead>())
15913 .map(|h| &h.1);
15914 let write_highlights = self
15915 .background_highlights
15916 .get(&TypeId::of::<DocumentHighlightWrite>())
15917 .map(|h| &h.1);
15918 let left_position = position.bias_left(buffer);
15919 let right_position = position.bias_right(buffer);
15920 read_highlights
15921 .into_iter()
15922 .chain(write_highlights)
15923 .flat_map(move |ranges| {
15924 let start_ix = match ranges.binary_search_by(|probe| {
15925 let cmp = probe.end.cmp(&left_position, buffer);
15926 if cmp.is_ge() {
15927 Ordering::Greater
15928 } else {
15929 Ordering::Less
15930 }
15931 }) {
15932 Ok(i) | Err(i) => i,
15933 };
15934
15935 ranges[start_ix..]
15936 .iter()
15937 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
15938 })
15939 }
15940
15941 pub fn has_background_highlights<T: 'static>(&self) -> bool {
15942 self.background_highlights
15943 .get(&TypeId::of::<T>())
15944 .map_or(false, |(_, highlights)| !highlights.is_empty())
15945 }
15946
15947 pub fn background_highlights_in_range(
15948 &self,
15949 search_range: Range<Anchor>,
15950 display_snapshot: &DisplaySnapshot,
15951 theme: &ThemeColors,
15952 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
15953 let mut results = Vec::new();
15954 for (color_fetcher, ranges) in self.background_highlights.values() {
15955 let color = color_fetcher(theme);
15956 let start_ix = match ranges.binary_search_by(|probe| {
15957 let cmp = probe
15958 .end
15959 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
15960 if cmp.is_gt() {
15961 Ordering::Greater
15962 } else {
15963 Ordering::Less
15964 }
15965 }) {
15966 Ok(i) | Err(i) => i,
15967 };
15968 for range in &ranges[start_ix..] {
15969 if range
15970 .start
15971 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
15972 .is_ge()
15973 {
15974 break;
15975 }
15976
15977 let start = range.start.to_display_point(display_snapshot);
15978 let end = range.end.to_display_point(display_snapshot);
15979 results.push((start..end, color))
15980 }
15981 }
15982 results
15983 }
15984
15985 pub fn background_highlight_row_ranges<T: 'static>(
15986 &self,
15987 search_range: Range<Anchor>,
15988 display_snapshot: &DisplaySnapshot,
15989 count: usize,
15990 ) -> Vec<RangeInclusive<DisplayPoint>> {
15991 let mut results = Vec::new();
15992 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
15993 return vec![];
15994 };
15995
15996 let start_ix = match ranges.binary_search_by(|probe| {
15997 let cmp = probe
15998 .end
15999 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16000 if cmp.is_gt() {
16001 Ordering::Greater
16002 } else {
16003 Ordering::Less
16004 }
16005 }) {
16006 Ok(i) | Err(i) => i,
16007 };
16008 let mut push_region = |start: Option<Point>, end: Option<Point>| {
16009 if let (Some(start_display), Some(end_display)) = (start, end) {
16010 results.push(
16011 start_display.to_display_point(display_snapshot)
16012 ..=end_display.to_display_point(display_snapshot),
16013 );
16014 }
16015 };
16016 let mut start_row: Option<Point> = None;
16017 let mut end_row: Option<Point> = None;
16018 if ranges.len() > count {
16019 return Vec::new();
16020 }
16021 for range in &ranges[start_ix..] {
16022 if range
16023 .start
16024 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16025 .is_ge()
16026 {
16027 break;
16028 }
16029 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
16030 if let Some(current_row) = &end_row {
16031 if end.row == current_row.row {
16032 continue;
16033 }
16034 }
16035 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
16036 if start_row.is_none() {
16037 assert_eq!(end_row, None);
16038 start_row = Some(start);
16039 end_row = Some(end);
16040 continue;
16041 }
16042 if let Some(current_end) = end_row.as_mut() {
16043 if start.row > current_end.row + 1 {
16044 push_region(start_row, end_row);
16045 start_row = Some(start);
16046 end_row = Some(end);
16047 } else {
16048 // Merge two hunks.
16049 *current_end = end;
16050 }
16051 } else {
16052 unreachable!();
16053 }
16054 }
16055 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
16056 push_region(start_row, end_row);
16057 results
16058 }
16059
16060 pub fn gutter_highlights_in_range(
16061 &self,
16062 search_range: Range<Anchor>,
16063 display_snapshot: &DisplaySnapshot,
16064 cx: &App,
16065 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
16066 let mut results = Vec::new();
16067 for (color_fetcher, ranges) in self.gutter_highlights.values() {
16068 let color = color_fetcher(cx);
16069 let start_ix = match ranges.binary_search_by(|probe| {
16070 let cmp = probe
16071 .end
16072 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
16073 if cmp.is_gt() {
16074 Ordering::Greater
16075 } else {
16076 Ordering::Less
16077 }
16078 }) {
16079 Ok(i) | Err(i) => i,
16080 };
16081 for range in &ranges[start_ix..] {
16082 if range
16083 .start
16084 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
16085 .is_ge()
16086 {
16087 break;
16088 }
16089
16090 let start = range.start.to_display_point(display_snapshot);
16091 let end = range.end.to_display_point(display_snapshot);
16092 results.push((start..end, color))
16093 }
16094 }
16095 results
16096 }
16097
16098 /// Get the text ranges corresponding to the redaction query
16099 pub fn redacted_ranges(
16100 &self,
16101 search_range: Range<Anchor>,
16102 display_snapshot: &DisplaySnapshot,
16103 cx: &App,
16104 ) -> Vec<Range<DisplayPoint>> {
16105 display_snapshot
16106 .buffer_snapshot
16107 .redacted_ranges(search_range, |file| {
16108 if let Some(file) = file {
16109 file.is_private()
16110 && EditorSettings::get(
16111 Some(SettingsLocation {
16112 worktree_id: file.worktree_id(cx),
16113 path: file.path().as_ref(),
16114 }),
16115 cx,
16116 )
16117 .redact_private_values
16118 } else {
16119 false
16120 }
16121 })
16122 .map(|range| {
16123 range.start.to_display_point(display_snapshot)
16124 ..range.end.to_display_point(display_snapshot)
16125 })
16126 .collect()
16127 }
16128
16129 pub fn highlight_text<T: 'static>(
16130 &mut self,
16131 ranges: Vec<Range<Anchor>>,
16132 style: HighlightStyle,
16133 cx: &mut Context<Self>,
16134 ) {
16135 self.display_map.update(cx, |map, _| {
16136 map.highlight_text(TypeId::of::<T>(), ranges, style)
16137 });
16138 cx.notify();
16139 }
16140
16141 pub(crate) fn highlight_inlays<T: 'static>(
16142 &mut self,
16143 highlights: Vec<InlayHighlight>,
16144 style: HighlightStyle,
16145 cx: &mut Context<Self>,
16146 ) {
16147 self.display_map.update(cx, |map, _| {
16148 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
16149 });
16150 cx.notify();
16151 }
16152
16153 pub fn text_highlights<'a, T: 'static>(
16154 &'a self,
16155 cx: &'a App,
16156 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
16157 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
16158 }
16159
16160 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
16161 let cleared = self
16162 .display_map
16163 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
16164 if cleared {
16165 cx.notify();
16166 }
16167 }
16168
16169 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
16170 (self.read_only(cx) || self.blink_manager.read(cx).visible())
16171 && self.focus_handle.is_focused(window)
16172 }
16173
16174 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
16175 self.show_cursor_when_unfocused = is_enabled;
16176 cx.notify();
16177 }
16178
16179 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
16180 cx.notify();
16181 }
16182
16183 fn on_buffer_event(
16184 &mut self,
16185 multibuffer: &Entity<MultiBuffer>,
16186 event: &multi_buffer::Event,
16187 window: &mut Window,
16188 cx: &mut Context<Self>,
16189 ) {
16190 match event {
16191 multi_buffer::Event::Edited {
16192 singleton_buffer_edited,
16193 edited_buffer: buffer_edited,
16194 } => {
16195 self.scrollbar_marker_state.dirty = true;
16196 self.active_indent_guides_state.dirty = true;
16197 self.refresh_active_diagnostics(cx);
16198 self.refresh_code_actions(window, cx);
16199 if self.has_active_inline_completion() {
16200 self.update_visible_inline_completion(window, cx);
16201 }
16202 if let Some(buffer) = buffer_edited {
16203 let buffer_id = buffer.read(cx).remote_id();
16204 if !self.registered_buffers.contains_key(&buffer_id) {
16205 if let Some(project) = self.project.as_ref() {
16206 project.update(cx, |project, cx| {
16207 self.registered_buffers.insert(
16208 buffer_id,
16209 project.register_buffer_with_language_servers(&buffer, cx),
16210 );
16211 })
16212 }
16213 }
16214 }
16215 cx.emit(EditorEvent::BufferEdited);
16216 cx.emit(SearchEvent::MatchesInvalidated);
16217 if *singleton_buffer_edited {
16218 if let Some(project) = &self.project {
16219 #[allow(clippy::mutable_key_type)]
16220 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
16221 multibuffer
16222 .all_buffers()
16223 .into_iter()
16224 .filter_map(|buffer| {
16225 buffer.update(cx, |buffer, cx| {
16226 let language = buffer.language()?;
16227 let should_discard = project.update(cx, |project, cx| {
16228 project.is_local()
16229 && !project.has_language_servers_for(buffer, cx)
16230 });
16231 should_discard.not().then_some(language.clone())
16232 })
16233 })
16234 .collect::<HashSet<_>>()
16235 });
16236 if !languages_affected.is_empty() {
16237 self.refresh_inlay_hints(
16238 InlayHintRefreshReason::BufferEdited(languages_affected),
16239 cx,
16240 );
16241 }
16242 }
16243 }
16244
16245 let Some(project) = &self.project else { return };
16246 let (telemetry, is_via_ssh) = {
16247 let project = project.read(cx);
16248 let telemetry = project.client().telemetry().clone();
16249 let is_via_ssh = project.is_via_ssh();
16250 (telemetry, is_via_ssh)
16251 };
16252 refresh_linked_ranges(self, window, cx);
16253 telemetry.log_edit_event("editor", is_via_ssh);
16254 }
16255 multi_buffer::Event::ExcerptsAdded {
16256 buffer,
16257 predecessor,
16258 excerpts,
16259 } => {
16260 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16261 let buffer_id = buffer.read(cx).remote_id();
16262 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
16263 if let Some(project) = &self.project {
16264 get_uncommitted_diff_for_buffer(
16265 project,
16266 [buffer.clone()],
16267 self.buffer.clone(),
16268 cx,
16269 )
16270 .detach();
16271 }
16272 }
16273 cx.emit(EditorEvent::ExcerptsAdded {
16274 buffer: buffer.clone(),
16275 predecessor: *predecessor,
16276 excerpts: excerpts.clone(),
16277 });
16278 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16279 }
16280 multi_buffer::Event::ExcerptsRemoved { ids } => {
16281 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
16282 let buffer = self.buffer.read(cx);
16283 self.registered_buffers
16284 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
16285 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16286 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
16287 }
16288 multi_buffer::Event::ExcerptsEdited {
16289 excerpt_ids,
16290 buffer_ids,
16291 } => {
16292 self.display_map.update(cx, |map, cx| {
16293 map.unfold_buffers(buffer_ids.iter().copied(), cx)
16294 });
16295 cx.emit(EditorEvent::ExcerptsEdited {
16296 ids: excerpt_ids.clone(),
16297 })
16298 }
16299 multi_buffer::Event::ExcerptsExpanded { ids } => {
16300 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
16301 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
16302 }
16303 multi_buffer::Event::Reparsed(buffer_id) => {
16304 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16305 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16306
16307 cx.emit(EditorEvent::Reparsed(*buffer_id));
16308 }
16309 multi_buffer::Event::DiffHunksToggled => {
16310 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16311 }
16312 multi_buffer::Event::LanguageChanged(buffer_id) => {
16313 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
16314 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
16315 cx.emit(EditorEvent::Reparsed(*buffer_id));
16316 cx.notify();
16317 }
16318 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
16319 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
16320 multi_buffer::Event::FileHandleChanged
16321 | multi_buffer::Event::Reloaded
16322 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
16323 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
16324 multi_buffer::Event::DiagnosticsUpdated => {
16325 self.refresh_active_diagnostics(cx);
16326 self.refresh_inline_diagnostics(true, window, cx);
16327 self.scrollbar_marker_state.dirty = true;
16328 cx.notify();
16329 }
16330 _ => {}
16331 };
16332 }
16333
16334 fn on_display_map_changed(
16335 &mut self,
16336 _: Entity<DisplayMap>,
16337 _: &mut Window,
16338 cx: &mut Context<Self>,
16339 ) {
16340 cx.notify();
16341 }
16342
16343 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16344 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
16345 self.update_edit_prediction_settings(cx);
16346 self.refresh_inline_completion(true, false, window, cx);
16347 self.refresh_inlay_hints(
16348 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
16349 self.selections.newest_anchor().head(),
16350 &self.buffer.read(cx).snapshot(cx),
16351 cx,
16352 )),
16353 cx,
16354 );
16355
16356 let old_cursor_shape = self.cursor_shape;
16357
16358 {
16359 let editor_settings = EditorSettings::get_global(cx);
16360 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
16361 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
16362 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
16363 }
16364
16365 if old_cursor_shape != self.cursor_shape {
16366 cx.emit(EditorEvent::CursorShapeChanged);
16367 }
16368
16369 let project_settings = ProjectSettings::get_global(cx);
16370 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
16371
16372 if self.mode == EditorMode::Full {
16373 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
16374 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
16375 if self.show_inline_diagnostics != show_inline_diagnostics {
16376 self.show_inline_diagnostics = show_inline_diagnostics;
16377 self.refresh_inline_diagnostics(false, window, cx);
16378 }
16379
16380 if self.git_blame_inline_enabled != inline_blame_enabled {
16381 self.toggle_git_blame_inline_internal(false, window, cx);
16382 }
16383 }
16384
16385 cx.notify();
16386 }
16387
16388 pub fn set_searchable(&mut self, searchable: bool) {
16389 self.searchable = searchable;
16390 }
16391
16392 pub fn searchable(&self) -> bool {
16393 self.searchable
16394 }
16395
16396 fn open_proposed_changes_editor(
16397 &mut self,
16398 _: &OpenProposedChangesEditor,
16399 window: &mut Window,
16400 cx: &mut Context<Self>,
16401 ) {
16402 let Some(workspace) = self.workspace() else {
16403 cx.propagate();
16404 return;
16405 };
16406
16407 let selections = self.selections.all::<usize>(cx);
16408 let multi_buffer = self.buffer.read(cx);
16409 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16410 let mut new_selections_by_buffer = HashMap::default();
16411 for selection in selections {
16412 for (buffer, range, _) in
16413 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
16414 {
16415 let mut range = range.to_point(buffer);
16416 range.start.column = 0;
16417 range.end.column = buffer.line_len(range.end.row);
16418 new_selections_by_buffer
16419 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
16420 .or_insert(Vec::new())
16421 .push(range)
16422 }
16423 }
16424
16425 let proposed_changes_buffers = new_selections_by_buffer
16426 .into_iter()
16427 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
16428 .collect::<Vec<_>>();
16429 let proposed_changes_editor = cx.new(|cx| {
16430 ProposedChangesEditor::new(
16431 "Proposed changes",
16432 proposed_changes_buffers,
16433 self.project.clone(),
16434 window,
16435 cx,
16436 )
16437 });
16438
16439 window.defer(cx, move |window, cx| {
16440 workspace.update(cx, |workspace, cx| {
16441 workspace.active_pane().update(cx, |pane, cx| {
16442 pane.add_item(
16443 Box::new(proposed_changes_editor),
16444 true,
16445 true,
16446 None,
16447 window,
16448 cx,
16449 );
16450 });
16451 });
16452 });
16453 }
16454
16455 pub fn open_excerpts_in_split(
16456 &mut self,
16457 _: &OpenExcerptsSplit,
16458 window: &mut Window,
16459 cx: &mut Context<Self>,
16460 ) {
16461 self.open_excerpts_common(None, true, window, cx)
16462 }
16463
16464 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
16465 self.open_excerpts_common(None, false, window, cx)
16466 }
16467
16468 fn open_excerpts_common(
16469 &mut self,
16470 jump_data: Option<JumpData>,
16471 split: bool,
16472 window: &mut Window,
16473 cx: &mut Context<Self>,
16474 ) {
16475 let Some(workspace) = self.workspace() else {
16476 cx.propagate();
16477 return;
16478 };
16479
16480 if self.buffer.read(cx).is_singleton() {
16481 cx.propagate();
16482 return;
16483 }
16484
16485 let mut new_selections_by_buffer = HashMap::default();
16486 match &jump_data {
16487 Some(JumpData::MultiBufferPoint {
16488 excerpt_id,
16489 position,
16490 anchor,
16491 line_offset_from_top,
16492 }) => {
16493 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
16494 if let Some(buffer) = multi_buffer_snapshot
16495 .buffer_id_for_excerpt(*excerpt_id)
16496 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
16497 {
16498 let buffer_snapshot = buffer.read(cx).snapshot();
16499 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
16500 language::ToPoint::to_point(anchor, &buffer_snapshot)
16501 } else {
16502 buffer_snapshot.clip_point(*position, Bias::Left)
16503 };
16504 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
16505 new_selections_by_buffer.insert(
16506 buffer,
16507 (
16508 vec![jump_to_offset..jump_to_offset],
16509 Some(*line_offset_from_top),
16510 ),
16511 );
16512 }
16513 }
16514 Some(JumpData::MultiBufferRow {
16515 row,
16516 line_offset_from_top,
16517 }) => {
16518 let point = MultiBufferPoint::new(row.0, 0);
16519 if let Some((buffer, buffer_point, _)) =
16520 self.buffer.read(cx).point_to_buffer_point(point, cx)
16521 {
16522 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
16523 new_selections_by_buffer
16524 .entry(buffer)
16525 .or_insert((Vec::new(), Some(*line_offset_from_top)))
16526 .0
16527 .push(buffer_offset..buffer_offset)
16528 }
16529 }
16530 None => {
16531 let selections = self.selections.all::<usize>(cx);
16532 let multi_buffer = self.buffer.read(cx);
16533 for selection in selections {
16534 for (snapshot, range, _, anchor) in multi_buffer
16535 .snapshot(cx)
16536 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
16537 {
16538 if let Some(anchor) = anchor {
16539 // selection is in a deleted hunk
16540 let Some(buffer_id) = anchor.buffer_id else {
16541 continue;
16542 };
16543 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
16544 continue;
16545 };
16546 let offset = text::ToOffset::to_offset(
16547 &anchor.text_anchor,
16548 &buffer_handle.read(cx).snapshot(),
16549 );
16550 let range = offset..offset;
16551 new_selections_by_buffer
16552 .entry(buffer_handle)
16553 .or_insert((Vec::new(), None))
16554 .0
16555 .push(range)
16556 } else {
16557 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
16558 else {
16559 continue;
16560 };
16561 new_selections_by_buffer
16562 .entry(buffer_handle)
16563 .or_insert((Vec::new(), None))
16564 .0
16565 .push(range)
16566 }
16567 }
16568 }
16569 }
16570 }
16571
16572 if new_selections_by_buffer.is_empty() {
16573 return;
16574 }
16575
16576 // We defer the pane interaction because we ourselves are a workspace item
16577 // and activating a new item causes the pane to call a method on us reentrantly,
16578 // which panics if we're on the stack.
16579 window.defer(cx, move |window, cx| {
16580 workspace.update(cx, |workspace, cx| {
16581 let pane = if split {
16582 workspace.adjacent_pane(window, cx)
16583 } else {
16584 workspace.active_pane().clone()
16585 };
16586
16587 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
16588 let editor = buffer
16589 .read(cx)
16590 .file()
16591 .is_none()
16592 .then(|| {
16593 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
16594 // so `workspace.open_project_item` will never find them, always opening a new editor.
16595 // Instead, we try to activate the existing editor in the pane first.
16596 let (editor, pane_item_index) =
16597 pane.read(cx).items().enumerate().find_map(|(i, item)| {
16598 let editor = item.downcast::<Editor>()?;
16599 let singleton_buffer =
16600 editor.read(cx).buffer().read(cx).as_singleton()?;
16601 if singleton_buffer == buffer {
16602 Some((editor, i))
16603 } else {
16604 None
16605 }
16606 })?;
16607 pane.update(cx, |pane, cx| {
16608 pane.activate_item(pane_item_index, true, true, window, cx)
16609 });
16610 Some(editor)
16611 })
16612 .flatten()
16613 .unwrap_or_else(|| {
16614 workspace.open_project_item::<Self>(
16615 pane.clone(),
16616 buffer,
16617 true,
16618 true,
16619 window,
16620 cx,
16621 )
16622 });
16623
16624 editor.update(cx, |editor, cx| {
16625 let autoscroll = match scroll_offset {
16626 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
16627 None => Autoscroll::newest(),
16628 };
16629 let nav_history = editor.nav_history.take();
16630 editor.change_selections(Some(autoscroll), window, cx, |s| {
16631 s.select_ranges(ranges);
16632 });
16633 editor.nav_history = nav_history;
16634 });
16635 }
16636 })
16637 });
16638 }
16639
16640 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
16641 let snapshot = self.buffer.read(cx).read(cx);
16642 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
16643 Some(
16644 ranges
16645 .iter()
16646 .map(move |range| {
16647 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
16648 })
16649 .collect(),
16650 )
16651 }
16652
16653 fn selection_replacement_ranges(
16654 &self,
16655 range: Range<OffsetUtf16>,
16656 cx: &mut App,
16657 ) -> Vec<Range<OffsetUtf16>> {
16658 let selections = self.selections.all::<OffsetUtf16>(cx);
16659 let newest_selection = selections
16660 .iter()
16661 .max_by_key(|selection| selection.id)
16662 .unwrap();
16663 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
16664 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
16665 let snapshot = self.buffer.read(cx).read(cx);
16666 selections
16667 .into_iter()
16668 .map(|mut selection| {
16669 selection.start.0 =
16670 (selection.start.0 as isize).saturating_add(start_delta) as usize;
16671 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
16672 snapshot.clip_offset_utf16(selection.start, Bias::Left)
16673 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
16674 })
16675 .collect()
16676 }
16677
16678 fn report_editor_event(
16679 &self,
16680 event_type: &'static str,
16681 file_extension: Option<String>,
16682 cx: &App,
16683 ) {
16684 if cfg!(any(test, feature = "test-support")) {
16685 return;
16686 }
16687
16688 let Some(project) = &self.project else { return };
16689
16690 // If None, we are in a file without an extension
16691 let file = self
16692 .buffer
16693 .read(cx)
16694 .as_singleton()
16695 .and_then(|b| b.read(cx).file());
16696 let file_extension = file_extension.or(file
16697 .as_ref()
16698 .and_then(|file| Path::new(file.file_name(cx)).extension())
16699 .and_then(|e| e.to_str())
16700 .map(|a| a.to_string()));
16701
16702 let vim_mode = cx
16703 .global::<SettingsStore>()
16704 .raw_user_settings()
16705 .get("vim_mode")
16706 == Some(&serde_json::Value::Bool(true));
16707
16708 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
16709 let copilot_enabled = edit_predictions_provider
16710 == language::language_settings::EditPredictionProvider::Copilot;
16711 let copilot_enabled_for_language = self
16712 .buffer
16713 .read(cx)
16714 .language_settings(cx)
16715 .show_edit_predictions;
16716
16717 let project = project.read(cx);
16718 telemetry::event!(
16719 event_type,
16720 file_extension,
16721 vim_mode,
16722 copilot_enabled,
16723 copilot_enabled_for_language,
16724 edit_predictions_provider,
16725 is_via_ssh = project.is_via_ssh(),
16726 );
16727 }
16728
16729 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
16730 /// with each line being an array of {text, highlight} objects.
16731 fn copy_highlight_json(
16732 &mut self,
16733 _: &CopyHighlightJson,
16734 window: &mut Window,
16735 cx: &mut Context<Self>,
16736 ) {
16737 #[derive(Serialize)]
16738 struct Chunk<'a> {
16739 text: String,
16740 highlight: Option<&'a str>,
16741 }
16742
16743 let snapshot = self.buffer.read(cx).snapshot(cx);
16744 let range = self
16745 .selected_text_range(false, window, cx)
16746 .and_then(|selection| {
16747 if selection.range.is_empty() {
16748 None
16749 } else {
16750 Some(selection.range)
16751 }
16752 })
16753 .unwrap_or_else(|| 0..snapshot.len());
16754
16755 let chunks = snapshot.chunks(range, true);
16756 let mut lines = Vec::new();
16757 let mut line: VecDeque<Chunk> = VecDeque::new();
16758
16759 let Some(style) = self.style.as_ref() else {
16760 return;
16761 };
16762
16763 for chunk in chunks {
16764 let highlight = chunk
16765 .syntax_highlight_id
16766 .and_then(|id| id.name(&style.syntax));
16767 let mut chunk_lines = chunk.text.split('\n').peekable();
16768 while let Some(text) = chunk_lines.next() {
16769 let mut merged_with_last_token = false;
16770 if let Some(last_token) = line.back_mut() {
16771 if last_token.highlight == highlight {
16772 last_token.text.push_str(text);
16773 merged_with_last_token = true;
16774 }
16775 }
16776
16777 if !merged_with_last_token {
16778 line.push_back(Chunk {
16779 text: text.into(),
16780 highlight,
16781 });
16782 }
16783
16784 if chunk_lines.peek().is_some() {
16785 if line.len() > 1 && line.front().unwrap().text.is_empty() {
16786 line.pop_front();
16787 }
16788 if line.len() > 1 && line.back().unwrap().text.is_empty() {
16789 line.pop_back();
16790 }
16791
16792 lines.push(mem::take(&mut line));
16793 }
16794 }
16795 }
16796
16797 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
16798 return;
16799 };
16800 cx.write_to_clipboard(ClipboardItem::new_string(lines));
16801 }
16802
16803 pub fn open_context_menu(
16804 &mut self,
16805 _: &OpenContextMenu,
16806 window: &mut Window,
16807 cx: &mut Context<Self>,
16808 ) {
16809 self.request_autoscroll(Autoscroll::newest(), cx);
16810 let position = self.selections.newest_display(cx).start;
16811 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
16812 }
16813
16814 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
16815 &self.inlay_hint_cache
16816 }
16817
16818 pub fn replay_insert_event(
16819 &mut self,
16820 text: &str,
16821 relative_utf16_range: Option<Range<isize>>,
16822 window: &mut Window,
16823 cx: &mut Context<Self>,
16824 ) {
16825 if !self.input_enabled {
16826 cx.emit(EditorEvent::InputIgnored { text: text.into() });
16827 return;
16828 }
16829 if let Some(relative_utf16_range) = relative_utf16_range {
16830 let selections = self.selections.all::<OffsetUtf16>(cx);
16831 self.change_selections(None, window, cx, |s| {
16832 let new_ranges = selections.into_iter().map(|range| {
16833 let start = OffsetUtf16(
16834 range
16835 .head()
16836 .0
16837 .saturating_add_signed(relative_utf16_range.start),
16838 );
16839 let end = OffsetUtf16(
16840 range
16841 .head()
16842 .0
16843 .saturating_add_signed(relative_utf16_range.end),
16844 );
16845 start..end
16846 });
16847 s.select_ranges(new_ranges);
16848 });
16849 }
16850
16851 self.handle_input(text, window, cx);
16852 }
16853
16854 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
16855 let Some(provider) = self.semantics_provider.as_ref() else {
16856 return false;
16857 };
16858
16859 let mut supports = false;
16860 self.buffer().update(cx, |this, cx| {
16861 this.for_each_buffer(|buffer| {
16862 supports |= provider.supports_inlay_hints(buffer, cx);
16863 });
16864 });
16865
16866 supports
16867 }
16868
16869 pub fn is_focused(&self, window: &Window) -> bool {
16870 self.focus_handle.is_focused(window)
16871 }
16872
16873 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16874 cx.emit(EditorEvent::Focused);
16875
16876 if let Some(descendant) = self
16877 .last_focused_descendant
16878 .take()
16879 .and_then(|descendant| descendant.upgrade())
16880 {
16881 window.focus(&descendant);
16882 } else {
16883 if let Some(blame) = self.blame.as_ref() {
16884 blame.update(cx, GitBlame::focus)
16885 }
16886
16887 self.blink_manager.update(cx, BlinkManager::enable);
16888 self.show_cursor_names(window, cx);
16889 self.buffer.update(cx, |buffer, cx| {
16890 buffer.finalize_last_transaction(cx);
16891 if self.leader_peer_id.is_none() {
16892 buffer.set_active_selections(
16893 &self.selections.disjoint_anchors(),
16894 self.selections.line_mode,
16895 self.cursor_shape,
16896 cx,
16897 );
16898 }
16899 });
16900 }
16901 }
16902
16903 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16904 cx.emit(EditorEvent::FocusedIn)
16905 }
16906
16907 fn handle_focus_out(
16908 &mut self,
16909 event: FocusOutEvent,
16910 _window: &mut Window,
16911 cx: &mut Context<Self>,
16912 ) {
16913 if event.blurred != self.focus_handle {
16914 self.last_focused_descendant = Some(event.blurred);
16915 }
16916 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
16917 }
16918
16919 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
16920 self.blink_manager.update(cx, BlinkManager::disable);
16921 self.buffer
16922 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
16923
16924 if let Some(blame) = self.blame.as_ref() {
16925 blame.update(cx, GitBlame::blur)
16926 }
16927 if !self.hover_state.focused(window, cx) {
16928 hide_hover(self, cx);
16929 }
16930 if !self
16931 .context_menu
16932 .borrow()
16933 .as_ref()
16934 .is_some_and(|context_menu| context_menu.focused(window, cx))
16935 {
16936 self.hide_context_menu(window, cx);
16937 }
16938 self.discard_inline_completion(false, cx);
16939 cx.emit(EditorEvent::Blurred);
16940 cx.notify();
16941 }
16942
16943 pub fn register_action<A: Action>(
16944 &mut self,
16945 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
16946 ) -> Subscription {
16947 let id = self.next_editor_action_id.post_inc();
16948 let listener = Arc::new(listener);
16949 self.editor_actions.borrow_mut().insert(
16950 id,
16951 Box::new(move |window, _| {
16952 let listener = listener.clone();
16953 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
16954 let action = action.downcast_ref().unwrap();
16955 if phase == DispatchPhase::Bubble {
16956 listener(action, window, cx)
16957 }
16958 })
16959 }),
16960 );
16961
16962 let editor_actions = self.editor_actions.clone();
16963 Subscription::new(move || {
16964 editor_actions.borrow_mut().remove(&id);
16965 })
16966 }
16967
16968 pub fn file_header_size(&self) -> u32 {
16969 FILE_HEADER_HEIGHT
16970 }
16971
16972 pub fn restore(
16973 &mut self,
16974 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
16975 window: &mut Window,
16976 cx: &mut Context<Self>,
16977 ) {
16978 let workspace = self.workspace();
16979 let project = self.project.as_ref();
16980 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
16981 let mut tasks = Vec::new();
16982 for (buffer_id, changes) in revert_changes {
16983 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
16984 buffer.update(cx, |buffer, cx| {
16985 buffer.edit(
16986 changes
16987 .into_iter()
16988 .map(|(range, text)| (range, text.to_string())),
16989 None,
16990 cx,
16991 );
16992 });
16993
16994 if let Some(project) =
16995 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
16996 {
16997 project.update(cx, |project, cx| {
16998 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
16999 })
17000 }
17001 }
17002 }
17003 tasks
17004 });
17005 cx.spawn_in(window, async move |_, cx| {
17006 for (buffer, task) in save_tasks {
17007 let result = task.await;
17008 if result.is_err() {
17009 let Some(path) = buffer
17010 .read_with(cx, |buffer, cx| buffer.project_path(cx))
17011 .ok()
17012 else {
17013 continue;
17014 };
17015 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
17016 let Some(task) = cx
17017 .update_window_entity(&workspace, |workspace, window, cx| {
17018 workspace
17019 .open_path_preview(path, None, false, false, false, window, cx)
17020 })
17021 .ok()
17022 else {
17023 continue;
17024 };
17025 task.await.log_err();
17026 }
17027 }
17028 }
17029 })
17030 .detach();
17031 self.change_selections(None, window, cx, |selections| selections.refresh());
17032 }
17033
17034 pub fn to_pixel_point(
17035 &self,
17036 source: multi_buffer::Anchor,
17037 editor_snapshot: &EditorSnapshot,
17038 window: &mut Window,
17039 ) -> Option<gpui::Point<Pixels>> {
17040 let source_point = source.to_display_point(editor_snapshot);
17041 self.display_to_pixel_point(source_point, editor_snapshot, window)
17042 }
17043
17044 pub fn display_to_pixel_point(
17045 &self,
17046 source: DisplayPoint,
17047 editor_snapshot: &EditorSnapshot,
17048 window: &mut Window,
17049 ) -> Option<gpui::Point<Pixels>> {
17050 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
17051 let text_layout_details = self.text_layout_details(window);
17052 let scroll_top = text_layout_details
17053 .scroll_anchor
17054 .scroll_position(editor_snapshot)
17055 .y;
17056
17057 if source.row().as_f32() < scroll_top.floor() {
17058 return None;
17059 }
17060 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
17061 let source_y = line_height * (source.row().as_f32() - scroll_top);
17062 Some(gpui::Point::new(source_x, source_y))
17063 }
17064
17065 pub fn has_visible_completions_menu(&self) -> bool {
17066 !self.edit_prediction_preview_is_active()
17067 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
17068 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
17069 })
17070 }
17071
17072 pub fn register_addon<T: Addon>(&mut self, instance: T) {
17073 self.addons
17074 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
17075 }
17076
17077 pub fn unregister_addon<T: Addon>(&mut self) {
17078 self.addons.remove(&std::any::TypeId::of::<T>());
17079 }
17080
17081 pub fn addon<T: Addon>(&self) -> Option<&T> {
17082 let type_id = std::any::TypeId::of::<T>();
17083 self.addons
17084 .get(&type_id)
17085 .and_then(|item| item.to_any().downcast_ref::<T>())
17086 }
17087
17088 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
17089 let text_layout_details = self.text_layout_details(window);
17090 let style = &text_layout_details.editor_style;
17091 let font_id = window.text_system().resolve_font(&style.text.font());
17092 let font_size = style.text.font_size.to_pixels(window.rem_size());
17093 let line_height = style.text.line_height_in_pixels(window.rem_size());
17094 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
17095
17096 gpui::Size::new(em_width, line_height)
17097 }
17098
17099 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
17100 self.load_diff_task.clone()
17101 }
17102
17103 fn read_selections_from_db(
17104 &mut self,
17105 item_id: u64,
17106 workspace_id: WorkspaceId,
17107 window: &mut Window,
17108 cx: &mut Context<Editor>,
17109 ) {
17110 if !self.is_singleton(cx)
17111 || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
17112 {
17113 return;
17114 }
17115 let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
17116 return;
17117 };
17118 if selections.is_empty() {
17119 return;
17120 }
17121
17122 let snapshot = self.buffer.read(cx).snapshot(cx);
17123 self.change_selections(None, window, cx, |s| {
17124 s.select_ranges(selections.into_iter().map(|(start, end)| {
17125 snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
17126 }));
17127 });
17128 }
17129}
17130
17131fn insert_extra_newline_brackets(
17132 buffer: &MultiBufferSnapshot,
17133 range: Range<usize>,
17134 language: &language::LanguageScope,
17135) -> bool {
17136 let leading_whitespace_len = buffer
17137 .reversed_chars_at(range.start)
17138 .take_while(|c| c.is_whitespace() && *c != '\n')
17139 .map(|c| c.len_utf8())
17140 .sum::<usize>();
17141 let trailing_whitespace_len = buffer
17142 .chars_at(range.end)
17143 .take_while(|c| c.is_whitespace() && *c != '\n')
17144 .map(|c| c.len_utf8())
17145 .sum::<usize>();
17146 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
17147
17148 language.brackets().any(|(pair, enabled)| {
17149 let pair_start = pair.start.trim_end();
17150 let pair_end = pair.end.trim_start();
17151
17152 enabled
17153 && pair.newline
17154 && buffer.contains_str_at(range.end, pair_end)
17155 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
17156 })
17157}
17158
17159fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
17160 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
17161 [(buffer, range, _)] => (*buffer, range.clone()),
17162 _ => return false,
17163 };
17164 let pair = {
17165 let mut result: Option<BracketMatch> = None;
17166
17167 for pair in buffer
17168 .all_bracket_ranges(range.clone())
17169 .filter(move |pair| {
17170 pair.open_range.start <= range.start && pair.close_range.end >= range.end
17171 })
17172 {
17173 let len = pair.close_range.end - pair.open_range.start;
17174
17175 if let Some(existing) = &result {
17176 let existing_len = existing.close_range.end - existing.open_range.start;
17177 if len > existing_len {
17178 continue;
17179 }
17180 }
17181
17182 result = Some(pair);
17183 }
17184
17185 result
17186 };
17187 let Some(pair) = pair else {
17188 return false;
17189 };
17190 pair.newline_only
17191 && buffer
17192 .chars_for_range(pair.open_range.end..range.start)
17193 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
17194 .all(|c| c.is_whitespace() && c != '\n')
17195}
17196
17197fn get_uncommitted_diff_for_buffer(
17198 project: &Entity<Project>,
17199 buffers: impl IntoIterator<Item = Entity<Buffer>>,
17200 buffer: Entity<MultiBuffer>,
17201 cx: &mut App,
17202) -> Task<()> {
17203 let mut tasks = Vec::new();
17204 project.update(cx, |project, cx| {
17205 for buffer in buffers {
17206 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
17207 }
17208 });
17209 cx.spawn(async move |cx| {
17210 let diffs = future::join_all(tasks).await;
17211 buffer
17212 .update(cx, |buffer, cx| {
17213 for diff in diffs.into_iter().flatten() {
17214 buffer.add_diff(diff, cx);
17215 }
17216 })
17217 .ok();
17218 })
17219}
17220
17221fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
17222 let tab_size = tab_size.get() as usize;
17223 let mut width = offset;
17224
17225 for ch in text.chars() {
17226 width += if ch == '\t' {
17227 tab_size - (width % tab_size)
17228 } else {
17229 1
17230 };
17231 }
17232
17233 width - offset
17234}
17235
17236#[cfg(test)]
17237mod tests {
17238 use super::*;
17239
17240 #[test]
17241 fn test_string_size_with_expanded_tabs() {
17242 let nz = |val| NonZeroU32::new(val).unwrap();
17243 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
17244 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
17245 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
17246 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
17247 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
17248 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
17249 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
17250 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
17251 }
17252}
17253
17254/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
17255struct WordBreakingTokenizer<'a> {
17256 input: &'a str,
17257}
17258
17259impl<'a> WordBreakingTokenizer<'a> {
17260 fn new(input: &'a str) -> Self {
17261 Self { input }
17262 }
17263}
17264
17265fn is_char_ideographic(ch: char) -> bool {
17266 use unicode_script::Script::*;
17267 use unicode_script::UnicodeScript;
17268 matches!(ch.script(), Han | Tangut | Yi)
17269}
17270
17271fn is_grapheme_ideographic(text: &str) -> bool {
17272 text.chars().any(is_char_ideographic)
17273}
17274
17275fn is_grapheme_whitespace(text: &str) -> bool {
17276 text.chars().any(|x| x.is_whitespace())
17277}
17278
17279fn should_stay_with_preceding_ideograph(text: &str) -> bool {
17280 text.chars().next().map_or(false, |ch| {
17281 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
17282 })
17283}
17284
17285#[derive(PartialEq, Eq, Debug, Clone, Copy)]
17286enum WordBreakToken<'a> {
17287 Word { token: &'a str, grapheme_len: usize },
17288 InlineWhitespace { token: &'a str, grapheme_len: usize },
17289 Newline,
17290}
17291
17292impl<'a> Iterator for WordBreakingTokenizer<'a> {
17293 /// Yields a span, the count of graphemes in the token, and whether it was
17294 /// whitespace. Note that it also breaks at word boundaries.
17295 type Item = WordBreakToken<'a>;
17296
17297 fn next(&mut self) -> Option<Self::Item> {
17298 use unicode_segmentation::UnicodeSegmentation;
17299 if self.input.is_empty() {
17300 return None;
17301 }
17302
17303 let mut iter = self.input.graphemes(true).peekable();
17304 let mut offset = 0;
17305 let mut grapheme_len = 0;
17306 if let Some(first_grapheme) = iter.next() {
17307 let is_newline = first_grapheme == "\n";
17308 let is_whitespace = is_grapheme_whitespace(first_grapheme);
17309 offset += first_grapheme.len();
17310 grapheme_len += 1;
17311 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
17312 if let Some(grapheme) = iter.peek().copied() {
17313 if should_stay_with_preceding_ideograph(grapheme) {
17314 offset += grapheme.len();
17315 grapheme_len += 1;
17316 }
17317 }
17318 } else {
17319 let mut words = self.input[offset..].split_word_bound_indices().peekable();
17320 let mut next_word_bound = words.peek().copied();
17321 if next_word_bound.map_or(false, |(i, _)| i == 0) {
17322 next_word_bound = words.next();
17323 }
17324 while let Some(grapheme) = iter.peek().copied() {
17325 if next_word_bound.map_or(false, |(i, _)| i == offset) {
17326 break;
17327 };
17328 if is_grapheme_whitespace(grapheme) != is_whitespace
17329 || (grapheme == "\n") != is_newline
17330 {
17331 break;
17332 };
17333 offset += grapheme.len();
17334 grapheme_len += 1;
17335 iter.next();
17336 }
17337 }
17338 let token = &self.input[..offset];
17339 self.input = &self.input[offset..];
17340 if token == "\n" {
17341 Some(WordBreakToken::Newline)
17342 } else if is_whitespace {
17343 Some(WordBreakToken::InlineWhitespace {
17344 token,
17345 grapheme_len,
17346 })
17347 } else {
17348 Some(WordBreakToken::Word {
17349 token,
17350 grapheme_len,
17351 })
17352 }
17353 } else {
17354 None
17355 }
17356 }
17357}
17358
17359#[test]
17360fn test_word_breaking_tokenizer() {
17361 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
17362 ("", &[]),
17363 (" ", &[whitespace(" ", 2)]),
17364 ("Ʒ", &[word("Ʒ", 1)]),
17365 ("Ǽ", &[word("Ǽ", 1)]),
17366 ("⋑", &[word("⋑", 1)]),
17367 ("⋑⋑", &[word("⋑⋑", 2)]),
17368 (
17369 "原理,进而",
17370 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
17371 ),
17372 (
17373 "hello world",
17374 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
17375 ),
17376 (
17377 "hello, world",
17378 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
17379 ),
17380 (
17381 " hello world",
17382 &[
17383 whitespace(" ", 2),
17384 word("hello", 5),
17385 whitespace(" ", 1),
17386 word("world", 5),
17387 ],
17388 ),
17389 (
17390 "这是什么 \n 钢笔",
17391 &[
17392 word("这", 1),
17393 word("是", 1),
17394 word("什", 1),
17395 word("么", 1),
17396 whitespace(" ", 1),
17397 newline(),
17398 whitespace(" ", 1),
17399 word("钢", 1),
17400 word("笔", 1),
17401 ],
17402 ),
17403 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
17404 ];
17405
17406 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17407 WordBreakToken::Word {
17408 token,
17409 grapheme_len,
17410 }
17411 }
17412
17413 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
17414 WordBreakToken::InlineWhitespace {
17415 token,
17416 grapheme_len,
17417 }
17418 }
17419
17420 fn newline() -> WordBreakToken<'static> {
17421 WordBreakToken::Newline
17422 }
17423
17424 for (input, result) in tests {
17425 assert_eq!(
17426 WordBreakingTokenizer::new(input)
17427 .collect::<Vec<_>>()
17428 .as_slice(),
17429 *result,
17430 );
17431 }
17432}
17433
17434fn wrap_with_prefix(
17435 line_prefix: String,
17436 unwrapped_text: String,
17437 wrap_column: usize,
17438 tab_size: NonZeroU32,
17439 preserve_existing_whitespace: bool,
17440) -> String {
17441 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
17442 let mut wrapped_text = String::new();
17443 let mut current_line = line_prefix.clone();
17444
17445 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
17446 let mut current_line_len = line_prefix_len;
17447 let mut in_whitespace = false;
17448 for token in tokenizer {
17449 let have_preceding_whitespace = in_whitespace;
17450 match token {
17451 WordBreakToken::Word {
17452 token,
17453 grapheme_len,
17454 } => {
17455 in_whitespace = false;
17456 if current_line_len + grapheme_len > wrap_column
17457 && current_line_len != line_prefix_len
17458 {
17459 wrapped_text.push_str(current_line.trim_end());
17460 wrapped_text.push('\n');
17461 current_line.truncate(line_prefix.len());
17462 current_line_len = line_prefix_len;
17463 }
17464 current_line.push_str(token);
17465 current_line_len += grapheme_len;
17466 }
17467 WordBreakToken::InlineWhitespace {
17468 mut token,
17469 mut grapheme_len,
17470 } => {
17471 in_whitespace = true;
17472 if have_preceding_whitespace && !preserve_existing_whitespace {
17473 continue;
17474 }
17475 if !preserve_existing_whitespace {
17476 token = " ";
17477 grapheme_len = 1;
17478 }
17479 if current_line_len + grapheme_len > wrap_column {
17480 wrapped_text.push_str(current_line.trim_end());
17481 wrapped_text.push('\n');
17482 current_line.truncate(line_prefix.len());
17483 current_line_len = line_prefix_len;
17484 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
17485 current_line.push_str(token);
17486 current_line_len += grapheme_len;
17487 }
17488 }
17489 WordBreakToken::Newline => {
17490 in_whitespace = true;
17491 if preserve_existing_whitespace {
17492 wrapped_text.push_str(current_line.trim_end());
17493 wrapped_text.push('\n');
17494 current_line.truncate(line_prefix.len());
17495 current_line_len = line_prefix_len;
17496 } else if have_preceding_whitespace {
17497 continue;
17498 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
17499 {
17500 wrapped_text.push_str(current_line.trim_end());
17501 wrapped_text.push('\n');
17502 current_line.truncate(line_prefix.len());
17503 current_line_len = line_prefix_len;
17504 } else if current_line_len != line_prefix_len {
17505 current_line.push(' ');
17506 current_line_len += 1;
17507 }
17508 }
17509 }
17510 }
17511
17512 if !current_line.is_empty() {
17513 wrapped_text.push_str(¤t_line);
17514 }
17515 wrapped_text
17516}
17517
17518#[test]
17519fn test_wrap_with_prefix() {
17520 assert_eq!(
17521 wrap_with_prefix(
17522 "# ".to_string(),
17523 "abcdefg".to_string(),
17524 4,
17525 NonZeroU32::new(4).unwrap(),
17526 false,
17527 ),
17528 "# abcdefg"
17529 );
17530 assert_eq!(
17531 wrap_with_prefix(
17532 "".to_string(),
17533 "\thello world".to_string(),
17534 8,
17535 NonZeroU32::new(4).unwrap(),
17536 false,
17537 ),
17538 "hello\nworld"
17539 );
17540 assert_eq!(
17541 wrap_with_prefix(
17542 "// ".to_string(),
17543 "xx \nyy zz aa bb cc".to_string(),
17544 12,
17545 NonZeroU32::new(4).unwrap(),
17546 false,
17547 ),
17548 "// xx yy zz\n// aa bb cc"
17549 );
17550 assert_eq!(
17551 wrap_with_prefix(
17552 String::new(),
17553 "这是什么 \n 钢笔".to_string(),
17554 3,
17555 NonZeroU32::new(4).unwrap(),
17556 false,
17557 ),
17558 "这是什\n么 钢\n笔"
17559 );
17560}
17561
17562pub trait CollaborationHub {
17563 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
17564 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
17565 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
17566}
17567
17568impl CollaborationHub for Entity<Project> {
17569 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
17570 self.read(cx).collaborators()
17571 }
17572
17573 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
17574 self.read(cx).user_store().read(cx).participant_indices()
17575 }
17576
17577 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
17578 let this = self.read(cx);
17579 let user_ids = this.collaborators().values().map(|c| c.user_id);
17580 this.user_store().read_with(cx, |user_store, cx| {
17581 user_store.participant_names(user_ids, cx)
17582 })
17583 }
17584}
17585
17586pub trait SemanticsProvider {
17587 fn hover(
17588 &self,
17589 buffer: &Entity<Buffer>,
17590 position: text::Anchor,
17591 cx: &mut App,
17592 ) -> Option<Task<Vec<project::Hover>>>;
17593
17594 fn inlay_hints(
17595 &self,
17596 buffer_handle: Entity<Buffer>,
17597 range: Range<text::Anchor>,
17598 cx: &mut App,
17599 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
17600
17601 fn resolve_inlay_hint(
17602 &self,
17603 hint: InlayHint,
17604 buffer_handle: Entity<Buffer>,
17605 server_id: LanguageServerId,
17606 cx: &mut App,
17607 ) -> Option<Task<anyhow::Result<InlayHint>>>;
17608
17609 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
17610
17611 fn document_highlights(
17612 &self,
17613 buffer: &Entity<Buffer>,
17614 position: text::Anchor,
17615 cx: &mut App,
17616 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
17617
17618 fn definitions(
17619 &self,
17620 buffer: &Entity<Buffer>,
17621 position: text::Anchor,
17622 kind: GotoDefinitionKind,
17623 cx: &mut App,
17624 ) -> Option<Task<Result<Vec<LocationLink>>>>;
17625
17626 fn range_for_rename(
17627 &self,
17628 buffer: &Entity<Buffer>,
17629 position: text::Anchor,
17630 cx: &mut App,
17631 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
17632
17633 fn perform_rename(
17634 &self,
17635 buffer: &Entity<Buffer>,
17636 position: text::Anchor,
17637 new_name: String,
17638 cx: &mut App,
17639 ) -> Option<Task<Result<ProjectTransaction>>>;
17640}
17641
17642pub trait CompletionProvider {
17643 fn completions(
17644 &self,
17645 buffer: &Entity<Buffer>,
17646 buffer_position: text::Anchor,
17647 trigger: CompletionContext,
17648 window: &mut Window,
17649 cx: &mut Context<Editor>,
17650 ) -> Task<Result<Option<Vec<Completion>>>>;
17651
17652 fn resolve_completions(
17653 &self,
17654 buffer: Entity<Buffer>,
17655 completion_indices: Vec<usize>,
17656 completions: Rc<RefCell<Box<[Completion]>>>,
17657 cx: &mut Context<Editor>,
17658 ) -> Task<Result<bool>>;
17659
17660 fn apply_additional_edits_for_completion(
17661 &self,
17662 _buffer: Entity<Buffer>,
17663 _completions: Rc<RefCell<Box<[Completion]>>>,
17664 _completion_index: usize,
17665 _push_to_history: bool,
17666 _cx: &mut Context<Editor>,
17667 ) -> Task<Result<Option<language::Transaction>>> {
17668 Task::ready(Ok(None))
17669 }
17670
17671 fn is_completion_trigger(
17672 &self,
17673 buffer: &Entity<Buffer>,
17674 position: language::Anchor,
17675 text: &str,
17676 trigger_in_words: bool,
17677 cx: &mut Context<Editor>,
17678 ) -> bool;
17679
17680 fn sort_completions(&self) -> bool {
17681 true
17682 }
17683}
17684
17685pub trait CodeActionProvider {
17686 fn id(&self) -> Arc<str>;
17687
17688 fn code_actions(
17689 &self,
17690 buffer: &Entity<Buffer>,
17691 range: Range<text::Anchor>,
17692 window: &mut Window,
17693 cx: &mut App,
17694 ) -> Task<Result<Vec<CodeAction>>>;
17695
17696 fn apply_code_action(
17697 &self,
17698 buffer_handle: Entity<Buffer>,
17699 action: CodeAction,
17700 excerpt_id: ExcerptId,
17701 push_to_history: bool,
17702 window: &mut Window,
17703 cx: &mut App,
17704 ) -> Task<Result<ProjectTransaction>>;
17705}
17706
17707impl CodeActionProvider for Entity<Project> {
17708 fn id(&self) -> Arc<str> {
17709 "project".into()
17710 }
17711
17712 fn code_actions(
17713 &self,
17714 buffer: &Entity<Buffer>,
17715 range: Range<text::Anchor>,
17716 _window: &mut Window,
17717 cx: &mut App,
17718 ) -> Task<Result<Vec<CodeAction>>> {
17719 self.update(cx, |project, cx| {
17720 let code_lens = project.code_lens(buffer, range.clone(), cx);
17721 let code_actions = project.code_actions(buffer, range, None, cx);
17722 cx.background_spawn(async move {
17723 let (code_lens, code_actions) = join(code_lens, code_actions).await;
17724 Ok(code_lens
17725 .context("code lens fetch")?
17726 .into_iter()
17727 .chain(code_actions.context("code action fetch")?)
17728 .collect())
17729 })
17730 })
17731 }
17732
17733 fn apply_code_action(
17734 &self,
17735 buffer_handle: Entity<Buffer>,
17736 action: CodeAction,
17737 _excerpt_id: ExcerptId,
17738 push_to_history: bool,
17739 _window: &mut Window,
17740 cx: &mut App,
17741 ) -> Task<Result<ProjectTransaction>> {
17742 self.update(cx, |project, cx| {
17743 project.apply_code_action(buffer_handle, action, push_to_history, cx)
17744 })
17745 }
17746}
17747
17748fn snippet_completions(
17749 project: &Project,
17750 buffer: &Entity<Buffer>,
17751 buffer_position: text::Anchor,
17752 cx: &mut App,
17753) -> Task<Result<Vec<Completion>>> {
17754 let language = buffer.read(cx).language_at(buffer_position);
17755 let language_name = language.as_ref().map(|language| language.lsp_id());
17756 let snippet_store = project.snippets().read(cx);
17757 let snippets = snippet_store.snippets_for(language_name, cx);
17758
17759 if snippets.is_empty() {
17760 return Task::ready(Ok(vec![]));
17761 }
17762 let snapshot = buffer.read(cx).text_snapshot();
17763 let chars: String = snapshot
17764 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
17765 .collect();
17766
17767 let scope = language.map(|language| language.default_scope());
17768 let executor = cx.background_executor().clone();
17769
17770 cx.background_spawn(async move {
17771 let classifier = CharClassifier::new(scope).for_completion(true);
17772 let mut last_word = chars
17773 .chars()
17774 .take_while(|c| classifier.is_word(*c))
17775 .collect::<String>();
17776 last_word = last_word.chars().rev().collect();
17777
17778 if last_word.is_empty() {
17779 return Ok(vec![]);
17780 }
17781
17782 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
17783 let to_lsp = |point: &text::Anchor| {
17784 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
17785 point_to_lsp(end)
17786 };
17787 let lsp_end = to_lsp(&buffer_position);
17788
17789 let candidates = snippets
17790 .iter()
17791 .enumerate()
17792 .flat_map(|(ix, snippet)| {
17793 snippet
17794 .prefix
17795 .iter()
17796 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
17797 })
17798 .collect::<Vec<StringMatchCandidate>>();
17799
17800 let mut matches = fuzzy::match_strings(
17801 &candidates,
17802 &last_word,
17803 last_word.chars().any(|c| c.is_uppercase()),
17804 100,
17805 &Default::default(),
17806 executor,
17807 )
17808 .await;
17809
17810 // Remove all candidates where the query's start does not match the start of any word in the candidate
17811 if let Some(query_start) = last_word.chars().next() {
17812 matches.retain(|string_match| {
17813 split_words(&string_match.string).any(|word| {
17814 // Check that the first codepoint of the word as lowercase matches the first
17815 // codepoint of the query as lowercase
17816 word.chars()
17817 .flat_map(|codepoint| codepoint.to_lowercase())
17818 .zip(query_start.to_lowercase())
17819 .all(|(word_cp, query_cp)| word_cp == query_cp)
17820 })
17821 });
17822 }
17823
17824 let matched_strings = matches
17825 .into_iter()
17826 .map(|m| m.string)
17827 .collect::<HashSet<_>>();
17828
17829 let result: Vec<Completion> = snippets
17830 .into_iter()
17831 .filter_map(|snippet| {
17832 let matching_prefix = snippet
17833 .prefix
17834 .iter()
17835 .find(|prefix| matched_strings.contains(*prefix))?;
17836 let start = as_offset - last_word.len();
17837 let start = snapshot.anchor_before(start);
17838 let range = start..buffer_position;
17839 let lsp_start = to_lsp(&start);
17840 let lsp_range = lsp::Range {
17841 start: lsp_start,
17842 end: lsp_end,
17843 };
17844 Some(Completion {
17845 old_range: range,
17846 new_text: snippet.body.clone(),
17847 source: CompletionSource::Lsp {
17848 server_id: LanguageServerId(usize::MAX),
17849 resolved: true,
17850 lsp_completion: Box::new(lsp::CompletionItem {
17851 label: snippet.prefix.first().unwrap().clone(),
17852 kind: Some(CompletionItemKind::SNIPPET),
17853 label_details: snippet.description.as_ref().map(|description| {
17854 lsp::CompletionItemLabelDetails {
17855 detail: Some(description.clone()),
17856 description: None,
17857 }
17858 }),
17859 insert_text_format: Some(InsertTextFormat::SNIPPET),
17860 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
17861 lsp::InsertReplaceEdit {
17862 new_text: snippet.body.clone(),
17863 insert: lsp_range,
17864 replace: lsp_range,
17865 },
17866 )),
17867 filter_text: Some(snippet.body.clone()),
17868 sort_text: Some(char::MAX.to_string()),
17869 ..lsp::CompletionItem::default()
17870 }),
17871 lsp_defaults: None,
17872 },
17873 label: CodeLabel {
17874 text: matching_prefix.clone(),
17875 runs: Vec::new(),
17876 filter_range: 0..matching_prefix.len(),
17877 },
17878 documentation: snippet
17879 .description
17880 .clone()
17881 .map(|description| CompletionDocumentation::SingleLine(description.into())),
17882 confirm: None,
17883 })
17884 })
17885 .collect();
17886
17887 Ok(result)
17888 })
17889}
17890
17891impl CompletionProvider for Entity<Project> {
17892 fn completions(
17893 &self,
17894 buffer: &Entity<Buffer>,
17895 buffer_position: text::Anchor,
17896 options: CompletionContext,
17897 _window: &mut Window,
17898 cx: &mut Context<Editor>,
17899 ) -> Task<Result<Option<Vec<Completion>>>> {
17900 self.update(cx, |project, cx| {
17901 let snippets = snippet_completions(project, buffer, buffer_position, cx);
17902 let project_completions = project.completions(buffer, buffer_position, options, cx);
17903 cx.background_spawn(async move {
17904 let snippets_completions = snippets.await?;
17905 match project_completions.await? {
17906 Some(mut completions) => {
17907 completions.extend(snippets_completions);
17908 Ok(Some(completions))
17909 }
17910 None => {
17911 if snippets_completions.is_empty() {
17912 Ok(None)
17913 } else {
17914 Ok(Some(snippets_completions))
17915 }
17916 }
17917 }
17918 })
17919 })
17920 }
17921
17922 fn resolve_completions(
17923 &self,
17924 buffer: Entity<Buffer>,
17925 completion_indices: Vec<usize>,
17926 completions: Rc<RefCell<Box<[Completion]>>>,
17927 cx: &mut Context<Editor>,
17928 ) -> Task<Result<bool>> {
17929 self.update(cx, |project, cx| {
17930 project.lsp_store().update(cx, |lsp_store, cx| {
17931 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
17932 })
17933 })
17934 }
17935
17936 fn apply_additional_edits_for_completion(
17937 &self,
17938 buffer: Entity<Buffer>,
17939 completions: Rc<RefCell<Box<[Completion]>>>,
17940 completion_index: usize,
17941 push_to_history: bool,
17942 cx: &mut Context<Editor>,
17943 ) -> Task<Result<Option<language::Transaction>>> {
17944 self.update(cx, |project, cx| {
17945 project.lsp_store().update(cx, |lsp_store, cx| {
17946 lsp_store.apply_additional_edits_for_completion(
17947 buffer,
17948 completions,
17949 completion_index,
17950 push_to_history,
17951 cx,
17952 )
17953 })
17954 })
17955 }
17956
17957 fn is_completion_trigger(
17958 &self,
17959 buffer: &Entity<Buffer>,
17960 position: language::Anchor,
17961 text: &str,
17962 trigger_in_words: bool,
17963 cx: &mut Context<Editor>,
17964 ) -> bool {
17965 let mut chars = text.chars();
17966 let char = if let Some(char) = chars.next() {
17967 char
17968 } else {
17969 return false;
17970 };
17971 if chars.next().is_some() {
17972 return false;
17973 }
17974
17975 let buffer = buffer.read(cx);
17976 let snapshot = buffer.snapshot();
17977 if !snapshot.settings_at(position, cx).show_completions_on_input {
17978 return false;
17979 }
17980 let classifier = snapshot.char_classifier_at(position).for_completion(true);
17981 if trigger_in_words && classifier.is_word(char) {
17982 return true;
17983 }
17984
17985 buffer.completion_triggers().contains(text)
17986 }
17987}
17988
17989impl SemanticsProvider for Entity<Project> {
17990 fn hover(
17991 &self,
17992 buffer: &Entity<Buffer>,
17993 position: text::Anchor,
17994 cx: &mut App,
17995 ) -> Option<Task<Vec<project::Hover>>> {
17996 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
17997 }
17998
17999 fn document_highlights(
18000 &self,
18001 buffer: &Entity<Buffer>,
18002 position: text::Anchor,
18003 cx: &mut App,
18004 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
18005 Some(self.update(cx, |project, cx| {
18006 project.document_highlights(buffer, position, cx)
18007 }))
18008 }
18009
18010 fn definitions(
18011 &self,
18012 buffer: &Entity<Buffer>,
18013 position: text::Anchor,
18014 kind: GotoDefinitionKind,
18015 cx: &mut App,
18016 ) -> Option<Task<Result<Vec<LocationLink>>>> {
18017 Some(self.update(cx, |project, cx| match kind {
18018 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
18019 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
18020 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
18021 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
18022 }))
18023 }
18024
18025 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
18026 // TODO: make this work for remote projects
18027 self.update(cx, |this, cx| {
18028 buffer.update(cx, |buffer, cx| {
18029 this.any_language_server_supports_inlay_hints(buffer, cx)
18030 })
18031 })
18032 }
18033
18034 fn inlay_hints(
18035 &self,
18036 buffer_handle: Entity<Buffer>,
18037 range: Range<text::Anchor>,
18038 cx: &mut App,
18039 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
18040 Some(self.update(cx, |project, cx| {
18041 project.inlay_hints(buffer_handle, range, cx)
18042 }))
18043 }
18044
18045 fn resolve_inlay_hint(
18046 &self,
18047 hint: InlayHint,
18048 buffer_handle: Entity<Buffer>,
18049 server_id: LanguageServerId,
18050 cx: &mut App,
18051 ) -> Option<Task<anyhow::Result<InlayHint>>> {
18052 Some(self.update(cx, |project, cx| {
18053 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
18054 }))
18055 }
18056
18057 fn range_for_rename(
18058 &self,
18059 buffer: &Entity<Buffer>,
18060 position: text::Anchor,
18061 cx: &mut App,
18062 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
18063 Some(self.update(cx, |project, cx| {
18064 let buffer = buffer.clone();
18065 let task = project.prepare_rename(buffer.clone(), position, cx);
18066 cx.spawn(async move |_, cx| {
18067 Ok(match task.await? {
18068 PrepareRenameResponse::Success(range) => Some(range),
18069 PrepareRenameResponse::InvalidPosition => None,
18070 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
18071 // Fallback on using TreeSitter info to determine identifier range
18072 buffer.update(cx, |buffer, _| {
18073 let snapshot = buffer.snapshot();
18074 let (range, kind) = snapshot.surrounding_word(position);
18075 if kind != Some(CharKind::Word) {
18076 return None;
18077 }
18078 Some(
18079 snapshot.anchor_before(range.start)
18080 ..snapshot.anchor_after(range.end),
18081 )
18082 })?
18083 }
18084 })
18085 })
18086 }))
18087 }
18088
18089 fn perform_rename(
18090 &self,
18091 buffer: &Entity<Buffer>,
18092 position: text::Anchor,
18093 new_name: String,
18094 cx: &mut App,
18095 ) -> Option<Task<Result<ProjectTransaction>>> {
18096 Some(self.update(cx, |project, cx| {
18097 project.perform_rename(buffer.clone(), position, new_name, cx)
18098 }))
18099 }
18100}
18101
18102fn inlay_hint_settings(
18103 location: Anchor,
18104 snapshot: &MultiBufferSnapshot,
18105 cx: &mut Context<Editor>,
18106) -> InlayHintSettings {
18107 let file = snapshot.file_at(location);
18108 let language = snapshot.language_at(location).map(|l| l.name());
18109 language_settings(language, file, cx).inlay_hints
18110}
18111
18112fn consume_contiguous_rows(
18113 contiguous_row_selections: &mut Vec<Selection<Point>>,
18114 selection: &Selection<Point>,
18115 display_map: &DisplaySnapshot,
18116 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
18117) -> (MultiBufferRow, MultiBufferRow) {
18118 contiguous_row_selections.push(selection.clone());
18119 let start_row = MultiBufferRow(selection.start.row);
18120 let mut end_row = ending_row(selection, display_map);
18121
18122 while let Some(next_selection) = selections.peek() {
18123 if next_selection.start.row <= end_row.0 {
18124 end_row = ending_row(next_selection, display_map);
18125 contiguous_row_selections.push(selections.next().unwrap().clone());
18126 } else {
18127 break;
18128 }
18129 }
18130 (start_row, end_row)
18131}
18132
18133fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
18134 if next_selection.end.column > 0 || next_selection.is_empty() {
18135 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
18136 } else {
18137 MultiBufferRow(next_selection.end.row)
18138 }
18139}
18140
18141impl EditorSnapshot {
18142 pub fn remote_selections_in_range<'a>(
18143 &'a self,
18144 range: &'a Range<Anchor>,
18145 collaboration_hub: &dyn CollaborationHub,
18146 cx: &'a App,
18147 ) -> impl 'a + Iterator<Item = RemoteSelection> {
18148 let participant_names = collaboration_hub.user_names(cx);
18149 let participant_indices = collaboration_hub.user_participant_indices(cx);
18150 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
18151 let collaborators_by_replica_id = collaborators_by_peer_id
18152 .iter()
18153 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
18154 .collect::<HashMap<_, _>>();
18155 self.buffer_snapshot
18156 .selections_in_range(range, false)
18157 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
18158 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
18159 let participant_index = participant_indices.get(&collaborator.user_id).copied();
18160 let user_name = participant_names.get(&collaborator.user_id).cloned();
18161 Some(RemoteSelection {
18162 replica_id,
18163 selection,
18164 cursor_shape,
18165 line_mode,
18166 participant_index,
18167 peer_id: collaborator.peer_id,
18168 user_name,
18169 })
18170 })
18171 }
18172
18173 pub fn hunks_for_ranges(
18174 &self,
18175 ranges: impl IntoIterator<Item = Range<Point>>,
18176 ) -> Vec<MultiBufferDiffHunk> {
18177 let mut hunks = Vec::new();
18178 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
18179 HashMap::default();
18180 for query_range in ranges {
18181 let query_rows =
18182 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
18183 for hunk in self.buffer_snapshot.diff_hunks_in_range(
18184 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
18185 ) {
18186 // Include deleted hunks that are adjacent to the query range, because
18187 // otherwise they would be missed.
18188 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
18189 if hunk.status().is_deleted() {
18190 intersects_range |= hunk.row_range.start == query_rows.end;
18191 intersects_range |= hunk.row_range.end == query_rows.start;
18192 }
18193 if intersects_range {
18194 if !processed_buffer_rows
18195 .entry(hunk.buffer_id)
18196 .or_default()
18197 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
18198 {
18199 continue;
18200 }
18201 hunks.push(hunk);
18202 }
18203 }
18204 }
18205
18206 hunks
18207 }
18208
18209 fn display_diff_hunks_for_rows<'a>(
18210 &'a self,
18211 display_rows: Range<DisplayRow>,
18212 folded_buffers: &'a HashSet<BufferId>,
18213 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
18214 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
18215 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
18216
18217 self.buffer_snapshot
18218 .diff_hunks_in_range(buffer_start..buffer_end)
18219 .filter_map(|hunk| {
18220 if folded_buffers.contains(&hunk.buffer_id) {
18221 return None;
18222 }
18223
18224 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
18225 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
18226
18227 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
18228 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
18229
18230 let display_hunk = if hunk_display_start.column() != 0 {
18231 DisplayDiffHunk::Folded {
18232 display_row: hunk_display_start.row(),
18233 }
18234 } else {
18235 let mut end_row = hunk_display_end.row();
18236 if hunk_display_end.column() > 0 {
18237 end_row.0 += 1;
18238 }
18239 let is_created_file = hunk.is_created_file();
18240 DisplayDiffHunk::Unfolded {
18241 status: hunk.status(),
18242 diff_base_byte_range: hunk.diff_base_byte_range,
18243 display_row_range: hunk_display_start.row()..end_row,
18244 multi_buffer_range: Anchor::range_in_buffer(
18245 hunk.excerpt_id,
18246 hunk.buffer_id,
18247 hunk.buffer_range,
18248 ),
18249 is_created_file,
18250 }
18251 };
18252
18253 Some(display_hunk)
18254 })
18255 }
18256
18257 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
18258 self.display_snapshot.buffer_snapshot.language_at(position)
18259 }
18260
18261 pub fn is_focused(&self) -> bool {
18262 self.is_focused
18263 }
18264
18265 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
18266 self.placeholder_text.as_ref()
18267 }
18268
18269 pub fn scroll_position(&self) -> gpui::Point<f32> {
18270 self.scroll_anchor.scroll_position(&self.display_snapshot)
18271 }
18272
18273 fn gutter_dimensions(
18274 &self,
18275 font_id: FontId,
18276 font_size: Pixels,
18277 max_line_number_width: Pixels,
18278 cx: &App,
18279 ) -> Option<GutterDimensions> {
18280 if !self.show_gutter {
18281 return None;
18282 }
18283
18284 let descent = cx.text_system().descent(font_id, font_size);
18285 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
18286 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
18287
18288 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
18289 matches!(
18290 ProjectSettings::get_global(cx).git.git_gutter,
18291 Some(GitGutterSetting::TrackedFiles)
18292 )
18293 });
18294 let gutter_settings = EditorSettings::get_global(cx).gutter;
18295 let show_line_numbers = self
18296 .show_line_numbers
18297 .unwrap_or(gutter_settings.line_numbers);
18298 let line_gutter_width = if show_line_numbers {
18299 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
18300 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
18301 max_line_number_width.max(min_width_for_number_on_gutter)
18302 } else {
18303 0.0.into()
18304 };
18305
18306 let show_code_actions = self
18307 .show_code_actions
18308 .unwrap_or(gutter_settings.code_actions);
18309
18310 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
18311 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
18312
18313 let git_blame_entries_width =
18314 self.git_blame_gutter_max_author_length
18315 .map(|max_author_length| {
18316 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
18317
18318 /// The number of characters to dedicate to gaps and margins.
18319 const SPACING_WIDTH: usize = 4;
18320
18321 let max_char_count = max_author_length
18322 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
18323 + ::git::SHORT_SHA_LENGTH
18324 + MAX_RELATIVE_TIMESTAMP.len()
18325 + SPACING_WIDTH;
18326
18327 em_advance * max_char_count
18328 });
18329
18330 let is_singleton = self.buffer_snapshot.is_singleton();
18331
18332 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
18333 left_padding += if !is_singleton {
18334 em_width * 4.0
18335 } else if show_code_actions || show_runnables || show_breakpoints {
18336 em_width * 3.0
18337 } else if show_git_gutter && show_line_numbers {
18338 em_width * 2.0
18339 } else if show_git_gutter || show_line_numbers {
18340 em_width
18341 } else {
18342 px(0.)
18343 };
18344
18345 let shows_folds = is_singleton && gutter_settings.folds;
18346
18347 let right_padding = if shows_folds && show_line_numbers {
18348 em_width * 4.0
18349 } else if shows_folds || (!is_singleton && show_line_numbers) {
18350 em_width * 3.0
18351 } else if show_line_numbers {
18352 em_width
18353 } else {
18354 px(0.)
18355 };
18356
18357 Some(GutterDimensions {
18358 left_padding,
18359 right_padding,
18360 width: line_gutter_width + left_padding + right_padding,
18361 margin: -descent,
18362 git_blame_entries_width,
18363 })
18364 }
18365
18366 pub fn render_crease_toggle(
18367 &self,
18368 buffer_row: MultiBufferRow,
18369 row_contains_cursor: bool,
18370 editor: Entity<Editor>,
18371 window: &mut Window,
18372 cx: &mut App,
18373 ) -> Option<AnyElement> {
18374 let folded = self.is_line_folded(buffer_row);
18375 let mut is_foldable = false;
18376
18377 if let Some(crease) = self
18378 .crease_snapshot
18379 .query_row(buffer_row, &self.buffer_snapshot)
18380 {
18381 is_foldable = true;
18382 match crease {
18383 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
18384 if let Some(render_toggle) = render_toggle {
18385 let toggle_callback =
18386 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
18387 if folded {
18388 editor.update(cx, |editor, cx| {
18389 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
18390 });
18391 } else {
18392 editor.update(cx, |editor, cx| {
18393 editor.unfold_at(
18394 &crate::UnfoldAt { buffer_row },
18395 window,
18396 cx,
18397 )
18398 });
18399 }
18400 });
18401 return Some((render_toggle)(
18402 buffer_row,
18403 folded,
18404 toggle_callback,
18405 window,
18406 cx,
18407 ));
18408 }
18409 }
18410 }
18411 }
18412
18413 is_foldable |= self.starts_indent(buffer_row);
18414
18415 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
18416 Some(
18417 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
18418 .toggle_state(folded)
18419 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
18420 if folded {
18421 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
18422 } else {
18423 this.fold_at(&FoldAt { buffer_row }, window, cx);
18424 }
18425 }))
18426 .into_any_element(),
18427 )
18428 } else {
18429 None
18430 }
18431 }
18432
18433 pub fn render_crease_trailer(
18434 &self,
18435 buffer_row: MultiBufferRow,
18436 window: &mut Window,
18437 cx: &mut App,
18438 ) -> Option<AnyElement> {
18439 let folded = self.is_line_folded(buffer_row);
18440 if let Crease::Inline { render_trailer, .. } = self
18441 .crease_snapshot
18442 .query_row(buffer_row, &self.buffer_snapshot)?
18443 {
18444 let render_trailer = render_trailer.as_ref()?;
18445 Some(render_trailer(buffer_row, folded, window, cx))
18446 } else {
18447 None
18448 }
18449 }
18450}
18451
18452impl Deref for EditorSnapshot {
18453 type Target = DisplaySnapshot;
18454
18455 fn deref(&self) -> &Self::Target {
18456 &self.display_snapshot
18457 }
18458}
18459
18460#[derive(Clone, Debug, PartialEq, Eq)]
18461pub enum EditorEvent {
18462 InputIgnored {
18463 text: Arc<str>,
18464 },
18465 InputHandled {
18466 utf16_range_to_replace: Option<Range<isize>>,
18467 text: Arc<str>,
18468 },
18469 ExcerptsAdded {
18470 buffer: Entity<Buffer>,
18471 predecessor: ExcerptId,
18472 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
18473 },
18474 ExcerptsRemoved {
18475 ids: Vec<ExcerptId>,
18476 },
18477 BufferFoldToggled {
18478 ids: Vec<ExcerptId>,
18479 folded: bool,
18480 },
18481 ExcerptsEdited {
18482 ids: Vec<ExcerptId>,
18483 },
18484 ExcerptsExpanded {
18485 ids: Vec<ExcerptId>,
18486 },
18487 BufferEdited,
18488 Edited {
18489 transaction_id: clock::Lamport,
18490 },
18491 Reparsed(BufferId),
18492 Focused,
18493 FocusedIn,
18494 Blurred,
18495 DirtyChanged,
18496 Saved,
18497 TitleChanged,
18498 DiffBaseChanged,
18499 SelectionsChanged {
18500 local: bool,
18501 },
18502 ScrollPositionChanged {
18503 local: bool,
18504 autoscroll: bool,
18505 },
18506 Closed,
18507 TransactionUndone {
18508 transaction_id: clock::Lamport,
18509 },
18510 TransactionBegun {
18511 transaction_id: clock::Lamport,
18512 },
18513 Reloaded,
18514 CursorShapeChanged,
18515}
18516
18517impl EventEmitter<EditorEvent> for Editor {}
18518
18519impl Focusable for Editor {
18520 fn focus_handle(&self, _cx: &App) -> FocusHandle {
18521 self.focus_handle.clone()
18522 }
18523}
18524
18525impl Render for Editor {
18526 fn render(&mut self, _: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
18527 let settings = ThemeSettings::get_global(cx);
18528
18529 let mut text_style = match self.mode {
18530 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
18531 color: cx.theme().colors().editor_foreground,
18532 font_family: settings.ui_font.family.clone(),
18533 font_features: settings.ui_font.features.clone(),
18534 font_fallbacks: settings.ui_font.fallbacks.clone(),
18535 font_size: rems(0.875).into(),
18536 font_weight: settings.ui_font.weight,
18537 line_height: relative(settings.buffer_line_height.value()),
18538 ..Default::default()
18539 },
18540 EditorMode::Full => TextStyle {
18541 color: cx.theme().colors().editor_foreground,
18542 font_family: settings.buffer_font.family.clone(),
18543 font_features: settings.buffer_font.features.clone(),
18544 font_fallbacks: settings.buffer_font.fallbacks.clone(),
18545 font_size: settings.buffer_font_size(cx).into(),
18546 font_weight: settings.buffer_font.weight,
18547 line_height: relative(settings.buffer_line_height.value()),
18548 ..Default::default()
18549 },
18550 };
18551 if let Some(text_style_refinement) = &self.text_style_refinement {
18552 text_style.refine(text_style_refinement)
18553 }
18554
18555 let background = match self.mode {
18556 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
18557 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
18558 EditorMode::Full => cx.theme().colors().editor_background,
18559 };
18560
18561 EditorElement::new(
18562 &cx.entity(),
18563 EditorStyle {
18564 background,
18565 local_player: cx.theme().players().local(),
18566 text: text_style,
18567 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
18568 syntax: cx.theme().syntax().clone(),
18569 status: cx.theme().status().clone(),
18570 inlay_hints_style: make_inlay_hints_style(cx),
18571 inline_completion_styles: make_suggestion_styles(cx),
18572 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
18573 },
18574 )
18575 }
18576}
18577
18578impl EntityInputHandler for Editor {
18579 fn text_for_range(
18580 &mut self,
18581 range_utf16: Range<usize>,
18582 adjusted_range: &mut Option<Range<usize>>,
18583 _: &mut Window,
18584 cx: &mut Context<Self>,
18585 ) -> Option<String> {
18586 let snapshot = self.buffer.read(cx).read(cx);
18587 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
18588 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
18589 if (start.0..end.0) != range_utf16 {
18590 adjusted_range.replace(start.0..end.0);
18591 }
18592 Some(snapshot.text_for_range(start..end).collect())
18593 }
18594
18595 fn selected_text_range(
18596 &mut self,
18597 ignore_disabled_input: bool,
18598 _: &mut Window,
18599 cx: &mut Context<Self>,
18600 ) -> Option<UTF16Selection> {
18601 // Prevent the IME menu from appearing when holding down an alphabetic key
18602 // while input is disabled.
18603 if !ignore_disabled_input && !self.input_enabled {
18604 return None;
18605 }
18606
18607 let selection = self.selections.newest::<OffsetUtf16>(cx);
18608 let range = selection.range();
18609
18610 Some(UTF16Selection {
18611 range: range.start.0..range.end.0,
18612 reversed: selection.reversed,
18613 })
18614 }
18615
18616 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
18617 let snapshot = self.buffer.read(cx).read(cx);
18618 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
18619 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
18620 }
18621
18622 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18623 self.clear_highlights::<InputComposition>(cx);
18624 self.ime_transaction.take();
18625 }
18626
18627 fn replace_text_in_range(
18628 &mut self,
18629 range_utf16: Option<Range<usize>>,
18630 text: &str,
18631 window: &mut Window,
18632 cx: &mut Context<Self>,
18633 ) {
18634 if !self.input_enabled {
18635 cx.emit(EditorEvent::InputIgnored { text: text.into() });
18636 return;
18637 }
18638
18639 self.transact(window, cx, |this, window, cx| {
18640 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
18641 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18642 Some(this.selection_replacement_ranges(range_utf16, cx))
18643 } else {
18644 this.marked_text_ranges(cx)
18645 };
18646
18647 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
18648 let newest_selection_id = this.selections.newest_anchor().id;
18649 this.selections
18650 .all::<OffsetUtf16>(cx)
18651 .iter()
18652 .zip(ranges_to_replace.iter())
18653 .find_map(|(selection, range)| {
18654 if selection.id == newest_selection_id {
18655 Some(
18656 (range.start.0 as isize - selection.head().0 as isize)
18657 ..(range.end.0 as isize - selection.head().0 as isize),
18658 )
18659 } else {
18660 None
18661 }
18662 })
18663 });
18664
18665 cx.emit(EditorEvent::InputHandled {
18666 utf16_range_to_replace: range_to_replace,
18667 text: text.into(),
18668 });
18669
18670 if let Some(new_selected_ranges) = new_selected_ranges {
18671 this.change_selections(None, window, cx, |selections| {
18672 selections.select_ranges(new_selected_ranges)
18673 });
18674 this.backspace(&Default::default(), window, cx);
18675 }
18676
18677 this.handle_input(text, window, cx);
18678 });
18679
18680 if let Some(transaction) = self.ime_transaction {
18681 self.buffer.update(cx, |buffer, cx| {
18682 buffer.group_until_transaction(transaction, cx);
18683 });
18684 }
18685
18686 self.unmark_text(window, cx);
18687 }
18688
18689 fn replace_and_mark_text_in_range(
18690 &mut self,
18691 range_utf16: Option<Range<usize>>,
18692 text: &str,
18693 new_selected_range_utf16: Option<Range<usize>>,
18694 window: &mut Window,
18695 cx: &mut Context<Self>,
18696 ) {
18697 if !self.input_enabled {
18698 return;
18699 }
18700
18701 let transaction = self.transact(window, cx, |this, window, cx| {
18702 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
18703 let snapshot = this.buffer.read(cx).read(cx);
18704 if let Some(relative_range_utf16) = range_utf16.as_ref() {
18705 for marked_range in &mut marked_ranges {
18706 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
18707 marked_range.start.0 += relative_range_utf16.start;
18708 marked_range.start =
18709 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
18710 marked_range.end =
18711 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
18712 }
18713 }
18714 Some(marked_ranges)
18715 } else if let Some(range_utf16) = range_utf16 {
18716 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
18717 Some(this.selection_replacement_ranges(range_utf16, cx))
18718 } else {
18719 None
18720 };
18721
18722 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
18723 let newest_selection_id = this.selections.newest_anchor().id;
18724 this.selections
18725 .all::<OffsetUtf16>(cx)
18726 .iter()
18727 .zip(ranges_to_replace.iter())
18728 .find_map(|(selection, range)| {
18729 if selection.id == newest_selection_id {
18730 Some(
18731 (range.start.0 as isize - selection.head().0 as isize)
18732 ..(range.end.0 as isize - selection.head().0 as isize),
18733 )
18734 } else {
18735 None
18736 }
18737 })
18738 });
18739
18740 cx.emit(EditorEvent::InputHandled {
18741 utf16_range_to_replace: range_to_replace,
18742 text: text.into(),
18743 });
18744
18745 if let Some(ranges) = ranges_to_replace {
18746 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
18747 }
18748
18749 let marked_ranges = {
18750 let snapshot = this.buffer.read(cx).read(cx);
18751 this.selections
18752 .disjoint_anchors()
18753 .iter()
18754 .map(|selection| {
18755 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
18756 })
18757 .collect::<Vec<_>>()
18758 };
18759
18760 if text.is_empty() {
18761 this.unmark_text(window, cx);
18762 } else {
18763 this.highlight_text::<InputComposition>(
18764 marked_ranges.clone(),
18765 HighlightStyle {
18766 underline: Some(UnderlineStyle {
18767 thickness: px(1.),
18768 color: None,
18769 wavy: false,
18770 }),
18771 ..Default::default()
18772 },
18773 cx,
18774 );
18775 }
18776
18777 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
18778 let use_autoclose = this.use_autoclose;
18779 let use_auto_surround = this.use_auto_surround;
18780 this.set_use_autoclose(false);
18781 this.set_use_auto_surround(false);
18782 this.handle_input(text, window, cx);
18783 this.set_use_autoclose(use_autoclose);
18784 this.set_use_auto_surround(use_auto_surround);
18785
18786 if let Some(new_selected_range) = new_selected_range_utf16 {
18787 let snapshot = this.buffer.read(cx).read(cx);
18788 let new_selected_ranges = marked_ranges
18789 .into_iter()
18790 .map(|marked_range| {
18791 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
18792 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
18793 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
18794 snapshot.clip_offset_utf16(new_start, Bias::Left)
18795 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
18796 })
18797 .collect::<Vec<_>>();
18798
18799 drop(snapshot);
18800 this.change_selections(None, window, cx, |selections| {
18801 selections.select_ranges(new_selected_ranges)
18802 });
18803 }
18804 });
18805
18806 self.ime_transaction = self.ime_transaction.or(transaction);
18807 if let Some(transaction) = self.ime_transaction {
18808 self.buffer.update(cx, |buffer, cx| {
18809 buffer.group_until_transaction(transaction, cx);
18810 });
18811 }
18812
18813 if self.text_highlights::<InputComposition>(cx).is_none() {
18814 self.ime_transaction.take();
18815 }
18816 }
18817
18818 fn bounds_for_range(
18819 &mut self,
18820 range_utf16: Range<usize>,
18821 element_bounds: gpui::Bounds<Pixels>,
18822 window: &mut Window,
18823 cx: &mut Context<Self>,
18824 ) -> Option<gpui::Bounds<Pixels>> {
18825 let text_layout_details = self.text_layout_details(window);
18826 let gpui::Size {
18827 width: em_width,
18828 height: line_height,
18829 } = self.character_size(window);
18830
18831 let snapshot = self.snapshot(window, cx);
18832 let scroll_position = snapshot.scroll_position();
18833 let scroll_left = scroll_position.x * em_width;
18834
18835 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
18836 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
18837 + self.gutter_dimensions.width
18838 + self.gutter_dimensions.margin;
18839 let y = line_height * (start.row().as_f32() - scroll_position.y);
18840
18841 Some(Bounds {
18842 origin: element_bounds.origin + point(x, y),
18843 size: size(em_width, line_height),
18844 })
18845 }
18846
18847 fn character_index_for_point(
18848 &mut self,
18849 point: gpui::Point<Pixels>,
18850 _window: &mut Window,
18851 _cx: &mut Context<Self>,
18852 ) -> Option<usize> {
18853 let position_map = self.last_position_map.as_ref()?;
18854 if !position_map.text_hitbox.contains(&point) {
18855 return None;
18856 }
18857 let display_point = position_map.point_for_position(point).previous_valid;
18858 let anchor = position_map
18859 .snapshot
18860 .display_point_to_anchor(display_point, Bias::Left);
18861 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
18862 Some(utf16_offset.0)
18863 }
18864}
18865
18866trait SelectionExt {
18867 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
18868 fn spanned_rows(
18869 &self,
18870 include_end_if_at_line_start: bool,
18871 map: &DisplaySnapshot,
18872 ) -> Range<MultiBufferRow>;
18873}
18874
18875impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
18876 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
18877 let start = self
18878 .start
18879 .to_point(&map.buffer_snapshot)
18880 .to_display_point(map);
18881 let end = self
18882 .end
18883 .to_point(&map.buffer_snapshot)
18884 .to_display_point(map);
18885 if self.reversed {
18886 end..start
18887 } else {
18888 start..end
18889 }
18890 }
18891
18892 fn spanned_rows(
18893 &self,
18894 include_end_if_at_line_start: bool,
18895 map: &DisplaySnapshot,
18896 ) -> Range<MultiBufferRow> {
18897 let start = self.start.to_point(&map.buffer_snapshot);
18898 let mut end = self.end.to_point(&map.buffer_snapshot);
18899 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
18900 end.row -= 1;
18901 }
18902
18903 let buffer_start = map.prev_line_boundary(start).0;
18904 let buffer_end = map.next_line_boundary(end).0;
18905 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
18906 }
18907}
18908
18909impl<T: InvalidationRegion> InvalidationStack<T> {
18910 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
18911 where
18912 S: Clone + ToOffset,
18913 {
18914 while let Some(region) = self.last() {
18915 let all_selections_inside_invalidation_ranges =
18916 if selections.len() == region.ranges().len() {
18917 selections
18918 .iter()
18919 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
18920 .all(|(selection, invalidation_range)| {
18921 let head = selection.head().to_offset(buffer);
18922 invalidation_range.start <= head && invalidation_range.end >= head
18923 })
18924 } else {
18925 false
18926 };
18927
18928 if all_selections_inside_invalidation_ranges {
18929 break;
18930 } else {
18931 self.pop();
18932 }
18933 }
18934 }
18935}
18936
18937impl<T> Default for InvalidationStack<T> {
18938 fn default() -> Self {
18939 Self(Default::default())
18940 }
18941}
18942
18943impl<T> Deref for InvalidationStack<T> {
18944 type Target = Vec<T>;
18945
18946 fn deref(&self) -> &Self::Target {
18947 &self.0
18948 }
18949}
18950
18951impl<T> DerefMut for InvalidationStack<T> {
18952 fn deref_mut(&mut self) -> &mut Self::Target {
18953 &mut self.0
18954 }
18955}
18956
18957impl InvalidationRegion for SnippetState {
18958 fn ranges(&self) -> &[Range<Anchor>] {
18959 &self.ranges[self.active_index]
18960 }
18961}
18962
18963pub fn diagnostic_block_renderer(
18964 diagnostic: Diagnostic,
18965 max_message_rows: Option<u8>,
18966 allow_closing: bool,
18967) -> RenderBlock {
18968 let (text_without_backticks, code_ranges) =
18969 highlight_diagnostic_message(&diagnostic, max_message_rows);
18970
18971 Arc::new(move |cx: &mut BlockContext| {
18972 let group_id: SharedString = cx.block_id.to_string().into();
18973
18974 let mut text_style = cx.window.text_style().clone();
18975 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
18976 let theme_settings = ThemeSettings::get_global(cx);
18977 text_style.font_family = theme_settings.buffer_font.family.clone();
18978 text_style.font_style = theme_settings.buffer_font.style;
18979 text_style.font_features = theme_settings.buffer_font.features.clone();
18980 text_style.font_weight = theme_settings.buffer_font.weight;
18981
18982 let multi_line_diagnostic = diagnostic.message.contains('\n');
18983
18984 let buttons = |diagnostic: &Diagnostic| {
18985 if multi_line_diagnostic {
18986 v_flex()
18987 } else {
18988 h_flex()
18989 }
18990 .when(allow_closing, |div| {
18991 div.children(diagnostic.is_primary.then(|| {
18992 IconButton::new("close-block", IconName::XCircle)
18993 .icon_color(Color::Muted)
18994 .size(ButtonSize::Compact)
18995 .style(ButtonStyle::Transparent)
18996 .visible_on_hover(group_id.clone())
18997 .on_click(move |_click, window, cx| {
18998 window.dispatch_action(Box::new(Cancel), cx)
18999 })
19000 .tooltip(|window, cx| {
19001 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
19002 })
19003 }))
19004 })
19005 .child(
19006 IconButton::new("copy-block", IconName::Copy)
19007 .icon_color(Color::Muted)
19008 .size(ButtonSize::Compact)
19009 .style(ButtonStyle::Transparent)
19010 .visible_on_hover(group_id.clone())
19011 .on_click({
19012 let message = diagnostic.message.clone();
19013 move |_click, _, cx| {
19014 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
19015 }
19016 })
19017 .tooltip(Tooltip::text("Copy diagnostic message")),
19018 )
19019 };
19020
19021 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
19022 AvailableSpace::min_size(),
19023 cx.window,
19024 cx.app,
19025 );
19026
19027 h_flex()
19028 .id(cx.block_id)
19029 .group(group_id.clone())
19030 .relative()
19031 .size_full()
19032 .block_mouse_down()
19033 .pl(cx.gutter_dimensions.width)
19034 .w(cx.max_width - cx.gutter_dimensions.full_width())
19035 .child(
19036 div()
19037 .flex()
19038 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
19039 .flex_shrink(),
19040 )
19041 .child(buttons(&diagnostic))
19042 .child(div().flex().flex_shrink_0().child(
19043 StyledText::new(text_without_backticks.clone()).with_default_highlights(
19044 &text_style,
19045 code_ranges.iter().map(|range| {
19046 (
19047 range.clone(),
19048 HighlightStyle {
19049 font_weight: Some(FontWeight::BOLD),
19050 ..Default::default()
19051 },
19052 )
19053 }),
19054 ),
19055 ))
19056 .into_any_element()
19057 })
19058}
19059
19060fn inline_completion_edit_text(
19061 current_snapshot: &BufferSnapshot,
19062 edits: &[(Range<Anchor>, String)],
19063 edit_preview: &EditPreview,
19064 include_deletions: bool,
19065 cx: &App,
19066) -> HighlightedText {
19067 let edits = edits
19068 .iter()
19069 .map(|(anchor, text)| {
19070 (
19071 anchor.start.text_anchor..anchor.end.text_anchor,
19072 text.clone(),
19073 )
19074 })
19075 .collect::<Vec<_>>();
19076
19077 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
19078}
19079
19080pub fn highlight_diagnostic_message(
19081 diagnostic: &Diagnostic,
19082 mut max_message_rows: Option<u8>,
19083) -> (SharedString, Vec<Range<usize>>) {
19084 let mut text_without_backticks = String::new();
19085 let mut code_ranges = Vec::new();
19086
19087 if let Some(source) = &diagnostic.source {
19088 text_without_backticks.push_str(source);
19089 code_ranges.push(0..source.len());
19090 text_without_backticks.push_str(": ");
19091 }
19092
19093 let mut prev_offset = 0;
19094 let mut in_code_block = false;
19095 let has_row_limit = max_message_rows.is_some();
19096 let mut newline_indices = diagnostic
19097 .message
19098 .match_indices('\n')
19099 .filter(|_| has_row_limit)
19100 .map(|(ix, _)| ix)
19101 .fuse()
19102 .peekable();
19103
19104 for (quote_ix, _) in diagnostic
19105 .message
19106 .match_indices('`')
19107 .chain([(diagnostic.message.len(), "")])
19108 {
19109 let mut first_newline_ix = None;
19110 let mut last_newline_ix = None;
19111 while let Some(newline_ix) = newline_indices.peek() {
19112 if *newline_ix < quote_ix {
19113 if first_newline_ix.is_none() {
19114 first_newline_ix = Some(*newline_ix);
19115 }
19116 last_newline_ix = Some(*newline_ix);
19117
19118 if let Some(rows_left) = &mut max_message_rows {
19119 if *rows_left == 0 {
19120 break;
19121 } else {
19122 *rows_left -= 1;
19123 }
19124 }
19125 let _ = newline_indices.next();
19126 } else {
19127 break;
19128 }
19129 }
19130 let prev_len = text_without_backticks.len();
19131 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
19132 text_without_backticks.push_str(new_text);
19133 if in_code_block {
19134 code_ranges.push(prev_len..text_without_backticks.len());
19135 }
19136 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
19137 in_code_block = !in_code_block;
19138 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
19139 text_without_backticks.push_str("...");
19140 break;
19141 }
19142 }
19143
19144 (text_without_backticks.into(), code_ranges)
19145}
19146
19147fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
19148 match severity {
19149 DiagnosticSeverity::ERROR => colors.error,
19150 DiagnosticSeverity::WARNING => colors.warning,
19151 DiagnosticSeverity::INFORMATION => colors.info,
19152 DiagnosticSeverity::HINT => colors.info,
19153 _ => colors.ignored,
19154 }
19155}
19156
19157pub fn styled_runs_for_code_label<'a>(
19158 label: &'a CodeLabel,
19159 syntax_theme: &'a theme::SyntaxTheme,
19160) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
19161 let fade_out = HighlightStyle {
19162 fade_out: Some(0.35),
19163 ..Default::default()
19164 };
19165
19166 let mut prev_end = label.filter_range.end;
19167 label
19168 .runs
19169 .iter()
19170 .enumerate()
19171 .flat_map(move |(ix, (range, highlight_id))| {
19172 let style = if let Some(style) = highlight_id.style(syntax_theme) {
19173 style
19174 } else {
19175 return Default::default();
19176 };
19177 let mut muted_style = style;
19178 muted_style.highlight(fade_out);
19179
19180 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
19181 if range.start >= label.filter_range.end {
19182 if range.start > prev_end {
19183 runs.push((prev_end..range.start, fade_out));
19184 }
19185 runs.push((range.clone(), muted_style));
19186 } else if range.end <= label.filter_range.end {
19187 runs.push((range.clone(), style));
19188 } else {
19189 runs.push((range.start..label.filter_range.end, style));
19190 runs.push((label.filter_range.end..range.end, muted_style));
19191 }
19192 prev_end = cmp::max(prev_end, range.end);
19193
19194 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
19195 runs.push((prev_end..label.text.len(), fade_out));
19196 }
19197
19198 runs
19199 })
19200}
19201
19202pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
19203 let mut prev_index = 0;
19204 let mut prev_codepoint: Option<char> = None;
19205 text.char_indices()
19206 .chain([(text.len(), '\0')])
19207 .filter_map(move |(index, codepoint)| {
19208 let prev_codepoint = prev_codepoint.replace(codepoint)?;
19209 let is_boundary = index == text.len()
19210 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
19211 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
19212 if is_boundary {
19213 let chunk = &text[prev_index..index];
19214 prev_index = index;
19215 Some(chunk)
19216 } else {
19217 None
19218 }
19219 })
19220}
19221
19222pub trait RangeToAnchorExt: Sized {
19223 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
19224
19225 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
19226 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
19227 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
19228 }
19229}
19230
19231impl<T: ToOffset> RangeToAnchorExt for Range<T> {
19232 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
19233 let start_offset = self.start.to_offset(snapshot);
19234 let end_offset = self.end.to_offset(snapshot);
19235 if start_offset == end_offset {
19236 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
19237 } else {
19238 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
19239 }
19240 }
19241}
19242
19243pub trait RowExt {
19244 fn as_f32(&self) -> f32;
19245
19246 fn next_row(&self) -> Self;
19247
19248 fn previous_row(&self) -> Self;
19249
19250 fn minus(&self, other: Self) -> u32;
19251}
19252
19253impl RowExt for DisplayRow {
19254 fn as_f32(&self) -> f32 {
19255 self.0 as f32
19256 }
19257
19258 fn next_row(&self) -> Self {
19259 Self(self.0 + 1)
19260 }
19261
19262 fn previous_row(&self) -> Self {
19263 Self(self.0.saturating_sub(1))
19264 }
19265
19266 fn minus(&self, other: Self) -> u32 {
19267 self.0 - other.0
19268 }
19269}
19270
19271impl RowExt for MultiBufferRow {
19272 fn as_f32(&self) -> f32 {
19273 self.0 as f32
19274 }
19275
19276 fn next_row(&self) -> Self {
19277 Self(self.0 + 1)
19278 }
19279
19280 fn previous_row(&self) -> Self {
19281 Self(self.0.saturating_sub(1))
19282 }
19283
19284 fn minus(&self, other: Self) -> u32 {
19285 self.0 - other.0
19286 }
19287}
19288
19289trait RowRangeExt {
19290 type Row;
19291
19292 fn len(&self) -> usize;
19293
19294 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
19295}
19296
19297impl RowRangeExt for Range<MultiBufferRow> {
19298 type Row = MultiBufferRow;
19299
19300 fn len(&self) -> usize {
19301 (self.end.0 - self.start.0) as usize
19302 }
19303
19304 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
19305 (self.start.0..self.end.0).map(MultiBufferRow)
19306 }
19307}
19308
19309impl RowRangeExt for Range<DisplayRow> {
19310 type Row = DisplayRow;
19311
19312 fn len(&self) -> usize {
19313 (self.end.0 - self.start.0) as usize
19314 }
19315
19316 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
19317 (self.start.0..self.end.0).map(DisplayRow)
19318 }
19319}
19320
19321/// If select range has more than one line, we
19322/// just point the cursor to range.start.
19323fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
19324 if range.start.row == range.end.row {
19325 range
19326 } else {
19327 range.start..range.start
19328 }
19329}
19330pub struct KillRing(ClipboardItem);
19331impl Global for KillRing {}
19332
19333const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
19334
19335struct BreakpointPromptEditor {
19336 pub(crate) prompt: Entity<Editor>,
19337 editor: WeakEntity<Editor>,
19338 breakpoint_anchor: Anchor,
19339 kind: BreakpointKind,
19340 block_ids: HashSet<CustomBlockId>,
19341 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
19342 _subscriptions: Vec<Subscription>,
19343}
19344
19345impl BreakpointPromptEditor {
19346 const MAX_LINES: u8 = 4;
19347
19348 fn new(
19349 editor: WeakEntity<Editor>,
19350 breakpoint_anchor: Anchor,
19351 kind: BreakpointKind,
19352 window: &mut Window,
19353 cx: &mut Context<Self>,
19354 ) -> Self {
19355 let buffer = cx.new(|cx| {
19356 Buffer::local(
19357 kind.log_message()
19358 .map(|msg| msg.to_string())
19359 .unwrap_or_default(),
19360 cx,
19361 )
19362 });
19363 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
19364
19365 let prompt = cx.new(|cx| {
19366 let mut prompt = Editor::new(
19367 EditorMode::AutoHeight {
19368 max_lines: Self::MAX_LINES as usize,
19369 },
19370 buffer,
19371 None,
19372 window,
19373 cx,
19374 );
19375 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
19376 prompt.set_show_cursor_when_unfocused(false, cx);
19377 prompt.set_placeholder_text(
19378 "Message to log when breakpoint is hit. Expressions within {} are interpolated.",
19379 cx,
19380 );
19381
19382 prompt
19383 });
19384
19385 Self {
19386 prompt,
19387 editor,
19388 breakpoint_anchor,
19389 kind,
19390 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
19391 block_ids: Default::default(),
19392 _subscriptions: vec![],
19393 }
19394 }
19395
19396 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
19397 self.block_ids.extend(block_ids)
19398 }
19399
19400 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
19401 if let Some(editor) = self.editor.upgrade() {
19402 let log_message = self
19403 .prompt
19404 .read(cx)
19405 .buffer
19406 .read(cx)
19407 .as_singleton()
19408 .expect("A multi buffer in breakpoint prompt isn't possible")
19409 .read(cx)
19410 .as_rope()
19411 .to_string();
19412
19413 editor.update(cx, |editor, cx| {
19414 editor.edit_breakpoint_at_anchor(
19415 self.breakpoint_anchor,
19416 self.kind.clone(),
19417 BreakpointEditAction::EditLogMessage(log_message.into()),
19418 cx,
19419 );
19420
19421 editor.remove_blocks(self.block_ids.clone(), None, cx);
19422 cx.focus_self(window);
19423 });
19424 }
19425 }
19426
19427 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
19428 self.editor
19429 .update(cx, |editor, cx| {
19430 editor.remove_blocks(self.block_ids.clone(), None, cx);
19431 window.focus(&editor.focus_handle);
19432 })
19433 .log_err();
19434 }
19435
19436 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
19437 let settings = ThemeSettings::get_global(cx);
19438 let text_style = TextStyle {
19439 color: if self.prompt.read(cx).read_only(cx) {
19440 cx.theme().colors().text_disabled
19441 } else {
19442 cx.theme().colors().text
19443 },
19444 font_family: settings.buffer_font.family.clone(),
19445 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19446 font_size: settings.buffer_font_size(cx).into(),
19447 font_weight: settings.buffer_font.weight,
19448 line_height: relative(settings.buffer_line_height.value()),
19449 ..Default::default()
19450 };
19451 EditorElement::new(
19452 &self.prompt,
19453 EditorStyle {
19454 background: cx.theme().colors().editor_background,
19455 local_player: cx.theme().players().local(),
19456 text: text_style,
19457 ..Default::default()
19458 },
19459 )
19460 }
19461}
19462
19463impl Render for BreakpointPromptEditor {
19464 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19465 let gutter_dimensions = *self.gutter_dimensions.lock();
19466 h_flex()
19467 .key_context("Editor")
19468 .bg(cx.theme().colors().editor_background)
19469 .border_y_1()
19470 .border_color(cx.theme().status().info_border)
19471 .size_full()
19472 .py(window.line_height() / 2.5)
19473 .on_action(cx.listener(Self::confirm))
19474 .on_action(cx.listener(Self::cancel))
19475 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
19476 .child(div().flex_1().child(self.render_prompt_editor(cx)))
19477 }
19478}
19479
19480impl Focusable for BreakpointPromptEditor {
19481 fn focus_handle(&self, cx: &App) -> FocusHandle {
19482 self.prompt.focus_handle(cx)
19483 }
19484}
19485
19486fn all_edits_insertions_or_deletions(
19487 edits: &Vec<(Range<Anchor>, String)>,
19488 snapshot: &MultiBufferSnapshot,
19489) -> bool {
19490 let mut all_insertions = true;
19491 let mut all_deletions = true;
19492
19493 for (range, new_text) in edits.iter() {
19494 let range_is_empty = range.to_offset(&snapshot).is_empty();
19495 let text_is_empty = new_text.is_empty();
19496
19497 if range_is_empty != text_is_empty {
19498 if range_is_empty {
19499 all_deletions = false;
19500 } else {
19501 all_insertions = false;
19502 }
19503 } else {
19504 return false;
19505 }
19506
19507 if !all_insertions && !all_deletions {
19508 return false;
19509 }
19510 }
19511 all_insertions || all_deletions
19512}
19513
19514struct MissingEditPredictionKeybindingTooltip;
19515
19516impl Render for MissingEditPredictionKeybindingTooltip {
19517 fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
19518 ui::tooltip_container(window, cx, |container, _, cx| {
19519 container
19520 .flex_shrink_0()
19521 .max_w_80()
19522 .min_h(rems_from_px(124.))
19523 .justify_between()
19524 .child(
19525 v_flex()
19526 .flex_1()
19527 .text_ui_sm(cx)
19528 .child(Label::new("Conflict with Accept Keybinding"))
19529 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
19530 )
19531 .child(
19532 h_flex()
19533 .pb_1()
19534 .gap_1()
19535 .items_end()
19536 .w_full()
19537 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
19538 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
19539 }))
19540 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
19541 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
19542 })),
19543 )
19544 })
19545 }
19546}
19547
19548#[derive(Debug, Clone, Copy, PartialEq)]
19549pub struct LineHighlight {
19550 pub background: Background,
19551 pub border: Option<gpui::Hsla>,
19552}
19553
19554impl From<Hsla> for LineHighlight {
19555 fn from(hsla: Hsla) -> Self {
19556 Self {
19557 background: hsla.into(),
19558 border: None,
19559 }
19560 }
19561}
19562
19563impl From<Background> for LineHighlight {
19564 fn from(background: Background) -> Self {
19565 Self {
19566 background,
19567 border: None,
19568 }
19569 }
19570}