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 display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26pub mod hover_popover;
27mod indent_guides;
28mod inlay_hint_cache;
29pub mod items;
30mod jsx_tag_auto_close;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod code_completion_tests;
44#[cfg(test)]
45mod editor_tests;
46#[cfg(test)]
47mod inline_completion_tests;
48mod signature_help;
49#[cfg(any(test, feature = "test-support"))]
50pub mod test;
51
52pub(crate) use actions::*;
53pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{Context as _, Result, anyhow};
56use blink_manager::BlinkManager;
57use buffer_diff::DiffHunkStatus;
58use client::{Collaborator, ParticipantIndex};
59use clock::ReplicaId;
60use collections::{BTreeMap, HashMap, HashSet, VecDeque};
61use convert_case::{Case, Casing};
62use display_map::*;
63pub use display_map::{ChunkRenderer, ChunkRendererContext, DisplayPoint, FoldPlaceholder};
64use editor_settings::GoToDefinitionFallback;
65pub use editor_settings::{
66 CurrentLineHighlight, EditorSettings, HideMouseMode, ScrollBeyondLastLine, SearchSettings,
67 ShowScrollbar,
68};
69pub use editor_settings_controls::*;
70use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap, layout_line};
71pub use element::{
72 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
73};
74use feature_flags::{Debugger, FeatureFlagAppExt};
75use futures::{
76 FutureExt,
77 future::{self, Shared, join},
78};
79use fuzzy::StringMatchCandidate;
80
81use ::git::Restore;
82use code_context_menus::{
83 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
84 CompletionsMenu, ContextMenuOrigin,
85};
86use git::blame::{GitBlame, GlobalBlameRenderer};
87use gpui::{
88 Action, Animation, AnimationExt, AnyElement, AnyWeakEntity, App, AppContext,
89 AsyncWindowContext, AvailableSpace, Background, Bounds, ClickEvent, ClipboardEntry,
90 ClipboardItem, Context, DispatchPhase, Edges, Entity, EntityInputHandler, EventEmitter,
91 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
92 KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement, Pixels, Render,
93 SharedString, Size, Stateful, Styled, Subscription, Task, TextStyle, TextStyleRefinement,
94 UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
95 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size,
96};
97use highlight_matching_bracket::refresh_matching_bracket_highlights;
98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight, find_file};
99pub use hover_popover::hover_markdown_style;
100use hover_popover::{HoverState, hide_hover};
101use indent_guides::ActiveIndentGuidesState;
102use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
103pub use inline_completion::Direction;
104use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
105pub use items::MAX_TAB_TITLE_LEN;
106use itertools::Itertools;
107use language::{
108 AutoindentMode, BracketMatch, BracketPair, Buffer, Capability, CharKind, CodeLabel,
109 CursorShape, DiagnosticEntry, DiffOptions, EditPredictionsMode, EditPreview, HighlightedText,
110 IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
111 TransactionId, TreeSitterOptions, WordsQuery,
112 language_settings::{
113 self, InlayHintSettings, LspInsertMode, RewrapBehavior, WordsCompletionMode,
114 all_language_settings, language_settings,
115 },
116 point_from_lsp, text_diff_with_options,
117};
118use language::{BufferRow, CharClassifier, Runnable, RunnableRange, point_to_lsp};
119use linked_editing_ranges::refresh_linked_ranges;
120use mouse_context_menu::MouseContextMenu;
121use persistence::DB;
122use project::{
123 ProjectPath,
124 debugger::breakpoint_store::{
125 BreakpointEditAction, BreakpointState, BreakpointStore, BreakpointStoreEvent,
126 },
127};
128
129pub use git::blame::BlameRenderer;
130pub use proposed_changes_editor::{
131 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
132};
133use smallvec::smallvec;
134use std::{cell::OnceCell, iter::Peekable};
135use task::{ResolvedTask, RunnableTag, TaskTemplate, TaskVariables};
136
137pub use lsp::CompletionContext;
138use lsp::{
139 CodeActionKind, CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity,
140 InsertTextFormat, InsertTextMode, LanguageServerId, LanguageServerName,
141};
142
143use language::BufferSnapshot;
144pub use lsp_ext::lsp_tasks;
145use movement::TextLayoutDetails;
146pub use multi_buffer::{
147 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, PathKey,
148 RowInfo, ToOffset, ToPoint,
149};
150use multi_buffer::{
151 ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
152 MultiOrSingleBufferOffsetRange, ToOffsetUtf16,
153};
154use parking_lot::Mutex;
155use project::{
156 CodeAction, Completion, CompletionIntent, CompletionSource, DocumentHighlight, InlayHint,
157 Location, LocationLink, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction,
158 TaskSourceKind,
159 debugger::breakpoint_store::Breakpoint,
160 lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
161 project_settings::{GitGutterSetting, ProjectSettings},
162};
163use rand::prelude::*;
164use rpc::{ErrorExt, proto::*};
165use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
166use selections_collection::{
167 MutableSelectionsCollection, SelectionsCollection, resolve_selections,
168};
169use serde::{Deserialize, Serialize};
170use settings::{Settings, SettingsLocation, SettingsStore, update_settings_file};
171use smallvec::SmallVec;
172use snippet::Snippet;
173use std::sync::Arc;
174use std::{
175 any::TypeId,
176 borrow::Cow,
177 cell::RefCell,
178 cmp::{self, Ordering, Reverse},
179 mem,
180 num::NonZeroU32,
181 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
182 path::{Path, PathBuf},
183 rc::Rc,
184 time::{Duration, Instant},
185};
186pub use sum_tree::Bias;
187use sum_tree::TreeMap;
188use text::{BufferId, FromAnchor, OffsetUtf16, Rope};
189use theme::{
190 ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings,
191 observe_buffer_font_size_adjustment,
192};
193use ui::{
194 ButtonSize, ButtonStyle, ContextMenu, Disclosure, IconButton, IconButtonShape, IconName,
195 IconSize, Key, Tooltip, h_flex, prelude::*,
196};
197use util::{RangeExt, ResultExt, TryFutureExt, maybe, post_inc};
198use workspace::{
199 Item as WorkspaceItem, ItemId, ItemNavHistory, OpenInTerminal, OpenTerminal,
200 RestoreOnStartupBehavior, SERIALIZATION_THROTTLE_TIME, SplitDirection, TabBarSettings, Toast,
201 ViewId, Workspace, WorkspaceId, WorkspaceSettings,
202 item::{ItemHandle, PreviewTabsSettings},
203 notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
204 searchable::SearchEvent,
205};
206
207use crate::hover_links::{find_url, find_url_from_range};
208use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
209
210pub const FILE_HEADER_HEIGHT: u32 = 2;
211pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
212pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
213const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
214const MAX_LINE_LEN: usize = 1024;
215const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
216const MAX_SELECTION_HISTORY_LEN: usize = 1024;
217pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
218#[doc(hidden)]
219pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
220const SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
221
222pub(crate) const CODE_ACTION_TIMEOUT: Duration = Duration::from_secs(5);
223pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(5);
224pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
225
226pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
227pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
228pub(crate) const MIN_LINE_NUMBER_DIGITS: u32 = 4;
229
230pub type RenderDiffHunkControlsFn = Arc<
231 dyn Fn(
232 u32,
233 &DiffHunkStatus,
234 Range<Anchor>,
235 bool,
236 Pixels,
237 &Entity<Editor>,
238 &mut Window,
239 &mut App,
240 ) -> AnyElement,
241>;
242
243const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
244 alt: true,
245 shift: true,
246 control: false,
247 platform: false,
248 function: false,
249};
250
251#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
252pub enum InlayId {
253 InlineCompletion(usize),
254 Hint(usize),
255}
256
257impl InlayId {
258 fn id(&self) -> usize {
259 match self {
260 Self::InlineCompletion(id) => *id,
261 Self::Hint(id) => *id,
262 }
263 }
264}
265
266pub enum DebugCurrentRowHighlight {}
267enum DocumentHighlightRead {}
268enum DocumentHighlightWrite {}
269enum InputComposition {}
270enum SelectedTextHighlight {}
271
272#[derive(Debug, Copy, Clone, PartialEq, Eq)]
273pub enum Navigated {
274 Yes,
275 No,
276}
277
278impl Navigated {
279 pub fn from_bool(yes: bool) -> Navigated {
280 if yes { Navigated::Yes } else { Navigated::No }
281 }
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
285enum DisplayDiffHunk {
286 Folded {
287 display_row: DisplayRow,
288 },
289 Unfolded {
290 is_created_file: bool,
291 diff_base_byte_range: Range<usize>,
292 display_row_range: Range<DisplayRow>,
293 multi_buffer_range: Range<Anchor>,
294 status: DiffHunkStatus,
295 },
296}
297
298pub enum HideMouseCursorOrigin {
299 TypingAction,
300 MovementAction,
301}
302
303pub fn init_settings(cx: &mut App) {
304 EditorSettings::register(cx);
305}
306
307pub fn init(cx: &mut App) {
308 init_settings(cx);
309
310 cx.set_global(GlobalBlameRenderer(Arc::new(())));
311
312 workspace::register_project_item::<Editor>(cx);
313 workspace::FollowableViewRegistry::register::<Editor>(cx);
314 workspace::register_serializable_item::<Editor>(cx);
315
316 cx.observe_new(
317 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
318 workspace.register_action(Editor::new_file);
319 workspace.register_action(Editor::new_file_vertical);
320 workspace.register_action(Editor::new_file_horizontal);
321 workspace.register_action(Editor::cancel_language_server_work);
322 },
323 )
324 .detach();
325
326 cx.on_action(move |_: &workspace::NewFile, cx| {
327 let app_state = workspace::AppState::global(cx);
328 if let Some(app_state) = app_state.upgrade() {
329 workspace::open_new(
330 Default::default(),
331 app_state,
332 cx,
333 |workspace, window, cx| {
334 Editor::new_file(workspace, &Default::default(), window, cx)
335 },
336 )
337 .detach();
338 }
339 });
340 cx.on_action(move |_: &workspace::NewWindow, cx| {
341 let app_state = workspace::AppState::global(cx);
342 if let Some(app_state) = app_state.upgrade() {
343 workspace::open_new(
344 Default::default(),
345 app_state,
346 cx,
347 |workspace, window, cx| {
348 cx.activate(true);
349 Editor::new_file(workspace, &Default::default(), window, cx)
350 },
351 )
352 .detach();
353 }
354 });
355}
356
357pub fn set_blame_renderer(renderer: impl BlameRenderer + 'static, cx: &mut App) {
358 cx.set_global(GlobalBlameRenderer(Arc::new(renderer)));
359}
360
361pub trait DiagnosticRenderer {
362 fn render_group(
363 &self,
364 diagnostic_group: Vec<DiagnosticEntry<Point>>,
365 buffer_id: BufferId,
366 snapshot: EditorSnapshot,
367 editor: WeakEntity<Editor>,
368 cx: &mut App,
369 ) -> Vec<BlockProperties<Anchor>>;
370}
371
372pub(crate) struct GlobalDiagnosticRenderer(pub Arc<dyn DiagnosticRenderer>);
373
374impl gpui::Global for GlobalDiagnosticRenderer {}
375pub fn set_diagnostic_renderer(renderer: impl DiagnosticRenderer + 'static, cx: &mut App) {
376 cx.set_global(GlobalDiagnosticRenderer(Arc::new(renderer)));
377}
378
379pub struct SearchWithinRange;
380
381trait InvalidationRegion {
382 fn ranges(&self) -> &[Range<Anchor>];
383}
384
385#[derive(Clone, Debug, PartialEq)]
386pub enum SelectPhase {
387 Begin {
388 position: DisplayPoint,
389 add: bool,
390 click_count: usize,
391 },
392 BeginColumnar {
393 position: DisplayPoint,
394 reset: bool,
395 goal_column: u32,
396 },
397 Extend {
398 position: DisplayPoint,
399 click_count: usize,
400 },
401 Update {
402 position: DisplayPoint,
403 goal_column: u32,
404 scroll_delta: gpui::Point<f32>,
405 },
406 End,
407}
408
409#[derive(Clone, Debug)]
410pub enum SelectMode {
411 Character,
412 Word(Range<Anchor>),
413 Line(Range<Anchor>),
414 All,
415}
416
417#[derive(Copy, Clone, PartialEq, Eq, Debug)]
418pub enum EditorMode {
419 SingleLine {
420 auto_width: bool,
421 },
422 AutoHeight {
423 max_lines: usize,
424 },
425 Full {
426 /// When set to `true`, the editor will scale its UI elements with the buffer font size.
427 scale_ui_elements_with_buffer_font_size: bool,
428 /// When set to `true`, the editor will render a background for the active line.
429 show_active_line_background: bool,
430 /// When set to `true`, the editor's height will be determined by its content.
431 sized_by_content: bool,
432 },
433}
434
435impl EditorMode {
436 pub fn full() -> Self {
437 Self::Full {
438 scale_ui_elements_with_buffer_font_size: true,
439 show_active_line_background: true,
440 sized_by_content: false,
441 }
442 }
443
444 pub fn is_full(&self) -> bool {
445 matches!(self, Self::Full { .. })
446 }
447}
448
449#[derive(Copy, Clone, Debug)]
450pub enum SoftWrap {
451 /// Prefer not to wrap at all.
452 ///
453 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
454 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
455 GitDiff,
456 /// Prefer a single line generally, unless an overly long line is encountered.
457 None,
458 /// Soft wrap lines that exceed the editor width.
459 EditorWidth,
460 /// Soft wrap lines at the preferred line length.
461 Column(u32),
462 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
463 Bounded(u32),
464}
465
466#[derive(Clone)]
467pub struct EditorStyle {
468 pub background: Hsla,
469 pub local_player: PlayerColor,
470 pub text: TextStyle,
471 pub scrollbar_width: Pixels,
472 pub syntax: Arc<SyntaxTheme>,
473 pub status: StatusColors,
474 pub inlay_hints_style: HighlightStyle,
475 pub inline_completion_styles: InlineCompletionStyles,
476 pub unnecessary_code_fade: f32,
477}
478
479impl Default for EditorStyle {
480 fn default() -> Self {
481 Self {
482 background: Hsla::default(),
483 local_player: PlayerColor::default(),
484 text: TextStyle::default(),
485 scrollbar_width: Pixels::default(),
486 syntax: Default::default(),
487 // HACK: Status colors don't have a real default.
488 // We should look into removing the status colors from the editor
489 // style and retrieve them directly from the theme.
490 status: StatusColors::dark(),
491 inlay_hints_style: HighlightStyle::default(),
492 inline_completion_styles: InlineCompletionStyles {
493 insertion: HighlightStyle::default(),
494 whitespace: HighlightStyle::default(),
495 },
496 unnecessary_code_fade: Default::default(),
497 }
498 }
499}
500
501pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
502 let show_background = language_settings::language_settings(None, None, cx)
503 .inlay_hints
504 .show_background;
505
506 HighlightStyle {
507 color: Some(cx.theme().status().hint),
508 background_color: show_background.then(|| cx.theme().status().hint_background),
509 ..HighlightStyle::default()
510 }
511}
512
513pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
514 InlineCompletionStyles {
515 insertion: HighlightStyle {
516 color: Some(cx.theme().status().predictive),
517 ..HighlightStyle::default()
518 },
519 whitespace: HighlightStyle {
520 background_color: Some(cx.theme().status().created_background),
521 ..HighlightStyle::default()
522 },
523 }
524}
525
526type CompletionId = usize;
527
528pub(crate) enum EditDisplayMode {
529 TabAccept,
530 DiffPopover,
531 Inline,
532}
533
534enum InlineCompletion {
535 Edit {
536 edits: Vec<(Range<Anchor>, String)>,
537 edit_preview: Option<EditPreview>,
538 display_mode: EditDisplayMode,
539 snapshot: BufferSnapshot,
540 },
541 Move {
542 target: Anchor,
543 snapshot: BufferSnapshot,
544 },
545}
546
547struct InlineCompletionState {
548 inlay_ids: Vec<InlayId>,
549 completion: InlineCompletion,
550 completion_id: Option<SharedString>,
551 invalidation_range: Range<Anchor>,
552}
553
554enum EditPredictionSettings {
555 Disabled,
556 Enabled {
557 show_in_menu: bool,
558 preview_requires_modifier: bool,
559 },
560}
561
562enum InlineCompletionHighlight {}
563
564#[derive(Debug, Clone)]
565struct InlineDiagnostic {
566 message: SharedString,
567 group_id: usize,
568 is_primary: bool,
569 start: Point,
570 severity: DiagnosticSeverity,
571}
572
573pub enum MenuInlineCompletionsPolicy {
574 Never,
575 ByProvider,
576}
577
578pub enum EditPredictionPreview {
579 /// Modifier is not pressed
580 Inactive { released_too_fast: bool },
581 /// Modifier pressed
582 Active {
583 since: Instant,
584 previous_scroll_position: Option<ScrollAnchor>,
585 },
586}
587
588impl EditPredictionPreview {
589 pub fn released_too_fast(&self) -> bool {
590 match self {
591 EditPredictionPreview::Inactive { released_too_fast } => *released_too_fast,
592 EditPredictionPreview::Active { .. } => false,
593 }
594 }
595
596 pub fn set_previous_scroll_position(&mut self, scroll_position: Option<ScrollAnchor>) {
597 if let EditPredictionPreview::Active {
598 previous_scroll_position,
599 ..
600 } = self
601 {
602 *previous_scroll_position = scroll_position;
603 }
604 }
605}
606
607pub struct ContextMenuOptions {
608 pub min_entries_visible: usize,
609 pub max_entries_visible: usize,
610 pub placement: Option<ContextMenuPlacement>,
611}
612
613#[derive(Debug, Clone, PartialEq, Eq)]
614pub enum ContextMenuPlacement {
615 Above,
616 Below,
617}
618
619#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
620struct EditorActionId(usize);
621
622impl EditorActionId {
623 pub fn post_inc(&mut self) -> Self {
624 let answer = self.0;
625
626 *self = Self(answer + 1);
627
628 Self(answer)
629 }
630}
631
632// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
633// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
634
635type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
636type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
637
638#[derive(Default)]
639struct ScrollbarMarkerState {
640 scrollbar_size: Size<Pixels>,
641 dirty: bool,
642 markers: Arc<[PaintQuad]>,
643 pending_refresh: Option<Task<Result<()>>>,
644}
645
646impl ScrollbarMarkerState {
647 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
648 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
649 }
650}
651
652#[derive(Clone, Debug)]
653struct RunnableTasks {
654 templates: Vec<(TaskSourceKind, TaskTemplate)>,
655 offset: multi_buffer::Anchor,
656 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
657 column: u32,
658 // Values of all named captures, including those starting with '_'
659 extra_variables: HashMap<String, String>,
660 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
661 context_range: Range<BufferOffset>,
662}
663
664impl RunnableTasks {
665 fn resolve<'a>(
666 &'a self,
667 cx: &'a task::TaskContext,
668 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
669 self.templates.iter().filter_map(|(kind, template)| {
670 template
671 .resolve_task(&kind.to_id_base(), cx)
672 .map(|task| (kind.clone(), task))
673 })
674 }
675}
676
677#[derive(Clone)]
678struct ResolvedTasks {
679 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
680 position: Anchor,
681}
682
683#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
684struct BufferOffset(usize);
685
686// Addons allow storing per-editor state in other crates (e.g. Vim)
687pub trait Addon: 'static {
688 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
689
690 fn render_buffer_header_controls(
691 &self,
692 _: &ExcerptInfo,
693 _: &Window,
694 _: &App,
695 ) -> Option<AnyElement> {
696 None
697 }
698
699 fn to_any(&self) -> &dyn std::any::Any;
700}
701
702/// A set of caret positions, registered when the editor was edited.
703pub struct ChangeList {
704 changes: Vec<Vec<Anchor>>,
705 /// Currently "selected" change.
706 position: Option<usize>,
707}
708
709impl ChangeList {
710 pub fn new() -> Self {
711 Self {
712 changes: Vec::new(),
713 position: None,
714 }
715 }
716
717 /// Moves to the next change in the list (based on the direction given) and returns the caret positions for the next change.
718 /// If reaches the end of the list in the direction, returns the corresponding change until called for a different direction.
719 pub fn next_change(&mut self, count: usize, direction: Direction) -> Option<&[Anchor]> {
720 if self.changes.is_empty() {
721 return None;
722 }
723
724 let prev = self.position.unwrap_or(self.changes.len());
725 let next = if direction == Direction::Prev {
726 prev.saturating_sub(count)
727 } else {
728 (prev + count).min(self.changes.len() - 1)
729 };
730 self.position = Some(next);
731 self.changes.get(next).map(|anchors| anchors.as_slice())
732 }
733
734 /// Adds a new change to the list, resetting the change list position.
735 pub fn push_to_change_list(&mut self, pop_state: bool, new_positions: Vec<Anchor>) {
736 self.position.take();
737 if pop_state {
738 self.changes.pop();
739 }
740 self.changes.push(new_positions.clone());
741 }
742
743 pub fn last(&self) -> Option<&[Anchor]> {
744 self.changes.last().map(|anchors| anchors.as_slice())
745 }
746}
747
748/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
749///
750/// See the [module level documentation](self) for more information.
751pub struct Editor {
752 focus_handle: FocusHandle,
753 last_focused_descendant: Option<WeakFocusHandle>,
754 /// The text buffer being edited
755 buffer: Entity<MultiBuffer>,
756 /// Map of how text in the buffer should be displayed.
757 /// Handles soft wraps, folds, fake inlay text insertions, etc.
758 pub display_map: Entity<DisplayMap>,
759 pub selections: SelectionsCollection,
760 pub scroll_manager: ScrollManager,
761 /// When inline assist editors are linked, they all render cursors because
762 /// typing enters text into each of them, even the ones that aren't focused.
763 pub(crate) show_cursor_when_unfocused: bool,
764 columnar_selection_tail: Option<Anchor>,
765 add_selections_state: Option<AddSelectionsState>,
766 select_next_state: Option<SelectNextState>,
767 select_prev_state: Option<SelectNextState>,
768 selection_history: SelectionHistory,
769 autoclose_regions: Vec<AutocloseRegion>,
770 snippet_stack: InvalidationStack<SnippetState>,
771 select_syntax_node_history: SelectSyntaxNodeHistory,
772 ime_transaction: Option<TransactionId>,
773 active_diagnostics: ActiveDiagnostic,
774 show_inline_diagnostics: bool,
775 inline_diagnostics_update: Task<()>,
776 inline_diagnostics_enabled: bool,
777 inline_diagnostics: Vec<(Anchor, InlineDiagnostic)>,
778 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
779 hard_wrap: Option<usize>,
780
781 // TODO: make this a access method
782 pub project: Option<Entity<Project>>,
783 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
784 completion_provider: Option<Box<dyn CompletionProvider>>,
785 collaboration_hub: Option<Box<dyn CollaborationHub>>,
786 blink_manager: Entity<BlinkManager>,
787 show_cursor_names: bool,
788 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
789 pub show_local_selections: bool,
790 mode: EditorMode,
791 show_breadcrumbs: bool,
792 show_gutter: bool,
793 show_scrollbars: bool,
794 disable_scrolling: bool,
795 disable_expand_excerpt_buttons: bool,
796 show_line_numbers: Option<bool>,
797 use_relative_line_numbers: Option<bool>,
798 show_git_diff_gutter: Option<bool>,
799 show_code_actions: Option<bool>,
800 show_runnables: Option<bool>,
801 show_breakpoints: Option<bool>,
802 show_wrap_guides: Option<bool>,
803 show_indent_guides: Option<bool>,
804 placeholder_text: Option<Arc<str>>,
805 highlight_order: usize,
806 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
807 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
808 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
809 scrollbar_marker_state: ScrollbarMarkerState,
810 active_indent_guides_state: ActiveIndentGuidesState,
811 nav_history: Option<ItemNavHistory>,
812 context_menu: RefCell<Option<CodeContextMenu>>,
813 context_menu_options: Option<ContextMenuOptions>,
814 mouse_context_menu: Option<MouseContextMenu>,
815 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
816 signature_help_state: SignatureHelpState,
817 auto_signature_help: Option<bool>,
818 find_all_references_task_sources: Vec<Anchor>,
819 next_completion_id: CompletionId,
820 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
821 code_actions_task: Option<Task<Result<()>>>,
822 quick_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
823 debounced_selection_highlight_task: Option<(Range<Anchor>, Task<()>)>,
824 document_highlights_task: Option<Task<()>>,
825 linked_editing_range_task: Option<Task<Option<()>>>,
826 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
827 pending_rename: Option<RenameState>,
828 searchable: bool,
829 cursor_shape: CursorShape,
830 current_line_highlight: Option<CurrentLineHighlight>,
831 collapse_matches: bool,
832 autoindent_mode: Option<AutoindentMode>,
833 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
834 input_enabled: bool,
835 use_modal_editing: bool,
836 read_only: bool,
837 leader_peer_id: Option<PeerId>,
838 remote_id: Option<ViewId>,
839 hover_state: HoverState,
840 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
841 gutter_hovered: bool,
842 hovered_link_state: Option<HoveredLinkState>,
843 edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
844 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
845 active_inline_completion: Option<InlineCompletionState>,
846 /// Used to prevent flickering as the user types while the menu is open
847 stale_inline_completion_in_menu: Option<InlineCompletionState>,
848 edit_prediction_settings: EditPredictionSettings,
849 inline_completions_hidden_for_vim_mode: bool,
850 show_inline_completions_override: Option<bool>,
851 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
852 edit_prediction_preview: EditPredictionPreview,
853 edit_prediction_indent_conflict: bool,
854 edit_prediction_requires_modifier_in_indent_conflict: bool,
855 inlay_hint_cache: InlayHintCache,
856 next_inlay_id: usize,
857 _subscriptions: Vec<Subscription>,
858 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
859 gutter_dimensions: GutterDimensions,
860 style: Option<EditorStyle>,
861 text_style_refinement: Option<TextStyleRefinement>,
862 next_editor_action_id: EditorActionId,
863 editor_actions:
864 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
865 use_autoclose: bool,
866 use_auto_surround: bool,
867 auto_replace_emoji_shortcode: bool,
868 jsx_tag_auto_close_enabled_in_any_buffer: bool,
869 show_git_blame_gutter: bool,
870 show_git_blame_inline: bool,
871 show_git_blame_inline_delay_task: Option<Task<()>>,
872 pub git_blame_inline_tooltip: Option<AnyWeakEntity>,
873 git_blame_inline_enabled: bool,
874 render_diff_hunk_controls: RenderDiffHunkControlsFn,
875 serialize_dirty_buffers: bool,
876 show_selection_menu: Option<bool>,
877 blame: Option<Entity<GitBlame>>,
878 blame_subscription: Option<Subscription>,
879 custom_context_menu: Option<
880 Box<
881 dyn 'static
882 + Fn(
883 &mut Self,
884 DisplayPoint,
885 &mut Window,
886 &mut Context<Self>,
887 ) -> Option<Entity<ui::ContextMenu>>,
888 >,
889 >,
890 last_bounds: Option<Bounds<Pixels>>,
891 last_position_map: Option<Rc<PositionMap>>,
892 expect_bounds_change: Option<Bounds<Pixels>>,
893 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
894 tasks_update_task: Option<Task<()>>,
895 breakpoint_store: Option<Entity<BreakpointStore>>,
896 /// Allow's a user to create a breakpoint by selecting this indicator
897 /// It should be None while a user is not hovering over the gutter
898 /// Otherwise it represents the point that the breakpoint will be shown
899 gutter_breakpoint_indicator: (Option<(DisplayPoint, bool)>, Option<Task<()>>),
900 in_project_search: bool,
901 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
902 breadcrumb_header: Option<String>,
903 focused_block: Option<FocusedBlock>,
904 next_scroll_position: NextScrollCursorCenterTopBottom,
905 addons: HashMap<TypeId, Box<dyn Addon>>,
906 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
907 load_diff_task: Option<Shared<Task<()>>>,
908 selection_mark_mode: bool,
909 toggle_fold_multiple_buffers: Task<()>,
910 _scroll_cursor_center_top_bottom_task: Task<()>,
911 serialize_selections: Task<()>,
912 serialize_folds: Task<()>,
913 mouse_cursor_hidden: bool,
914 hide_mouse_mode: HideMouseMode,
915 pub change_list: ChangeList,
916}
917
918#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
919enum NextScrollCursorCenterTopBottom {
920 #[default]
921 Center,
922 Top,
923 Bottom,
924}
925
926impl NextScrollCursorCenterTopBottom {
927 fn next(&self) -> Self {
928 match self {
929 Self::Center => Self::Top,
930 Self::Top => Self::Bottom,
931 Self::Bottom => Self::Center,
932 }
933 }
934}
935
936#[derive(Clone)]
937pub struct EditorSnapshot {
938 pub mode: EditorMode,
939 show_gutter: bool,
940 show_line_numbers: Option<bool>,
941 show_git_diff_gutter: Option<bool>,
942 show_code_actions: Option<bool>,
943 show_runnables: Option<bool>,
944 show_breakpoints: Option<bool>,
945 git_blame_gutter_max_author_length: Option<usize>,
946 pub display_snapshot: DisplaySnapshot,
947 pub placeholder_text: Option<Arc<str>>,
948 is_focused: bool,
949 scroll_anchor: ScrollAnchor,
950 ongoing_scroll: OngoingScroll,
951 current_line_highlight: CurrentLineHighlight,
952 gutter_hovered: bool,
953}
954
955#[derive(Default, Debug, Clone, Copy)]
956pub struct GutterDimensions {
957 pub left_padding: Pixels,
958 pub right_padding: Pixels,
959 pub width: Pixels,
960 pub margin: Pixels,
961 pub git_blame_entries_width: Option<Pixels>,
962}
963
964impl GutterDimensions {
965 /// The full width of the space taken up by the gutter.
966 pub fn full_width(&self) -> Pixels {
967 self.margin + self.width
968 }
969
970 /// The width of the space reserved for the fold indicators,
971 /// use alongside 'justify_end' and `gutter_width` to
972 /// right align content with the line numbers
973 pub fn fold_area_width(&self) -> Pixels {
974 self.margin + self.right_padding
975 }
976}
977
978#[derive(Debug)]
979pub struct RemoteSelection {
980 pub replica_id: ReplicaId,
981 pub selection: Selection<Anchor>,
982 pub cursor_shape: CursorShape,
983 pub peer_id: PeerId,
984 pub line_mode: bool,
985 pub participant_index: Option<ParticipantIndex>,
986 pub user_name: Option<SharedString>,
987}
988
989#[derive(Clone, Debug)]
990struct SelectionHistoryEntry {
991 selections: Arc<[Selection<Anchor>]>,
992 select_next_state: Option<SelectNextState>,
993 select_prev_state: Option<SelectNextState>,
994 add_selections_state: Option<AddSelectionsState>,
995}
996
997enum SelectionHistoryMode {
998 Normal,
999 Undoing,
1000 Redoing,
1001}
1002
1003#[derive(Clone, PartialEq, Eq, Hash)]
1004struct HoveredCursor {
1005 replica_id: u16,
1006 selection_id: usize,
1007}
1008
1009impl Default for SelectionHistoryMode {
1010 fn default() -> Self {
1011 Self::Normal
1012 }
1013}
1014
1015#[derive(Default)]
1016struct SelectionHistory {
1017 #[allow(clippy::type_complexity)]
1018 selections_by_transaction:
1019 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
1020 mode: SelectionHistoryMode,
1021 undo_stack: VecDeque<SelectionHistoryEntry>,
1022 redo_stack: VecDeque<SelectionHistoryEntry>,
1023}
1024
1025impl SelectionHistory {
1026 fn insert_transaction(
1027 &mut self,
1028 transaction_id: TransactionId,
1029 selections: Arc<[Selection<Anchor>]>,
1030 ) {
1031 self.selections_by_transaction
1032 .insert(transaction_id, (selections, None));
1033 }
1034
1035 #[allow(clippy::type_complexity)]
1036 fn transaction(
1037 &self,
1038 transaction_id: TransactionId,
1039 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1040 self.selections_by_transaction.get(&transaction_id)
1041 }
1042
1043 #[allow(clippy::type_complexity)]
1044 fn transaction_mut(
1045 &mut self,
1046 transaction_id: TransactionId,
1047 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
1048 self.selections_by_transaction.get_mut(&transaction_id)
1049 }
1050
1051 fn push(&mut self, entry: SelectionHistoryEntry) {
1052 if !entry.selections.is_empty() {
1053 match self.mode {
1054 SelectionHistoryMode::Normal => {
1055 self.push_undo(entry);
1056 self.redo_stack.clear();
1057 }
1058 SelectionHistoryMode::Undoing => self.push_redo(entry),
1059 SelectionHistoryMode::Redoing => self.push_undo(entry),
1060 }
1061 }
1062 }
1063
1064 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
1065 if self
1066 .undo_stack
1067 .back()
1068 .map_or(true, |e| e.selections != entry.selections)
1069 {
1070 self.undo_stack.push_back(entry);
1071 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1072 self.undo_stack.pop_front();
1073 }
1074 }
1075 }
1076
1077 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
1078 if self
1079 .redo_stack
1080 .back()
1081 .map_or(true, |e| e.selections != entry.selections)
1082 {
1083 self.redo_stack.push_back(entry);
1084 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
1085 self.redo_stack.pop_front();
1086 }
1087 }
1088 }
1089}
1090
1091struct RowHighlight {
1092 index: usize,
1093 range: Range<Anchor>,
1094 color: Hsla,
1095 should_autoscroll: bool,
1096}
1097
1098#[derive(Clone, Debug)]
1099struct AddSelectionsState {
1100 above: bool,
1101 stack: Vec<usize>,
1102}
1103
1104#[derive(Clone)]
1105struct SelectNextState {
1106 query: AhoCorasick,
1107 wordwise: bool,
1108 done: bool,
1109}
1110
1111impl std::fmt::Debug for SelectNextState {
1112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1113 f.debug_struct(std::any::type_name::<Self>())
1114 .field("wordwise", &self.wordwise)
1115 .field("done", &self.done)
1116 .finish()
1117 }
1118}
1119
1120#[derive(Debug)]
1121struct AutocloseRegion {
1122 selection_id: usize,
1123 range: Range<Anchor>,
1124 pair: BracketPair,
1125}
1126
1127#[derive(Debug)]
1128struct SnippetState {
1129 ranges: Vec<Vec<Range<Anchor>>>,
1130 active_index: usize,
1131 choices: Vec<Option<Vec<String>>>,
1132}
1133
1134#[doc(hidden)]
1135pub struct RenameState {
1136 pub range: Range<Anchor>,
1137 pub old_name: Arc<str>,
1138 pub editor: Entity<Editor>,
1139 block_id: CustomBlockId,
1140}
1141
1142struct InvalidationStack<T>(Vec<T>);
1143
1144struct RegisteredInlineCompletionProvider {
1145 provider: Arc<dyn InlineCompletionProviderHandle>,
1146 _subscription: Subscription,
1147}
1148
1149#[derive(Debug, PartialEq, Eq)]
1150pub struct ActiveDiagnosticGroup {
1151 pub active_range: Range<Anchor>,
1152 pub active_message: String,
1153 pub group_id: usize,
1154 pub blocks: HashSet<CustomBlockId>,
1155}
1156
1157#[derive(Debug, PartialEq, Eq)]
1158#[allow(clippy::large_enum_variant)]
1159pub(crate) enum ActiveDiagnostic {
1160 None,
1161 All,
1162 Group(ActiveDiagnosticGroup),
1163}
1164
1165#[derive(Serialize, Deserialize, Clone, Debug)]
1166pub struct ClipboardSelection {
1167 /// The number of bytes in this selection.
1168 pub len: usize,
1169 /// Whether this was a full-line selection.
1170 pub is_entire_line: bool,
1171 /// The indentation of the first line when this content was originally copied.
1172 pub first_line_indent: u32,
1173}
1174
1175// selections, scroll behavior, was newest selection reversed
1176type SelectSyntaxNodeHistoryState = (
1177 Box<[Selection<usize>]>,
1178 SelectSyntaxNodeScrollBehavior,
1179 bool,
1180);
1181
1182#[derive(Default)]
1183struct SelectSyntaxNodeHistory {
1184 stack: Vec<SelectSyntaxNodeHistoryState>,
1185 // disable temporarily to allow changing selections without losing the stack
1186 pub disable_clearing: bool,
1187}
1188
1189impl SelectSyntaxNodeHistory {
1190 pub fn try_clear(&mut self) {
1191 if !self.disable_clearing {
1192 self.stack.clear();
1193 }
1194 }
1195
1196 pub fn push(&mut self, selection: SelectSyntaxNodeHistoryState) {
1197 self.stack.push(selection);
1198 }
1199
1200 pub fn pop(&mut self) -> Option<SelectSyntaxNodeHistoryState> {
1201 self.stack.pop()
1202 }
1203}
1204
1205enum SelectSyntaxNodeScrollBehavior {
1206 CursorTop,
1207 FitSelection,
1208 CursorBottom,
1209}
1210
1211#[derive(Debug)]
1212pub(crate) struct NavigationData {
1213 cursor_anchor: Anchor,
1214 cursor_position: Point,
1215 scroll_anchor: ScrollAnchor,
1216 scroll_top_row: u32,
1217}
1218
1219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1220pub enum GotoDefinitionKind {
1221 Symbol,
1222 Declaration,
1223 Type,
1224 Implementation,
1225}
1226
1227#[derive(Debug, Clone)]
1228enum InlayHintRefreshReason {
1229 ModifiersChanged(bool),
1230 Toggle(bool),
1231 SettingsChange(InlayHintSettings),
1232 NewLinesShown,
1233 BufferEdited(HashSet<Arc<Language>>),
1234 RefreshRequested,
1235 ExcerptsRemoved(Vec<ExcerptId>),
1236}
1237
1238impl InlayHintRefreshReason {
1239 fn description(&self) -> &'static str {
1240 match self {
1241 Self::ModifiersChanged(_) => "modifiers changed",
1242 Self::Toggle(_) => "toggle",
1243 Self::SettingsChange(_) => "settings change",
1244 Self::NewLinesShown => "new lines shown",
1245 Self::BufferEdited(_) => "buffer edited",
1246 Self::RefreshRequested => "refresh requested",
1247 Self::ExcerptsRemoved(_) => "excerpts removed",
1248 }
1249 }
1250}
1251
1252pub enum FormatTarget {
1253 Buffers,
1254 Ranges(Vec<Range<MultiBufferPoint>>),
1255}
1256
1257pub(crate) struct FocusedBlock {
1258 id: BlockId,
1259 focus_handle: WeakFocusHandle,
1260}
1261
1262#[derive(Clone)]
1263enum JumpData {
1264 MultiBufferRow {
1265 row: MultiBufferRow,
1266 line_offset_from_top: u32,
1267 },
1268 MultiBufferPoint {
1269 excerpt_id: ExcerptId,
1270 position: Point,
1271 anchor: text::Anchor,
1272 line_offset_from_top: u32,
1273 },
1274}
1275
1276pub enum MultibufferSelectionMode {
1277 First,
1278 All,
1279}
1280
1281#[derive(Clone, Copy, Debug, Default)]
1282pub struct RewrapOptions {
1283 pub override_language_settings: bool,
1284 pub preserve_existing_whitespace: bool,
1285}
1286
1287impl Editor {
1288 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1289 let buffer = cx.new(|cx| Buffer::local("", cx));
1290 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1291 Self::new(
1292 EditorMode::SingleLine { auto_width: false },
1293 buffer,
1294 None,
1295 window,
1296 cx,
1297 )
1298 }
1299
1300 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1301 let buffer = cx.new(|cx| Buffer::local("", cx));
1302 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1303 Self::new(EditorMode::full(), buffer, None, window, cx)
1304 }
1305
1306 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1307 let buffer = cx.new(|cx| Buffer::local("", cx));
1308 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1309 Self::new(
1310 EditorMode::SingleLine { auto_width: true },
1311 buffer,
1312 None,
1313 window,
1314 cx,
1315 )
1316 }
1317
1318 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1319 let buffer = cx.new(|cx| Buffer::local("", cx));
1320 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1321 Self::new(
1322 EditorMode::AutoHeight { max_lines },
1323 buffer,
1324 None,
1325 window,
1326 cx,
1327 )
1328 }
1329
1330 pub fn for_buffer(
1331 buffer: Entity<Buffer>,
1332 project: Option<Entity<Project>>,
1333 window: &mut Window,
1334 cx: &mut Context<Self>,
1335 ) -> Self {
1336 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1337 Self::new(EditorMode::full(), buffer, project, window, cx)
1338 }
1339
1340 pub fn for_multibuffer(
1341 buffer: Entity<MultiBuffer>,
1342 project: Option<Entity<Project>>,
1343 window: &mut Window,
1344 cx: &mut Context<Self>,
1345 ) -> Self {
1346 Self::new(EditorMode::full(), buffer, project, window, cx)
1347 }
1348
1349 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1350 let mut clone = Self::new(
1351 self.mode,
1352 self.buffer.clone(),
1353 self.project.clone(),
1354 window,
1355 cx,
1356 );
1357 self.display_map.update(cx, |display_map, cx| {
1358 let snapshot = display_map.snapshot(cx);
1359 clone.display_map.update(cx, |display_map, cx| {
1360 display_map.set_state(&snapshot, cx);
1361 });
1362 });
1363 clone.folds_did_change(cx);
1364 clone.selections.clone_state(&self.selections);
1365 clone.scroll_manager.clone_state(&self.scroll_manager);
1366 clone.searchable = self.searchable;
1367 clone.read_only = self.read_only;
1368 clone
1369 }
1370
1371 pub fn new(
1372 mode: EditorMode,
1373 buffer: Entity<MultiBuffer>,
1374 project: Option<Entity<Project>>,
1375 window: &mut Window,
1376 cx: &mut Context<Self>,
1377 ) -> Self {
1378 let style = window.text_style();
1379 let font_size = style.font_size.to_pixels(window.rem_size());
1380 let editor = cx.entity().downgrade();
1381 let fold_placeholder = FoldPlaceholder {
1382 constrain_width: true,
1383 render: Arc::new(move |fold_id, fold_range, cx| {
1384 let editor = editor.clone();
1385 div()
1386 .id(fold_id)
1387 .bg(cx.theme().colors().ghost_element_background)
1388 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1389 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1390 .rounded_xs()
1391 .size_full()
1392 .cursor_pointer()
1393 .child("⋯")
1394 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1395 .on_click(move |_, _window, cx| {
1396 editor
1397 .update(cx, |editor, cx| {
1398 editor.unfold_ranges(
1399 &[fold_range.start..fold_range.end],
1400 true,
1401 false,
1402 cx,
1403 );
1404 cx.stop_propagation();
1405 })
1406 .ok();
1407 })
1408 .into_any()
1409 }),
1410 merge_adjacent: true,
1411 ..Default::default()
1412 };
1413 let display_map = cx.new(|cx| {
1414 DisplayMap::new(
1415 buffer.clone(),
1416 style.font(),
1417 font_size,
1418 None,
1419 FILE_HEADER_HEIGHT,
1420 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1421 fold_placeholder,
1422 cx,
1423 )
1424 });
1425
1426 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1427
1428 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1429
1430 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1431 .then(|| language_settings::SoftWrap::None);
1432
1433 let mut project_subscriptions = Vec::new();
1434 if mode.is_full() {
1435 if let Some(project) = project.as_ref() {
1436 project_subscriptions.push(cx.subscribe_in(
1437 project,
1438 window,
1439 |editor, _, event, window, cx| match event {
1440 project::Event::RefreshCodeLens => {
1441 // we always query lens with actions, without storing them, always refreshing them
1442 }
1443 project::Event::RefreshInlayHints => {
1444 editor
1445 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1446 }
1447 project::Event::SnippetEdit(id, snippet_edits) => {
1448 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1449 let focus_handle = editor.focus_handle(cx);
1450 if focus_handle.is_focused(window) {
1451 let snapshot = buffer.read(cx).snapshot();
1452 for (range, snippet) in snippet_edits {
1453 let editor_range =
1454 language::range_from_lsp(*range).to_offset(&snapshot);
1455 editor
1456 .insert_snippet(
1457 &[editor_range],
1458 snippet.clone(),
1459 window,
1460 cx,
1461 )
1462 .ok();
1463 }
1464 }
1465 }
1466 }
1467 _ => {}
1468 },
1469 ));
1470 if let Some(task_inventory) = project
1471 .read(cx)
1472 .task_store()
1473 .read(cx)
1474 .task_inventory()
1475 .cloned()
1476 {
1477 project_subscriptions.push(cx.observe_in(
1478 &task_inventory,
1479 window,
1480 |editor, _, window, cx| {
1481 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1482 },
1483 ));
1484 };
1485
1486 project_subscriptions.push(cx.subscribe_in(
1487 &project.read(cx).breakpoint_store(),
1488 window,
1489 |editor, _, event, window, cx| match event {
1490 BreakpointStoreEvent::ActiveDebugLineChanged => {
1491 if editor.go_to_active_debug_line(window, cx) {
1492 cx.stop_propagation();
1493 }
1494 }
1495 _ => {}
1496 },
1497 ));
1498 }
1499 }
1500
1501 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1502
1503 let inlay_hint_settings =
1504 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1505 let focus_handle = cx.focus_handle();
1506 cx.on_focus(&focus_handle, window, Self::handle_focus)
1507 .detach();
1508 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1509 .detach();
1510 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1511 .detach();
1512 cx.on_blur(&focus_handle, window, Self::handle_blur)
1513 .detach();
1514
1515 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1516 Some(false)
1517 } else {
1518 None
1519 };
1520
1521 let breakpoint_store = match (mode, project.as_ref()) {
1522 (EditorMode::Full { .. }, Some(project)) => Some(project.read(cx).breakpoint_store()),
1523 _ => None,
1524 };
1525
1526 let mut code_action_providers = Vec::new();
1527 let mut load_uncommitted_diff = None;
1528 if let Some(project) = project.clone() {
1529 load_uncommitted_diff = Some(
1530 get_uncommitted_diff_for_buffer(
1531 &project,
1532 buffer.read(cx).all_buffers(),
1533 buffer.clone(),
1534 cx,
1535 )
1536 .shared(),
1537 );
1538 code_action_providers.push(Rc::new(project) as Rc<_>);
1539 }
1540
1541 let mut this = Self {
1542 focus_handle,
1543 show_cursor_when_unfocused: false,
1544 last_focused_descendant: None,
1545 buffer: buffer.clone(),
1546 display_map: display_map.clone(),
1547 selections,
1548 scroll_manager: ScrollManager::new(cx),
1549 columnar_selection_tail: None,
1550 add_selections_state: None,
1551 select_next_state: None,
1552 select_prev_state: None,
1553 selection_history: Default::default(),
1554 autoclose_regions: Default::default(),
1555 snippet_stack: Default::default(),
1556 select_syntax_node_history: SelectSyntaxNodeHistory::default(),
1557 ime_transaction: Default::default(),
1558 active_diagnostics: ActiveDiagnostic::None,
1559 show_inline_diagnostics: ProjectSettings::get_global(cx).diagnostics.inline.enabled,
1560 inline_diagnostics_update: Task::ready(()),
1561 inline_diagnostics: Vec::new(),
1562 soft_wrap_mode_override,
1563 hard_wrap: None,
1564 completion_provider: project.clone().map(|project| Box::new(project) as _),
1565 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1566 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1567 project,
1568 blink_manager: blink_manager.clone(),
1569 show_local_selections: true,
1570 show_scrollbars: true,
1571 disable_scrolling: false,
1572 mode,
1573 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1574 show_gutter: mode.is_full(),
1575 show_line_numbers: None,
1576 use_relative_line_numbers: None,
1577 disable_expand_excerpt_buttons: false,
1578 show_git_diff_gutter: None,
1579 show_code_actions: None,
1580 show_runnables: None,
1581 show_breakpoints: None,
1582 show_wrap_guides: None,
1583 show_indent_guides,
1584 placeholder_text: None,
1585 highlight_order: 0,
1586 highlighted_rows: HashMap::default(),
1587 background_highlights: Default::default(),
1588 gutter_highlights: TreeMap::default(),
1589 scrollbar_marker_state: ScrollbarMarkerState::default(),
1590 active_indent_guides_state: ActiveIndentGuidesState::default(),
1591 nav_history: None,
1592 context_menu: RefCell::new(None),
1593 context_menu_options: None,
1594 mouse_context_menu: None,
1595 completion_tasks: Default::default(),
1596 signature_help_state: SignatureHelpState::default(),
1597 auto_signature_help: None,
1598 find_all_references_task_sources: Vec::new(),
1599 next_completion_id: 0,
1600 next_inlay_id: 0,
1601 code_action_providers,
1602 available_code_actions: Default::default(),
1603 code_actions_task: Default::default(),
1604 quick_selection_highlight_task: Default::default(),
1605 debounced_selection_highlight_task: Default::default(),
1606 document_highlights_task: Default::default(),
1607 linked_editing_range_task: Default::default(),
1608 pending_rename: Default::default(),
1609 searchable: true,
1610 cursor_shape: EditorSettings::get_global(cx)
1611 .cursor_shape
1612 .unwrap_or_default(),
1613 current_line_highlight: None,
1614 autoindent_mode: Some(AutoindentMode::EachLine),
1615 collapse_matches: false,
1616 workspace: None,
1617 input_enabled: true,
1618 use_modal_editing: mode.is_full(),
1619 read_only: false,
1620 use_autoclose: true,
1621 use_auto_surround: true,
1622 auto_replace_emoji_shortcode: false,
1623 jsx_tag_auto_close_enabled_in_any_buffer: false,
1624 leader_peer_id: None,
1625 remote_id: None,
1626 hover_state: Default::default(),
1627 pending_mouse_down: None,
1628 hovered_link_state: Default::default(),
1629 edit_prediction_provider: None,
1630 active_inline_completion: None,
1631 stale_inline_completion_in_menu: None,
1632 edit_prediction_preview: EditPredictionPreview::Inactive {
1633 released_too_fast: false,
1634 },
1635 inline_diagnostics_enabled: mode.is_full(),
1636 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1637
1638 gutter_hovered: false,
1639 pixel_position_of_newest_cursor: None,
1640 last_bounds: None,
1641 last_position_map: None,
1642 expect_bounds_change: None,
1643 gutter_dimensions: GutterDimensions::default(),
1644 style: None,
1645 show_cursor_names: false,
1646 hovered_cursors: Default::default(),
1647 next_editor_action_id: EditorActionId::default(),
1648 editor_actions: Rc::default(),
1649 inline_completions_hidden_for_vim_mode: false,
1650 show_inline_completions_override: None,
1651 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1652 edit_prediction_settings: EditPredictionSettings::Disabled,
1653 edit_prediction_indent_conflict: false,
1654 edit_prediction_requires_modifier_in_indent_conflict: true,
1655 custom_context_menu: None,
1656 show_git_blame_gutter: false,
1657 show_git_blame_inline: false,
1658 show_selection_menu: None,
1659 show_git_blame_inline_delay_task: None,
1660 git_blame_inline_tooltip: None,
1661 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1662 render_diff_hunk_controls: Arc::new(render_diff_hunk_controls),
1663 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1664 .session
1665 .restore_unsaved_buffers,
1666 blame: None,
1667 blame_subscription: None,
1668 tasks: Default::default(),
1669
1670 breakpoint_store,
1671 gutter_breakpoint_indicator: (None, None),
1672 _subscriptions: vec![
1673 cx.observe(&buffer, Self::on_buffer_changed),
1674 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1675 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1676 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1677 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1678 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1679 cx.observe_window_activation(window, |editor, window, cx| {
1680 let active = window.is_window_active();
1681 editor.blink_manager.update(cx, |blink_manager, cx| {
1682 if active {
1683 blink_manager.enable(cx);
1684 } else {
1685 blink_manager.disable(cx);
1686 }
1687 });
1688 }),
1689 ],
1690 tasks_update_task: None,
1691 linked_edit_ranges: Default::default(),
1692 in_project_search: false,
1693 previous_search_ranges: None,
1694 breadcrumb_header: None,
1695 focused_block: None,
1696 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1697 addons: HashMap::default(),
1698 registered_buffers: HashMap::default(),
1699 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1700 selection_mark_mode: false,
1701 toggle_fold_multiple_buffers: Task::ready(()),
1702 serialize_selections: Task::ready(()),
1703 serialize_folds: Task::ready(()),
1704 text_style_refinement: None,
1705 load_diff_task: load_uncommitted_diff,
1706 mouse_cursor_hidden: false,
1707 hide_mouse_mode: EditorSettings::get_global(cx)
1708 .hide_mouse
1709 .unwrap_or_default(),
1710 change_list: ChangeList::new(),
1711 };
1712 if let Some(breakpoints) = this.breakpoint_store.as_ref() {
1713 this._subscriptions
1714 .push(cx.observe(breakpoints, |_, _, cx| {
1715 cx.notify();
1716 }));
1717 }
1718 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1719 this._subscriptions.extend(project_subscriptions);
1720
1721 this._subscriptions.push(cx.subscribe_in(
1722 &cx.entity(),
1723 window,
1724 |editor, _, e: &EditorEvent, window, cx| match e {
1725 EditorEvent::ScrollPositionChanged { local, .. } => {
1726 if *local {
1727 let new_anchor = editor.scroll_manager.anchor();
1728 let snapshot = editor.snapshot(window, cx);
1729 editor.update_restoration_data(cx, move |data| {
1730 data.scroll_position = (
1731 new_anchor.top_row(&snapshot.buffer_snapshot),
1732 new_anchor.offset,
1733 );
1734 });
1735 editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
1736 }
1737 }
1738 EditorEvent::Edited { .. } => {
1739 if !vim_enabled(cx) {
1740 let (map, selections) = editor.selections.all_adjusted_display(cx);
1741 let pop_state = editor
1742 .change_list
1743 .last()
1744 .map(|previous| {
1745 previous.len() == selections.len()
1746 && previous.iter().enumerate().all(|(ix, p)| {
1747 p.to_display_point(&map).row()
1748 == selections[ix].head().row()
1749 })
1750 })
1751 .unwrap_or(false);
1752 let new_positions = selections
1753 .into_iter()
1754 .map(|s| map.display_point_to_anchor(s.head(), Bias::Left))
1755 .collect();
1756 editor
1757 .change_list
1758 .push_to_change_list(pop_state, new_positions);
1759 }
1760 }
1761 _ => (),
1762 },
1763 ));
1764
1765 this.end_selection(window, cx);
1766 this.scroll_manager.show_scrollbars(window, cx);
1767 jsx_tag_auto_close::refresh_enabled_in_any_buffer(&mut this, &buffer, cx);
1768
1769 if mode.is_full() {
1770 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1771 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1772
1773 if this.git_blame_inline_enabled {
1774 this.git_blame_inline_enabled = true;
1775 this.start_git_blame_inline(false, window, cx);
1776 }
1777
1778 this.go_to_active_debug_line(window, cx);
1779
1780 if let Some(buffer) = buffer.read(cx).as_singleton() {
1781 if let Some(project) = this.project.as_ref() {
1782 let handle = project.update(cx, |project, cx| {
1783 project.register_buffer_with_language_servers(&buffer, cx)
1784 });
1785 this.registered_buffers
1786 .insert(buffer.read(cx).remote_id(), handle);
1787 }
1788 }
1789 }
1790
1791 this.report_editor_event("Editor Opened", None, cx);
1792 this
1793 }
1794
1795 pub fn deploy_mouse_context_menu(
1796 &mut self,
1797 position: gpui::Point<Pixels>,
1798 context_menu: Entity<ContextMenu>,
1799 window: &mut Window,
1800 cx: &mut Context<Self>,
1801 ) {
1802 self.mouse_context_menu = Some(MouseContextMenu::new(
1803 self,
1804 crate::mouse_context_menu::MenuPosition::PinnedToScreen(position),
1805 context_menu,
1806 window,
1807 cx,
1808 ));
1809 }
1810
1811 pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
1812 self.mouse_context_menu
1813 .as_ref()
1814 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1815 }
1816
1817 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1818 self.key_context_internal(self.has_active_inline_completion(), window, cx)
1819 }
1820
1821 fn key_context_internal(
1822 &self,
1823 has_active_edit_prediction: bool,
1824 window: &Window,
1825 cx: &App,
1826 ) -> KeyContext {
1827 let mut key_context = KeyContext::new_with_defaults();
1828 key_context.add("Editor");
1829 let mode = match self.mode {
1830 EditorMode::SingleLine { .. } => "single_line",
1831 EditorMode::AutoHeight { .. } => "auto_height",
1832 EditorMode::Full { .. } => "full",
1833 };
1834
1835 if EditorSettings::jupyter_enabled(cx) {
1836 key_context.add("jupyter");
1837 }
1838
1839 key_context.set("mode", mode);
1840 if self.pending_rename.is_some() {
1841 key_context.add("renaming");
1842 }
1843
1844 match self.context_menu.borrow().as_ref() {
1845 Some(CodeContextMenu::Completions(_)) => {
1846 key_context.add("menu");
1847 key_context.add("showing_completions");
1848 }
1849 Some(CodeContextMenu::CodeActions(_)) => {
1850 key_context.add("menu");
1851 key_context.add("showing_code_actions")
1852 }
1853 None => {}
1854 }
1855
1856 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1857 if !self.focus_handle(cx).contains_focused(window, cx)
1858 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1859 {
1860 for addon in self.addons.values() {
1861 addon.extend_key_context(&mut key_context, cx)
1862 }
1863 }
1864
1865 if let Some(singleton_buffer) = self.buffer.read(cx).as_singleton() {
1866 if let Some(extension) = singleton_buffer
1867 .read(cx)
1868 .file()
1869 .and_then(|file| file.path().extension()?.to_str())
1870 {
1871 key_context.set("extension", extension.to_string());
1872 }
1873 } else {
1874 key_context.add("multibuffer");
1875 }
1876
1877 if has_active_edit_prediction {
1878 if self.edit_prediction_in_conflict() {
1879 key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
1880 } else {
1881 key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
1882 key_context.add("copilot_suggestion");
1883 }
1884 }
1885
1886 if self.selection_mark_mode {
1887 key_context.add("selection_mode");
1888 }
1889
1890 key_context
1891 }
1892
1893 pub fn hide_mouse_cursor(&mut self, origin: &HideMouseCursorOrigin) {
1894 self.mouse_cursor_hidden = match origin {
1895 HideMouseCursorOrigin::TypingAction => {
1896 matches!(
1897 self.hide_mouse_mode,
1898 HideMouseMode::OnTyping | HideMouseMode::OnTypingAndMovement
1899 )
1900 }
1901 HideMouseCursorOrigin::MovementAction => {
1902 matches!(self.hide_mouse_mode, HideMouseMode::OnTypingAndMovement)
1903 }
1904 };
1905 }
1906
1907 pub fn edit_prediction_in_conflict(&self) -> bool {
1908 if !self.show_edit_predictions_in_menu() {
1909 return false;
1910 }
1911
1912 let showing_completions = self
1913 .context_menu
1914 .borrow()
1915 .as_ref()
1916 .map_or(false, |context| {
1917 matches!(context, CodeContextMenu::Completions(_))
1918 });
1919
1920 showing_completions
1921 || self.edit_prediction_requires_modifier()
1922 // Require modifier key when the cursor is on leading whitespace, to allow `tab`
1923 // bindings to insert tab characters.
1924 || (self.edit_prediction_requires_modifier_in_indent_conflict && self.edit_prediction_indent_conflict)
1925 }
1926
1927 pub fn accept_edit_prediction_keybind(
1928 &self,
1929 window: &Window,
1930 cx: &App,
1931 ) -> AcceptEditPredictionBinding {
1932 let key_context = self.key_context_internal(true, window, cx);
1933 let in_conflict = self.edit_prediction_in_conflict();
1934
1935 AcceptEditPredictionBinding(
1936 window
1937 .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
1938 .into_iter()
1939 .filter(|binding| {
1940 !in_conflict
1941 || binding
1942 .keystrokes()
1943 .first()
1944 .map_or(false, |keystroke| keystroke.modifiers.modified())
1945 })
1946 .rev()
1947 .min_by_key(|binding| {
1948 binding
1949 .keystrokes()
1950 .first()
1951 .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
1952 }),
1953 )
1954 }
1955
1956 pub fn new_file(
1957 workspace: &mut Workspace,
1958 _: &workspace::NewFile,
1959 window: &mut Window,
1960 cx: &mut Context<Workspace>,
1961 ) {
1962 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1963 "Failed to create buffer",
1964 window,
1965 cx,
1966 |e, _, _| match e.error_code() {
1967 ErrorCode::RemoteUpgradeRequired => Some(format!(
1968 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1969 e.error_tag("required").unwrap_or("the latest version")
1970 )),
1971 _ => None,
1972 },
1973 );
1974 }
1975
1976 pub fn new_in_workspace(
1977 workspace: &mut Workspace,
1978 window: &mut Window,
1979 cx: &mut Context<Workspace>,
1980 ) -> Task<Result<Entity<Editor>>> {
1981 let project = workspace.project().clone();
1982 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1983
1984 cx.spawn_in(window, async move |workspace, cx| {
1985 let buffer = create.await?;
1986 workspace.update_in(cx, |workspace, window, cx| {
1987 let editor =
1988 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1989 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1990 editor
1991 })
1992 })
1993 }
1994
1995 fn new_file_vertical(
1996 workspace: &mut Workspace,
1997 _: &workspace::NewFileSplitVertical,
1998 window: &mut Window,
1999 cx: &mut Context<Workspace>,
2000 ) {
2001 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
2002 }
2003
2004 fn new_file_horizontal(
2005 workspace: &mut Workspace,
2006 _: &workspace::NewFileSplitHorizontal,
2007 window: &mut Window,
2008 cx: &mut Context<Workspace>,
2009 ) {
2010 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
2011 }
2012
2013 fn new_file_in_direction(
2014 workspace: &mut Workspace,
2015 direction: SplitDirection,
2016 window: &mut Window,
2017 cx: &mut Context<Workspace>,
2018 ) {
2019 let project = workspace.project().clone();
2020 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2021
2022 cx.spawn_in(window, async move |workspace, cx| {
2023 let buffer = create.await?;
2024 workspace.update_in(cx, move |workspace, window, cx| {
2025 workspace.split_item(
2026 direction,
2027 Box::new(
2028 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
2029 ),
2030 window,
2031 cx,
2032 )
2033 })?;
2034 anyhow::Ok(())
2035 })
2036 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
2037 match e.error_code() {
2038 ErrorCode::RemoteUpgradeRequired => Some(format!(
2039 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2040 e.error_tag("required").unwrap_or("the latest version")
2041 )),
2042 _ => None,
2043 }
2044 });
2045 }
2046
2047 pub fn leader_peer_id(&self) -> Option<PeerId> {
2048 self.leader_peer_id
2049 }
2050
2051 pub fn buffer(&self) -> &Entity<MultiBuffer> {
2052 &self.buffer
2053 }
2054
2055 pub fn workspace(&self) -> Option<Entity<Workspace>> {
2056 self.workspace.as_ref()?.0.upgrade()
2057 }
2058
2059 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
2060 self.buffer().read(cx).title(cx)
2061 }
2062
2063 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
2064 let git_blame_gutter_max_author_length = self
2065 .render_git_blame_gutter(cx)
2066 .then(|| {
2067 if let Some(blame) = self.blame.as_ref() {
2068 let max_author_length =
2069 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2070 Some(max_author_length)
2071 } else {
2072 None
2073 }
2074 })
2075 .flatten();
2076
2077 EditorSnapshot {
2078 mode: self.mode,
2079 show_gutter: self.show_gutter,
2080 show_line_numbers: self.show_line_numbers,
2081 show_git_diff_gutter: self.show_git_diff_gutter,
2082 show_code_actions: self.show_code_actions,
2083 show_runnables: self.show_runnables,
2084 show_breakpoints: self.show_breakpoints,
2085 git_blame_gutter_max_author_length,
2086 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2087 scroll_anchor: self.scroll_manager.anchor(),
2088 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2089 placeholder_text: self.placeholder_text.clone(),
2090 is_focused: self.focus_handle.is_focused(window),
2091 current_line_highlight: self
2092 .current_line_highlight
2093 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2094 gutter_hovered: self.gutter_hovered,
2095 }
2096 }
2097
2098 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
2099 self.buffer.read(cx).language_at(point, cx)
2100 }
2101
2102 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
2103 self.buffer.read(cx).read(cx).file_at(point).cloned()
2104 }
2105
2106 pub fn active_excerpt(
2107 &self,
2108 cx: &App,
2109 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
2110 self.buffer
2111 .read(cx)
2112 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2113 }
2114
2115 pub fn mode(&self) -> EditorMode {
2116 self.mode
2117 }
2118
2119 pub fn set_mode(&mut self, mode: EditorMode) {
2120 self.mode = mode;
2121 }
2122
2123 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2124 self.collaboration_hub.as_deref()
2125 }
2126
2127 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2128 self.collaboration_hub = Some(hub);
2129 }
2130
2131 pub fn set_in_project_search(&mut self, in_project_search: bool) {
2132 self.in_project_search = in_project_search;
2133 }
2134
2135 pub fn set_custom_context_menu(
2136 &mut self,
2137 f: impl 'static
2138 + Fn(
2139 &mut Self,
2140 DisplayPoint,
2141 &mut Window,
2142 &mut Context<Self>,
2143 ) -> Option<Entity<ui::ContextMenu>>,
2144 ) {
2145 self.custom_context_menu = Some(Box::new(f))
2146 }
2147
2148 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2149 self.completion_provider = provider;
2150 }
2151
2152 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2153 self.semantics_provider.clone()
2154 }
2155
2156 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2157 self.semantics_provider = provider;
2158 }
2159
2160 pub fn set_edit_prediction_provider<T>(
2161 &mut self,
2162 provider: Option<Entity<T>>,
2163 window: &mut Window,
2164 cx: &mut Context<Self>,
2165 ) where
2166 T: EditPredictionProvider,
2167 {
2168 self.edit_prediction_provider =
2169 provider.map(|provider| RegisteredInlineCompletionProvider {
2170 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
2171 if this.focus_handle.is_focused(window) {
2172 this.update_visible_inline_completion(window, cx);
2173 }
2174 }),
2175 provider: Arc::new(provider),
2176 });
2177 self.update_edit_prediction_settings(cx);
2178 self.refresh_inline_completion(false, false, window, cx);
2179 }
2180
2181 pub fn placeholder_text(&self) -> Option<&str> {
2182 self.placeholder_text.as_deref()
2183 }
2184
2185 pub fn set_placeholder_text(
2186 &mut self,
2187 placeholder_text: impl Into<Arc<str>>,
2188 cx: &mut Context<Self>,
2189 ) {
2190 let placeholder_text = Some(placeholder_text.into());
2191 if self.placeholder_text != placeholder_text {
2192 self.placeholder_text = placeholder_text;
2193 cx.notify();
2194 }
2195 }
2196
2197 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
2198 self.cursor_shape = cursor_shape;
2199
2200 // Disrupt blink for immediate user feedback that the cursor shape has changed
2201 self.blink_manager.update(cx, BlinkManager::show_cursor);
2202
2203 cx.notify();
2204 }
2205
2206 pub fn set_current_line_highlight(
2207 &mut self,
2208 current_line_highlight: Option<CurrentLineHighlight>,
2209 ) {
2210 self.current_line_highlight = current_line_highlight;
2211 }
2212
2213 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2214 self.collapse_matches = collapse_matches;
2215 }
2216
2217 fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
2218 let buffers = self.buffer.read(cx).all_buffers();
2219 let Some(project) = self.project.as_ref() else {
2220 return;
2221 };
2222 project.update(cx, |project, cx| {
2223 for buffer in buffers {
2224 self.registered_buffers
2225 .entry(buffer.read(cx).remote_id())
2226 .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
2227 }
2228 })
2229 }
2230
2231 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2232 if self.collapse_matches {
2233 return range.start..range.start;
2234 }
2235 range.clone()
2236 }
2237
2238 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
2239 if self.display_map.read(cx).clip_at_line_ends != clip {
2240 self.display_map
2241 .update(cx, |map, _| map.clip_at_line_ends = clip);
2242 }
2243 }
2244
2245 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2246 self.input_enabled = input_enabled;
2247 }
2248
2249 pub fn set_inline_completions_hidden_for_vim_mode(
2250 &mut self,
2251 hidden: bool,
2252 window: &mut Window,
2253 cx: &mut Context<Self>,
2254 ) {
2255 if hidden != self.inline_completions_hidden_for_vim_mode {
2256 self.inline_completions_hidden_for_vim_mode = hidden;
2257 if hidden {
2258 self.update_visible_inline_completion(window, cx);
2259 } else {
2260 self.refresh_inline_completion(true, false, window, cx);
2261 }
2262 }
2263 }
2264
2265 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
2266 self.menu_inline_completions_policy = value;
2267 }
2268
2269 pub fn set_autoindent(&mut self, autoindent: bool) {
2270 if autoindent {
2271 self.autoindent_mode = Some(AutoindentMode::EachLine);
2272 } else {
2273 self.autoindent_mode = None;
2274 }
2275 }
2276
2277 pub fn read_only(&self, cx: &App) -> bool {
2278 self.read_only || self.buffer.read(cx).read_only()
2279 }
2280
2281 pub fn set_read_only(&mut self, read_only: bool) {
2282 self.read_only = read_only;
2283 }
2284
2285 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2286 self.use_autoclose = autoclose;
2287 }
2288
2289 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2290 self.use_auto_surround = auto_surround;
2291 }
2292
2293 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2294 self.auto_replace_emoji_shortcode = auto_replace;
2295 }
2296
2297 pub fn toggle_edit_predictions(
2298 &mut self,
2299 _: &ToggleEditPrediction,
2300 window: &mut Window,
2301 cx: &mut Context<Self>,
2302 ) {
2303 if self.show_inline_completions_override.is_some() {
2304 self.set_show_edit_predictions(None, window, cx);
2305 } else {
2306 let show_edit_predictions = !self.edit_predictions_enabled();
2307 self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
2308 }
2309 }
2310
2311 pub fn set_show_edit_predictions(
2312 &mut self,
2313 show_edit_predictions: Option<bool>,
2314 window: &mut Window,
2315 cx: &mut Context<Self>,
2316 ) {
2317 self.show_inline_completions_override = show_edit_predictions;
2318 self.update_edit_prediction_settings(cx);
2319
2320 if let Some(false) = show_edit_predictions {
2321 self.discard_inline_completion(false, cx);
2322 } else {
2323 self.refresh_inline_completion(false, true, window, cx);
2324 }
2325 }
2326
2327 fn inline_completions_disabled_in_scope(
2328 &self,
2329 buffer: &Entity<Buffer>,
2330 buffer_position: language::Anchor,
2331 cx: &App,
2332 ) -> bool {
2333 let snapshot = buffer.read(cx).snapshot();
2334 let settings = snapshot.settings_at(buffer_position, cx);
2335
2336 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
2337 return false;
2338 };
2339
2340 scope.override_name().map_or(false, |scope_name| {
2341 settings
2342 .edit_predictions_disabled_in
2343 .iter()
2344 .any(|s| s == scope_name)
2345 })
2346 }
2347
2348 pub fn set_use_modal_editing(&mut self, to: bool) {
2349 self.use_modal_editing = to;
2350 }
2351
2352 pub fn use_modal_editing(&self) -> bool {
2353 self.use_modal_editing
2354 }
2355
2356 fn selections_did_change(
2357 &mut self,
2358 local: bool,
2359 old_cursor_position: &Anchor,
2360 show_completions: bool,
2361 window: &mut Window,
2362 cx: &mut Context<Self>,
2363 ) {
2364 window.invalidate_character_coordinates();
2365
2366 // Copy selections to primary selection buffer
2367 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
2368 if local {
2369 let selections = self.selections.all::<usize>(cx);
2370 let buffer_handle = self.buffer.read(cx).read(cx);
2371
2372 let mut text = String::new();
2373 for (index, selection) in selections.iter().enumerate() {
2374 let text_for_selection = buffer_handle
2375 .text_for_range(selection.start..selection.end)
2376 .collect::<String>();
2377
2378 text.push_str(&text_for_selection);
2379 if index != selections.len() - 1 {
2380 text.push('\n');
2381 }
2382 }
2383
2384 if !text.is_empty() {
2385 cx.write_to_primary(ClipboardItem::new_string(text));
2386 }
2387 }
2388
2389 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
2390 self.buffer.update(cx, |buffer, cx| {
2391 buffer.set_active_selections(
2392 &self.selections.disjoint_anchors(),
2393 self.selections.line_mode,
2394 self.cursor_shape,
2395 cx,
2396 )
2397 });
2398 }
2399 let display_map = self
2400 .display_map
2401 .update(cx, |display_map, cx| display_map.snapshot(cx));
2402 let buffer = &display_map.buffer_snapshot;
2403 self.add_selections_state = None;
2404 self.select_next_state = None;
2405 self.select_prev_state = None;
2406 self.select_syntax_node_history.try_clear();
2407 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2408 self.snippet_stack
2409 .invalidate(&self.selections.disjoint_anchors(), buffer);
2410 self.take_rename(false, window, cx);
2411
2412 let new_cursor_position = self.selections.newest_anchor().head();
2413
2414 self.push_to_nav_history(
2415 *old_cursor_position,
2416 Some(new_cursor_position.to_point(buffer)),
2417 false,
2418 cx,
2419 );
2420
2421 if local {
2422 let new_cursor_position = self.selections.newest_anchor().head();
2423 let mut context_menu = self.context_menu.borrow_mut();
2424 let completion_menu = match context_menu.as_ref() {
2425 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2426 _ => {
2427 *context_menu = None;
2428 None
2429 }
2430 };
2431 if let Some(buffer_id) = new_cursor_position.buffer_id {
2432 if !self.registered_buffers.contains_key(&buffer_id) {
2433 if let Some(project) = self.project.as_ref() {
2434 project.update(cx, |project, cx| {
2435 let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
2436 return;
2437 };
2438 self.registered_buffers.insert(
2439 buffer_id,
2440 project.register_buffer_with_language_servers(&buffer, cx),
2441 );
2442 })
2443 }
2444 }
2445 }
2446
2447 if let Some(completion_menu) = completion_menu {
2448 let cursor_position = new_cursor_position.to_offset(buffer);
2449 let (word_range, kind) =
2450 buffer.surrounding_word(completion_menu.initial_position, true);
2451 if kind == Some(CharKind::Word)
2452 && word_range.to_inclusive().contains(&cursor_position)
2453 {
2454 let mut completion_menu = completion_menu.clone();
2455 drop(context_menu);
2456
2457 let query = Self::completion_query(buffer, cursor_position);
2458 cx.spawn(async move |this, cx| {
2459 completion_menu
2460 .filter(query.as_deref(), cx.background_executor().clone())
2461 .await;
2462
2463 this.update(cx, |this, cx| {
2464 let mut context_menu = this.context_menu.borrow_mut();
2465 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2466 else {
2467 return;
2468 };
2469
2470 if menu.id > completion_menu.id {
2471 return;
2472 }
2473
2474 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2475 drop(context_menu);
2476 cx.notify();
2477 })
2478 })
2479 .detach();
2480
2481 if show_completions {
2482 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2483 }
2484 } else {
2485 drop(context_menu);
2486 self.hide_context_menu(window, cx);
2487 }
2488 } else {
2489 drop(context_menu);
2490 }
2491
2492 hide_hover(self, cx);
2493
2494 if old_cursor_position.to_display_point(&display_map).row()
2495 != new_cursor_position.to_display_point(&display_map).row()
2496 {
2497 self.available_code_actions.take();
2498 }
2499 self.refresh_code_actions(window, cx);
2500 self.refresh_document_highlights(cx);
2501 self.refresh_selected_text_highlights(window, cx);
2502 refresh_matching_bracket_highlights(self, window, cx);
2503 self.update_visible_inline_completion(window, cx);
2504 self.edit_prediction_requires_modifier_in_indent_conflict = true;
2505 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2506 if self.git_blame_inline_enabled {
2507 self.start_inline_blame_timer(window, cx);
2508 }
2509 }
2510
2511 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2512 cx.emit(EditorEvent::SelectionsChanged { local });
2513
2514 let selections = &self.selections.disjoint;
2515 if selections.len() == 1 {
2516 cx.emit(SearchEvent::ActiveMatchChanged)
2517 }
2518 if local {
2519 if let Some((_, _, buffer_snapshot)) = buffer.as_singleton() {
2520 let inmemory_selections = selections
2521 .iter()
2522 .map(|s| {
2523 text::ToPoint::to_point(&s.range().start.text_anchor, buffer_snapshot)
2524 ..text::ToPoint::to_point(&s.range().end.text_anchor, buffer_snapshot)
2525 })
2526 .collect();
2527 self.update_restoration_data(cx, |data| {
2528 data.selections = inmemory_selections;
2529 });
2530
2531 if WorkspaceSettings::get(None, cx).restore_on_startup
2532 != RestoreOnStartupBehavior::None
2533 {
2534 if let Some(workspace_id) =
2535 self.workspace.as_ref().and_then(|workspace| workspace.1)
2536 {
2537 let snapshot = self.buffer().read(cx).snapshot(cx);
2538 let selections = selections.clone();
2539 let background_executor = cx.background_executor().clone();
2540 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2541 self.serialize_selections = cx.background_spawn(async move {
2542 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2543 let db_selections = selections
2544 .iter()
2545 .map(|selection| {
2546 (
2547 selection.start.to_offset(&snapshot),
2548 selection.end.to_offset(&snapshot),
2549 )
2550 })
2551 .collect();
2552
2553 DB.save_editor_selections(editor_id, workspace_id, db_selections)
2554 .await
2555 .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
2556 .log_err();
2557 });
2558 }
2559 }
2560 }
2561 }
2562
2563 cx.notify();
2564 }
2565
2566 fn folds_did_change(&mut self, cx: &mut Context<Self>) {
2567 use text::ToOffset as _;
2568 use text::ToPoint as _;
2569
2570 if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
2571 return;
2572 }
2573
2574 let Some(singleton) = self.buffer().read(cx).as_singleton() else {
2575 return;
2576 };
2577
2578 let snapshot = singleton.read(cx).snapshot();
2579 let inmemory_folds = self.display_map.update(cx, |display_map, cx| {
2580 let display_snapshot = display_map.snapshot(cx);
2581
2582 display_snapshot
2583 .folds_in_range(0..display_snapshot.buffer_snapshot.len())
2584 .map(|fold| {
2585 fold.range.start.text_anchor.to_point(&snapshot)
2586 ..fold.range.end.text_anchor.to_point(&snapshot)
2587 })
2588 .collect()
2589 });
2590 self.update_restoration_data(cx, |data| {
2591 data.folds = inmemory_folds;
2592 });
2593
2594 let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) else {
2595 return;
2596 };
2597 let background_executor = cx.background_executor().clone();
2598 let editor_id = cx.entity().entity_id().as_u64() as ItemId;
2599 let db_folds = self.display_map.update(cx, |display_map, cx| {
2600 display_map
2601 .snapshot(cx)
2602 .folds_in_range(0..snapshot.len())
2603 .map(|fold| {
2604 (
2605 fold.range.start.text_anchor.to_offset(&snapshot),
2606 fold.range.end.text_anchor.to_offset(&snapshot),
2607 )
2608 })
2609 .collect()
2610 });
2611 self.serialize_folds = cx.background_spawn(async move {
2612 background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
2613 DB.save_editor_folds(editor_id, workspace_id, db_folds)
2614 .await
2615 .with_context(|| {
2616 format!(
2617 "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
2618 )
2619 })
2620 .log_err();
2621 });
2622 }
2623
2624 pub fn sync_selections(
2625 &mut self,
2626 other: Entity<Editor>,
2627 cx: &mut Context<Self>,
2628 ) -> gpui::Subscription {
2629 let other_selections = other.read(cx).selections.disjoint.to_vec();
2630 self.selections.change_with(cx, |selections| {
2631 selections.select_anchors(other_selections);
2632 });
2633
2634 let other_subscription =
2635 cx.subscribe(&other, |this, other, other_evt, cx| match other_evt {
2636 EditorEvent::SelectionsChanged { local: true } => {
2637 let other_selections = other.read(cx).selections.disjoint.to_vec();
2638 if other_selections.is_empty() {
2639 return;
2640 }
2641 this.selections.change_with(cx, |selections| {
2642 selections.select_anchors(other_selections);
2643 });
2644 }
2645 _ => {}
2646 });
2647
2648 let this_subscription =
2649 cx.subscribe_self::<EditorEvent>(move |this, this_evt, cx| match this_evt {
2650 EditorEvent::SelectionsChanged { local: true } => {
2651 let these_selections = this.selections.disjoint.to_vec();
2652 if these_selections.is_empty() {
2653 return;
2654 }
2655 other.update(cx, |other_editor, cx| {
2656 other_editor.selections.change_with(cx, |selections| {
2657 selections.select_anchors(these_selections);
2658 })
2659 });
2660 }
2661 _ => {}
2662 });
2663
2664 Subscription::join(other_subscription, this_subscription)
2665 }
2666
2667 pub fn change_selections<R>(
2668 &mut self,
2669 autoscroll: Option<Autoscroll>,
2670 window: &mut Window,
2671 cx: &mut Context<Self>,
2672 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2673 ) -> R {
2674 self.change_selections_inner(autoscroll, true, window, cx, change)
2675 }
2676
2677 fn change_selections_inner<R>(
2678 &mut self,
2679 autoscroll: Option<Autoscroll>,
2680 request_completions: bool,
2681 window: &mut Window,
2682 cx: &mut Context<Self>,
2683 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2684 ) -> R {
2685 let old_cursor_position = self.selections.newest_anchor().head();
2686 self.push_to_selection_history();
2687
2688 let (changed, result) = self.selections.change_with(cx, change);
2689
2690 if changed {
2691 if let Some(autoscroll) = autoscroll {
2692 self.request_autoscroll(autoscroll, cx);
2693 }
2694 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2695
2696 if self.should_open_signature_help_automatically(
2697 &old_cursor_position,
2698 self.signature_help_state.backspace_pressed(),
2699 cx,
2700 ) {
2701 self.show_signature_help(&ShowSignatureHelp, window, cx);
2702 }
2703 self.signature_help_state.set_backspace_pressed(false);
2704 }
2705
2706 result
2707 }
2708
2709 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2710 where
2711 I: IntoIterator<Item = (Range<S>, T)>,
2712 S: ToOffset,
2713 T: Into<Arc<str>>,
2714 {
2715 if self.read_only(cx) {
2716 return;
2717 }
2718
2719 self.buffer
2720 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2721 }
2722
2723 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2724 where
2725 I: IntoIterator<Item = (Range<S>, T)>,
2726 S: ToOffset,
2727 T: Into<Arc<str>>,
2728 {
2729 if self.read_only(cx) {
2730 return;
2731 }
2732
2733 self.buffer.update(cx, |buffer, cx| {
2734 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2735 });
2736 }
2737
2738 pub fn edit_with_block_indent<I, S, T>(
2739 &mut self,
2740 edits: I,
2741 original_indent_columns: Vec<Option<u32>>,
2742 cx: &mut Context<Self>,
2743 ) where
2744 I: IntoIterator<Item = (Range<S>, T)>,
2745 S: ToOffset,
2746 T: Into<Arc<str>>,
2747 {
2748 if self.read_only(cx) {
2749 return;
2750 }
2751
2752 self.buffer.update(cx, |buffer, cx| {
2753 buffer.edit(
2754 edits,
2755 Some(AutoindentMode::Block {
2756 original_indent_columns,
2757 }),
2758 cx,
2759 )
2760 });
2761 }
2762
2763 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2764 self.hide_context_menu(window, cx);
2765
2766 match phase {
2767 SelectPhase::Begin {
2768 position,
2769 add,
2770 click_count,
2771 } => self.begin_selection(position, add, click_count, window, cx),
2772 SelectPhase::BeginColumnar {
2773 position,
2774 goal_column,
2775 reset,
2776 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2777 SelectPhase::Extend {
2778 position,
2779 click_count,
2780 } => self.extend_selection(position, click_count, window, cx),
2781 SelectPhase::Update {
2782 position,
2783 goal_column,
2784 scroll_delta,
2785 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2786 SelectPhase::End => self.end_selection(window, cx),
2787 }
2788 }
2789
2790 fn extend_selection(
2791 &mut self,
2792 position: DisplayPoint,
2793 click_count: usize,
2794 window: &mut Window,
2795 cx: &mut Context<Self>,
2796 ) {
2797 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2798 let tail = self.selections.newest::<usize>(cx).tail();
2799 self.begin_selection(position, false, click_count, window, cx);
2800
2801 let position = position.to_offset(&display_map, Bias::Left);
2802 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2803
2804 let mut pending_selection = self
2805 .selections
2806 .pending_anchor()
2807 .expect("extend_selection not called with pending selection");
2808 if position >= tail {
2809 pending_selection.start = tail_anchor;
2810 } else {
2811 pending_selection.end = tail_anchor;
2812 pending_selection.reversed = true;
2813 }
2814
2815 let mut pending_mode = self.selections.pending_mode().unwrap();
2816 match &mut pending_mode {
2817 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2818 _ => {}
2819 }
2820
2821 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2822 s.set_pending(pending_selection, pending_mode)
2823 });
2824 }
2825
2826 fn begin_selection(
2827 &mut self,
2828 position: DisplayPoint,
2829 add: bool,
2830 click_count: usize,
2831 window: &mut Window,
2832 cx: &mut Context<Self>,
2833 ) {
2834 if !self.focus_handle.is_focused(window) {
2835 self.last_focused_descendant = None;
2836 window.focus(&self.focus_handle);
2837 }
2838
2839 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2840 let buffer = &display_map.buffer_snapshot;
2841 let newest_selection = self.selections.newest_anchor().clone();
2842 let position = display_map.clip_point(position, Bias::Left);
2843
2844 let start;
2845 let end;
2846 let mode;
2847 let mut auto_scroll;
2848 match click_count {
2849 1 => {
2850 start = buffer.anchor_before(position.to_point(&display_map));
2851 end = start;
2852 mode = SelectMode::Character;
2853 auto_scroll = true;
2854 }
2855 2 => {
2856 let range = movement::surrounding_word(&display_map, position);
2857 start = buffer.anchor_before(range.start.to_point(&display_map));
2858 end = buffer.anchor_before(range.end.to_point(&display_map));
2859 mode = SelectMode::Word(start..end);
2860 auto_scroll = true;
2861 }
2862 3 => {
2863 let position = display_map
2864 .clip_point(position, Bias::Left)
2865 .to_point(&display_map);
2866 let line_start = display_map.prev_line_boundary(position).0;
2867 let next_line_start = buffer.clip_point(
2868 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2869 Bias::Left,
2870 );
2871 start = buffer.anchor_before(line_start);
2872 end = buffer.anchor_before(next_line_start);
2873 mode = SelectMode::Line(start..end);
2874 auto_scroll = true;
2875 }
2876 _ => {
2877 start = buffer.anchor_before(0);
2878 end = buffer.anchor_before(buffer.len());
2879 mode = SelectMode::All;
2880 auto_scroll = false;
2881 }
2882 }
2883 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2884
2885 let point_to_delete: Option<usize> = {
2886 let selected_points: Vec<Selection<Point>> =
2887 self.selections.disjoint_in_range(start..end, cx);
2888
2889 if !add || click_count > 1 {
2890 None
2891 } else if !selected_points.is_empty() {
2892 Some(selected_points[0].id)
2893 } else {
2894 let clicked_point_already_selected =
2895 self.selections.disjoint.iter().find(|selection| {
2896 selection.start.to_point(buffer) == start.to_point(buffer)
2897 || selection.end.to_point(buffer) == end.to_point(buffer)
2898 });
2899
2900 clicked_point_already_selected.map(|selection| selection.id)
2901 }
2902 };
2903
2904 let selections_count = self.selections.count();
2905
2906 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2907 if let Some(point_to_delete) = point_to_delete {
2908 s.delete(point_to_delete);
2909
2910 if selections_count == 1 {
2911 s.set_pending_anchor_range(start..end, mode);
2912 }
2913 } else {
2914 if !add {
2915 s.clear_disjoint();
2916 } else if click_count > 1 {
2917 s.delete(newest_selection.id)
2918 }
2919
2920 s.set_pending_anchor_range(start..end, mode);
2921 }
2922 });
2923 }
2924
2925 fn begin_columnar_selection(
2926 &mut self,
2927 position: DisplayPoint,
2928 goal_column: u32,
2929 reset: bool,
2930 window: &mut Window,
2931 cx: &mut Context<Self>,
2932 ) {
2933 if !self.focus_handle.is_focused(window) {
2934 self.last_focused_descendant = None;
2935 window.focus(&self.focus_handle);
2936 }
2937
2938 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2939
2940 if reset {
2941 let pointer_position = display_map
2942 .buffer_snapshot
2943 .anchor_before(position.to_point(&display_map));
2944
2945 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2946 s.clear_disjoint();
2947 s.set_pending_anchor_range(
2948 pointer_position..pointer_position,
2949 SelectMode::Character,
2950 );
2951 });
2952 }
2953
2954 let tail = self.selections.newest::<Point>(cx).tail();
2955 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2956
2957 if !reset {
2958 self.select_columns(
2959 tail.to_display_point(&display_map),
2960 position,
2961 goal_column,
2962 &display_map,
2963 window,
2964 cx,
2965 );
2966 }
2967 }
2968
2969 fn update_selection(
2970 &mut self,
2971 position: DisplayPoint,
2972 goal_column: u32,
2973 scroll_delta: gpui::Point<f32>,
2974 window: &mut Window,
2975 cx: &mut Context<Self>,
2976 ) {
2977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2978
2979 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2980 let tail = tail.to_display_point(&display_map);
2981 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2982 } else if let Some(mut pending) = self.selections.pending_anchor() {
2983 let buffer = self.buffer.read(cx).snapshot(cx);
2984 let head;
2985 let tail;
2986 let mode = self.selections.pending_mode().unwrap();
2987 match &mode {
2988 SelectMode::Character => {
2989 head = position.to_point(&display_map);
2990 tail = pending.tail().to_point(&buffer);
2991 }
2992 SelectMode::Word(original_range) => {
2993 let original_display_range = original_range.start.to_display_point(&display_map)
2994 ..original_range.end.to_display_point(&display_map);
2995 let original_buffer_range = original_display_range.start.to_point(&display_map)
2996 ..original_display_range.end.to_point(&display_map);
2997 if movement::is_inside_word(&display_map, position)
2998 || original_display_range.contains(&position)
2999 {
3000 let word_range = movement::surrounding_word(&display_map, position);
3001 if word_range.start < original_display_range.start {
3002 head = word_range.start.to_point(&display_map);
3003 } else {
3004 head = word_range.end.to_point(&display_map);
3005 }
3006 } else {
3007 head = position.to_point(&display_map);
3008 }
3009
3010 if head <= original_buffer_range.start {
3011 tail = original_buffer_range.end;
3012 } else {
3013 tail = original_buffer_range.start;
3014 }
3015 }
3016 SelectMode::Line(original_range) => {
3017 let original_range = original_range.to_point(&display_map.buffer_snapshot);
3018
3019 let position = display_map
3020 .clip_point(position, Bias::Left)
3021 .to_point(&display_map);
3022 let line_start = display_map.prev_line_boundary(position).0;
3023 let next_line_start = buffer.clip_point(
3024 display_map.next_line_boundary(position).0 + Point::new(1, 0),
3025 Bias::Left,
3026 );
3027
3028 if line_start < original_range.start {
3029 head = line_start
3030 } else {
3031 head = next_line_start
3032 }
3033
3034 if head <= original_range.start {
3035 tail = original_range.end;
3036 } else {
3037 tail = original_range.start;
3038 }
3039 }
3040 SelectMode::All => {
3041 return;
3042 }
3043 };
3044
3045 if head < tail {
3046 pending.start = buffer.anchor_before(head);
3047 pending.end = buffer.anchor_before(tail);
3048 pending.reversed = true;
3049 } else {
3050 pending.start = buffer.anchor_before(tail);
3051 pending.end = buffer.anchor_before(head);
3052 pending.reversed = false;
3053 }
3054
3055 self.change_selections(None, window, cx, |s| {
3056 s.set_pending(pending, mode);
3057 });
3058 } else {
3059 log::error!("update_selection dispatched with no pending selection");
3060 return;
3061 }
3062
3063 self.apply_scroll_delta(scroll_delta, window, cx);
3064 cx.notify();
3065 }
3066
3067 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3068 self.columnar_selection_tail.take();
3069 if self.selections.pending_anchor().is_some() {
3070 let selections = self.selections.all::<usize>(cx);
3071 self.change_selections(None, window, cx, |s| {
3072 s.select(selections);
3073 s.clear_pending();
3074 });
3075 }
3076 }
3077
3078 fn select_columns(
3079 &mut self,
3080 tail: DisplayPoint,
3081 head: DisplayPoint,
3082 goal_column: u32,
3083 display_map: &DisplaySnapshot,
3084 window: &mut Window,
3085 cx: &mut Context<Self>,
3086 ) {
3087 let start_row = cmp::min(tail.row(), head.row());
3088 let end_row = cmp::max(tail.row(), head.row());
3089 let start_column = cmp::min(tail.column(), goal_column);
3090 let end_column = cmp::max(tail.column(), goal_column);
3091 let reversed = start_column < tail.column();
3092
3093 let selection_ranges = (start_row.0..=end_row.0)
3094 .map(DisplayRow)
3095 .filter_map(|row| {
3096 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3097 let start = display_map
3098 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3099 .to_point(display_map);
3100 let end = display_map
3101 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3102 .to_point(display_map);
3103 if reversed {
3104 Some(end..start)
3105 } else {
3106 Some(start..end)
3107 }
3108 } else {
3109 None
3110 }
3111 })
3112 .collect::<Vec<_>>();
3113
3114 self.change_selections(None, window, cx, |s| {
3115 s.select_ranges(selection_ranges);
3116 });
3117 cx.notify();
3118 }
3119
3120 pub fn has_non_empty_selection(&self, cx: &mut App) -> bool {
3121 self.selections
3122 .all_adjusted(cx)
3123 .iter()
3124 .any(|selection| !selection.is_empty())
3125 }
3126
3127 pub fn has_pending_nonempty_selection(&self) -> bool {
3128 let pending_nonempty_selection = match self.selections.pending_anchor() {
3129 Some(Selection { start, end, .. }) => start != end,
3130 None => false,
3131 };
3132
3133 pending_nonempty_selection
3134 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3135 }
3136
3137 pub fn has_pending_selection(&self) -> bool {
3138 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3139 }
3140
3141 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
3142 self.selection_mark_mode = false;
3143
3144 if self.clear_expanded_diff_hunks(cx) {
3145 cx.notify();
3146 return;
3147 }
3148 if self.dismiss_menus_and_popups(true, window, cx) {
3149 return;
3150 }
3151
3152 if self.mode.is_full()
3153 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
3154 {
3155 return;
3156 }
3157
3158 cx.propagate();
3159 }
3160
3161 pub fn dismiss_menus_and_popups(
3162 &mut self,
3163 is_user_requested: bool,
3164 window: &mut Window,
3165 cx: &mut Context<Self>,
3166 ) -> bool {
3167 if self.take_rename(false, window, cx).is_some() {
3168 return true;
3169 }
3170
3171 if hide_hover(self, cx) {
3172 return true;
3173 }
3174
3175 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3176 return true;
3177 }
3178
3179 if self.hide_context_menu(window, cx).is_some() {
3180 return true;
3181 }
3182
3183 if self.mouse_context_menu.take().is_some() {
3184 return true;
3185 }
3186
3187 if is_user_requested && self.discard_inline_completion(true, cx) {
3188 return true;
3189 }
3190
3191 if self.snippet_stack.pop().is_some() {
3192 return true;
3193 }
3194
3195 if self.mode.is_full() && matches!(self.active_diagnostics, ActiveDiagnostic::Group(_)) {
3196 self.dismiss_diagnostics(cx);
3197 return true;
3198 }
3199
3200 false
3201 }
3202
3203 fn linked_editing_ranges_for(
3204 &self,
3205 selection: Range<text::Anchor>,
3206 cx: &App,
3207 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
3208 if self.linked_edit_ranges.is_empty() {
3209 return None;
3210 }
3211 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3212 selection.end.buffer_id.and_then(|end_buffer_id| {
3213 if selection.start.buffer_id != Some(end_buffer_id) {
3214 return None;
3215 }
3216 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3217 let snapshot = buffer.read(cx).snapshot();
3218 self.linked_edit_ranges
3219 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3220 .map(|ranges| (ranges, snapshot, buffer))
3221 })?;
3222 use text::ToOffset as TO;
3223 // find offset from the start of current range to current cursor position
3224 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3225
3226 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3227 let start_difference = start_offset - start_byte_offset;
3228 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3229 let end_difference = end_offset - start_byte_offset;
3230 // Current range has associated linked ranges.
3231 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3232 for range in linked_ranges.iter() {
3233 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3234 let end_offset = start_offset + end_difference;
3235 let start_offset = start_offset + start_difference;
3236 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3237 continue;
3238 }
3239 if self.selections.disjoint_anchor_ranges().any(|s| {
3240 if s.start.buffer_id != selection.start.buffer_id
3241 || s.end.buffer_id != selection.end.buffer_id
3242 {
3243 return false;
3244 }
3245 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3246 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3247 }) {
3248 continue;
3249 }
3250 let start = buffer_snapshot.anchor_after(start_offset);
3251 let end = buffer_snapshot.anchor_after(end_offset);
3252 linked_edits
3253 .entry(buffer.clone())
3254 .or_default()
3255 .push(start..end);
3256 }
3257 Some(linked_edits)
3258 }
3259
3260 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3261 let text: Arc<str> = text.into();
3262
3263 if self.read_only(cx) {
3264 return;
3265 }
3266
3267 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3268
3269 let selections = self.selections.all_adjusted(cx);
3270 let mut bracket_inserted = false;
3271 let mut edits = Vec::new();
3272 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3273 let mut new_selections = Vec::with_capacity(selections.len());
3274 let mut new_autoclose_regions = Vec::new();
3275 let snapshot = self.buffer.read(cx).read(cx);
3276 let mut clear_linked_edit_ranges = false;
3277
3278 for (selection, autoclose_region) in
3279 self.selections_with_autoclose_regions(selections, &snapshot)
3280 {
3281 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3282 // Determine if the inserted text matches the opening or closing
3283 // bracket of any of this language's bracket pairs.
3284 let mut bracket_pair = None;
3285 let mut is_bracket_pair_start = false;
3286 let mut is_bracket_pair_end = false;
3287 if !text.is_empty() {
3288 let mut bracket_pair_matching_end = None;
3289 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3290 // and they are removing the character that triggered IME popup.
3291 for (pair, enabled) in scope.brackets() {
3292 if !pair.close && !pair.surround {
3293 continue;
3294 }
3295
3296 if enabled && pair.start.ends_with(text.as_ref()) {
3297 let prefix_len = pair.start.len() - text.len();
3298 let preceding_text_matches_prefix = prefix_len == 0
3299 || (selection.start.column >= (prefix_len as u32)
3300 && snapshot.contains_str_at(
3301 Point::new(
3302 selection.start.row,
3303 selection.start.column - (prefix_len as u32),
3304 ),
3305 &pair.start[..prefix_len],
3306 ));
3307 if preceding_text_matches_prefix {
3308 bracket_pair = Some(pair.clone());
3309 is_bracket_pair_start = true;
3310 break;
3311 }
3312 }
3313 if pair.end.as_str() == text.as_ref() && bracket_pair_matching_end.is_none()
3314 {
3315 // take first bracket pair matching end, but don't break in case a later bracket
3316 // pair matches start
3317 bracket_pair_matching_end = Some(pair.clone());
3318 }
3319 }
3320 if bracket_pair.is_none() && bracket_pair_matching_end.is_some() {
3321 bracket_pair = Some(bracket_pair_matching_end.unwrap());
3322 is_bracket_pair_end = true;
3323 }
3324 }
3325
3326 if let Some(bracket_pair) = bracket_pair {
3327 let snapshot_settings = snapshot.language_settings_at(selection.start, cx);
3328 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3329 let auto_surround =
3330 self.use_auto_surround && snapshot_settings.use_auto_surround;
3331 if selection.is_empty() {
3332 if is_bracket_pair_start {
3333 // If the inserted text is a suffix of an opening bracket and the
3334 // selection is preceded by the rest of the opening bracket, then
3335 // insert the closing bracket.
3336 let following_text_allows_autoclose = snapshot
3337 .chars_at(selection.start)
3338 .next()
3339 .map_or(true, |c| scope.should_autoclose_before(c));
3340
3341 let preceding_text_allows_autoclose = selection.start.column == 0
3342 || snapshot.reversed_chars_at(selection.start).next().map_or(
3343 true,
3344 |c| {
3345 bracket_pair.start != bracket_pair.end
3346 || !snapshot
3347 .char_classifier_at(selection.start)
3348 .is_word(c)
3349 },
3350 );
3351
3352 let is_closing_quote = if bracket_pair.end == bracket_pair.start
3353 && bracket_pair.start.len() == 1
3354 {
3355 let target = bracket_pair.start.chars().next().unwrap();
3356 let current_line_count = snapshot
3357 .reversed_chars_at(selection.start)
3358 .take_while(|&c| c != '\n')
3359 .filter(|&c| c == target)
3360 .count();
3361 current_line_count % 2 == 1
3362 } else {
3363 false
3364 };
3365
3366 if autoclose
3367 && bracket_pair.close
3368 && following_text_allows_autoclose
3369 && preceding_text_allows_autoclose
3370 && !is_closing_quote
3371 {
3372 let anchor = snapshot.anchor_before(selection.end);
3373 new_selections.push((selection.map(|_| anchor), text.len()));
3374 new_autoclose_regions.push((
3375 anchor,
3376 text.len(),
3377 selection.id,
3378 bracket_pair.clone(),
3379 ));
3380 edits.push((
3381 selection.range(),
3382 format!("{}{}", text, bracket_pair.end).into(),
3383 ));
3384 bracket_inserted = true;
3385 continue;
3386 }
3387 }
3388
3389 if let Some(region) = autoclose_region {
3390 // If the selection is followed by an auto-inserted closing bracket,
3391 // then don't insert that closing bracket again; just move the selection
3392 // past the closing bracket.
3393 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3394 && text.as_ref() == region.pair.end.as_str();
3395 if should_skip {
3396 let anchor = snapshot.anchor_after(selection.end);
3397 new_selections
3398 .push((selection.map(|_| anchor), region.pair.end.len()));
3399 continue;
3400 }
3401 }
3402
3403 let always_treat_brackets_as_autoclosed = snapshot
3404 .language_settings_at(selection.start, cx)
3405 .always_treat_brackets_as_autoclosed;
3406 if always_treat_brackets_as_autoclosed
3407 && is_bracket_pair_end
3408 && snapshot.contains_str_at(selection.end, text.as_ref())
3409 {
3410 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3411 // and the inserted text is a closing bracket and the selection is followed
3412 // by the closing bracket then move the selection past the closing bracket.
3413 let anchor = snapshot.anchor_after(selection.end);
3414 new_selections.push((selection.map(|_| anchor), text.len()));
3415 continue;
3416 }
3417 }
3418 // If an opening bracket is 1 character long and is typed while
3419 // text is selected, then surround that text with the bracket pair.
3420 else if auto_surround
3421 && bracket_pair.surround
3422 && is_bracket_pair_start
3423 && bracket_pair.start.chars().count() == 1
3424 {
3425 edits.push((selection.start..selection.start, text.clone()));
3426 edits.push((
3427 selection.end..selection.end,
3428 bracket_pair.end.as_str().into(),
3429 ));
3430 bracket_inserted = true;
3431 new_selections.push((
3432 Selection {
3433 id: selection.id,
3434 start: snapshot.anchor_after(selection.start),
3435 end: snapshot.anchor_before(selection.end),
3436 reversed: selection.reversed,
3437 goal: selection.goal,
3438 },
3439 0,
3440 ));
3441 continue;
3442 }
3443 }
3444 }
3445
3446 if self.auto_replace_emoji_shortcode
3447 && selection.is_empty()
3448 && text.as_ref().ends_with(':')
3449 {
3450 if let Some(possible_emoji_short_code) =
3451 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3452 {
3453 if !possible_emoji_short_code.is_empty() {
3454 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3455 let emoji_shortcode_start = Point::new(
3456 selection.start.row,
3457 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3458 );
3459
3460 // Remove shortcode from buffer
3461 edits.push((
3462 emoji_shortcode_start..selection.start,
3463 "".to_string().into(),
3464 ));
3465 new_selections.push((
3466 Selection {
3467 id: selection.id,
3468 start: snapshot.anchor_after(emoji_shortcode_start),
3469 end: snapshot.anchor_before(selection.start),
3470 reversed: selection.reversed,
3471 goal: selection.goal,
3472 },
3473 0,
3474 ));
3475
3476 // Insert emoji
3477 let selection_start_anchor = snapshot.anchor_after(selection.start);
3478 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3479 edits.push((selection.start..selection.end, emoji.to_string().into()));
3480
3481 continue;
3482 }
3483 }
3484 }
3485 }
3486
3487 // If not handling any auto-close operation, then just replace the selected
3488 // text with the given input and move the selection to the end of the
3489 // newly inserted text.
3490 let anchor = snapshot.anchor_after(selection.end);
3491 if !self.linked_edit_ranges.is_empty() {
3492 let start_anchor = snapshot.anchor_before(selection.start);
3493
3494 let is_word_char = text.chars().next().map_or(true, |char| {
3495 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3496 classifier.is_word(char)
3497 });
3498
3499 if is_word_char {
3500 if let Some(ranges) = self
3501 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3502 {
3503 for (buffer, edits) in ranges {
3504 linked_edits
3505 .entry(buffer.clone())
3506 .or_default()
3507 .extend(edits.into_iter().map(|range| (range, text.clone())));
3508 }
3509 }
3510 } else {
3511 clear_linked_edit_ranges = true;
3512 }
3513 }
3514
3515 new_selections.push((selection.map(|_| anchor), 0));
3516 edits.push((selection.start..selection.end, text.clone()));
3517 }
3518
3519 drop(snapshot);
3520
3521 self.transact(window, cx, |this, window, cx| {
3522 if clear_linked_edit_ranges {
3523 this.linked_edit_ranges.clear();
3524 }
3525 let initial_buffer_versions =
3526 jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
3527
3528 this.buffer.update(cx, |buffer, cx| {
3529 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3530 });
3531 for (buffer, edits) in linked_edits {
3532 buffer.update(cx, |buffer, cx| {
3533 let snapshot = buffer.snapshot();
3534 let edits = edits
3535 .into_iter()
3536 .map(|(range, text)| {
3537 use text::ToPoint as TP;
3538 let end_point = TP::to_point(&range.end, &snapshot);
3539 let start_point = TP::to_point(&range.start, &snapshot);
3540 (start_point..end_point, text)
3541 })
3542 .sorted_by_key(|(range, _)| range.start);
3543 buffer.edit(edits, None, cx);
3544 })
3545 }
3546 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3547 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3548 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
3549 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
3550 .zip(new_selection_deltas)
3551 .map(|(selection, delta)| Selection {
3552 id: selection.id,
3553 start: selection.start + delta,
3554 end: selection.end + delta,
3555 reversed: selection.reversed,
3556 goal: SelectionGoal::None,
3557 })
3558 .collect::<Vec<_>>();
3559
3560 let mut i = 0;
3561 for (position, delta, selection_id, pair) in new_autoclose_regions {
3562 let position = position.to_offset(&map.buffer_snapshot) + delta;
3563 let start = map.buffer_snapshot.anchor_before(position);
3564 let end = map.buffer_snapshot.anchor_after(position);
3565 while let Some(existing_state) = this.autoclose_regions.get(i) {
3566 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
3567 Ordering::Less => i += 1,
3568 Ordering::Greater => break,
3569 Ordering::Equal => {
3570 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
3571 Ordering::Less => i += 1,
3572 Ordering::Equal => break,
3573 Ordering::Greater => break,
3574 }
3575 }
3576 }
3577 }
3578 this.autoclose_regions.insert(
3579 i,
3580 AutocloseRegion {
3581 selection_id,
3582 range: start..end,
3583 pair,
3584 },
3585 );
3586 }
3587
3588 let had_active_inline_completion = this.has_active_inline_completion();
3589 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
3590 s.select(new_selections)
3591 });
3592
3593 if !bracket_inserted {
3594 if let Some(on_type_format_task) =
3595 this.trigger_on_type_formatting(text.to_string(), window, cx)
3596 {
3597 on_type_format_task.detach_and_log_err(cx);
3598 }
3599 }
3600
3601 let editor_settings = EditorSettings::get_global(cx);
3602 if bracket_inserted
3603 && (editor_settings.auto_signature_help
3604 || editor_settings.show_signature_help_after_edits)
3605 {
3606 this.show_signature_help(&ShowSignatureHelp, window, cx);
3607 }
3608
3609 let trigger_in_words =
3610 this.show_edit_predictions_in_menu() || !had_active_inline_completion;
3611 if this.hard_wrap.is_some() {
3612 let latest: Range<Point> = this.selections.newest(cx).range();
3613 if latest.is_empty()
3614 && this
3615 .buffer()
3616 .read(cx)
3617 .snapshot(cx)
3618 .line_len(MultiBufferRow(latest.start.row))
3619 == latest.start.column
3620 {
3621 this.rewrap_impl(
3622 RewrapOptions {
3623 override_language_settings: true,
3624 preserve_existing_whitespace: true,
3625 },
3626 cx,
3627 )
3628 }
3629 }
3630 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3631 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3632 this.refresh_inline_completion(true, false, window, cx);
3633 jsx_tag_auto_close::handle_from(this, initial_buffer_versions, window, cx);
3634 });
3635 }
3636
3637 fn find_possible_emoji_shortcode_at_position(
3638 snapshot: &MultiBufferSnapshot,
3639 position: Point,
3640 ) -> Option<String> {
3641 let mut chars = Vec::new();
3642 let mut found_colon = false;
3643 for char in snapshot.reversed_chars_at(position).take(100) {
3644 // Found a possible emoji shortcode in the middle of the buffer
3645 if found_colon {
3646 if char.is_whitespace() {
3647 chars.reverse();
3648 return Some(chars.iter().collect());
3649 }
3650 // If the previous character is not a whitespace, we are in the middle of a word
3651 // and we only want to complete the shortcode if the word is made up of other emojis
3652 let mut containing_word = String::new();
3653 for ch in snapshot
3654 .reversed_chars_at(position)
3655 .skip(chars.len() + 1)
3656 .take(100)
3657 {
3658 if ch.is_whitespace() {
3659 break;
3660 }
3661 containing_word.push(ch);
3662 }
3663 let containing_word = containing_word.chars().rev().collect::<String>();
3664 if util::word_consists_of_emojis(containing_word.as_str()) {
3665 chars.reverse();
3666 return Some(chars.iter().collect());
3667 }
3668 }
3669
3670 if char.is_whitespace() || !char.is_ascii() {
3671 return None;
3672 }
3673 if char == ':' {
3674 found_colon = true;
3675 } else {
3676 chars.push(char);
3677 }
3678 }
3679 // Found a possible emoji shortcode at the beginning of the buffer
3680 chars.reverse();
3681 Some(chars.iter().collect())
3682 }
3683
3684 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3685 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3686 self.transact(window, cx, |this, window, cx| {
3687 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3688 let selections = this.selections.all::<usize>(cx);
3689 let multi_buffer = this.buffer.read(cx);
3690 let buffer = multi_buffer.snapshot(cx);
3691 selections
3692 .iter()
3693 .map(|selection| {
3694 let start_point = selection.start.to_point(&buffer);
3695 let mut indent =
3696 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3697 indent.len = cmp::min(indent.len, start_point.column);
3698 let start = selection.start;
3699 let end = selection.end;
3700 let selection_is_empty = start == end;
3701 let language_scope = buffer.language_scope_at(start);
3702 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3703 &language_scope
3704 {
3705 let insert_extra_newline =
3706 insert_extra_newline_brackets(&buffer, start..end, language)
3707 || insert_extra_newline_tree_sitter(&buffer, start..end);
3708
3709 // Comment extension on newline is allowed only for cursor selections
3710 let comment_delimiter = maybe!({
3711 if !selection_is_empty {
3712 return None;
3713 }
3714
3715 if !multi_buffer.language_settings(cx).extend_comment_on_newline {
3716 return None;
3717 }
3718
3719 let delimiters = language.line_comment_prefixes();
3720 let max_len_of_delimiter =
3721 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3722 let (snapshot, range) =
3723 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3724
3725 let mut index_of_first_non_whitespace = 0;
3726 let comment_candidate = snapshot
3727 .chars_for_range(range)
3728 .skip_while(|c| {
3729 let should_skip = c.is_whitespace();
3730 if should_skip {
3731 index_of_first_non_whitespace += 1;
3732 }
3733 should_skip
3734 })
3735 .take(max_len_of_delimiter)
3736 .collect::<String>();
3737 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3738 comment_candidate.starts_with(comment_prefix.as_ref())
3739 })?;
3740 let cursor_is_placed_after_comment_marker =
3741 index_of_first_non_whitespace + comment_prefix.len()
3742 <= start_point.column as usize;
3743 if cursor_is_placed_after_comment_marker {
3744 Some(comment_prefix.clone())
3745 } else {
3746 None
3747 }
3748 });
3749 (comment_delimiter, insert_extra_newline)
3750 } else {
3751 (None, false)
3752 };
3753
3754 let capacity_for_delimiter = comment_delimiter
3755 .as_deref()
3756 .map(str::len)
3757 .unwrap_or_default();
3758 let mut new_text =
3759 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3760 new_text.push('\n');
3761 new_text.extend(indent.chars());
3762 if let Some(delimiter) = &comment_delimiter {
3763 new_text.push_str(delimiter);
3764 }
3765 if insert_extra_newline {
3766 new_text = new_text.repeat(2);
3767 }
3768
3769 let anchor = buffer.anchor_after(end);
3770 let new_selection = selection.map(|_| anchor);
3771 (
3772 (start..end, new_text),
3773 (insert_extra_newline, new_selection),
3774 )
3775 })
3776 .unzip()
3777 };
3778
3779 this.edit_with_autoindent(edits, cx);
3780 let buffer = this.buffer.read(cx).snapshot(cx);
3781 let new_selections = selection_fixup_info
3782 .into_iter()
3783 .map(|(extra_newline_inserted, new_selection)| {
3784 let mut cursor = new_selection.end.to_point(&buffer);
3785 if extra_newline_inserted {
3786 cursor.row -= 1;
3787 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3788 }
3789 new_selection.map(|_| cursor)
3790 })
3791 .collect();
3792
3793 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3794 s.select(new_selections)
3795 });
3796 this.refresh_inline_completion(true, false, window, cx);
3797 });
3798 }
3799
3800 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3801 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3802
3803 let buffer = self.buffer.read(cx);
3804 let snapshot = buffer.snapshot(cx);
3805
3806 let mut edits = Vec::new();
3807 let mut rows = Vec::new();
3808
3809 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3810 let cursor = selection.head();
3811 let row = cursor.row;
3812
3813 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3814
3815 let newline = "\n".to_string();
3816 edits.push((start_of_line..start_of_line, newline));
3817
3818 rows.push(row + rows_inserted as u32);
3819 }
3820
3821 self.transact(window, cx, |editor, window, cx| {
3822 editor.edit(edits, cx);
3823
3824 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3825 let mut index = 0;
3826 s.move_cursors_with(|map, _, _| {
3827 let row = rows[index];
3828 index += 1;
3829
3830 let point = Point::new(row, 0);
3831 let boundary = map.next_line_boundary(point).1;
3832 let clipped = map.clip_point(boundary, Bias::Left);
3833
3834 (clipped, SelectionGoal::None)
3835 });
3836 });
3837
3838 let mut indent_edits = Vec::new();
3839 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3840 for row in rows {
3841 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3842 for (row, indent) in indents {
3843 if indent.len == 0 {
3844 continue;
3845 }
3846
3847 let text = match indent.kind {
3848 IndentKind::Space => " ".repeat(indent.len as usize),
3849 IndentKind::Tab => "\t".repeat(indent.len as usize),
3850 };
3851 let point = Point::new(row.0, 0);
3852 indent_edits.push((point..point, text));
3853 }
3854 }
3855 editor.edit(indent_edits, cx);
3856 });
3857 }
3858
3859 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3860 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
3861
3862 let buffer = self.buffer.read(cx);
3863 let snapshot = buffer.snapshot(cx);
3864
3865 let mut edits = Vec::new();
3866 let mut rows = Vec::new();
3867 let mut rows_inserted = 0;
3868
3869 for selection in self.selections.all_adjusted(cx) {
3870 let cursor = selection.head();
3871 let row = cursor.row;
3872
3873 let point = Point::new(row + 1, 0);
3874 let start_of_line = snapshot.clip_point(point, Bias::Left);
3875
3876 let newline = "\n".to_string();
3877 edits.push((start_of_line..start_of_line, newline));
3878
3879 rows_inserted += 1;
3880 rows.push(row + rows_inserted);
3881 }
3882
3883 self.transact(window, cx, |editor, window, cx| {
3884 editor.edit(edits, cx);
3885
3886 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3887 let mut index = 0;
3888 s.move_cursors_with(|map, _, _| {
3889 let row = rows[index];
3890 index += 1;
3891
3892 let point = Point::new(row, 0);
3893 let boundary = map.next_line_boundary(point).1;
3894 let clipped = map.clip_point(boundary, Bias::Left);
3895
3896 (clipped, SelectionGoal::None)
3897 });
3898 });
3899
3900 let mut indent_edits = Vec::new();
3901 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3902 for row in rows {
3903 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3904 for (row, indent) in indents {
3905 if indent.len == 0 {
3906 continue;
3907 }
3908
3909 let text = match indent.kind {
3910 IndentKind::Space => " ".repeat(indent.len as usize),
3911 IndentKind::Tab => "\t".repeat(indent.len as usize),
3912 };
3913 let point = Point::new(row.0, 0);
3914 indent_edits.push((point..point, text));
3915 }
3916 }
3917 editor.edit(indent_edits, cx);
3918 });
3919 }
3920
3921 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3922 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3923 original_indent_columns: Vec::new(),
3924 });
3925 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3926 }
3927
3928 fn insert_with_autoindent_mode(
3929 &mut self,
3930 text: &str,
3931 autoindent_mode: Option<AutoindentMode>,
3932 window: &mut Window,
3933 cx: &mut Context<Self>,
3934 ) {
3935 if self.read_only(cx) {
3936 return;
3937 }
3938
3939 let text: Arc<str> = text.into();
3940 self.transact(window, cx, |this, window, cx| {
3941 let old_selections = this.selections.all_adjusted(cx);
3942 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3943 let anchors = {
3944 let snapshot = buffer.read(cx);
3945 old_selections
3946 .iter()
3947 .map(|s| {
3948 let anchor = snapshot.anchor_after(s.head());
3949 s.map(|_| anchor)
3950 })
3951 .collect::<Vec<_>>()
3952 };
3953 buffer.edit(
3954 old_selections
3955 .iter()
3956 .map(|s| (s.start..s.end, text.clone())),
3957 autoindent_mode,
3958 cx,
3959 );
3960 anchors
3961 });
3962
3963 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3964 s.select_anchors(selection_anchors);
3965 });
3966
3967 cx.notify();
3968 });
3969 }
3970
3971 fn trigger_completion_on_input(
3972 &mut self,
3973 text: &str,
3974 trigger_in_words: bool,
3975 window: &mut Window,
3976 cx: &mut Context<Self>,
3977 ) {
3978 let ignore_completion_provider = self
3979 .context_menu
3980 .borrow()
3981 .as_ref()
3982 .map(|menu| match menu {
3983 CodeContextMenu::Completions(completions_menu) => {
3984 completions_menu.ignore_completion_provider
3985 }
3986 CodeContextMenu::CodeActions(_) => false,
3987 })
3988 .unwrap_or(false);
3989
3990 if ignore_completion_provider {
3991 self.show_word_completions(&ShowWordCompletions, window, cx);
3992 } else if self.is_completion_trigger(text, trigger_in_words, cx) {
3993 self.show_completions(
3994 &ShowCompletions {
3995 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3996 },
3997 window,
3998 cx,
3999 );
4000 } else {
4001 self.hide_context_menu(window, cx);
4002 }
4003 }
4004
4005 fn is_completion_trigger(
4006 &self,
4007 text: &str,
4008 trigger_in_words: bool,
4009 cx: &mut Context<Self>,
4010 ) -> bool {
4011 let position = self.selections.newest_anchor().head();
4012 let multibuffer = self.buffer.read(cx);
4013 let Some(buffer) = position
4014 .buffer_id
4015 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
4016 else {
4017 return false;
4018 };
4019
4020 if let Some(completion_provider) = &self.completion_provider {
4021 completion_provider.is_completion_trigger(
4022 &buffer,
4023 position.text_anchor,
4024 text,
4025 trigger_in_words,
4026 cx,
4027 )
4028 } else {
4029 false
4030 }
4031 }
4032
4033 /// If any empty selections is touching the start of its innermost containing autoclose
4034 /// region, expand it to select the brackets.
4035 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4036 let selections = self.selections.all::<usize>(cx);
4037 let buffer = self.buffer.read(cx).read(cx);
4038 let new_selections = self
4039 .selections_with_autoclose_regions(selections, &buffer)
4040 .map(|(mut selection, region)| {
4041 if !selection.is_empty() {
4042 return selection;
4043 }
4044
4045 if let Some(region) = region {
4046 let mut range = region.range.to_offset(&buffer);
4047 if selection.start == range.start && range.start >= region.pair.start.len() {
4048 range.start -= region.pair.start.len();
4049 if buffer.contains_str_at(range.start, ®ion.pair.start)
4050 && buffer.contains_str_at(range.end, ®ion.pair.end)
4051 {
4052 range.end += region.pair.end.len();
4053 selection.start = range.start;
4054 selection.end = range.end;
4055
4056 return selection;
4057 }
4058 }
4059 }
4060
4061 let always_treat_brackets_as_autoclosed = buffer
4062 .language_settings_at(selection.start, cx)
4063 .always_treat_brackets_as_autoclosed;
4064
4065 if !always_treat_brackets_as_autoclosed {
4066 return selection;
4067 }
4068
4069 if let Some(scope) = buffer.language_scope_at(selection.start) {
4070 for (pair, enabled) in scope.brackets() {
4071 if !enabled || !pair.close {
4072 continue;
4073 }
4074
4075 if buffer.contains_str_at(selection.start, &pair.end) {
4076 let pair_start_len = pair.start.len();
4077 if buffer.contains_str_at(
4078 selection.start.saturating_sub(pair_start_len),
4079 &pair.start,
4080 ) {
4081 selection.start -= pair_start_len;
4082 selection.end += pair.end.len();
4083
4084 return selection;
4085 }
4086 }
4087 }
4088 }
4089
4090 selection
4091 })
4092 .collect();
4093
4094 drop(buffer);
4095 self.change_selections(None, window, cx, |selections| {
4096 selections.select(new_selections)
4097 });
4098 }
4099
4100 /// Iterate the given selections, and for each one, find the smallest surrounding
4101 /// autoclose region. This uses the ordering of the selections and the autoclose
4102 /// regions to avoid repeated comparisons.
4103 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
4104 &'a self,
4105 selections: impl IntoIterator<Item = Selection<D>>,
4106 buffer: &'a MultiBufferSnapshot,
4107 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
4108 let mut i = 0;
4109 let mut regions = self.autoclose_regions.as_slice();
4110 selections.into_iter().map(move |selection| {
4111 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
4112
4113 let mut enclosing = None;
4114 while let Some(pair_state) = regions.get(i) {
4115 if pair_state.range.end.to_offset(buffer) < range.start {
4116 regions = ®ions[i + 1..];
4117 i = 0;
4118 } else if pair_state.range.start.to_offset(buffer) > range.end {
4119 break;
4120 } else {
4121 if pair_state.selection_id == selection.id {
4122 enclosing = Some(pair_state);
4123 }
4124 i += 1;
4125 }
4126 }
4127
4128 (selection, enclosing)
4129 })
4130 }
4131
4132 /// Remove any autoclose regions that no longer contain their selection.
4133 fn invalidate_autoclose_regions(
4134 &mut self,
4135 mut selections: &[Selection<Anchor>],
4136 buffer: &MultiBufferSnapshot,
4137 ) {
4138 self.autoclose_regions.retain(|state| {
4139 let mut i = 0;
4140 while let Some(selection) = selections.get(i) {
4141 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4142 selections = &selections[1..];
4143 continue;
4144 }
4145 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4146 break;
4147 }
4148 if selection.id == state.selection_id {
4149 return true;
4150 } else {
4151 i += 1;
4152 }
4153 }
4154 false
4155 });
4156 }
4157
4158 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4159 let offset = position.to_offset(buffer);
4160 let (word_range, kind) = buffer.surrounding_word(offset, true);
4161 if offset > word_range.start && kind == Some(CharKind::Word) {
4162 Some(
4163 buffer
4164 .text_for_range(word_range.start..offset)
4165 .collect::<String>(),
4166 )
4167 } else {
4168 None
4169 }
4170 }
4171
4172 pub fn toggle_inlay_hints(
4173 &mut self,
4174 _: &ToggleInlayHints,
4175 _: &mut Window,
4176 cx: &mut Context<Self>,
4177 ) {
4178 self.refresh_inlay_hints(
4179 InlayHintRefreshReason::Toggle(!self.inlay_hints_enabled()),
4180 cx,
4181 );
4182 }
4183
4184 pub fn inlay_hints_enabled(&self) -> bool {
4185 self.inlay_hint_cache.enabled
4186 }
4187
4188 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
4189 if self.semantics_provider.is_none() || !self.mode.is_full() {
4190 return;
4191 }
4192
4193 let reason_description = reason.description();
4194 let ignore_debounce = matches!(
4195 reason,
4196 InlayHintRefreshReason::SettingsChange(_)
4197 | InlayHintRefreshReason::Toggle(_)
4198 | InlayHintRefreshReason::ExcerptsRemoved(_)
4199 | InlayHintRefreshReason::ModifiersChanged(_)
4200 );
4201 let (invalidate_cache, required_languages) = match reason {
4202 InlayHintRefreshReason::ModifiersChanged(enabled) => {
4203 match self.inlay_hint_cache.modifiers_override(enabled) {
4204 Some(enabled) => {
4205 if enabled {
4206 (InvalidationStrategy::RefreshRequested, None)
4207 } else {
4208 self.splice_inlays(
4209 &self
4210 .visible_inlay_hints(cx)
4211 .iter()
4212 .map(|inlay| inlay.id)
4213 .collect::<Vec<InlayId>>(),
4214 Vec::new(),
4215 cx,
4216 );
4217 return;
4218 }
4219 }
4220 None => return,
4221 }
4222 }
4223 InlayHintRefreshReason::Toggle(enabled) => {
4224 if self.inlay_hint_cache.toggle(enabled) {
4225 if enabled {
4226 (InvalidationStrategy::RefreshRequested, None)
4227 } else {
4228 self.splice_inlays(
4229 &self
4230 .visible_inlay_hints(cx)
4231 .iter()
4232 .map(|inlay| inlay.id)
4233 .collect::<Vec<InlayId>>(),
4234 Vec::new(),
4235 cx,
4236 );
4237 return;
4238 }
4239 } else {
4240 return;
4241 }
4242 }
4243 InlayHintRefreshReason::SettingsChange(new_settings) => {
4244 match self.inlay_hint_cache.update_settings(
4245 &self.buffer,
4246 new_settings,
4247 self.visible_inlay_hints(cx),
4248 cx,
4249 ) {
4250 ControlFlow::Break(Some(InlaySplice {
4251 to_remove,
4252 to_insert,
4253 })) => {
4254 self.splice_inlays(&to_remove, to_insert, cx);
4255 return;
4256 }
4257 ControlFlow::Break(None) => return,
4258 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4259 }
4260 }
4261 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4262 if let Some(InlaySplice {
4263 to_remove,
4264 to_insert,
4265 }) = self.inlay_hint_cache.remove_excerpts(&excerpts_removed)
4266 {
4267 self.splice_inlays(&to_remove, to_insert, cx);
4268 }
4269 self.display_map.update(cx, |display_map, _| {
4270 display_map.remove_inlays_for_excerpts(&excerpts_removed)
4271 });
4272 return;
4273 }
4274 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4275 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4276 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4277 }
4278 InlayHintRefreshReason::RefreshRequested => {
4279 (InvalidationStrategy::RefreshRequested, None)
4280 }
4281 };
4282
4283 if let Some(InlaySplice {
4284 to_remove,
4285 to_insert,
4286 }) = self.inlay_hint_cache.spawn_hint_refresh(
4287 reason_description,
4288 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4289 invalidate_cache,
4290 ignore_debounce,
4291 cx,
4292 ) {
4293 self.splice_inlays(&to_remove, to_insert, cx);
4294 }
4295 }
4296
4297 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
4298 self.display_map
4299 .read(cx)
4300 .current_inlays()
4301 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4302 .cloned()
4303 .collect()
4304 }
4305
4306 pub fn excerpts_for_inlay_hints_query(
4307 &self,
4308 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4309 cx: &mut Context<Editor>,
4310 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
4311 let Some(project) = self.project.as_ref() else {
4312 return HashMap::default();
4313 };
4314 let project = project.read(cx);
4315 let multi_buffer = self.buffer().read(cx);
4316 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4317 let multi_buffer_visible_start = self
4318 .scroll_manager
4319 .anchor()
4320 .anchor
4321 .to_point(&multi_buffer_snapshot);
4322 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4323 multi_buffer_visible_start
4324 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4325 Bias::Left,
4326 );
4327 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4328 multi_buffer_snapshot
4329 .range_to_buffer_ranges(multi_buffer_visible_range)
4330 .into_iter()
4331 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4332 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
4333 let buffer_file = project::File::from_dyn(buffer.file())?;
4334 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4335 let worktree_entry = buffer_worktree
4336 .read(cx)
4337 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4338 if worktree_entry.is_ignored {
4339 return None;
4340 }
4341
4342 let language = buffer.language()?;
4343 if let Some(restrict_to_languages) = restrict_to_languages {
4344 if !restrict_to_languages.contains(language) {
4345 return None;
4346 }
4347 }
4348 Some((
4349 excerpt_id,
4350 (
4351 multi_buffer.buffer(buffer.remote_id()).unwrap(),
4352 buffer.version().clone(),
4353 excerpt_visible_range,
4354 ),
4355 ))
4356 })
4357 .collect()
4358 }
4359
4360 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
4361 TextLayoutDetails {
4362 text_system: window.text_system().clone(),
4363 editor_style: self.style.clone().unwrap(),
4364 rem_size: window.rem_size(),
4365 scroll_anchor: self.scroll_manager.anchor(),
4366 visible_rows: self.visible_line_count(),
4367 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4368 }
4369 }
4370
4371 pub fn splice_inlays(
4372 &self,
4373 to_remove: &[InlayId],
4374 to_insert: Vec<Inlay>,
4375 cx: &mut Context<Self>,
4376 ) {
4377 self.display_map.update(cx, |display_map, cx| {
4378 display_map.splice_inlays(to_remove, to_insert, cx)
4379 });
4380 cx.notify();
4381 }
4382
4383 fn trigger_on_type_formatting(
4384 &self,
4385 input: String,
4386 window: &mut Window,
4387 cx: &mut Context<Self>,
4388 ) -> Option<Task<Result<()>>> {
4389 if input.len() != 1 {
4390 return None;
4391 }
4392
4393 let project = self.project.as_ref()?;
4394 let position = self.selections.newest_anchor().head();
4395 let (buffer, buffer_position) = self
4396 .buffer
4397 .read(cx)
4398 .text_anchor_for_position(position, cx)?;
4399
4400 let settings = language_settings::language_settings(
4401 buffer
4402 .read(cx)
4403 .language_at(buffer_position)
4404 .map(|l| l.name()),
4405 buffer.read(cx).file(),
4406 cx,
4407 );
4408 if !settings.use_on_type_format {
4409 return None;
4410 }
4411
4412 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4413 // hence we do LSP request & edit on host side only — add formats to host's history.
4414 let push_to_lsp_host_history = true;
4415 // If this is not the host, append its history with new edits.
4416 let push_to_client_history = project.read(cx).is_via_collab();
4417
4418 let on_type_formatting = project.update(cx, |project, cx| {
4419 project.on_type_format(
4420 buffer.clone(),
4421 buffer_position,
4422 input,
4423 push_to_lsp_host_history,
4424 cx,
4425 )
4426 });
4427 Some(cx.spawn_in(window, async move |editor, cx| {
4428 if let Some(transaction) = on_type_formatting.await? {
4429 if push_to_client_history {
4430 buffer
4431 .update(cx, |buffer, _| {
4432 buffer.push_transaction(transaction, Instant::now());
4433 buffer.finalize_last_transaction();
4434 })
4435 .ok();
4436 }
4437 editor.update(cx, |editor, cx| {
4438 editor.refresh_document_highlights(cx);
4439 })?;
4440 }
4441 Ok(())
4442 }))
4443 }
4444
4445 pub fn show_word_completions(
4446 &mut self,
4447 _: &ShowWordCompletions,
4448 window: &mut Window,
4449 cx: &mut Context<Self>,
4450 ) {
4451 self.open_completions_menu(true, None, window, cx);
4452 }
4453
4454 pub fn show_completions(
4455 &mut self,
4456 options: &ShowCompletions,
4457 window: &mut Window,
4458 cx: &mut Context<Self>,
4459 ) {
4460 self.open_completions_menu(false, options.trigger.as_deref(), window, cx);
4461 }
4462
4463 fn open_completions_menu(
4464 &mut self,
4465 ignore_completion_provider: bool,
4466 trigger: Option<&str>,
4467 window: &mut Window,
4468 cx: &mut Context<Self>,
4469 ) {
4470 if self.pending_rename.is_some() {
4471 return;
4472 }
4473 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
4474 return;
4475 }
4476
4477 let position = self.selections.newest_anchor().head();
4478 if position.diff_base_anchor.is_some() {
4479 return;
4480 }
4481 let (buffer, buffer_position) =
4482 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4483 output
4484 } else {
4485 return;
4486 };
4487 let buffer_snapshot = buffer.read(cx).snapshot();
4488 let show_completion_documentation = buffer_snapshot
4489 .settings_at(buffer_position, cx)
4490 .show_completion_documentation;
4491
4492 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4493
4494 let trigger_kind = match trigger {
4495 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
4496 CompletionTriggerKind::TRIGGER_CHARACTER
4497 }
4498 _ => CompletionTriggerKind::INVOKED,
4499 };
4500 let completion_context = CompletionContext {
4501 trigger_character: trigger.and_then(|trigger| {
4502 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4503 Some(String::from(trigger))
4504 } else {
4505 None
4506 }
4507 }),
4508 trigger_kind,
4509 };
4510
4511 let (old_range, word_kind) = buffer_snapshot.surrounding_word(buffer_position);
4512 let (old_range, word_to_exclude) = if word_kind == Some(CharKind::Word) {
4513 let word_to_exclude = buffer_snapshot
4514 .text_for_range(old_range.clone())
4515 .collect::<String>();
4516 (
4517 buffer_snapshot.anchor_before(old_range.start)
4518 ..buffer_snapshot.anchor_after(old_range.end),
4519 Some(word_to_exclude),
4520 )
4521 } else {
4522 (buffer_position..buffer_position, None)
4523 };
4524
4525 let completion_settings = language_settings(
4526 buffer_snapshot
4527 .language_at(buffer_position)
4528 .map(|language| language.name()),
4529 buffer_snapshot.file(),
4530 cx,
4531 )
4532 .completions;
4533
4534 // The document can be large, so stay in reasonable bounds when searching for words,
4535 // otherwise completion pop-up might be slow to appear.
4536 const WORD_LOOKUP_ROWS: u32 = 5_000;
4537 let buffer_row = text::ToPoint::to_point(&buffer_position, &buffer_snapshot).row;
4538 let min_word_search = buffer_snapshot.clip_point(
4539 Point::new(buffer_row.saturating_sub(WORD_LOOKUP_ROWS), 0),
4540 Bias::Left,
4541 );
4542 let max_word_search = buffer_snapshot.clip_point(
4543 Point::new(buffer_row + WORD_LOOKUP_ROWS, 0).min(buffer_snapshot.max_point()),
4544 Bias::Right,
4545 );
4546 let word_search_range = buffer_snapshot.point_to_offset(min_word_search)
4547 ..buffer_snapshot.point_to_offset(max_word_search);
4548
4549 let provider = self
4550 .completion_provider
4551 .as_ref()
4552 .filter(|_| !ignore_completion_provider);
4553 let skip_digits = query
4554 .as_ref()
4555 .map_or(true, |query| !query.chars().any(|c| c.is_digit(10)));
4556
4557 let (mut words, provided_completions) = match provider {
4558 Some(provider) => {
4559 let completions = provider.completions(
4560 position.excerpt_id,
4561 &buffer,
4562 buffer_position,
4563 completion_context,
4564 window,
4565 cx,
4566 );
4567
4568 let words = match completion_settings.words {
4569 WordsCompletionMode::Disabled => Task::ready(BTreeMap::default()),
4570 WordsCompletionMode::Enabled | WordsCompletionMode::Fallback => cx
4571 .background_spawn(async move {
4572 buffer_snapshot.words_in_range(WordsQuery {
4573 fuzzy_contents: None,
4574 range: word_search_range,
4575 skip_digits,
4576 })
4577 }),
4578 };
4579
4580 (words, completions)
4581 }
4582 None => (
4583 cx.background_spawn(async move {
4584 buffer_snapshot.words_in_range(WordsQuery {
4585 fuzzy_contents: None,
4586 range: word_search_range,
4587 skip_digits,
4588 })
4589 }),
4590 Task::ready(Ok(None)),
4591 ),
4592 };
4593
4594 let sort_completions = provider
4595 .as_ref()
4596 .map_or(false, |provider| provider.sort_completions());
4597
4598 let filter_completions = provider
4599 .as_ref()
4600 .map_or(true, |provider| provider.filter_completions());
4601
4602 let id = post_inc(&mut self.next_completion_id);
4603 let task = cx.spawn_in(window, async move |editor, cx| {
4604 async move {
4605 editor.update(cx, |this, _| {
4606 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4607 })?;
4608
4609 let mut completions = Vec::new();
4610 if let Some(provided_completions) = provided_completions.await.log_err().flatten() {
4611 completions.extend(provided_completions);
4612 if completion_settings.words == WordsCompletionMode::Fallback {
4613 words = Task::ready(BTreeMap::default());
4614 }
4615 }
4616
4617 let mut words = words.await;
4618 if let Some(word_to_exclude) = &word_to_exclude {
4619 words.remove(word_to_exclude);
4620 }
4621 for lsp_completion in &completions {
4622 words.remove(&lsp_completion.new_text);
4623 }
4624 completions.extend(words.into_iter().map(|(word, word_range)| Completion {
4625 replace_range: old_range.clone(),
4626 new_text: word.clone(),
4627 label: CodeLabel::plain(word, None),
4628 icon_path: None,
4629 documentation: None,
4630 source: CompletionSource::BufferWord {
4631 word_range,
4632 resolved: false,
4633 },
4634 insert_text_mode: Some(InsertTextMode::AS_IS),
4635 confirm: None,
4636 }));
4637
4638 let menu = if completions.is_empty() {
4639 None
4640 } else {
4641 let mut menu = CompletionsMenu::new(
4642 id,
4643 sort_completions,
4644 show_completion_documentation,
4645 ignore_completion_provider,
4646 position,
4647 buffer.clone(),
4648 completions.into(),
4649 );
4650
4651 menu.filter(
4652 if filter_completions {
4653 query.as_deref()
4654 } else {
4655 None
4656 },
4657 cx.background_executor().clone(),
4658 )
4659 .await;
4660
4661 menu.visible().then_some(menu)
4662 };
4663
4664 editor.update_in(cx, |editor, window, cx| {
4665 match editor.context_menu.borrow().as_ref() {
4666 None => {}
4667 Some(CodeContextMenu::Completions(prev_menu)) => {
4668 if prev_menu.id > id {
4669 return;
4670 }
4671 }
4672 _ => return,
4673 }
4674
4675 if editor.focus_handle.is_focused(window) && menu.is_some() {
4676 let mut menu = menu.unwrap();
4677 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
4678
4679 *editor.context_menu.borrow_mut() =
4680 Some(CodeContextMenu::Completions(menu));
4681
4682 if editor.show_edit_predictions_in_menu() {
4683 editor.update_visible_inline_completion(window, cx);
4684 } else {
4685 editor.discard_inline_completion(false, cx);
4686 }
4687
4688 cx.notify();
4689 } else if editor.completion_tasks.len() <= 1 {
4690 // If there are no more completion tasks and the last menu was
4691 // empty, we should hide it.
4692 let was_hidden = editor.hide_context_menu(window, cx).is_none();
4693 // If it was already hidden and we don't show inline
4694 // completions in the menu, we should also show the
4695 // inline-completion when available.
4696 if was_hidden && editor.show_edit_predictions_in_menu() {
4697 editor.update_visible_inline_completion(window, cx);
4698 }
4699 }
4700 })?;
4701
4702 anyhow::Ok(())
4703 }
4704 .log_err()
4705 .await
4706 });
4707
4708 self.completion_tasks.push((id, task));
4709 }
4710
4711 #[cfg(feature = "test-support")]
4712 pub fn current_completions(&self) -> Option<Vec<project::Completion>> {
4713 let menu = self.context_menu.borrow();
4714 if let CodeContextMenu::Completions(menu) = menu.as_ref()? {
4715 let completions = menu.completions.borrow();
4716 Some(completions.to_vec())
4717 } else {
4718 None
4719 }
4720 }
4721
4722 pub fn confirm_completion(
4723 &mut self,
4724 action: &ConfirmCompletion,
4725 window: &mut Window,
4726 cx: &mut Context<Self>,
4727 ) -> Option<Task<Result<()>>> {
4728 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4729 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
4730 }
4731
4732 pub fn confirm_completion_insert(
4733 &mut self,
4734 _: &ConfirmCompletionInsert,
4735 window: &mut Window,
4736 cx: &mut Context<Self>,
4737 ) -> Option<Task<Result<()>>> {
4738 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4739 self.do_completion(None, CompletionIntent::CompleteWithInsert, window, cx)
4740 }
4741
4742 pub fn confirm_completion_replace(
4743 &mut self,
4744 _: &ConfirmCompletionReplace,
4745 window: &mut Window,
4746 cx: &mut Context<Self>,
4747 ) -> Option<Task<Result<()>>> {
4748 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4749 self.do_completion(None, CompletionIntent::CompleteWithReplace, window, cx)
4750 }
4751
4752 pub fn compose_completion(
4753 &mut self,
4754 action: &ComposeCompletion,
4755 window: &mut Window,
4756 cx: &mut Context<Self>,
4757 ) -> Option<Task<Result<()>>> {
4758 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
4759 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
4760 }
4761
4762 fn do_completion(
4763 &mut self,
4764 item_ix: Option<usize>,
4765 intent: CompletionIntent,
4766 window: &mut Window,
4767 cx: &mut Context<Editor>,
4768 ) -> Option<Task<Result<()>>> {
4769 use language::ToOffset as _;
4770
4771 let CodeContextMenu::Completions(completions_menu) = self.hide_context_menu(window, cx)?
4772 else {
4773 return None;
4774 };
4775
4776 let candidate_id = {
4777 let entries = completions_menu.entries.borrow();
4778 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
4779 if self.show_edit_predictions_in_menu() {
4780 self.discard_inline_completion(true, cx);
4781 }
4782 mat.candidate_id
4783 };
4784
4785 let buffer_handle = completions_menu.buffer;
4786 let completion = completions_menu
4787 .completions
4788 .borrow()
4789 .get(candidate_id)?
4790 .clone();
4791 cx.stop_propagation();
4792
4793 let snippet;
4794 let new_text;
4795 if completion.is_snippet() {
4796 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4797 new_text = snippet.as_ref().unwrap().text.clone();
4798 } else {
4799 snippet = None;
4800 new_text = completion.new_text.clone();
4801 };
4802
4803 let replace_range = choose_completion_range(&completion, intent, &buffer_handle, cx);
4804 let buffer = buffer_handle.read(cx);
4805 let snapshot = self.buffer.read(cx).snapshot(cx);
4806 let replace_range_multibuffer = {
4807 let excerpt = snapshot
4808 .excerpt_containing(self.selections.newest_anchor().range())
4809 .unwrap();
4810 let multibuffer_anchor = snapshot
4811 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.start))
4812 .unwrap()
4813 ..snapshot
4814 .anchor_in_excerpt(excerpt.id(), buffer.anchor_before(replace_range.end))
4815 .unwrap();
4816 multibuffer_anchor.start.to_offset(&snapshot)
4817 ..multibuffer_anchor.end.to_offset(&snapshot)
4818 };
4819 let newest_anchor = self.selections.newest_anchor();
4820 if newest_anchor.head().buffer_id != Some(buffer.remote_id()) {
4821 return None;
4822 }
4823
4824 let old_text = buffer
4825 .text_for_range(replace_range.clone())
4826 .collect::<String>();
4827 let lookbehind = newest_anchor
4828 .start
4829 .text_anchor
4830 .to_offset(buffer)
4831 .saturating_sub(replace_range.start);
4832 let lookahead = replace_range
4833 .end
4834 .saturating_sub(newest_anchor.end.text_anchor.to_offset(buffer));
4835 let prefix = &old_text[..old_text.len().saturating_sub(lookahead)];
4836 let suffix = &old_text[lookbehind.min(old_text.len())..];
4837
4838 let selections = self.selections.all::<usize>(cx);
4839 let mut ranges = Vec::new();
4840 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4841
4842 for selection in &selections {
4843 let range = if selection.id == newest_anchor.id {
4844 replace_range_multibuffer.clone()
4845 } else {
4846 let mut range = selection.range();
4847
4848 // if prefix is present, don't duplicate it
4849 if snapshot.contains_str_at(range.start.saturating_sub(lookbehind), prefix) {
4850 range.start = range.start.saturating_sub(lookbehind);
4851
4852 // if suffix is also present, mimic the newest cursor and replace it
4853 if selection.id != newest_anchor.id
4854 && snapshot.contains_str_at(range.end, suffix)
4855 {
4856 range.end += lookahead;
4857 }
4858 }
4859 range
4860 };
4861
4862 ranges.push(range);
4863
4864 if !self.linked_edit_ranges.is_empty() {
4865 let start_anchor = snapshot.anchor_before(selection.head());
4866 let end_anchor = snapshot.anchor_after(selection.tail());
4867 if let Some(ranges) = self
4868 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4869 {
4870 for (buffer, edits) in ranges {
4871 linked_edits
4872 .entry(buffer.clone())
4873 .or_default()
4874 .extend(edits.into_iter().map(|range| (range, new_text.to_owned())));
4875 }
4876 }
4877 }
4878 }
4879
4880 cx.emit(EditorEvent::InputHandled {
4881 utf16_range_to_replace: None,
4882 text: new_text.clone().into(),
4883 });
4884
4885 self.transact(window, cx, |this, window, cx| {
4886 if let Some(mut snippet) = snippet {
4887 snippet.text = new_text.to_string();
4888 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4889 } else {
4890 this.buffer.update(cx, |buffer, cx| {
4891 let auto_indent = match completion.insert_text_mode {
4892 Some(InsertTextMode::AS_IS) => None,
4893 _ => this.autoindent_mode.clone(),
4894 };
4895 let edits = ranges.into_iter().map(|range| (range, new_text.as_str()));
4896 buffer.edit(edits, auto_indent, cx);
4897 });
4898 }
4899 for (buffer, edits) in linked_edits {
4900 buffer.update(cx, |buffer, cx| {
4901 let snapshot = buffer.snapshot();
4902 let edits = edits
4903 .into_iter()
4904 .map(|(range, text)| {
4905 use text::ToPoint as TP;
4906 let end_point = TP::to_point(&range.end, &snapshot);
4907 let start_point = TP::to_point(&range.start, &snapshot);
4908 (start_point..end_point, text)
4909 })
4910 .sorted_by_key(|(range, _)| range.start);
4911 buffer.edit(edits, None, cx);
4912 })
4913 }
4914
4915 this.refresh_inline_completion(true, false, window, cx);
4916 });
4917
4918 let show_new_completions_on_confirm = completion
4919 .confirm
4920 .as_ref()
4921 .map_or(false, |confirm| confirm(intent, window, cx));
4922 if show_new_completions_on_confirm {
4923 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4924 }
4925
4926 let provider = self.completion_provider.as_ref()?;
4927 drop(completion);
4928 let apply_edits = provider.apply_additional_edits_for_completion(
4929 buffer_handle,
4930 completions_menu.completions.clone(),
4931 candidate_id,
4932 true,
4933 cx,
4934 );
4935
4936 let editor_settings = EditorSettings::get_global(cx);
4937 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4938 // After the code completion is finished, users often want to know what signatures are needed.
4939 // so we should automatically call signature_help
4940 self.show_signature_help(&ShowSignatureHelp, window, cx);
4941 }
4942
4943 Some(cx.foreground_executor().spawn(async move {
4944 apply_edits.await?;
4945 Ok(())
4946 }))
4947 }
4948
4949 pub fn toggle_code_actions(
4950 &mut self,
4951 action: &ToggleCodeActions,
4952 window: &mut Window,
4953 cx: &mut Context<Self>,
4954 ) {
4955 let mut context_menu = self.context_menu.borrow_mut();
4956 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4957 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4958 // Toggle if we're selecting the same one
4959 *context_menu = None;
4960 cx.notify();
4961 return;
4962 } else {
4963 // Otherwise, clear it and start a new one
4964 *context_menu = None;
4965 cx.notify();
4966 }
4967 }
4968 drop(context_menu);
4969 let snapshot = self.snapshot(window, cx);
4970 let deployed_from_indicator = action.deployed_from_indicator;
4971 let mut task = self.code_actions_task.take();
4972 let action = action.clone();
4973 cx.spawn_in(window, async move |editor, cx| {
4974 while let Some(prev_task) = task {
4975 prev_task.await.log_err();
4976 task = editor.update(cx, |this, _| this.code_actions_task.take())?;
4977 }
4978
4979 let spawned_test_task = editor.update_in(cx, |editor, window, cx| {
4980 if editor.focus_handle.is_focused(window) {
4981 let multibuffer_point = action
4982 .deployed_from_indicator
4983 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4984 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4985 let (buffer, buffer_row) = snapshot
4986 .buffer_snapshot
4987 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4988 .and_then(|(buffer_snapshot, range)| {
4989 editor
4990 .buffer
4991 .read(cx)
4992 .buffer(buffer_snapshot.remote_id())
4993 .map(|buffer| (buffer, range.start.row))
4994 })?;
4995 let (_, code_actions) = editor
4996 .available_code_actions
4997 .clone()
4998 .and_then(|(location, code_actions)| {
4999 let snapshot = location.buffer.read(cx).snapshot();
5000 let point_range = location.range.to_point(&snapshot);
5001 let point_range = point_range.start.row..=point_range.end.row;
5002 if point_range.contains(&buffer_row) {
5003 Some((location, code_actions))
5004 } else {
5005 None
5006 }
5007 })
5008 .unzip();
5009 let buffer_id = buffer.read(cx).remote_id();
5010 let tasks = editor
5011 .tasks
5012 .get(&(buffer_id, buffer_row))
5013 .map(|t| Arc::new(t.to_owned()));
5014 if tasks.is_none() && code_actions.is_none() {
5015 return None;
5016 }
5017
5018 editor.completion_tasks.clear();
5019 editor.discard_inline_completion(false, cx);
5020 let task_context =
5021 tasks
5022 .as_ref()
5023 .zip(editor.project.clone())
5024 .map(|(tasks, project)| {
5025 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
5026 });
5027
5028 let debugger_flag = cx.has_flag::<Debugger>();
5029
5030 Some(cx.spawn_in(window, async move |editor, cx| {
5031 let task_context = match task_context {
5032 Some(task_context) => task_context.await,
5033 None => None,
5034 };
5035 let resolved_tasks =
5036 tasks
5037 .zip(task_context)
5038 .map(|(tasks, task_context)| ResolvedTasks {
5039 templates: tasks.resolve(&task_context).collect(),
5040 position: snapshot.buffer_snapshot.anchor_before(Point::new(
5041 multibuffer_point.row,
5042 tasks.column,
5043 )),
5044 });
5045 let spawn_straight_away = resolved_tasks.as_ref().map_or(false, |tasks| {
5046 tasks
5047 .templates
5048 .iter()
5049 .filter(|task| {
5050 if matches!(task.1.task_type(), task::TaskType::Debug(_)) {
5051 debugger_flag
5052 } else {
5053 true
5054 }
5055 })
5056 .count()
5057 == 1
5058 }) && code_actions
5059 .as_ref()
5060 .map_or(true, |actions| actions.is_empty());
5061 if let Ok(task) = editor.update_in(cx, |editor, window, cx| {
5062 *editor.context_menu.borrow_mut() =
5063 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
5064 buffer,
5065 actions: CodeActionContents::new(
5066 resolved_tasks,
5067 code_actions,
5068 cx,
5069 ),
5070 selected_item: Default::default(),
5071 scroll_handle: UniformListScrollHandle::default(),
5072 deployed_from_indicator,
5073 }));
5074 if spawn_straight_away {
5075 if let Some(task) = editor.confirm_code_action(
5076 &ConfirmCodeAction { item_ix: Some(0) },
5077 window,
5078 cx,
5079 ) {
5080 cx.notify();
5081 return task;
5082 }
5083 }
5084 cx.notify();
5085 Task::ready(Ok(()))
5086 }) {
5087 task.await
5088 } else {
5089 Ok(())
5090 }
5091 }))
5092 } else {
5093 Some(Task::ready(Ok(())))
5094 }
5095 })?;
5096 if let Some(task) = spawned_test_task {
5097 task.await?;
5098 }
5099
5100 Ok::<_, anyhow::Error>(())
5101 })
5102 .detach_and_log_err(cx);
5103 }
5104
5105 pub fn confirm_code_action(
5106 &mut self,
5107 action: &ConfirmCodeAction,
5108 window: &mut Window,
5109 cx: &mut Context<Self>,
5110 ) -> Option<Task<Result<()>>> {
5111 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
5112
5113 let actions_menu =
5114 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
5115 menu
5116 } else {
5117 return None;
5118 };
5119
5120 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
5121 let action = actions_menu.actions.get(action_ix)?;
5122 let title = action.label();
5123 let buffer = actions_menu.buffer;
5124 let workspace = self.workspace()?;
5125
5126 match action {
5127 CodeActionsItem::Task(task_source_kind, resolved_task) => {
5128 match resolved_task.task_type() {
5129 task::TaskType::Script => workspace.update(cx, |workspace, cx| {
5130 workspace.schedule_resolved_task(
5131 task_source_kind,
5132 resolved_task,
5133 false,
5134 window,
5135 cx,
5136 );
5137
5138 Some(Task::ready(Ok(())))
5139 }),
5140 task::TaskType::Debug(_) => {
5141 workspace.update(cx, |workspace, cx| {
5142 workspace.schedule_debug_task(resolved_task, window, cx);
5143 });
5144 Some(Task::ready(Ok(())))
5145 }
5146 }
5147 }
5148 CodeActionsItem::CodeAction {
5149 excerpt_id,
5150 action,
5151 provider,
5152 } => {
5153 let apply_code_action =
5154 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
5155 let workspace = workspace.downgrade();
5156 Some(cx.spawn_in(window, async move |editor, cx| {
5157 let project_transaction = apply_code_action.await?;
5158 Self::open_project_transaction(
5159 &editor,
5160 workspace,
5161 project_transaction,
5162 title,
5163 cx,
5164 )
5165 .await
5166 }))
5167 }
5168 }
5169 }
5170
5171 pub async fn open_project_transaction(
5172 this: &WeakEntity<Editor>,
5173 workspace: WeakEntity<Workspace>,
5174 transaction: ProjectTransaction,
5175 title: String,
5176 cx: &mut AsyncWindowContext,
5177 ) -> Result<()> {
5178 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
5179 cx.update(|_, cx| {
5180 entries.sort_unstable_by_key(|(buffer, _)| {
5181 buffer.read(cx).file().map(|f| f.path().clone())
5182 });
5183 })?;
5184
5185 // If the project transaction's edits are all contained within this editor, then
5186 // avoid opening a new editor to display them.
5187
5188 if let Some((buffer, transaction)) = entries.first() {
5189 if entries.len() == 1 {
5190 let excerpt = this.update(cx, |editor, cx| {
5191 editor
5192 .buffer()
5193 .read(cx)
5194 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
5195 })?;
5196 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
5197 if excerpted_buffer == *buffer {
5198 let all_edits_within_excerpt = buffer.read_with(cx, |buffer, _| {
5199 let excerpt_range = excerpt_range.to_offset(buffer);
5200 buffer
5201 .edited_ranges_for_transaction::<usize>(transaction)
5202 .all(|range| {
5203 excerpt_range.start <= range.start
5204 && excerpt_range.end >= range.end
5205 })
5206 })?;
5207
5208 if all_edits_within_excerpt {
5209 return Ok(());
5210 }
5211 }
5212 }
5213 }
5214 } else {
5215 return Ok(());
5216 }
5217
5218 let mut ranges_to_highlight = Vec::new();
5219 let excerpt_buffer = cx.new(|cx| {
5220 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
5221 for (buffer_handle, transaction) in &entries {
5222 let edited_ranges = buffer_handle
5223 .read(cx)
5224 .edited_ranges_for_transaction::<Point>(transaction)
5225 .collect::<Vec<_>>();
5226 let (ranges, _) = multibuffer.set_excerpts_for_path(
5227 PathKey::for_buffer(buffer_handle, cx),
5228 buffer_handle.clone(),
5229 edited_ranges,
5230 DEFAULT_MULTIBUFFER_CONTEXT,
5231 cx,
5232 );
5233
5234 ranges_to_highlight.extend(ranges);
5235 }
5236 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
5237 multibuffer
5238 })?;
5239
5240 workspace.update_in(cx, |workspace, window, cx| {
5241 let project = workspace.project().clone();
5242 let editor =
5243 cx.new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), window, cx));
5244 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
5245 editor.update(cx, |editor, cx| {
5246 editor.highlight_background::<Self>(
5247 &ranges_to_highlight,
5248 |theme| theme.editor_highlighted_line_background,
5249 cx,
5250 );
5251 });
5252 })?;
5253
5254 Ok(())
5255 }
5256
5257 pub fn clear_code_action_providers(&mut self) {
5258 self.code_action_providers.clear();
5259 self.available_code_actions.take();
5260 }
5261
5262 pub fn add_code_action_provider(
5263 &mut self,
5264 provider: Rc<dyn CodeActionProvider>,
5265 window: &mut Window,
5266 cx: &mut Context<Self>,
5267 ) {
5268 if self
5269 .code_action_providers
5270 .iter()
5271 .any(|existing_provider| existing_provider.id() == provider.id())
5272 {
5273 return;
5274 }
5275
5276 self.code_action_providers.push(provider);
5277 self.refresh_code_actions(window, cx);
5278 }
5279
5280 pub fn remove_code_action_provider(
5281 &mut self,
5282 id: Arc<str>,
5283 window: &mut Window,
5284 cx: &mut Context<Self>,
5285 ) {
5286 self.code_action_providers
5287 .retain(|provider| provider.id() != id);
5288 self.refresh_code_actions(window, cx);
5289 }
5290
5291 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
5292 let newest_selection = self.selections.newest_anchor().clone();
5293 let newest_selection_adjusted = self.selections.newest_adjusted(cx).clone();
5294 let buffer = self.buffer.read(cx);
5295 if newest_selection.head().diff_base_anchor.is_some() {
5296 return None;
5297 }
5298 let (start_buffer, start) =
5299 buffer.text_anchor_for_position(newest_selection_adjusted.start, cx)?;
5300 let (end_buffer, end) =
5301 buffer.text_anchor_for_position(newest_selection_adjusted.end, cx)?;
5302 if start_buffer != end_buffer {
5303 return None;
5304 }
5305
5306 self.code_actions_task = Some(cx.spawn_in(window, async move |this, cx| {
5307 cx.background_executor()
5308 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
5309 .await;
5310
5311 let (providers, tasks) = this.update_in(cx, |this, window, cx| {
5312 let providers = this.code_action_providers.clone();
5313 let tasks = this
5314 .code_action_providers
5315 .iter()
5316 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
5317 .collect::<Vec<_>>();
5318 (providers, tasks)
5319 })?;
5320
5321 let mut actions = Vec::new();
5322 for (provider, provider_actions) in
5323 providers.into_iter().zip(future::join_all(tasks).await)
5324 {
5325 if let Some(provider_actions) = provider_actions.log_err() {
5326 actions.extend(provider_actions.into_iter().map(|action| {
5327 AvailableCodeAction {
5328 excerpt_id: newest_selection.start.excerpt_id,
5329 action,
5330 provider: provider.clone(),
5331 }
5332 }));
5333 }
5334 }
5335
5336 this.update(cx, |this, cx| {
5337 this.available_code_actions = if actions.is_empty() {
5338 None
5339 } else {
5340 Some((
5341 Location {
5342 buffer: start_buffer,
5343 range: start..end,
5344 },
5345 actions.into(),
5346 ))
5347 };
5348 cx.notify();
5349 })
5350 }));
5351 None
5352 }
5353
5354 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5355 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5356 self.show_git_blame_inline = false;
5357
5358 self.show_git_blame_inline_delay_task =
5359 Some(cx.spawn_in(window, async move |this, cx| {
5360 cx.background_executor().timer(delay).await;
5361
5362 this.update(cx, |this, cx| {
5363 this.show_git_blame_inline = true;
5364 cx.notify();
5365 })
5366 .log_err();
5367 }));
5368 }
5369 }
5370
5371 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
5372 if self.pending_rename.is_some() {
5373 return None;
5374 }
5375
5376 let provider = self.semantics_provider.clone()?;
5377 let buffer = self.buffer.read(cx);
5378 let newest_selection = self.selections.newest_anchor().clone();
5379 let cursor_position = newest_selection.head();
5380 let (cursor_buffer, cursor_buffer_position) =
5381 buffer.text_anchor_for_position(cursor_position, cx)?;
5382 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5383 if cursor_buffer != tail_buffer {
5384 return None;
5385 }
5386 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
5387 self.document_highlights_task = Some(cx.spawn(async move |this, cx| {
5388 cx.background_executor()
5389 .timer(Duration::from_millis(debounce))
5390 .await;
5391
5392 let highlights = if let Some(highlights) = cx
5393 .update(|cx| {
5394 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5395 })
5396 .ok()
5397 .flatten()
5398 {
5399 highlights.await.log_err()
5400 } else {
5401 None
5402 };
5403
5404 if let Some(highlights) = highlights {
5405 this.update(cx, |this, cx| {
5406 if this.pending_rename.is_some() {
5407 return;
5408 }
5409
5410 let buffer_id = cursor_position.buffer_id;
5411 let buffer = this.buffer.read(cx);
5412 if !buffer
5413 .text_anchor_for_position(cursor_position, cx)
5414 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5415 {
5416 return;
5417 }
5418
5419 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5420 let mut write_ranges = Vec::new();
5421 let mut read_ranges = Vec::new();
5422 for highlight in highlights {
5423 for (excerpt_id, excerpt_range) in
5424 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
5425 {
5426 let start = highlight
5427 .range
5428 .start
5429 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5430 let end = highlight
5431 .range
5432 .end
5433 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5434 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5435 continue;
5436 }
5437
5438 let range = Anchor {
5439 buffer_id,
5440 excerpt_id,
5441 text_anchor: start,
5442 diff_base_anchor: None,
5443 }..Anchor {
5444 buffer_id,
5445 excerpt_id,
5446 text_anchor: end,
5447 diff_base_anchor: None,
5448 };
5449 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5450 write_ranges.push(range);
5451 } else {
5452 read_ranges.push(range);
5453 }
5454 }
5455 }
5456
5457 this.highlight_background::<DocumentHighlightRead>(
5458 &read_ranges,
5459 |theme| theme.editor_document_highlight_read_background,
5460 cx,
5461 );
5462 this.highlight_background::<DocumentHighlightWrite>(
5463 &write_ranges,
5464 |theme| theme.editor_document_highlight_write_background,
5465 cx,
5466 );
5467 cx.notify();
5468 })
5469 .log_err();
5470 }
5471 }));
5472 None
5473 }
5474
5475 fn prepare_highlight_query_from_selection(
5476 &mut self,
5477 cx: &mut Context<Editor>,
5478 ) -> Option<(String, Range<Anchor>)> {
5479 if matches!(self.mode, EditorMode::SingleLine { .. }) {
5480 return None;
5481 }
5482 if !EditorSettings::get_global(cx).selection_highlight {
5483 return None;
5484 }
5485 if self.selections.count() != 1 || self.selections.line_mode {
5486 return None;
5487 }
5488 let selection = self.selections.newest::<Point>(cx);
5489 if selection.is_empty() || selection.start.row != selection.end.row {
5490 return None;
5491 }
5492 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5493 let selection_anchor_range = selection.range().to_anchors(&multi_buffer_snapshot);
5494 let query = multi_buffer_snapshot
5495 .text_for_range(selection_anchor_range.clone())
5496 .collect::<String>();
5497 if query.trim().is_empty() {
5498 return None;
5499 }
5500 Some((query, selection_anchor_range))
5501 }
5502
5503 fn update_selection_occurrence_highlights(
5504 &mut self,
5505 query_text: String,
5506 query_range: Range<Anchor>,
5507 multi_buffer_range_to_query: Range<Point>,
5508 use_debounce: bool,
5509 window: &mut Window,
5510 cx: &mut Context<Editor>,
5511 ) -> Task<()> {
5512 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5513 cx.spawn_in(window, async move |editor, cx| {
5514 if use_debounce {
5515 cx.background_executor()
5516 .timer(SELECTION_HIGHLIGHT_DEBOUNCE_TIMEOUT)
5517 .await;
5518 }
5519 let match_task = cx.background_spawn(async move {
5520 let buffer_ranges = multi_buffer_snapshot
5521 .range_to_buffer_ranges(multi_buffer_range_to_query)
5522 .into_iter()
5523 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty());
5524 let mut match_ranges = Vec::new();
5525 for (buffer_snapshot, search_range, excerpt_id) in buffer_ranges {
5526 match_ranges.extend(
5527 project::search::SearchQuery::text(
5528 query_text.clone(),
5529 false,
5530 false,
5531 false,
5532 Default::default(),
5533 Default::default(),
5534 false,
5535 None,
5536 )
5537 .unwrap()
5538 .search(&buffer_snapshot, Some(search_range.clone()))
5539 .await
5540 .into_iter()
5541 .filter_map(|match_range| {
5542 let match_start = buffer_snapshot
5543 .anchor_after(search_range.start + match_range.start);
5544 let match_end =
5545 buffer_snapshot.anchor_before(search_range.start + match_range.end);
5546 let match_anchor_range = Anchor::range_in_buffer(
5547 excerpt_id,
5548 buffer_snapshot.remote_id(),
5549 match_start..match_end,
5550 );
5551 (match_anchor_range != query_range).then_some(match_anchor_range)
5552 }),
5553 );
5554 }
5555 match_ranges
5556 });
5557 let match_ranges = match_task.await;
5558 editor
5559 .update_in(cx, |editor, _, cx| {
5560 editor.clear_background_highlights::<SelectedTextHighlight>(cx);
5561 if !match_ranges.is_empty() {
5562 editor.highlight_background::<SelectedTextHighlight>(
5563 &match_ranges,
5564 |theme| theme.editor_document_highlight_bracket_background,
5565 cx,
5566 )
5567 }
5568 })
5569 .log_err();
5570 })
5571 }
5572
5573 fn refresh_selected_text_highlights(&mut self, window: &mut Window, cx: &mut Context<Editor>) {
5574 let Some((query_text, query_range)) = self.prepare_highlight_query_from_selection(cx)
5575 else {
5576 self.clear_background_highlights::<SelectedTextHighlight>(cx);
5577 self.quick_selection_highlight_task.take();
5578 self.debounced_selection_highlight_task.take();
5579 return;
5580 };
5581 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
5582 if self
5583 .quick_selection_highlight_task
5584 .as_ref()
5585 .map_or(true, |(prev_anchor_range, _)| {
5586 prev_anchor_range != &query_range
5587 })
5588 {
5589 let multi_buffer_visible_start = self
5590 .scroll_manager
5591 .anchor()
5592 .anchor
5593 .to_point(&multi_buffer_snapshot);
5594 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
5595 multi_buffer_visible_start
5596 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
5597 Bias::Left,
5598 );
5599 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
5600 self.quick_selection_highlight_task = Some((
5601 query_range.clone(),
5602 self.update_selection_occurrence_highlights(
5603 query_text.clone(),
5604 query_range.clone(),
5605 multi_buffer_visible_range,
5606 false,
5607 window,
5608 cx,
5609 ),
5610 ));
5611 }
5612 if self
5613 .debounced_selection_highlight_task
5614 .as_ref()
5615 .map_or(true, |(prev_anchor_range, _)| {
5616 prev_anchor_range != &query_range
5617 })
5618 {
5619 let multi_buffer_start = multi_buffer_snapshot
5620 .anchor_before(0)
5621 .to_point(&multi_buffer_snapshot);
5622 let multi_buffer_end = multi_buffer_snapshot
5623 .anchor_after(multi_buffer_snapshot.len())
5624 .to_point(&multi_buffer_snapshot);
5625 let multi_buffer_full_range = multi_buffer_start..multi_buffer_end;
5626 self.debounced_selection_highlight_task = Some((
5627 query_range.clone(),
5628 self.update_selection_occurrence_highlights(
5629 query_text,
5630 query_range,
5631 multi_buffer_full_range,
5632 true,
5633 window,
5634 cx,
5635 ),
5636 ));
5637 }
5638 }
5639
5640 pub fn refresh_inline_completion(
5641 &mut self,
5642 debounce: bool,
5643 user_requested: bool,
5644 window: &mut Window,
5645 cx: &mut Context<Self>,
5646 ) -> Option<()> {
5647 let provider = self.edit_prediction_provider()?;
5648 let cursor = self.selections.newest_anchor().head();
5649 let (buffer, cursor_buffer_position) =
5650 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5651
5652 if !self.edit_predictions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
5653 self.discard_inline_completion(false, cx);
5654 return None;
5655 }
5656
5657 if !user_requested
5658 && (!self.should_show_edit_predictions()
5659 || !self.is_focused(window)
5660 || buffer.read(cx).is_empty())
5661 {
5662 self.discard_inline_completion(false, cx);
5663 return None;
5664 }
5665
5666 self.update_visible_inline_completion(window, cx);
5667 provider.refresh(
5668 self.project.clone(),
5669 buffer,
5670 cursor_buffer_position,
5671 debounce,
5672 cx,
5673 );
5674 Some(())
5675 }
5676
5677 fn show_edit_predictions_in_menu(&self) -> bool {
5678 match self.edit_prediction_settings {
5679 EditPredictionSettings::Disabled => false,
5680 EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
5681 }
5682 }
5683
5684 pub fn edit_predictions_enabled(&self) -> bool {
5685 match self.edit_prediction_settings {
5686 EditPredictionSettings::Disabled => false,
5687 EditPredictionSettings::Enabled { .. } => true,
5688 }
5689 }
5690
5691 fn edit_prediction_requires_modifier(&self) -> bool {
5692 match self.edit_prediction_settings {
5693 EditPredictionSettings::Disabled => false,
5694 EditPredictionSettings::Enabled {
5695 preview_requires_modifier,
5696 ..
5697 } => preview_requires_modifier,
5698 }
5699 }
5700
5701 pub fn update_edit_prediction_settings(&mut self, cx: &mut Context<Self>) {
5702 if self.edit_prediction_provider.is_none() {
5703 self.edit_prediction_settings = EditPredictionSettings::Disabled;
5704 } else {
5705 let selection = self.selections.newest_anchor();
5706 let cursor = selection.head();
5707
5708 if let Some((buffer, cursor_buffer_position)) =
5709 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5710 {
5711 self.edit_prediction_settings =
5712 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
5713 }
5714 }
5715 }
5716
5717 fn edit_prediction_settings_at_position(
5718 &self,
5719 buffer: &Entity<Buffer>,
5720 buffer_position: language::Anchor,
5721 cx: &App,
5722 ) -> EditPredictionSettings {
5723 if !self.mode.is_full()
5724 || !self.show_inline_completions_override.unwrap_or(true)
5725 || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
5726 {
5727 return EditPredictionSettings::Disabled;
5728 }
5729
5730 let buffer = buffer.read(cx);
5731
5732 let file = buffer.file();
5733
5734 if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
5735 return EditPredictionSettings::Disabled;
5736 };
5737
5738 let by_provider = matches!(
5739 self.menu_inline_completions_policy,
5740 MenuInlineCompletionsPolicy::ByProvider
5741 );
5742
5743 let show_in_menu = by_provider
5744 && self
5745 .edit_prediction_provider
5746 .as_ref()
5747 .map_or(false, |provider| {
5748 provider.provider.show_completions_in_menu()
5749 });
5750
5751 let preview_requires_modifier =
5752 all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Subtle;
5753
5754 EditPredictionSettings::Enabled {
5755 show_in_menu,
5756 preview_requires_modifier,
5757 }
5758 }
5759
5760 fn should_show_edit_predictions(&self) -> bool {
5761 self.snippet_stack.is_empty() && self.edit_predictions_enabled()
5762 }
5763
5764 pub fn edit_prediction_preview_is_active(&self) -> bool {
5765 matches!(
5766 self.edit_prediction_preview,
5767 EditPredictionPreview::Active { .. }
5768 )
5769 }
5770
5771 pub fn edit_predictions_enabled_at_cursor(&self, cx: &App) -> bool {
5772 let cursor = self.selections.newest_anchor().head();
5773 if let Some((buffer, cursor_position)) =
5774 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5775 {
5776 self.edit_predictions_enabled_in_buffer(&buffer, cursor_position, cx)
5777 } else {
5778 false
5779 }
5780 }
5781
5782 fn edit_predictions_enabled_in_buffer(
5783 &self,
5784 buffer: &Entity<Buffer>,
5785 buffer_position: language::Anchor,
5786 cx: &App,
5787 ) -> bool {
5788 maybe!({
5789 if self.read_only(cx) {
5790 return Some(false);
5791 }
5792 let provider = self.edit_prediction_provider()?;
5793 if !provider.is_enabled(&buffer, buffer_position, cx) {
5794 return Some(false);
5795 }
5796 let buffer = buffer.read(cx);
5797 let Some(file) = buffer.file() else {
5798 return Some(true);
5799 };
5800 let settings = all_language_settings(Some(file), cx);
5801 Some(settings.edit_predictions_enabled_for_file(file, cx))
5802 })
5803 .unwrap_or(false)
5804 }
5805
5806 fn cycle_inline_completion(
5807 &mut self,
5808 direction: Direction,
5809 window: &mut Window,
5810 cx: &mut Context<Self>,
5811 ) -> Option<()> {
5812 let provider = self.edit_prediction_provider()?;
5813 let cursor = self.selections.newest_anchor().head();
5814 let (buffer, cursor_buffer_position) =
5815 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5816 if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
5817 return None;
5818 }
5819
5820 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5821 self.update_visible_inline_completion(window, cx);
5822
5823 Some(())
5824 }
5825
5826 pub fn show_inline_completion(
5827 &mut self,
5828 _: &ShowEditPrediction,
5829 window: &mut Window,
5830 cx: &mut Context<Self>,
5831 ) {
5832 if !self.has_active_inline_completion() {
5833 self.refresh_inline_completion(false, true, window, cx);
5834 return;
5835 }
5836
5837 self.update_visible_inline_completion(window, cx);
5838 }
5839
5840 pub fn display_cursor_names(
5841 &mut self,
5842 _: &DisplayCursorNames,
5843 window: &mut Window,
5844 cx: &mut Context<Self>,
5845 ) {
5846 self.show_cursor_names(window, cx);
5847 }
5848
5849 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5850 self.show_cursor_names = true;
5851 cx.notify();
5852 cx.spawn_in(window, async move |this, cx| {
5853 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5854 this.update(cx, |this, cx| {
5855 this.show_cursor_names = false;
5856 cx.notify()
5857 })
5858 .ok()
5859 })
5860 .detach();
5861 }
5862
5863 pub fn next_edit_prediction(
5864 &mut self,
5865 _: &NextEditPrediction,
5866 window: &mut Window,
5867 cx: &mut Context<Self>,
5868 ) {
5869 if self.has_active_inline_completion() {
5870 self.cycle_inline_completion(Direction::Next, window, cx);
5871 } else {
5872 let is_copilot_disabled = self
5873 .refresh_inline_completion(false, true, window, cx)
5874 .is_none();
5875 if is_copilot_disabled {
5876 cx.propagate();
5877 }
5878 }
5879 }
5880
5881 pub fn previous_edit_prediction(
5882 &mut self,
5883 _: &PreviousEditPrediction,
5884 window: &mut Window,
5885 cx: &mut Context<Self>,
5886 ) {
5887 if self.has_active_inline_completion() {
5888 self.cycle_inline_completion(Direction::Prev, window, cx);
5889 } else {
5890 let is_copilot_disabled = self
5891 .refresh_inline_completion(false, true, window, cx)
5892 .is_none();
5893 if is_copilot_disabled {
5894 cx.propagate();
5895 }
5896 }
5897 }
5898
5899 pub fn accept_edit_prediction(
5900 &mut self,
5901 _: &AcceptEditPrediction,
5902 window: &mut Window,
5903 cx: &mut Context<Self>,
5904 ) {
5905 if self.show_edit_predictions_in_menu() {
5906 self.hide_context_menu(window, cx);
5907 }
5908
5909 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5910 return;
5911 };
5912
5913 self.report_inline_completion_event(
5914 active_inline_completion.completion_id.clone(),
5915 true,
5916 cx,
5917 );
5918
5919 match &active_inline_completion.completion {
5920 InlineCompletion::Move { target, .. } => {
5921 let target = *target;
5922
5923 if let Some(position_map) = &self.last_position_map {
5924 if position_map
5925 .visible_row_range
5926 .contains(&target.to_display_point(&position_map.snapshot).row())
5927 || !self.edit_prediction_requires_modifier()
5928 {
5929 self.unfold_ranges(&[target..target], true, false, cx);
5930 // Note that this is also done in vim's handler of the Tab action.
5931 self.change_selections(
5932 Some(Autoscroll::newest()),
5933 window,
5934 cx,
5935 |selections| {
5936 selections.select_anchor_ranges([target..target]);
5937 },
5938 );
5939 self.clear_row_highlights::<EditPredictionPreview>();
5940
5941 self.edit_prediction_preview
5942 .set_previous_scroll_position(None);
5943 } else {
5944 self.edit_prediction_preview
5945 .set_previous_scroll_position(Some(
5946 position_map.snapshot.scroll_anchor,
5947 ));
5948
5949 self.highlight_rows::<EditPredictionPreview>(
5950 target..target,
5951 cx.theme().colors().editor_highlighted_line_background,
5952 true,
5953 cx,
5954 );
5955 self.request_autoscroll(Autoscroll::fit(), cx);
5956 }
5957 }
5958 }
5959 InlineCompletion::Edit { edits, .. } => {
5960 if let Some(provider) = self.edit_prediction_provider() {
5961 provider.accept(cx);
5962 }
5963
5964 let snapshot = self.buffer.read(cx).snapshot(cx);
5965 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
5966
5967 self.buffer.update(cx, |buffer, cx| {
5968 buffer.edit(edits.iter().cloned(), None, cx)
5969 });
5970
5971 self.change_selections(None, window, cx, |s| {
5972 s.select_anchor_ranges([last_edit_end..last_edit_end])
5973 });
5974
5975 self.update_visible_inline_completion(window, cx);
5976 if self.active_inline_completion.is_none() {
5977 self.refresh_inline_completion(true, true, window, cx);
5978 }
5979
5980 cx.notify();
5981 }
5982 }
5983
5984 self.edit_prediction_requires_modifier_in_indent_conflict = false;
5985 }
5986
5987 pub fn accept_partial_inline_completion(
5988 &mut self,
5989 _: &AcceptPartialEditPrediction,
5990 window: &mut Window,
5991 cx: &mut Context<Self>,
5992 ) {
5993 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
5994 return;
5995 };
5996 if self.selections.count() != 1 {
5997 return;
5998 }
5999
6000 self.report_inline_completion_event(
6001 active_inline_completion.completion_id.clone(),
6002 true,
6003 cx,
6004 );
6005
6006 match &active_inline_completion.completion {
6007 InlineCompletion::Move { target, .. } => {
6008 let target = *target;
6009 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
6010 selections.select_anchor_ranges([target..target]);
6011 });
6012 }
6013 InlineCompletion::Edit { edits, .. } => {
6014 // Find an insertion that starts at the cursor position.
6015 let snapshot = self.buffer.read(cx).snapshot(cx);
6016 let cursor_offset = self.selections.newest::<usize>(cx).head();
6017 let insertion = edits.iter().find_map(|(range, text)| {
6018 let range = range.to_offset(&snapshot);
6019 if range.is_empty() && range.start == cursor_offset {
6020 Some(text)
6021 } else {
6022 None
6023 }
6024 });
6025
6026 if let Some(text) = insertion {
6027 let mut partial_completion = text
6028 .chars()
6029 .by_ref()
6030 .take_while(|c| c.is_alphabetic())
6031 .collect::<String>();
6032 if partial_completion.is_empty() {
6033 partial_completion = text
6034 .chars()
6035 .by_ref()
6036 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
6037 .collect::<String>();
6038 }
6039
6040 cx.emit(EditorEvent::InputHandled {
6041 utf16_range_to_replace: None,
6042 text: partial_completion.clone().into(),
6043 });
6044
6045 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
6046
6047 self.refresh_inline_completion(true, true, window, cx);
6048 cx.notify();
6049 } else {
6050 self.accept_edit_prediction(&Default::default(), window, cx);
6051 }
6052 }
6053 }
6054 }
6055
6056 fn discard_inline_completion(
6057 &mut self,
6058 should_report_inline_completion_event: bool,
6059 cx: &mut Context<Self>,
6060 ) -> bool {
6061 if should_report_inline_completion_event {
6062 let completion_id = self
6063 .active_inline_completion
6064 .as_ref()
6065 .and_then(|active_completion| active_completion.completion_id.clone());
6066
6067 self.report_inline_completion_event(completion_id, false, cx);
6068 }
6069
6070 if let Some(provider) = self.edit_prediction_provider() {
6071 provider.discard(cx);
6072 }
6073
6074 self.take_active_inline_completion(cx)
6075 }
6076
6077 fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
6078 let Some(provider) = self.edit_prediction_provider() else {
6079 return;
6080 };
6081
6082 let Some((_, buffer, _)) = self
6083 .buffer
6084 .read(cx)
6085 .excerpt_containing(self.selections.newest_anchor().head(), cx)
6086 else {
6087 return;
6088 };
6089
6090 let extension = buffer
6091 .read(cx)
6092 .file()
6093 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
6094
6095 let event_type = match accepted {
6096 true => "Edit Prediction Accepted",
6097 false => "Edit Prediction Discarded",
6098 };
6099 telemetry::event!(
6100 event_type,
6101 provider = provider.name(),
6102 prediction_id = id,
6103 suggestion_accepted = accepted,
6104 file_extension = extension,
6105 );
6106 }
6107
6108 pub fn has_active_inline_completion(&self) -> bool {
6109 self.active_inline_completion.is_some()
6110 }
6111
6112 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
6113 let Some(active_inline_completion) = self.active_inline_completion.take() else {
6114 return false;
6115 };
6116
6117 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
6118 self.clear_highlights::<InlineCompletionHighlight>(cx);
6119 self.stale_inline_completion_in_menu = Some(active_inline_completion);
6120 true
6121 }
6122
6123 /// Returns true when we're displaying the edit prediction popover below the cursor
6124 /// like we are not previewing and the LSP autocomplete menu is visible
6125 /// or we are in `when_holding_modifier` mode.
6126 pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
6127 if self.edit_prediction_preview_is_active()
6128 || !self.show_edit_predictions_in_menu()
6129 || !self.edit_predictions_enabled()
6130 {
6131 return false;
6132 }
6133
6134 if self.has_visible_completions_menu() {
6135 return true;
6136 }
6137
6138 has_completion && self.edit_prediction_requires_modifier()
6139 }
6140
6141 fn handle_modifiers_changed(
6142 &mut self,
6143 modifiers: Modifiers,
6144 position_map: &PositionMap,
6145 window: &mut Window,
6146 cx: &mut Context<Self>,
6147 ) {
6148 if self.show_edit_predictions_in_menu() {
6149 self.update_edit_prediction_preview(&modifiers, window, cx);
6150 }
6151
6152 self.update_selection_mode(&modifiers, position_map, window, cx);
6153
6154 let mouse_position = window.mouse_position();
6155 if !position_map.text_hitbox.is_hovered(window) {
6156 return;
6157 }
6158
6159 self.update_hovered_link(
6160 position_map.point_for_position(mouse_position),
6161 &position_map.snapshot,
6162 modifiers,
6163 window,
6164 cx,
6165 )
6166 }
6167
6168 fn update_selection_mode(
6169 &mut self,
6170 modifiers: &Modifiers,
6171 position_map: &PositionMap,
6172 window: &mut Window,
6173 cx: &mut Context<Self>,
6174 ) {
6175 if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
6176 return;
6177 }
6178
6179 let mouse_position = window.mouse_position();
6180 let point_for_position = position_map.point_for_position(mouse_position);
6181 let position = point_for_position.previous_valid;
6182
6183 self.select(
6184 SelectPhase::BeginColumnar {
6185 position,
6186 reset: false,
6187 goal_column: point_for_position.exact_unclipped.column(),
6188 },
6189 window,
6190 cx,
6191 );
6192 }
6193
6194 fn update_edit_prediction_preview(
6195 &mut self,
6196 modifiers: &Modifiers,
6197 window: &mut Window,
6198 cx: &mut Context<Self>,
6199 ) {
6200 let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
6201 let Some(accept_keystroke) = accept_keybind.keystroke() else {
6202 return;
6203 };
6204
6205 if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
6206 if matches!(
6207 self.edit_prediction_preview,
6208 EditPredictionPreview::Inactive { .. }
6209 ) {
6210 self.edit_prediction_preview = EditPredictionPreview::Active {
6211 previous_scroll_position: None,
6212 since: Instant::now(),
6213 };
6214
6215 self.update_visible_inline_completion(window, cx);
6216 cx.notify();
6217 }
6218 } else if let EditPredictionPreview::Active {
6219 previous_scroll_position,
6220 since,
6221 } = self.edit_prediction_preview
6222 {
6223 if let (Some(previous_scroll_position), Some(position_map)) =
6224 (previous_scroll_position, self.last_position_map.as_ref())
6225 {
6226 self.set_scroll_position(
6227 previous_scroll_position
6228 .scroll_position(&position_map.snapshot.display_snapshot),
6229 window,
6230 cx,
6231 );
6232 }
6233
6234 self.edit_prediction_preview = EditPredictionPreview::Inactive {
6235 released_too_fast: since.elapsed() < Duration::from_millis(200),
6236 };
6237 self.clear_row_highlights::<EditPredictionPreview>();
6238 self.update_visible_inline_completion(window, cx);
6239 cx.notify();
6240 }
6241 }
6242
6243 fn update_visible_inline_completion(
6244 &mut self,
6245 _window: &mut Window,
6246 cx: &mut Context<Self>,
6247 ) -> Option<()> {
6248 let selection = self.selections.newest_anchor();
6249 let cursor = selection.head();
6250 let multibuffer = self.buffer.read(cx).snapshot(cx);
6251 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
6252 let excerpt_id = cursor.excerpt_id;
6253
6254 let show_in_menu = self.show_edit_predictions_in_menu();
6255 let completions_menu_has_precedence = !show_in_menu
6256 && (self.context_menu.borrow().is_some()
6257 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
6258
6259 if completions_menu_has_precedence
6260 || !offset_selection.is_empty()
6261 || self
6262 .active_inline_completion
6263 .as_ref()
6264 .map_or(false, |completion| {
6265 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
6266 let invalidation_range = invalidation_range.start..=invalidation_range.end;
6267 !invalidation_range.contains(&offset_selection.head())
6268 })
6269 {
6270 self.discard_inline_completion(false, cx);
6271 return None;
6272 }
6273
6274 self.take_active_inline_completion(cx);
6275 let Some(provider) = self.edit_prediction_provider() else {
6276 self.edit_prediction_settings = EditPredictionSettings::Disabled;
6277 return None;
6278 };
6279
6280 let (buffer, cursor_buffer_position) =
6281 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
6282
6283 self.edit_prediction_settings =
6284 self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
6285
6286 self.edit_prediction_indent_conflict = multibuffer.is_line_whitespace_upto(cursor);
6287
6288 if self.edit_prediction_indent_conflict {
6289 let cursor_point = cursor.to_point(&multibuffer);
6290
6291 let indents = multibuffer.suggested_indents(cursor_point.row..cursor_point.row + 1, cx);
6292
6293 if let Some((_, indent)) = indents.iter().next() {
6294 if indent.len == cursor_point.column {
6295 self.edit_prediction_indent_conflict = false;
6296 }
6297 }
6298 }
6299
6300 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
6301 let edits = inline_completion
6302 .edits
6303 .into_iter()
6304 .flat_map(|(range, new_text)| {
6305 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
6306 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
6307 Some((start..end, new_text))
6308 })
6309 .collect::<Vec<_>>();
6310 if edits.is_empty() {
6311 return None;
6312 }
6313
6314 let first_edit_start = edits.first().unwrap().0.start;
6315 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
6316 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
6317
6318 let last_edit_end = edits.last().unwrap().0.end;
6319 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
6320 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
6321
6322 let cursor_row = cursor.to_point(&multibuffer).row;
6323
6324 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
6325
6326 let mut inlay_ids = Vec::new();
6327 let invalidation_row_range;
6328 let move_invalidation_row_range = if cursor_row < edit_start_row {
6329 Some(cursor_row..edit_end_row)
6330 } else if cursor_row > edit_end_row {
6331 Some(edit_start_row..cursor_row)
6332 } else {
6333 None
6334 };
6335 let is_move =
6336 move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
6337 let completion = if is_move {
6338 invalidation_row_range =
6339 move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
6340 let target = first_edit_start;
6341 InlineCompletion::Move { target, snapshot }
6342 } else {
6343 let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
6344 && !self.inline_completions_hidden_for_vim_mode;
6345
6346 if show_completions_in_buffer {
6347 if edits
6348 .iter()
6349 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
6350 {
6351 let mut inlays = Vec::new();
6352 for (range, new_text) in &edits {
6353 let inlay = Inlay::inline_completion(
6354 post_inc(&mut self.next_inlay_id),
6355 range.start,
6356 new_text.as_str(),
6357 );
6358 inlay_ids.push(inlay.id);
6359 inlays.push(inlay);
6360 }
6361
6362 self.splice_inlays(&[], inlays, cx);
6363 } else {
6364 let background_color = cx.theme().status().deleted_background;
6365 self.highlight_text::<InlineCompletionHighlight>(
6366 edits.iter().map(|(range, _)| range.clone()).collect(),
6367 HighlightStyle {
6368 background_color: Some(background_color),
6369 ..Default::default()
6370 },
6371 cx,
6372 );
6373 }
6374 }
6375
6376 invalidation_row_range = edit_start_row..edit_end_row;
6377
6378 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
6379 if provider.show_tab_accept_marker() {
6380 EditDisplayMode::TabAccept
6381 } else {
6382 EditDisplayMode::Inline
6383 }
6384 } else {
6385 EditDisplayMode::DiffPopover
6386 };
6387
6388 InlineCompletion::Edit {
6389 edits,
6390 edit_preview: inline_completion.edit_preview,
6391 display_mode,
6392 snapshot,
6393 }
6394 };
6395
6396 let invalidation_range = multibuffer
6397 .anchor_before(Point::new(invalidation_row_range.start, 0))
6398 ..multibuffer.anchor_after(Point::new(
6399 invalidation_row_range.end,
6400 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
6401 ));
6402
6403 self.stale_inline_completion_in_menu = None;
6404 self.active_inline_completion = Some(InlineCompletionState {
6405 inlay_ids,
6406 completion,
6407 completion_id: inline_completion.id,
6408 invalidation_range,
6409 });
6410
6411 cx.notify();
6412
6413 Some(())
6414 }
6415
6416 pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
6417 Some(self.edit_prediction_provider.as_ref()?.provider.clone())
6418 }
6419
6420 fn render_code_actions_indicator(
6421 &self,
6422 _style: &EditorStyle,
6423 row: DisplayRow,
6424 is_active: bool,
6425 breakpoint: Option<&(Anchor, Breakpoint)>,
6426 cx: &mut Context<Self>,
6427 ) -> Option<IconButton> {
6428 let color = Color::Muted;
6429 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6430 let show_tooltip = !self.context_menu_visible();
6431
6432 if self.available_code_actions.is_some() {
6433 Some(
6434 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
6435 .shape(ui::IconButtonShape::Square)
6436 .icon_size(IconSize::XSmall)
6437 .icon_color(color)
6438 .toggle_state(is_active)
6439 .when(show_tooltip, |this| {
6440 this.tooltip({
6441 let focus_handle = self.focus_handle.clone();
6442 move |window, cx| {
6443 Tooltip::for_action_in(
6444 "Toggle Code Actions",
6445 &ToggleCodeActions {
6446 deployed_from_indicator: None,
6447 },
6448 &focus_handle,
6449 window,
6450 cx,
6451 )
6452 }
6453 })
6454 })
6455 .on_click(cx.listener(move |editor, _e, window, cx| {
6456 window.focus(&editor.focus_handle(cx));
6457 editor.toggle_code_actions(
6458 &ToggleCodeActions {
6459 deployed_from_indicator: Some(row),
6460 },
6461 window,
6462 cx,
6463 );
6464 }))
6465 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6466 editor.set_breakpoint_context_menu(
6467 row,
6468 position,
6469 event.down.position,
6470 window,
6471 cx,
6472 );
6473 })),
6474 )
6475 } else {
6476 None
6477 }
6478 }
6479
6480 fn clear_tasks(&mut self) {
6481 self.tasks.clear()
6482 }
6483
6484 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
6485 if self.tasks.insert(key, value).is_some() {
6486 // This case should hopefully be rare, but just in case...
6487 log::error!(
6488 "multiple different run targets found on a single line, only the last target will be rendered"
6489 )
6490 }
6491 }
6492
6493 /// Get all display points of breakpoints that will be rendered within editor
6494 ///
6495 /// This function is used to handle overlaps between breakpoints and Code action/runner symbol.
6496 /// It's also used to set the color of line numbers with breakpoints to the breakpoint color.
6497 /// TODO debugger: Use this function to color toggle symbols that house nested breakpoints
6498 fn active_breakpoints(
6499 &self,
6500 range: Range<DisplayRow>,
6501 window: &mut Window,
6502 cx: &mut Context<Self>,
6503 ) -> HashMap<DisplayRow, (Anchor, Breakpoint)> {
6504 let mut breakpoint_display_points = HashMap::default();
6505
6506 let Some(breakpoint_store) = self.breakpoint_store.clone() else {
6507 return breakpoint_display_points;
6508 };
6509
6510 let snapshot = self.snapshot(window, cx);
6511
6512 let multi_buffer_snapshot = &snapshot.display_snapshot.buffer_snapshot;
6513 let Some(project) = self.project.as_ref() else {
6514 return breakpoint_display_points;
6515 };
6516
6517 let range = snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left)
6518 ..snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
6519
6520 for (buffer_snapshot, range, excerpt_id) in
6521 multi_buffer_snapshot.range_to_buffer_ranges(range)
6522 {
6523 let Some(buffer) = project.read_with(cx, |this, cx| {
6524 this.buffer_for_id(buffer_snapshot.remote_id(), cx)
6525 }) else {
6526 continue;
6527 };
6528 let breakpoints = breakpoint_store.read(cx).breakpoints(
6529 &buffer,
6530 Some(
6531 buffer_snapshot.anchor_before(range.start)
6532 ..buffer_snapshot.anchor_after(range.end),
6533 ),
6534 buffer_snapshot,
6535 cx,
6536 );
6537 for (anchor, breakpoint) in breakpoints {
6538 let multi_buffer_anchor =
6539 Anchor::in_buffer(excerpt_id, buffer_snapshot.remote_id(), *anchor);
6540 let position = multi_buffer_anchor
6541 .to_point(&multi_buffer_snapshot)
6542 .to_display_point(&snapshot);
6543
6544 breakpoint_display_points
6545 .insert(position.row(), (multi_buffer_anchor, breakpoint.clone()));
6546 }
6547 }
6548
6549 breakpoint_display_points
6550 }
6551
6552 fn breakpoint_context_menu(
6553 &self,
6554 anchor: Anchor,
6555 window: &mut Window,
6556 cx: &mut Context<Self>,
6557 ) -> Entity<ui::ContextMenu> {
6558 let weak_editor = cx.weak_entity();
6559 let focus_handle = self.focus_handle(cx);
6560
6561 let row = self
6562 .buffer
6563 .read(cx)
6564 .snapshot(cx)
6565 .summary_for_anchor::<Point>(&anchor)
6566 .row;
6567
6568 let breakpoint = self
6569 .breakpoint_at_row(row, window, cx)
6570 .map(|(anchor, bp)| (anchor, Arc::from(bp)));
6571
6572 let log_breakpoint_msg = if breakpoint.as_ref().is_some_and(|bp| bp.1.message.is_some()) {
6573 "Edit Log Breakpoint"
6574 } else {
6575 "Set Log Breakpoint"
6576 };
6577
6578 let condition_breakpoint_msg = if breakpoint
6579 .as_ref()
6580 .is_some_and(|bp| bp.1.condition.is_some())
6581 {
6582 "Edit Condition Breakpoint"
6583 } else {
6584 "Set Condition Breakpoint"
6585 };
6586
6587 let hit_condition_breakpoint_msg = if breakpoint
6588 .as_ref()
6589 .is_some_and(|bp| bp.1.hit_condition.is_some())
6590 {
6591 "Edit Hit Condition Breakpoint"
6592 } else {
6593 "Set Hit Condition Breakpoint"
6594 };
6595
6596 let set_breakpoint_msg = if breakpoint.as_ref().is_some() {
6597 "Unset Breakpoint"
6598 } else {
6599 "Set Breakpoint"
6600 };
6601
6602 let run_to_cursor = command_palette_hooks::CommandPaletteFilter::try_global(cx)
6603 .map_or(false, |filter| !filter.is_hidden(&DebuggerRunToCursor));
6604
6605 let toggle_state_msg = breakpoint.as_ref().map_or(None, |bp| match bp.1.state {
6606 BreakpointState::Enabled => Some("Disable"),
6607 BreakpointState::Disabled => Some("Enable"),
6608 });
6609
6610 let (anchor, breakpoint) =
6611 breakpoint.unwrap_or_else(|| (anchor, Arc::new(Breakpoint::new_standard())));
6612
6613 ui::ContextMenu::build(window, cx, |menu, _, _cx| {
6614 menu.on_blur_subscription(Subscription::new(|| {}))
6615 .context(focus_handle)
6616 .when(run_to_cursor, |this| {
6617 let weak_editor = weak_editor.clone();
6618 this.entry("Run to cursor", None, move |window, cx| {
6619 weak_editor
6620 .update(cx, |editor, cx| {
6621 editor.change_selections(None, window, cx, |s| {
6622 s.select_ranges([Point::new(row, 0)..Point::new(row, 0)])
6623 });
6624 })
6625 .ok();
6626
6627 window.dispatch_action(Box::new(DebuggerRunToCursor), cx);
6628 })
6629 .separator()
6630 })
6631 .when_some(toggle_state_msg, |this, msg| {
6632 this.entry(msg, None, {
6633 let weak_editor = weak_editor.clone();
6634 let breakpoint = breakpoint.clone();
6635 move |_window, cx| {
6636 weak_editor
6637 .update(cx, |this, cx| {
6638 this.edit_breakpoint_at_anchor(
6639 anchor,
6640 breakpoint.as_ref().clone(),
6641 BreakpointEditAction::InvertState,
6642 cx,
6643 );
6644 })
6645 .log_err();
6646 }
6647 })
6648 })
6649 .entry(set_breakpoint_msg, None, {
6650 let weak_editor = weak_editor.clone();
6651 let breakpoint = breakpoint.clone();
6652 move |_window, cx| {
6653 weak_editor
6654 .update(cx, |this, cx| {
6655 this.edit_breakpoint_at_anchor(
6656 anchor,
6657 breakpoint.as_ref().clone(),
6658 BreakpointEditAction::Toggle,
6659 cx,
6660 );
6661 })
6662 .log_err();
6663 }
6664 })
6665 .entry(log_breakpoint_msg, None, {
6666 let breakpoint = breakpoint.clone();
6667 let weak_editor = weak_editor.clone();
6668 move |window, cx| {
6669 weak_editor
6670 .update(cx, |this, cx| {
6671 this.add_edit_breakpoint_block(
6672 anchor,
6673 breakpoint.as_ref(),
6674 BreakpointPromptEditAction::Log,
6675 window,
6676 cx,
6677 );
6678 })
6679 .log_err();
6680 }
6681 })
6682 .entry(condition_breakpoint_msg, None, {
6683 let breakpoint = breakpoint.clone();
6684 let weak_editor = weak_editor.clone();
6685 move |window, cx| {
6686 weak_editor
6687 .update(cx, |this, cx| {
6688 this.add_edit_breakpoint_block(
6689 anchor,
6690 breakpoint.as_ref(),
6691 BreakpointPromptEditAction::Condition,
6692 window,
6693 cx,
6694 );
6695 })
6696 .log_err();
6697 }
6698 })
6699 .entry(hit_condition_breakpoint_msg, None, move |window, cx| {
6700 weak_editor
6701 .update(cx, |this, cx| {
6702 this.add_edit_breakpoint_block(
6703 anchor,
6704 breakpoint.as_ref(),
6705 BreakpointPromptEditAction::HitCondition,
6706 window,
6707 cx,
6708 );
6709 })
6710 .log_err();
6711 })
6712 })
6713 }
6714
6715 fn render_breakpoint(
6716 &self,
6717 position: Anchor,
6718 row: DisplayRow,
6719 breakpoint: &Breakpoint,
6720 cx: &mut Context<Self>,
6721 ) -> IconButton {
6722 let (color, icon) = {
6723 let icon = match (&breakpoint.message.is_some(), breakpoint.is_disabled()) {
6724 (false, false) => ui::IconName::DebugBreakpoint,
6725 (true, false) => ui::IconName::DebugLogBreakpoint,
6726 (false, true) => ui::IconName::DebugDisabledBreakpoint,
6727 (true, true) => ui::IconName::DebugDisabledLogBreakpoint,
6728 };
6729
6730 let color = if self
6731 .gutter_breakpoint_indicator
6732 .0
6733 .is_some_and(|(point, is_visible)| is_visible && point.row() == row)
6734 {
6735 Color::Hint
6736 } else {
6737 Color::Debugger
6738 };
6739
6740 (color, icon)
6741 };
6742
6743 let breakpoint = Arc::from(breakpoint.clone());
6744
6745 IconButton::new(("breakpoint_indicator", row.0 as usize), icon)
6746 .icon_size(IconSize::XSmall)
6747 .size(ui::ButtonSize::None)
6748 .icon_color(color)
6749 .style(ButtonStyle::Transparent)
6750 .on_click(cx.listener({
6751 let breakpoint = breakpoint.clone();
6752
6753 move |editor, event: &ClickEvent, window, cx| {
6754 let edit_action = if event.modifiers().platform || breakpoint.is_disabled() {
6755 BreakpointEditAction::InvertState
6756 } else {
6757 BreakpointEditAction::Toggle
6758 };
6759
6760 window.focus(&editor.focus_handle(cx));
6761 editor.edit_breakpoint_at_anchor(
6762 position,
6763 breakpoint.as_ref().clone(),
6764 edit_action,
6765 cx,
6766 );
6767 }
6768 }))
6769 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6770 editor.set_breakpoint_context_menu(
6771 row,
6772 Some(position),
6773 event.down.position,
6774 window,
6775 cx,
6776 );
6777 }))
6778 }
6779
6780 fn build_tasks_context(
6781 project: &Entity<Project>,
6782 buffer: &Entity<Buffer>,
6783 buffer_row: u32,
6784 tasks: &Arc<RunnableTasks>,
6785 cx: &mut Context<Self>,
6786 ) -> Task<Option<task::TaskContext>> {
6787 let position = Point::new(buffer_row, tasks.column);
6788 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
6789 let location = Location {
6790 buffer: buffer.clone(),
6791 range: range_start..range_start,
6792 };
6793 // Fill in the environmental variables from the tree-sitter captures
6794 let mut captured_task_variables = TaskVariables::default();
6795 for (capture_name, value) in tasks.extra_variables.clone() {
6796 captured_task_variables.insert(
6797 task::VariableName::Custom(capture_name.into()),
6798 value.clone(),
6799 );
6800 }
6801 project.update(cx, |project, cx| {
6802 project.task_store().update(cx, |task_store, cx| {
6803 task_store.task_context_for_location(captured_task_variables, location, cx)
6804 })
6805 })
6806 }
6807
6808 pub fn spawn_nearest_task(
6809 &mut self,
6810 action: &SpawnNearestTask,
6811 window: &mut Window,
6812 cx: &mut Context<Self>,
6813 ) {
6814 let Some((workspace, _)) = self.workspace.clone() else {
6815 return;
6816 };
6817 let Some(project) = self.project.clone() else {
6818 return;
6819 };
6820
6821 // Try to find a closest, enclosing node using tree-sitter that has a
6822 // task
6823 let Some((buffer, buffer_row, tasks)) = self
6824 .find_enclosing_node_task(cx)
6825 // Or find the task that's closest in row-distance.
6826 .or_else(|| self.find_closest_task(cx))
6827 else {
6828 return;
6829 };
6830
6831 let reveal_strategy = action.reveal;
6832 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
6833 cx.spawn_in(window, async move |_, cx| {
6834 let context = task_context.await?;
6835 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
6836
6837 let resolved = resolved_task.resolved.as_mut()?;
6838 resolved.reveal = reveal_strategy;
6839
6840 workspace
6841 .update_in(cx, |workspace, window, cx| {
6842 workspace.schedule_resolved_task(
6843 task_source_kind,
6844 resolved_task,
6845 false,
6846 window,
6847 cx,
6848 );
6849 })
6850 .ok()
6851 })
6852 .detach();
6853 }
6854
6855 fn find_closest_task(
6856 &mut self,
6857 cx: &mut Context<Self>,
6858 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6859 let cursor_row = self.selections.newest_adjusted(cx).head().row;
6860
6861 let ((buffer_id, row), tasks) = self
6862 .tasks
6863 .iter()
6864 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
6865
6866 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
6867 let tasks = Arc::new(tasks.to_owned());
6868 Some((buffer, *row, tasks))
6869 }
6870
6871 fn find_enclosing_node_task(
6872 &mut self,
6873 cx: &mut Context<Self>,
6874 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
6875 let snapshot = self.buffer.read(cx).snapshot(cx);
6876 let offset = self.selections.newest::<usize>(cx).head();
6877 let excerpt = snapshot.excerpt_containing(offset..offset)?;
6878 let buffer_id = excerpt.buffer().remote_id();
6879
6880 let layer = excerpt.buffer().syntax_layer_at(offset)?;
6881 let mut cursor = layer.node().walk();
6882
6883 while cursor.goto_first_child_for_byte(offset).is_some() {
6884 if cursor.node().end_byte() == offset {
6885 cursor.goto_next_sibling();
6886 }
6887 }
6888
6889 // Ascend to the smallest ancestor that contains the range and has a task.
6890 loop {
6891 let node = cursor.node();
6892 let node_range = node.byte_range();
6893 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
6894
6895 // Check if this node contains our offset
6896 if node_range.start <= offset && node_range.end >= offset {
6897 // If it contains offset, check for task
6898 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
6899 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
6900 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
6901 }
6902 }
6903
6904 if !cursor.goto_parent() {
6905 break;
6906 }
6907 }
6908 None
6909 }
6910
6911 fn render_run_indicator(
6912 &self,
6913 _style: &EditorStyle,
6914 is_active: bool,
6915 row: DisplayRow,
6916 breakpoint: Option<(Anchor, Breakpoint)>,
6917 cx: &mut Context<Self>,
6918 ) -> IconButton {
6919 let color = Color::Muted;
6920 let position = breakpoint.as_ref().map(|(anchor, _)| *anchor);
6921
6922 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
6923 .shape(ui::IconButtonShape::Square)
6924 .icon_size(IconSize::XSmall)
6925 .icon_color(color)
6926 .toggle_state(is_active)
6927 .on_click(cx.listener(move |editor, _e, window, cx| {
6928 window.focus(&editor.focus_handle(cx));
6929 editor.toggle_code_actions(
6930 &ToggleCodeActions {
6931 deployed_from_indicator: Some(row),
6932 },
6933 window,
6934 cx,
6935 );
6936 }))
6937 .on_right_click(cx.listener(move |editor, event: &ClickEvent, window, cx| {
6938 editor.set_breakpoint_context_menu(row, position, event.down.position, window, cx);
6939 }))
6940 }
6941
6942 pub fn context_menu_visible(&self) -> bool {
6943 !self.edit_prediction_preview_is_active()
6944 && self
6945 .context_menu
6946 .borrow()
6947 .as_ref()
6948 .map_or(false, |menu| menu.visible())
6949 }
6950
6951 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
6952 self.context_menu
6953 .borrow()
6954 .as_ref()
6955 .map(|menu| menu.origin())
6956 }
6957
6958 pub fn set_context_menu_options(&mut self, options: ContextMenuOptions) {
6959 self.context_menu_options = Some(options);
6960 }
6961
6962 const EDIT_PREDICTION_POPOVER_PADDING_X: Pixels = Pixels(24.);
6963 const EDIT_PREDICTION_POPOVER_PADDING_Y: Pixels = Pixels(2.);
6964
6965 fn render_edit_prediction_popover(
6966 &mut self,
6967 text_bounds: &Bounds<Pixels>,
6968 content_origin: gpui::Point<Pixels>,
6969 editor_snapshot: &EditorSnapshot,
6970 visible_row_range: Range<DisplayRow>,
6971 scroll_top: f32,
6972 scroll_bottom: f32,
6973 line_layouts: &[LineWithInvisibles],
6974 line_height: Pixels,
6975 scroll_pixel_position: gpui::Point<Pixels>,
6976 newest_selection_head: Option<DisplayPoint>,
6977 editor_width: Pixels,
6978 style: &EditorStyle,
6979 window: &mut Window,
6980 cx: &mut App,
6981 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
6982 let active_inline_completion = self.active_inline_completion.as_ref()?;
6983
6984 if self.edit_prediction_visible_in_cursor_popover(true) {
6985 return None;
6986 }
6987
6988 match &active_inline_completion.completion {
6989 InlineCompletion::Move { target, .. } => {
6990 let target_display_point = target.to_display_point(editor_snapshot);
6991
6992 if self.edit_prediction_requires_modifier() {
6993 if !self.edit_prediction_preview_is_active() {
6994 return None;
6995 }
6996
6997 self.render_edit_prediction_modifier_jump_popover(
6998 text_bounds,
6999 content_origin,
7000 visible_row_range,
7001 line_layouts,
7002 line_height,
7003 scroll_pixel_position,
7004 newest_selection_head,
7005 target_display_point,
7006 window,
7007 cx,
7008 )
7009 } else {
7010 self.render_edit_prediction_eager_jump_popover(
7011 text_bounds,
7012 content_origin,
7013 editor_snapshot,
7014 visible_row_range,
7015 scroll_top,
7016 scroll_bottom,
7017 line_height,
7018 scroll_pixel_position,
7019 target_display_point,
7020 editor_width,
7021 window,
7022 cx,
7023 )
7024 }
7025 }
7026 InlineCompletion::Edit {
7027 display_mode: EditDisplayMode::Inline,
7028 ..
7029 } => None,
7030 InlineCompletion::Edit {
7031 display_mode: EditDisplayMode::TabAccept,
7032 edits,
7033 ..
7034 } => {
7035 let range = &edits.first()?.0;
7036 let target_display_point = range.end.to_display_point(editor_snapshot);
7037
7038 self.render_edit_prediction_end_of_line_popover(
7039 "Accept",
7040 editor_snapshot,
7041 visible_row_range,
7042 target_display_point,
7043 line_height,
7044 scroll_pixel_position,
7045 content_origin,
7046 editor_width,
7047 window,
7048 cx,
7049 )
7050 }
7051 InlineCompletion::Edit {
7052 edits,
7053 edit_preview,
7054 display_mode: EditDisplayMode::DiffPopover,
7055 snapshot,
7056 } => self.render_edit_prediction_diff_popover(
7057 text_bounds,
7058 content_origin,
7059 editor_snapshot,
7060 visible_row_range,
7061 line_layouts,
7062 line_height,
7063 scroll_pixel_position,
7064 newest_selection_head,
7065 editor_width,
7066 style,
7067 edits,
7068 edit_preview,
7069 snapshot,
7070 window,
7071 cx,
7072 ),
7073 }
7074 }
7075
7076 fn render_edit_prediction_modifier_jump_popover(
7077 &mut self,
7078 text_bounds: &Bounds<Pixels>,
7079 content_origin: gpui::Point<Pixels>,
7080 visible_row_range: Range<DisplayRow>,
7081 line_layouts: &[LineWithInvisibles],
7082 line_height: Pixels,
7083 scroll_pixel_position: gpui::Point<Pixels>,
7084 newest_selection_head: Option<DisplayPoint>,
7085 target_display_point: DisplayPoint,
7086 window: &mut Window,
7087 cx: &mut App,
7088 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7089 let scrolled_content_origin =
7090 content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
7091
7092 const SCROLL_PADDING_Y: Pixels = px(12.);
7093
7094 if target_display_point.row() < visible_row_range.start {
7095 return self.render_edit_prediction_scroll_popover(
7096 |_| SCROLL_PADDING_Y,
7097 IconName::ArrowUp,
7098 visible_row_range,
7099 line_layouts,
7100 newest_selection_head,
7101 scrolled_content_origin,
7102 window,
7103 cx,
7104 );
7105 } else if target_display_point.row() >= visible_row_range.end {
7106 return self.render_edit_prediction_scroll_popover(
7107 |size| text_bounds.size.height - size.height - SCROLL_PADDING_Y,
7108 IconName::ArrowDown,
7109 visible_row_range,
7110 line_layouts,
7111 newest_selection_head,
7112 scrolled_content_origin,
7113 window,
7114 cx,
7115 );
7116 }
7117
7118 const POLE_WIDTH: Pixels = px(2.);
7119
7120 let line_layout =
7121 line_layouts.get(target_display_point.row().minus(visible_row_range.start) as usize)?;
7122 let target_column = target_display_point.column() as usize;
7123
7124 let target_x = line_layout.x_for_index(target_column);
7125 let target_y =
7126 (target_display_point.row().as_f32() * line_height) - scroll_pixel_position.y;
7127
7128 let flag_on_right = target_x < text_bounds.size.width / 2.;
7129
7130 let mut border_color = Self::edit_prediction_callout_popover_border_color(cx);
7131 border_color.l += 0.001;
7132
7133 let mut element = v_flex()
7134 .items_end()
7135 .when(flag_on_right, |el| el.items_start())
7136 .child(if flag_on_right {
7137 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7138 .rounded_bl(px(0.))
7139 .rounded_tl(px(0.))
7140 .border_l_2()
7141 .border_color(border_color)
7142 } else {
7143 self.render_edit_prediction_line_popover("Jump", None, window, cx)?
7144 .rounded_br(px(0.))
7145 .rounded_tr(px(0.))
7146 .border_r_2()
7147 .border_color(border_color)
7148 })
7149 .child(div().w(POLE_WIDTH).bg(border_color).h(line_height))
7150 .into_any();
7151
7152 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7153
7154 let mut origin = scrolled_content_origin + point(target_x, target_y)
7155 - point(
7156 if flag_on_right {
7157 POLE_WIDTH
7158 } else {
7159 size.width - POLE_WIDTH
7160 },
7161 size.height - line_height,
7162 );
7163
7164 origin.x = origin.x.max(content_origin.x);
7165
7166 element.prepaint_at(origin, window, cx);
7167
7168 Some((element, origin))
7169 }
7170
7171 fn render_edit_prediction_scroll_popover(
7172 &mut self,
7173 to_y: impl Fn(Size<Pixels>) -> Pixels,
7174 scroll_icon: IconName,
7175 visible_row_range: Range<DisplayRow>,
7176 line_layouts: &[LineWithInvisibles],
7177 newest_selection_head: Option<DisplayPoint>,
7178 scrolled_content_origin: gpui::Point<Pixels>,
7179 window: &mut Window,
7180 cx: &mut App,
7181 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7182 let mut element = self
7183 .render_edit_prediction_line_popover("Scroll", Some(scroll_icon), window, cx)?
7184 .into_any();
7185
7186 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7187
7188 let cursor = newest_selection_head?;
7189 let cursor_row_layout =
7190 line_layouts.get(cursor.row().minus(visible_row_range.start) as usize)?;
7191 let cursor_column = cursor.column() as usize;
7192
7193 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
7194
7195 let origin = scrolled_content_origin + point(cursor_character_x, to_y(size));
7196
7197 element.prepaint_at(origin, window, cx);
7198 Some((element, origin))
7199 }
7200
7201 fn render_edit_prediction_eager_jump_popover(
7202 &mut self,
7203 text_bounds: &Bounds<Pixels>,
7204 content_origin: gpui::Point<Pixels>,
7205 editor_snapshot: &EditorSnapshot,
7206 visible_row_range: Range<DisplayRow>,
7207 scroll_top: f32,
7208 scroll_bottom: f32,
7209 line_height: Pixels,
7210 scroll_pixel_position: gpui::Point<Pixels>,
7211 target_display_point: DisplayPoint,
7212 editor_width: Pixels,
7213 window: &mut Window,
7214 cx: &mut App,
7215 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7216 if target_display_point.row().as_f32() < scroll_top {
7217 let mut element = self
7218 .render_edit_prediction_line_popover(
7219 "Jump to Edit",
7220 Some(IconName::ArrowUp),
7221 window,
7222 cx,
7223 )?
7224 .into_any();
7225
7226 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7227 let offset = point(
7228 (text_bounds.size.width - size.width) / 2.,
7229 Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7230 );
7231
7232 let origin = text_bounds.origin + offset;
7233 element.prepaint_at(origin, window, cx);
7234 Some((element, origin))
7235 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
7236 let mut element = self
7237 .render_edit_prediction_line_popover(
7238 "Jump to Edit",
7239 Some(IconName::ArrowDown),
7240 window,
7241 cx,
7242 )?
7243 .into_any();
7244
7245 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7246 let offset = point(
7247 (text_bounds.size.width - size.width) / 2.,
7248 text_bounds.size.height - size.height - Self::EDIT_PREDICTION_POPOVER_PADDING_Y,
7249 );
7250
7251 let origin = text_bounds.origin + offset;
7252 element.prepaint_at(origin, window, cx);
7253 Some((element, origin))
7254 } else {
7255 self.render_edit_prediction_end_of_line_popover(
7256 "Jump to Edit",
7257 editor_snapshot,
7258 visible_row_range,
7259 target_display_point,
7260 line_height,
7261 scroll_pixel_position,
7262 content_origin,
7263 editor_width,
7264 window,
7265 cx,
7266 )
7267 }
7268 }
7269
7270 fn render_edit_prediction_end_of_line_popover(
7271 self: &mut Editor,
7272 label: &'static str,
7273 editor_snapshot: &EditorSnapshot,
7274 visible_row_range: Range<DisplayRow>,
7275 target_display_point: DisplayPoint,
7276 line_height: Pixels,
7277 scroll_pixel_position: gpui::Point<Pixels>,
7278 content_origin: gpui::Point<Pixels>,
7279 editor_width: Pixels,
7280 window: &mut Window,
7281 cx: &mut App,
7282 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7283 let target_line_end = DisplayPoint::new(
7284 target_display_point.row(),
7285 editor_snapshot.line_len(target_display_point.row()),
7286 );
7287
7288 let mut element = self
7289 .render_edit_prediction_line_popover(label, None, window, cx)?
7290 .into_any();
7291
7292 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7293
7294 let line_origin = self.display_to_pixel_point(target_line_end, editor_snapshot, window)?;
7295
7296 let start_point = content_origin - point(scroll_pixel_position.x, Pixels::ZERO);
7297 let mut origin = start_point
7298 + line_origin
7299 + point(Self::EDIT_PREDICTION_POPOVER_PADDING_X, Pixels::ZERO);
7300 origin.x = origin.x.max(content_origin.x);
7301
7302 let max_x = content_origin.x + editor_width - size.width;
7303
7304 if origin.x > max_x {
7305 let offset = line_height + Self::EDIT_PREDICTION_POPOVER_PADDING_Y;
7306
7307 let icon = if visible_row_range.contains(&(target_display_point.row() + 2)) {
7308 origin.y += offset;
7309 IconName::ArrowUp
7310 } else {
7311 origin.y -= offset;
7312 IconName::ArrowDown
7313 };
7314
7315 element = self
7316 .render_edit_prediction_line_popover(label, Some(icon), window, cx)?
7317 .into_any();
7318
7319 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7320
7321 origin.x = content_origin.x + editor_width - size.width - px(2.);
7322 }
7323
7324 element.prepaint_at(origin, window, cx);
7325 Some((element, origin))
7326 }
7327
7328 fn render_edit_prediction_diff_popover(
7329 self: &Editor,
7330 text_bounds: &Bounds<Pixels>,
7331 content_origin: gpui::Point<Pixels>,
7332 editor_snapshot: &EditorSnapshot,
7333 visible_row_range: Range<DisplayRow>,
7334 line_layouts: &[LineWithInvisibles],
7335 line_height: Pixels,
7336 scroll_pixel_position: gpui::Point<Pixels>,
7337 newest_selection_head: Option<DisplayPoint>,
7338 editor_width: Pixels,
7339 style: &EditorStyle,
7340 edits: &Vec<(Range<Anchor>, String)>,
7341 edit_preview: &Option<language::EditPreview>,
7342 snapshot: &language::BufferSnapshot,
7343 window: &mut Window,
7344 cx: &mut App,
7345 ) -> Option<(AnyElement, gpui::Point<Pixels>)> {
7346 let edit_start = edits
7347 .first()
7348 .unwrap()
7349 .0
7350 .start
7351 .to_display_point(editor_snapshot);
7352 let edit_end = edits
7353 .last()
7354 .unwrap()
7355 .0
7356 .end
7357 .to_display_point(editor_snapshot);
7358
7359 let is_visible = visible_row_range.contains(&edit_start.row())
7360 || visible_row_range.contains(&edit_end.row());
7361 if !is_visible {
7362 return None;
7363 }
7364
7365 let highlighted_edits =
7366 crate::inline_completion_edit_text(&snapshot, edits, edit_preview.as_ref()?, false, cx);
7367
7368 let styled_text = highlighted_edits.to_styled_text(&style.text);
7369 let line_count = highlighted_edits.text.lines().count();
7370
7371 const BORDER_WIDTH: Pixels = px(1.);
7372
7373 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7374 let has_keybind = keybind.is_some();
7375
7376 let mut element = h_flex()
7377 .items_start()
7378 .child(
7379 h_flex()
7380 .bg(cx.theme().colors().editor_background)
7381 .border(BORDER_WIDTH)
7382 .shadow_sm()
7383 .border_color(cx.theme().colors().border)
7384 .rounded_l_lg()
7385 .when(line_count > 1, |el| el.rounded_br_lg())
7386 .pr_1()
7387 .child(styled_text),
7388 )
7389 .child(
7390 h_flex()
7391 .h(line_height + BORDER_WIDTH * 2.)
7392 .px_1p5()
7393 .gap_1()
7394 // Workaround: For some reason, there's a gap if we don't do this
7395 .ml(-BORDER_WIDTH)
7396 .shadow(smallvec![gpui::BoxShadow {
7397 color: gpui::black().opacity(0.05),
7398 offset: point(px(1.), px(1.)),
7399 blur_radius: px(2.),
7400 spread_radius: px(0.),
7401 }])
7402 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
7403 .border(BORDER_WIDTH)
7404 .border_color(cx.theme().colors().border)
7405 .rounded_r_lg()
7406 .id("edit_prediction_diff_popover_keybind")
7407 .when(!has_keybind, |el| {
7408 let status_colors = cx.theme().status();
7409
7410 el.bg(status_colors.error_background)
7411 .border_color(status_colors.error.opacity(0.6))
7412 .child(Icon::new(IconName::Info).color(Color::Error))
7413 .cursor_default()
7414 .hoverable_tooltip(move |_window, cx| {
7415 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7416 })
7417 })
7418 .children(keybind),
7419 )
7420 .into_any();
7421
7422 let longest_row =
7423 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
7424 let longest_line_width = if visible_row_range.contains(&longest_row) {
7425 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
7426 } else {
7427 layout_line(
7428 longest_row,
7429 editor_snapshot,
7430 style,
7431 editor_width,
7432 |_| false,
7433 window,
7434 cx,
7435 )
7436 .width
7437 };
7438
7439 let viewport_bounds =
7440 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
7441 right: -EditorElement::SCROLLBAR_WIDTH,
7442 ..Default::default()
7443 });
7444
7445 let x_after_longest =
7446 text_bounds.origin.x + longest_line_width + Self::EDIT_PREDICTION_POPOVER_PADDING_X
7447 - scroll_pixel_position.x;
7448
7449 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
7450
7451 // Fully visible if it can be displayed within the window (allow overlapping other
7452 // panes). However, this is only allowed if the popover starts within text_bounds.
7453 let can_position_to_the_right = x_after_longest < text_bounds.right()
7454 && x_after_longest + element_bounds.width < viewport_bounds.right();
7455
7456 let mut origin = if can_position_to_the_right {
7457 point(
7458 x_after_longest,
7459 text_bounds.origin.y + edit_start.row().as_f32() * line_height
7460 - scroll_pixel_position.y,
7461 )
7462 } else {
7463 let cursor_row = newest_selection_head.map(|head| head.row());
7464 let above_edit = edit_start
7465 .row()
7466 .0
7467 .checked_sub(line_count as u32)
7468 .map(DisplayRow);
7469 let below_edit = Some(edit_end.row() + 1);
7470 let above_cursor =
7471 cursor_row.and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
7472 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
7473
7474 // Place the edit popover adjacent to the edit if there is a location
7475 // available that is onscreen and does not obscure the cursor. Otherwise,
7476 // place it adjacent to the cursor.
7477 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
7478 .into_iter()
7479 .flatten()
7480 .find(|&start_row| {
7481 let end_row = start_row + line_count as u32;
7482 visible_row_range.contains(&start_row)
7483 && visible_row_range.contains(&end_row)
7484 && cursor_row.map_or(true, |cursor_row| {
7485 !((start_row..end_row).contains(&cursor_row))
7486 })
7487 })?;
7488
7489 content_origin
7490 + point(
7491 -scroll_pixel_position.x,
7492 row_target.as_f32() * line_height - scroll_pixel_position.y,
7493 )
7494 };
7495
7496 origin.x -= BORDER_WIDTH;
7497
7498 window.defer_draw(element, origin, 1);
7499
7500 // Do not return an element, since it will already be drawn due to defer_draw.
7501 None
7502 }
7503
7504 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
7505 px(30.)
7506 }
7507
7508 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
7509 if self.read_only(cx) {
7510 cx.theme().players().read_only()
7511 } else {
7512 self.style.as_ref().unwrap().local_player
7513 }
7514 }
7515
7516 fn render_edit_prediction_accept_keybind(
7517 &self,
7518 window: &mut Window,
7519 cx: &App,
7520 ) -> Option<AnyElement> {
7521 let accept_binding = self.accept_edit_prediction_keybind(window, cx);
7522 let accept_keystroke = accept_binding.keystroke()?;
7523
7524 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7525
7526 let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
7527 Color::Accent
7528 } else {
7529 Color::Muted
7530 };
7531
7532 h_flex()
7533 .px_0p5()
7534 .when(is_platform_style_mac, |parent| parent.gap_0p5())
7535 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7536 .text_size(TextSize::XSmall.rems(cx))
7537 .child(h_flex().children(ui::render_modifiers(
7538 &accept_keystroke.modifiers,
7539 PlatformStyle::platform(),
7540 Some(modifiers_color),
7541 Some(IconSize::XSmall.rems().into()),
7542 true,
7543 )))
7544 .when(is_platform_style_mac, |parent| {
7545 parent.child(accept_keystroke.key.clone())
7546 })
7547 .when(!is_platform_style_mac, |parent| {
7548 parent.child(
7549 Key::new(
7550 util::capitalize(&accept_keystroke.key),
7551 Some(Color::Default),
7552 )
7553 .size(Some(IconSize::XSmall.rems().into())),
7554 )
7555 })
7556 .into_any()
7557 .into()
7558 }
7559
7560 fn render_edit_prediction_line_popover(
7561 &self,
7562 label: impl Into<SharedString>,
7563 icon: Option<IconName>,
7564 window: &mut Window,
7565 cx: &App,
7566 ) -> Option<Stateful<Div>> {
7567 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
7568
7569 let keybind = self.render_edit_prediction_accept_keybind(window, cx);
7570 let has_keybind = keybind.is_some();
7571
7572 let result = h_flex()
7573 .id("ep-line-popover")
7574 .py_0p5()
7575 .pl_1()
7576 .pr(padding_right)
7577 .gap_1()
7578 .rounded_md()
7579 .border_1()
7580 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7581 .border_color(Self::edit_prediction_callout_popover_border_color(cx))
7582 .shadow_sm()
7583 .when(!has_keybind, |el| {
7584 let status_colors = cx.theme().status();
7585
7586 el.bg(status_colors.error_background)
7587 .border_color(status_colors.error.opacity(0.6))
7588 .pl_2()
7589 .child(Icon::new(IconName::ZedPredictError).color(Color::Error))
7590 .cursor_default()
7591 .hoverable_tooltip(move |_window, cx| {
7592 cx.new(|_| MissingEditPredictionKeybindingTooltip).into()
7593 })
7594 })
7595 .children(keybind)
7596 .child(
7597 Label::new(label)
7598 .size(LabelSize::Small)
7599 .when(!has_keybind, |el| {
7600 el.color(cx.theme().status().error.into()).strikethrough()
7601 }),
7602 )
7603 .when(!has_keybind, |el| {
7604 el.child(
7605 h_flex().ml_1().child(
7606 Icon::new(IconName::Info)
7607 .size(IconSize::Small)
7608 .color(cx.theme().status().error.into()),
7609 ),
7610 )
7611 })
7612 .when_some(icon, |element, icon| {
7613 element.child(
7614 div()
7615 .mt(px(1.5))
7616 .child(Icon::new(icon).size(IconSize::Small)),
7617 )
7618 });
7619
7620 Some(result)
7621 }
7622
7623 fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
7624 let accent_color = cx.theme().colors().text_accent;
7625 let editor_bg_color = cx.theme().colors().editor_background;
7626 editor_bg_color.blend(accent_color.opacity(0.1))
7627 }
7628
7629 fn edit_prediction_callout_popover_border_color(cx: &App) -> Hsla {
7630 let accent_color = cx.theme().colors().text_accent;
7631 let editor_bg_color = cx.theme().colors().editor_background;
7632 editor_bg_color.blend(accent_color.opacity(0.6))
7633 }
7634
7635 fn render_edit_prediction_cursor_popover(
7636 &self,
7637 min_width: Pixels,
7638 max_width: Pixels,
7639 cursor_point: Point,
7640 style: &EditorStyle,
7641 accept_keystroke: Option<&gpui::Keystroke>,
7642 _window: &Window,
7643 cx: &mut Context<Editor>,
7644 ) -> Option<AnyElement> {
7645 let provider = self.edit_prediction_provider.as_ref()?;
7646
7647 if provider.provider.needs_terms_acceptance(cx) {
7648 return Some(
7649 h_flex()
7650 .min_w(min_width)
7651 .flex_1()
7652 .px_2()
7653 .py_1()
7654 .gap_3()
7655 .elevation_2(cx)
7656 .hover(|style| style.bg(cx.theme().colors().element_hover))
7657 .id("accept-terms")
7658 .cursor_pointer()
7659 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
7660 .on_click(cx.listener(|this, _event, window, cx| {
7661 cx.stop_propagation();
7662 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
7663 window.dispatch_action(
7664 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
7665 cx,
7666 );
7667 }))
7668 .child(
7669 h_flex()
7670 .flex_1()
7671 .gap_2()
7672 .child(Icon::new(IconName::ZedPredict))
7673 .child(Label::new("Accept Terms of Service"))
7674 .child(div().w_full())
7675 .child(
7676 Icon::new(IconName::ArrowUpRight)
7677 .color(Color::Muted)
7678 .size(IconSize::Small),
7679 )
7680 .into_any_element(),
7681 )
7682 .into_any(),
7683 );
7684 }
7685
7686 let is_refreshing = provider.provider.is_refreshing(cx);
7687
7688 fn pending_completion_container() -> Div {
7689 h_flex()
7690 .h_full()
7691 .flex_1()
7692 .gap_2()
7693 .child(Icon::new(IconName::ZedPredict))
7694 }
7695
7696 let completion = match &self.active_inline_completion {
7697 Some(prediction) => {
7698 if !self.has_visible_completions_menu() {
7699 const RADIUS: Pixels = px(6.);
7700 const BORDER_WIDTH: Pixels = px(1.);
7701
7702 return Some(
7703 h_flex()
7704 .elevation_2(cx)
7705 .border(BORDER_WIDTH)
7706 .border_color(cx.theme().colors().border)
7707 .when(accept_keystroke.is_none(), |el| {
7708 el.border_color(cx.theme().status().error)
7709 })
7710 .rounded(RADIUS)
7711 .rounded_tl(px(0.))
7712 .overflow_hidden()
7713 .child(div().px_1p5().child(match &prediction.completion {
7714 InlineCompletion::Move { target, snapshot } => {
7715 use text::ToPoint as _;
7716 if target.text_anchor.to_point(&snapshot).row > cursor_point.row
7717 {
7718 Icon::new(IconName::ZedPredictDown)
7719 } else {
7720 Icon::new(IconName::ZedPredictUp)
7721 }
7722 }
7723 InlineCompletion::Edit { .. } => Icon::new(IconName::ZedPredict),
7724 }))
7725 .child(
7726 h_flex()
7727 .gap_1()
7728 .py_1()
7729 .px_2()
7730 .rounded_r(RADIUS - BORDER_WIDTH)
7731 .border_l_1()
7732 .border_color(cx.theme().colors().border)
7733 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7734 .when(self.edit_prediction_preview.released_too_fast(), |el| {
7735 el.child(
7736 Label::new("Hold")
7737 .size(LabelSize::Small)
7738 .when(accept_keystroke.is_none(), |el| {
7739 el.strikethrough()
7740 })
7741 .line_height_style(LineHeightStyle::UiLabel),
7742 )
7743 })
7744 .id("edit_prediction_cursor_popover_keybind")
7745 .when(accept_keystroke.is_none(), |el| {
7746 let status_colors = cx.theme().status();
7747
7748 el.bg(status_colors.error_background)
7749 .border_color(status_colors.error.opacity(0.6))
7750 .child(Icon::new(IconName::Info).color(Color::Error))
7751 .cursor_default()
7752 .hoverable_tooltip(move |_window, cx| {
7753 cx.new(|_| MissingEditPredictionKeybindingTooltip)
7754 .into()
7755 })
7756 })
7757 .when_some(
7758 accept_keystroke.as_ref(),
7759 |el, accept_keystroke| {
7760 el.child(h_flex().children(ui::render_modifiers(
7761 &accept_keystroke.modifiers,
7762 PlatformStyle::platform(),
7763 Some(Color::Default),
7764 Some(IconSize::XSmall.rems().into()),
7765 false,
7766 )))
7767 },
7768 ),
7769 )
7770 .into_any(),
7771 );
7772 }
7773
7774 self.render_edit_prediction_cursor_popover_preview(
7775 prediction,
7776 cursor_point,
7777 style,
7778 cx,
7779 )?
7780 }
7781
7782 None if is_refreshing => match &self.stale_inline_completion_in_menu {
7783 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
7784 stale_completion,
7785 cursor_point,
7786 style,
7787 cx,
7788 )?,
7789
7790 None => {
7791 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
7792 }
7793 },
7794
7795 None => pending_completion_container().child(Label::new("No Prediction")),
7796 };
7797
7798 let completion = if is_refreshing {
7799 completion
7800 .with_animation(
7801 "loading-completion",
7802 Animation::new(Duration::from_secs(2))
7803 .repeat()
7804 .with_easing(pulsating_between(0.4, 0.8)),
7805 |label, delta| label.opacity(delta),
7806 )
7807 .into_any_element()
7808 } else {
7809 completion.into_any_element()
7810 };
7811
7812 let has_completion = self.active_inline_completion.is_some();
7813
7814 let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
7815 Some(
7816 h_flex()
7817 .min_w(min_width)
7818 .max_w(max_width)
7819 .flex_1()
7820 .elevation_2(cx)
7821 .border_color(cx.theme().colors().border)
7822 .child(
7823 div()
7824 .flex_1()
7825 .py_1()
7826 .px_2()
7827 .overflow_hidden()
7828 .child(completion),
7829 )
7830 .when_some(accept_keystroke, |el, accept_keystroke| {
7831 if !accept_keystroke.modifiers.modified() {
7832 return el;
7833 }
7834
7835 el.child(
7836 h_flex()
7837 .h_full()
7838 .border_l_1()
7839 .rounded_r_lg()
7840 .border_color(cx.theme().colors().border)
7841 .bg(Self::edit_prediction_line_popover_bg_color(cx))
7842 .gap_1()
7843 .py_1()
7844 .px_2()
7845 .child(
7846 h_flex()
7847 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7848 .when(is_platform_style_mac, |parent| parent.gap_1())
7849 .child(h_flex().children(ui::render_modifiers(
7850 &accept_keystroke.modifiers,
7851 PlatformStyle::platform(),
7852 Some(if !has_completion {
7853 Color::Muted
7854 } else {
7855 Color::Default
7856 }),
7857 None,
7858 false,
7859 ))),
7860 )
7861 .child(Label::new("Preview").into_any_element())
7862 .opacity(if has_completion { 1.0 } else { 0.4 }),
7863 )
7864 })
7865 .into_any(),
7866 )
7867 }
7868
7869 fn render_edit_prediction_cursor_popover_preview(
7870 &self,
7871 completion: &InlineCompletionState,
7872 cursor_point: Point,
7873 style: &EditorStyle,
7874 cx: &mut Context<Editor>,
7875 ) -> Option<Div> {
7876 use text::ToPoint as _;
7877
7878 fn render_relative_row_jump(
7879 prefix: impl Into<String>,
7880 current_row: u32,
7881 target_row: u32,
7882 ) -> Div {
7883 let (row_diff, arrow) = if target_row < current_row {
7884 (current_row - target_row, IconName::ArrowUp)
7885 } else {
7886 (target_row - current_row, IconName::ArrowDown)
7887 };
7888
7889 h_flex()
7890 .child(
7891 Label::new(format!("{}{}", prefix.into(), row_diff))
7892 .color(Color::Muted)
7893 .size(LabelSize::Small),
7894 )
7895 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
7896 }
7897
7898 match &completion.completion {
7899 InlineCompletion::Move {
7900 target, snapshot, ..
7901 } => Some(
7902 h_flex()
7903 .px_2()
7904 .gap_2()
7905 .flex_1()
7906 .child(
7907 if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
7908 Icon::new(IconName::ZedPredictDown)
7909 } else {
7910 Icon::new(IconName::ZedPredictUp)
7911 },
7912 )
7913 .child(Label::new("Jump to Edit")),
7914 ),
7915
7916 InlineCompletion::Edit {
7917 edits,
7918 edit_preview,
7919 snapshot,
7920 display_mode: _,
7921 } => {
7922 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
7923
7924 let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
7925 &snapshot,
7926 &edits,
7927 edit_preview.as_ref()?,
7928 true,
7929 cx,
7930 )
7931 .first_line_preview();
7932
7933 let styled_text = gpui::StyledText::new(highlighted_edits.text)
7934 .with_default_highlights(&style.text, highlighted_edits.highlights);
7935
7936 let preview = h_flex()
7937 .gap_1()
7938 .min_w_16()
7939 .child(styled_text)
7940 .when(has_more_lines, |parent| parent.child("…"));
7941
7942 let left = if first_edit_row != cursor_point.row {
7943 render_relative_row_jump("", cursor_point.row, first_edit_row)
7944 .into_any_element()
7945 } else {
7946 Icon::new(IconName::ZedPredict).into_any_element()
7947 };
7948
7949 Some(
7950 h_flex()
7951 .h_full()
7952 .flex_1()
7953 .gap_2()
7954 .pr_1()
7955 .overflow_x_hidden()
7956 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
7957 .child(left)
7958 .child(preview),
7959 )
7960 }
7961 }
7962 }
7963
7964 fn render_context_menu(
7965 &self,
7966 style: &EditorStyle,
7967 max_height_in_lines: u32,
7968 window: &mut Window,
7969 cx: &mut Context<Editor>,
7970 ) -> Option<AnyElement> {
7971 let menu = self.context_menu.borrow();
7972 let menu = menu.as_ref()?;
7973 if !menu.visible() {
7974 return None;
7975 };
7976 Some(menu.render(style, max_height_in_lines, window, cx))
7977 }
7978
7979 fn render_context_menu_aside(
7980 &mut self,
7981 max_size: Size<Pixels>,
7982 window: &mut Window,
7983 cx: &mut Context<Editor>,
7984 ) -> Option<AnyElement> {
7985 self.context_menu.borrow_mut().as_mut().and_then(|menu| {
7986 if menu.visible() {
7987 menu.render_aside(self, max_size, window, cx)
7988 } else {
7989 None
7990 }
7991 })
7992 }
7993
7994 fn hide_context_menu(
7995 &mut self,
7996 window: &mut Window,
7997 cx: &mut Context<Self>,
7998 ) -> Option<CodeContextMenu> {
7999 cx.notify();
8000 self.completion_tasks.clear();
8001 let context_menu = self.context_menu.borrow_mut().take();
8002 self.stale_inline_completion_in_menu.take();
8003 self.update_visible_inline_completion(window, cx);
8004 context_menu
8005 }
8006
8007 fn show_snippet_choices(
8008 &mut self,
8009 choices: &Vec<String>,
8010 selection: Range<Anchor>,
8011 cx: &mut Context<Self>,
8012 ) {
8013 if selection.start.buffer_id.is_none() {
8014 return;
8015 }
8016 let buffer_id = selection.start.buffer_id.unwrap();
8017 let buffer = self.buffer().read(cx).buffer(buffer_id);
8018 let id = post_inc(&mut self.next_completion_id);
8019
8020 if let Some(buffer) = buffer {
8021 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
8022 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
8023 ));
8024 }
8025 }
8026
8027 pub fn insert_snippet(
8028 &mut self,
8029 insertion_ranges: &[Range<usize>],
8030 snippet: Snippet,
8031 window: &mut Window,
8032 cx: &mut Context<Self>,
8033 ) -> Result<()> {
8034 struct Tabstop<T> {
8035 is_end_tabstop: bool,
8036 ranges: Vec<Range<T>>,
8037 choices: Option<Vec<String>>,
8038 }
8039
8040 let tabstops = self.buffer.update(cx, |buffer, cx| {
8041 let snippet_text: Arc<str> = snippet.text.clone().into();
8042 let edits = insertion_ranges
8043 .iter()
8044 .cloned()
8045 .map(|range| (range, snippet_text.clone()));
8046 buffer.edit(edits, Some(AutoindentMode::EachLine), cx);
8047
8048 let snapshot = &*buffer.read(cx);
8049 let snippet = &snippet;
8050 snippet
8051 .tabstops
8052 .iter()
8053 .map(|tabstop| {
8054 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
8055 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
8056 });
8057 let mut tabstop_ranges = tabstop
8058 .ranges
8059 .iter()
8060 .flat_map(|tabstop_range| {
8061 let mut delta = 0_isize;
8062 insertion_ranges.iter().map(move |insertion_range| {
8063 let insertion_start = insertion_range.start as isize + delta;
8064 delta +=
8065 snippet.text.len() as isize - insertion_range.len() as isize;
8066
8067 let start = ((insertion_start + tabstop_range.start) as usize)
8068 .min(snapshot.len());
8069 let end = ((insertion_start + tabstop_range.end) as usize)
8070 .min(snapshot.len());
8071 snapshot.anchor_before(start)..snapshot.anchor_after(end)
8072 })
8073 })
8074 .collect::<Vec<_>>();
8075 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
8076
8077 Tabstop {
8078 is_end_tabstop,
8079 ranges: tabstop_ranges,
8080 choices: tabstop.choices.clone(),
8081 }
8082 })
8083 .collect::<Vec<_>>()
8084 });
8085 if let Some(tabstop) = tabstops.first() {
8086 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8087 s.select_ranges(tabstop.ranges.iter().cloned());
8088 });
8089
8090 if let Some(choices) = &tabstop.choices {
8091 if let Some(selection) = tabstop.ranges.first() {
8092 self.show_snippet_choices(choices, selection.clone(), cx)
8093 }
8094 }
8095
8096 // If we're already at the last tabstop and it's at the end of the snippet,
8097 // we're done, we don't need to keep the state around.
8098 if !tabstop.is_end_tabstop {
8099 let choices = tabstops
8100 .iter()
8101 .map(|tabstop| tabstop.choices.clone())
8102 .collect();
8103
8104 let ranges = tabstops
8105 .into_iter()
8106 .map(|tabstop| tabstop.ranges)
8107 .collect::<Vec<_>>();
8108
8109 self.snippet_stack.push(SnippetState {
8110 active_index: 0,
8111 ranges,
8112 choices,
8113 });
8114 }
8115
8116 // Check whether the just-entered snippet ends with an auto-closable bracket.
8117 if self.autoclose_regions.is_empty() {
8118 let snapshot = self.buffer.read(cx).snapshot(cx);
8119 for selection in &mut self.selections.all::<Point>(cx) {
8120 let selection_head = selection.head();
8121 let Some(scope) = snapshot.language_scope_at(selection_head) else {
8122 continue;
8123 };
8124
8125 let mut bracket_pair = None;
8126 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
8127 let prev_chars = snapshot
8128 .reversed_chars_at(selection_head)
8129 .collect::<String>();
8130 for (pair, enabled) in scope.brackets() {
8131 if enabled
8132 && pair.close
8133 && prev_chars.starts_with(pair.start.as_str())
8134 && next_chars.starts_with(pair.end.as_str())
8135 {
8136 bracket_pair = Some(pair.clone());
8137 break;
8138 }
8139 }
8140 if let Some(pair) = bracket_pair {
8141 let snapshot_settings = snapshot.language_settings_at(selection_head, cx);
8142 let autoclose_enabled =
8143 self.use_autoclose && snapshot_settings.use_autoclose;
8144 if autoclose_enabled {
8145 let start = snapshot.anchor_after(selection_head);
8146 let end = snapshot.anchor_after(selection_head);
8147 self.autoclose_regions.push(AutocloseRegion {
8148 selection_id: selection.id,
8149 range: start..end,
8150 pair,
8151 });
8152 }
8153 }
8154 }
8155 }
8156 }
8157 Ok(())
8158 }
8159
8160 pub fn move_to_next_snippet_tabstop(
8161 &mut self,
8162 window: &mut Window,
8163 cx: &mut Context<Self>,
8164 ) -> bool {
8165 self.move_to_snippet_tabstop(Bias::Right, window, cx)
8166 }
8167
8168 pub fn move_to_prev_snippet_tabstop(
8169 &mut self,
8170 window: &mut Window,
8171 cx: &mut Context<Self>,
8172 ) -> bool {
8173 self.move_to_snippet_tabstop(Bias::Left, window, cx)
8174 }
8175
8176 pub fn move_to_snippet_tabstop(
8177 &mut self,
8178 bias: Bias,
8179 window: &mut Window,
8180 cx: &mut Context<Self>,
8181 ) -> bool {
8182 if let Some(mut snippet) = self.snippet_stack.pop() {
8183 match bias {
8184 Bias::Left => {
8185 if snippet.active_index > 0 {
8186 snippet.active_index -= 1;
8187 } else {
8188 self.snippet_stack.push(snippet);
8189 return false;
8190 }
8191 }
8192 Bias::Right => {
8193 if snippet.active_index + 1 < snippet.ranges.len() {
8194 snippet.active_index += 1;
8195 } else {
8196 self.snippet_stack.push(snippet);
8197 return false;
8198 }
8199 }
8200 }
8201 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
8202 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8203 s.select_anchor_ranges(current_ranges.iter().cloned())
8204 });
8205
8206 if let Some(choices) = &snippet.choices[snippet.active_index] {
8207 if let Some(selection) = current_ranges.first() {
8208 self.show_snippet_choices(&choices, selection.clone(), cx);
8209 }
8210 }
8211
8212 // If snippet state is not at the last tabstop, push it back on the stack
8213 if snippet.active_index + 1 < snippet.ranges.len() {
8214 self.snippet_stack.push(snippet);
8215 }
8216 return true;
8217 }
8218 }
8219
8220 false
8221 }
8222
8223 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
8224 self.transact(window, cx, |this, window, cx| {
8225 this.select_all(&SelectAll, window, cx);
8226 this.insert("", window, cx);
8227 });
8228 }
8229
8230 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
8231 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8232 self.transact(window, cx, |this, window, cx| {
8233 this.select_autoclose_pair(window, cx);
8234 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
8235 if !this.linked_edit_ranges.is_empty() {
8236 let selections = this.selections.all::<MultiBufferPoint>(cx);
8237 let snapshot = this.buffer.read(cx).snapshot(cx);
8238
8239 for selection in selections.iter() {
8240 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
8241 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
8242 if selection_start.buffer_id != selection_end.buffer_id {
8243 continue;
8244 }
8245 if let Some(ranges) =
8246 this.linked_editing_ranges_for(selection_start..selection_end, cx)
8247 {
8248 for (buffer, entries) in ranges {
8249 linked_ranges.entry(buffer).or_default().extend(entries);
8250 }
8251 }
8252 }
8253 }
8254
8255 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8256 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
8257 for selection in &mut selections {
8258 if selection.is_empty() {
8259 let old_head = selection.head();
8260 let mut new_head =
8261 movement::left(&display_map, old_head.to_display_point(&display_map))
8262 .to_point(&display_map);
8263 if let Some((buffer, line_buffer_range)) = display_map
8264 .buffer_snapshot
8265 .buffer_line_for_row(MultiBufferRow(old_head.row))
8266 {
8267 let indent_size = buffer.indent_size_for_line(line_buffer_range.start.row);
8268 let indent_len = match indent_size.kind {
8269 IndentKind::Space => {
8270 buffer.settings_at(line_buffer_range.start, cx).tab_size
8271 }
8272 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
8273 };
8274 if old_head.column <= indent_size.len && old_head.column > 0 {
8275 let indent_len = indent_len.get();
8276 new_head = cmp::min(
8277 new_head,
8278 MultiBufferPoint::new(
8279 old_head.row,
8280 ((old_head.column - 1) / indent_len) * indent_len,
8281 ),
8282 );
8283 }
8284 }
8285
8286 selection.set_head(new_head, SelectionGoal::None);
8287 }
8288 }
8289
8290 this.signature_help_state.set_backspace_pressed(true);
8291 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8292 s.select(selections)
8293 });
8294 this.insert("", window, cx);
8295 let empty_str: Arc<str> = Arc::from("");
8296 for (buffer, edits) in linked_ranges {
8297 let snapshot = buffer.read(cx).snapshot();
8298 use text::ToPoint as TP;
8299
8300 let edits = edits
8301 .into_iter()
8302 .map(|range| {
8303 let end_point = TP::to_point(&range.end, &snapshot);
8304 let mut start_point = TP::to_point(&range.start, &snapshot);
8305
8306 if end_point == start_point {
8307 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
8308 .saturating_sub(1);
8309 start_point =
8310 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
8311 };
8312
8313 (start_point..end_point, empty_str.clone())
8314 })
8315 .sorted_by_key(|(range, _)| range.start)
8316 .collect::<Vec<_>>();
8317 buffer.update(cx, |this, cx| {
8318 this.edit(edits, None, cx);
8319 })
8320 }
8321 this.refresh_inline_completion(true, false, window, cx);
8322 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
8323 });
8324 }
8325
8326 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
8327 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8328 self.transact(window, cx, |this, window, cx| {
8329 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8330 s.move_with(|map, selection| {
8331 if selection.is_empty() {
8332 let cursor = movement::right(map, selection.head());
8333 selection.end = cursor;
8334 selection.reversed = true;
8335 selection.goal = SelectionGoal::None;
8336 }
8337 })
8338 });
8339 this.insert("", window, cx);
8340 this.refresh_inline_completion(true, false, window, cx);
8341 });
8342 }
8343
8344 pub fn backtab(&mut self, _: &Backtab, window: &mut Window, cx: &mut Context<Self>) {
8345 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8346 if self.move_to_prev_snippet_tabstop(window, cx) {
8347 return;
8348 }
8349 self.outdent(&Outdent, window, cx);
8350 }
8351
8352 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
8353 if self.move_to_next_snippet_tabstop(window, cx) {
8354 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8355 return;
8356 }
8357 if self.read_only(cx) {
8358 return;
8359 }
8360 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8361 let mut selections = self.selections.all_adjusted(cx);
8362 let buffer = self.buffer.read(cx);
8363 let snapshot = buffer.snapshot(cx);
8364 let rows_iter = selections.iter().map(|s| s.head().row);
8365 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
8366
8367 let mut edits = Vec::new();
8368 let mut prev_edited_row = 0;
8369 let mut row_delta = 0;
8370 for selection in &mut selections {
8371 if selection.start.row != prev_edited_row {
8372 row_delta = 0;
8373 }
8374 prev_edited_row = selection.end.row;
8375
8376 // If the selection is non-empty, then increase the indentation of the selected lines.
8377 if !selection.is_empty() {
8378 row_delta =
8379 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8380 continue;
8381 }
8382
8383 // If the selection is empty and the cursor is in the leading whitespace before the
8384 // suggested indentation, then auto-indent the line.
8385 let cursor = selection.head();
8386 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
8387 if let Some(suggested_indent) =
8388 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
8389 {
8390 if cursor.column < suggested_indent.len
8391 && cursor.column <= current_indent.len
8392 && current_indent.len <= suggested_indent.len
8393 {
8394 selection.start = Point::new(cursor.row, suggested_indent.len);
8395 selection.end = selection.start;
8396 if row_delta == 0 {
8397 edits.extend(Buffer::edit_for_indent_size_adjustment(
8398 cursor.row,
8399 current_indent,
8400 suggested_indent,
8401 ));
8402 row_delta = suggested_indent.len - current_indent.len;
8403 }
8404 continue;
8405 }
8406 }
8407
8408 // Otherwise, insert a hard or soft tab.
8409 let settings = buffer.language_settings_at(cursor, cx);
8410 let tab_size = if settings.hard_tabs {
8411 IndentSize::tab()
8412 } else {
8413 let tab_size = settings.tab_size.get();
8414 let indent_remainder = snapshot
8415 .text_for_range(Point::new(cursor.row, 0)..cursor)
8416 .flat_map(str::chars)
8417 .fold(row_delta % tab_size, |counter: u32, c| {
8418 if c == '\t' {
8419 0
8420 } else {
8421 (counter + 1) % tab_size
8422 }
8423 });
8424
8425 let chars_to_next_tab_stop = tab_size - indent_remainder;
8426 IndentSize::spaces(chars_to_next_tab_stop)
8427 };
8428 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
8429 selection.end = selection.start;
8430 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
8431 row_delta += tab_size.len;
8432 }
8433
8434 self.transact(window, cx, |this, window, cx| {
8435 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8436 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8437 s.select(selections)
8438 });
8439 this.refresh_inline_completion(true, false, window, cx);
8440 });
8441 }
8442
8443 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
8444 if self.read_only(cx) {
8445 return;
8446 }
8447 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8448 let mut selections = self.selections.all::<Point>(cx);
8449 let mut prev_edited_row = 0;
8450 let mut row_delta = 0;
8451 let mut edits = Vec::new();
8452 let buffer = self.buffer.read(cx);
8453 let snapshot = buffer.snapshot(cx);
8454 for selection in &mut selections {
8455 if selection.start.row != prev_edited_row {
8456 row_delta = 0;
8457 }
8458 prev_edited_row = selection.end.row;
8459
8460 row_delta =
8461 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
8462 }
8463
8464 self.transact(window, cx, |this, window, cx| {
8465 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
8466 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8467 s.select(selections)
8468 });
8469 });
8470 }
8471
8472 fn indent_selection(
8473 buffer: &MultiBuffer,
8474 snapshot: &MultiBufferSnapshot,
8475 selection: &mut Selection<Point>,
8476 edits: &mut Vec<(Range<Point>, String)>,
8477 delta_for_start_row: u32,
8478 cx: &App,
8479 ) -> u32 {
8480 let settings = buffer.language_settings_at(selection.start, cx);
8481 let tab_size = settings.tab_size.get();
8482 let indent_kind = if settings.hard_tabs {
8483 IndentKind::Tab
8484 } else {
8485 IndentKind::Space
8486 };
8487 let mut start_row = selection.start.row;
8488 let mut end_row = selection.end.row + 1;
8489
8490 // If a selection ends at the beginning of a line, don't indent
8491 // that last line.
8492 if selection.end.column == 0 && selection.end.row > selection.start.row {
8493 end_row -= 1;
8494 }
8495
8496 // Avoid re-indenting a row that has already been indented by a
8497 // previous selection, but still update this selection's column
8498 // to reflect that indentation.
8499 if delta_for_start_row > 0 {
8500 start_row += 1;
8501 selection.start.column += delta_for_start_row;
8502 if selection.end.row == selection.start.row {
8503 selection.end.column += delta_for_start_row;
8504 }
8505 }
8506
8507 let mut delta_for_end_row = 0;
8508 let has_multiple_rows = start_row + 1 != end_row;
8509 for row in start_row..end_row {
8510 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
8511 let indent_delta = match (current_indent.kind, indent_kind) {
8512 (IndentKind::Space, IndentKind::Space) => {
8513 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
8514 IndentSize::spaces(columns_to_next_tab_stop)
8515 }
8516 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
8517 (_, IndentKind::Tab) => IndentSize::tab(),
8518 };
8519
8520 let start = if has_multiple_rows || current_indent.len < selection.start.column {
8521 0
8522 } else {
8523 selection.start.column
8524 };
8525 let row_start = Point::new(row, start);
8526 edits.push((
8527 row_start..row_start,
8528 indent_delta.chars().collect::<String>(),
8529 ));
8530
8531 // Update this selection's endpoints to reflect the indentation.
8532 if row == selection.start.row {
8533 selection.start.column += indent_delta.len;
8534 }
8535 if row == selection.end.row {
8536 selection.end.column += indent_delta.len;
8537 delta_for_end_row = indent_delta.len;
8538 }
8539 }
8540
8541 if selection.start.row == selection.end.row {
8542 delta_for_start_row + delta_for_end_row
8543 } else {
8544 delta_for_end_row
8545 }
8546 }
8547
8548 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
8549 if self.read_only(cx) {
8550 return;
8551 }
8552 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8553 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8554 let selections = self.selections.all::<Point>(cx);
8555 let mut deletion_ranges = Vec::new();
8556 let mut last_outdent = None;
8557 {
8558 let buffer = self.buffer.read(cx);
8559 let snapshot = buffer.snapshot(cx);
8560 for selection in &selections {
8561 let settings = buffer.language_settings_at(selection.start, cx);
8562 let tab_size = settings.tab_size.get();
8563 let mut rows = selection.spanned_rows(false, &display_map);
8564
8565 // Avoid re-outdenting a row that has already been outdented by a
8566 // previous selection.
8567 if let Some(last_row) = last_outdent {
8568 if last_row == rows.start {
8569 rows.start = rows.start.next_row();
8570 }
8571 }
8572 let has_multiple_rows = rows.len() > 1;
8573 for row in rows.iter_rows() {
8574 let indent_size = snapshot.indent_size_for_line(row);
8575 if indent_size.len > 0 {
8576 let deletion_len = match indent_size.kind {
8577 IndentKind::Space => {
8578 let columns_to_prev_tab_stop = indent_size.len % tab_size;
8579 if columns_to_prev_tab_stop == 0 {
8580 tab_size
8581 } else {
8582 columns_to_prev_tab_stop
8583 }
8584 }
8585 IndentKind::Tab => 1,
8586 };
8587 let start = if has_multiple_rows
8588 || deletion_len > selection.start.column
8589 || indent_size.len < selection.start.column
8590 {
8591 0
8592 } else {
8593 selection.start.column - deletion_len
8594 };
8595 deletion_ranges.push(
8596 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
8597 );
8598 last_outdent = Some(row);
8599 }
8600 }
8601 }
8602 }
8603
8604 self.transact(window, cx, |this, window, cx| {
8605 this.buffer.update(cx, |buffer, cx| {
8606 let empty_str: Arc<str> = Arc::default();
8607 buffer.edit(
8608 deletion_ranges
8609 .into_iter()
8610 .map(|range| (range, empty_str.clone())),
8611 None,
8612 cx,
8613 );
8614 });
8615 let selections = this.selections.all::<usize>(cx);
8616 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8617 s.select(selections)
8618 });
8619 });
8620 }
8621
8622 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
8623 if self.read_only(cx) {
8624 return;
8625 }
8626 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8627 let selections = self
8628 .selections
8629 .all::<usize>(cx)
8630 .into_iter()
8631 .map(|s| s.range());
8632
8633 self.transact(window, cx, |this, window, cx| {
8634 this.buffer.update(cx, |buffer, cx| {
8635 buffer.autoindent_ranges(selections, cx);
8636 });
8637 let selections = this.selections.all::<usize>(cx);
8638 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8639 s.select(selections)
8640 });
8641 });
8642 }
8643
8644 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
8645 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8646 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8647 let selections = self.selections.all::<Point>(cx);
8648
8649 let mut new_cursors = Vec::new();
8650 let mut edit_ranges = Vec::new();
8651 let mut selections = selections.iter().peekable();
8652 while let Some(selection) = selections.next() {
8653 let mut rows = selection.spanned_rows(false, &display_map);
8654 let goal_display_column = selection.head().to_display_point(&display_map).column();
8655
8656 // Accumulate contiguous regions of rows that we want to delete.
8657 while let Some(next_selection) = selections.peek() {
8658 let next_rows = next_selection.spanned_rows(false, &display_map);
8659 if next_rows.start <= rows.end {
8660 rows.end = next_rows.end;
8661 selections.next().unwrap();
8662 } else {
8663 break;
8664 }
8665 }
8666
8667 let buffer = &display_map.buffer_snapshot;
8668 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
8669 let edit_end;
8670 let cursor_buffer_row;
8671 if buffer.max_point().row >= rows.end.0 {
8672 // If there's a line after the range, delete the \n from the end of the row range
8673 // and position the cursor on the next line.
8674 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
8675 cursor_buffer_row = rows.end;
8676 } else {
8677 // If there isn't a line after the range, delete the \n from the line before the
8678 // start of the row range and position the cursor there.
8679 edit_start = edit_start.saturating_sub(1);
8680 edit_end = buffer.len();
8681 cursor_buffer_row = rows.start.previous_row();
8682 }
8683
8684 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
8685 *cursor.column_mut() =
8686 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
8687
8688 new_cursors.push((
8689 selection.id,
8690 buffer.anchor_after(cursor.to_point(&display_map)),
8691 ));
8692 edit_ranges.push(edit_start..edit_end);
8693 }
8694
8695 self.transact(window, cx, |this, window, cx| {
8696 let buffer = this.buffer.update(cx, |buffer, cx| {
8697 let empty_str: Arc<str> = Arc::default();
8698 buffer.edit(
8699 edit_ranges
8700 .into_iter()
8701 .map(|range| (range, empty_str.clone())),
8702 None,
8703 cx,
8704 );
8705 buffer.snapshot(cx)
8706 });
8707 let new_selections = new_cursors
8708 .into_iter()
8709 .map(|(id, cursor)| {
8710 let cursor = cursor.to_point(&buffer);
8711 Selection {
8712 id,
8713 start: cursor,
8714 end: cursor,
8715 reversed: false,
8716 goal: SelectionGoal::None,
8717 }
8718 })
8719 .collect();
8720
8721 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8722 s.select(new_selections);
8723 });
8724 });
8725 }
8726
8727 pub fn join_lines_impl(
8728 &mut self,
8729 insert_whitespace: bool,
8730 window: &mut Window,
8731 cx: &mut Context<Self>,
8732 ) {
8733 if self.read_only(cx) {
8734 return;
8735 }
8736 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
8737 for selection in self.selections.all::<Point>(cx) {
8738 let start = MultiBufferRow(selection.start.row);
8739 // Treat single line selections as if they include the next line. Otherwise this action
8740 // would do nothing for single line selections individual cursors.
8741 let end = if selection.start.row == selection.end.row {
8742 MultiBufferRow(selection.start.row + 1)
8743 } else {
8744 MultiBufferRow(selection.end.row)
8745 };
8746
8747 if let Some(last_row_range) = row_ranges.last_mut() {
8748 if start <= last_row_range.end {
8749 last_row_range.end = end;
8750 continue;
8751 }
8752 }
8753 row_ranges.push(start..end);
8754 }
8755
8756 let snapshot = self.buffer.read(cx).snapshot(cx);
8757 let mut cursor_positions = Vec::new();
8758 for row_range in &row_ranges {
8759 let anchor = snapshot.anchor_before(Point::new(
8760 row_range.end.previous_row().0,
8761 snapshot.line_len(row_range.end.previous_row()),
8762 ));
8763 cursor_positions.push(anchor..anchor);
8764 }
8765
8766 self.transact(window, cx, |this, window, cx| {
8767 for row_range in row_ranges.into_iter().rev() {
8768 for row in row_range.iter_rows().rev() {
8769 let end_of_line = Point::new(row.0, snapshot.line_len(row));
8770 let next_line_row = row.next_row();
8771 let indent = snapshot.indent_size_for_line(next_line_row);
8772 let start_of_next_line = Point::new(next_line_row.0, indent.len);
8773
8774 let replace =
8775 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
8776 " "
8777 } else {
8778 ""
8779 };
8780
8781 this.buffer.update(cx, |buffer, cx| {
8782 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
8783 });
8784 }
8785 }
8786
8787 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8788 s.select_anchor_ranges(cursor_positions)
8789 });
8790 });
8791 }
8792
8793 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
8794 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8795 self.join_lines_impl(true, window, cx);
8796 }
8797
8798 pub fn sort_lines_case_sensitive(
8799 &mut self,
8800 _: &SortLinesCaseSensitive,
8801 window: &mut Window,
8802 cx: &mut Context<Self>,
8803 ) {
8804 self.manipulate_lines(window, cx, |lines| lines.sort())
8805 }
8806
8807 pub fn sort_lines_case_insensitive(
8808 &mut self,
8809 _: &SortLinesCaseInsensitive,
8810 window: &mut Window,
8811 cx: &mut Context<Self>,
8812 ) {
8813 self.manipulate_lines(window, cx, |lines| {
8814 lines.sort_by_key(|line| line.to_lowercase())
8815 })
8816 }
8817
8818 pub fn unique_lines_case_insensitive(
8819 &mut self,
8820 _: &UniqueLinesCaseInsensitive,
8821 window: &mut Window,
8822 cx: &mut Context<Self>,
8823 ) {
8824 self.manipulate_lines(window, cx, |lines| {
8825 let mut seen = HashSet::default();
8826 lines.retain(|line| seen.insert(line.to_lowercase()));
8827 })
8828 }
8829
8830 pub fn unique_lines_case_sensitive(
8831 &mut self,
8832 _: &UniqueLinesCaseSensitive,
8833 window: &mut Window,
8834 cx: &mut Context<Self>,
8835 ) {
8836 self.manipulate_lines(window, cx, |lines| {
8837 let mut seen = HashSet::default();
8838 lines.retain(|line| seen.insert(*line));
8839 })
8840 }
8841
8842 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
8843 let Some(project) = self.project.clone() else {
8844 return;
8845 };
8846 self.reload(project, window, cx)
8847 .detach_and_notify_err(window, cx);
8848 }
8849
8850 pub fn restore_file(
8851 &mut self,
8852 _: &::git::RestoreFile,
8853 window: &mut Window,
8854 cx: &mut Context<Self>,
8855 ) {
8856 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8857 let mut buffer_ids = HashSet::default();
8858 let snapshot = self.buffer().read(cx).snapshot(cx);
8859 for selection in self.selections.all::<usize>(cx) {
8860 buffer_ids.extend(snapshot.buffer_ids_for_range(selection.range()))
8861 }
8862
8863 let buffer = self.buffer().read(cx);
8864 let ranges = buffer_ids
8865 .into_iter()
8866 .flat_map(|buffer_id| buffer.excerpt_ranges_for_buffer(buffer_id, cx))
8867 .collect::<Vec<_>>();
8868
8869 self.restore_hunks_in_ranges(ranges, window, cx);
8870 }
8871
8872 pub fn git_restore(&mut self, _: &Restore, window: &mut Window, cx: &mut Context<Self>) {
8873 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
8874 let selections = self
8875 .selections
8876 .all(cx)
8877 .into_iter()
8878 .map(|s| s.range())
8879 .collect();
8880 self.restore_hunks_in_ranges(selections, window, cx);
8881 }
8882
8883 pub fn restore_hunks_in_ranges(
8884 &mut self,
8885 ranges: Vec<Range<Point>>,
8886 window: &mut Window,
8887 cx: &mut Context<Editor>,
8888 ) {
8889 let mut revert_changes = HashMap::default();
8890 let chunk_by = self
8891 .snapshot(window, cx)
8892 .hunks_for_ranges(ranges)
8893 .into_iter()
8894 .chunk_by(|hunk| hunk.buffer_id);
8895 for (buffer_id, hunks) in &chunk_by {
8896 let hunks = hunks.collect::<Vec<_>>();
8897 for hunk in &hunks {
8898 self.prepare_restore_change(&mut revert_changes, hunk, cx);
8899 }
8900 self.do_stage_or_unstage(false, buffer_id, hunks.into_iter(), cx);
8901 }
8902 drop(chunk_by);
8903 if !revert_changes.is_empty() {
8904 self.transact(window, cx, |editor, window, cx| {
8905 editor.restore(revert_changes, window, cx);
8906 });
8907 }
8908 }
8909
8910 pub fn open_active_item_in_terminal(
8911 &mut self,
8912 _: &OpenInTerminal,
8913 window: &mut Window,
8914 cx: &mut Context<Self>,
8915 ) {
8916 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
8917 let project_path = buffer.read(cx).project_path(cx)?;
8918 let project = self.project.as_ref()?.read(cx);
8919 let entry = project.entry_for_path(&project_path, cx)?;
8920 let parent = match &entry.canonical_path {
8921 Some(canonical_path) => canonical_path.to_path_buf(),
8922 None => project.absolute_path(&project_path, cx)?,
8923 }
8924 .parent()?
8925 .to_path_buf();
8926 Some(parent)
8927 }) {
8928 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
8929 }
8930 }
8931
8932 fn set_breakpoint_context_menu(
8933 &mut self,
8934 display_row: DisplayRow,
8935 position: Option<Anchor>,
8936 clicked_point: gpui::Point<Pixels>,
8937 window: &mut Window,
8938 cx: &mut Context<Self>,
8939 ) {
8940 if !cx.has_flag::<Debugger>() {
8941 return;
8942 }
8943 let source = self
8944 .buffer
8945 .read(cx)
8946 .snapshot(cx)
8947 .anchor_before(Point::new(display_row.0, 0u32));
8948
8949 let context_menu = self.breakpoint_context_menu(position.unwrap_or(source), window, cx);
8950
8951 self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
8952 self,
8953 source,
8954 clicked_point,
8955 context_menu,
8956 window,
8957 cx,
8958 );
8959 }
8960
8961 fn add_edit_breakpoint_block(
8962 &mut self,
8963 anchor: Anchor,
8964 breakpoint: &Breakpoint,
8965 edit_action: BreakpointPromptEditAction,
8966 window: &mut Window,
8967 cx: &mut Context<Self>,
8968 ) {
8969 let weak_editor = cx.weak_entity();
8970 let bp_prompt = cx.new(|cx| {
8971 BreakpointPromptEditor::new(
8972 weak_editor,
8973 anchor,
8974 breakpoint.clone(),
8975 edit_action,
8976 window,
8977 cx,
8978 )
8979 });
8980
8981 let height = bp_prompt.update(cx, |this, cx| {
8982 this.prompt
8983 .update(cx, |prompt, cx| prompt.max_point(cx).row().0 + 1 + 2)
8984 });
8985 let cloned_prompt = bp_prompt.clone();
8986 let blocks = vec![BlockProperties {
8987 style: BlockStyle::Sticky,
8988 placement: BlockPlacement::Above(anchor),
8989 height: Some(height),
8990 render: Arc::new(move |cx| {
8991 *cloned_prompt.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
8992 cloned_prompt.clone().into_any_element()
8993 }),
8994 priority: 0,
8995 }];
8996
8997 let focus_handle = bp_prompt.focus_handle(cx);
8998 window.focus(&focus_handle);
8999
9000 let block_ids = self.insert_blocks(blocks, None, cx);
9001 bp_prompt.update(cx, |prompt, _| {
9002 prompt.add_block_ids(block_ids);
9003 });
9004 }
9005
9006 pub(crate) fn breakpoint_at_row(
9007 &self,
9008 row: u32,
9009 window: &mut Window,
9010 cx: &mut Context<Self>,
9011 ) -> Option<(Anchor, Breakpoint)> {
9012 let snapshot = self.snapshot(window, cx);
9013 let breakpoint_position = snapshot.buffer_snapshot.anchor_before(Point::new(row, 0));
9014
9015 self.breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9016 }
9017
9018 pub(crate) fn breakpoint_at_anchor(
9019 &self,
9020 breakpoint_position: Anchor,
9021 snapshot: &EditorSnapshot,
9022 cx: &mut Context<Self>,
9023 ) -> Option<(Anchor, Breakpoint)> {
9024 let project = self.project.clone()?;
9025
9026 let buffer_id = breakpoint_position.buffer_id.or_else(|| {
9027 snapshot
9028 .buffer_snapshot
9029 .buffer_id_for_excerpt(breakpoint_position.excerpt_id)
9030 })?;
9031
9032 let enclosing_excerpt = breakpoint_position.excerpt_id;
9033 let buffer = project.read_with(cx, |project, cx| project.buffer_for_id(buffer_id, cx))?;
9034 let buffer_snapshot = buffer.read(cx).snapshot();
9035
9036 let row = buffer_snapshot
9037 .summary_for_anchor::<text::PointUtf16>(&breakpoint_position.text_anchor)
9038 .row;
9039
9040 let line_len = snapshot.buffer_snapshot.line_len(MultiBufferRow(row));
9041 let anchor_end = snapshot
9042 .buffer_snapshot
9043 .anchor_after(Point::new(row, line_len));
9044
9045 let bp = self
9046 .breakpoint_store
9047 .as_ref()?
9048 .read_with(cx, |breakpoint_store, cx| {
9049 breakpoint_store
9050 .breakpoints(
9051 &buffer,
9052 Some(breakpoint_position.text_anchor..anchor_end.text_anchor),
9053 &buffer_snapshot,
9054 cx,
9055 )
9056 .next()
9057 .and_then(|(anchor, bp)| {
9058 let breakpoint_row = buffer_snapshot
9059 .summary_for_anchor::<text::PointUtf16>(anchor)
9060 .row;
9061
9062 if breakpoint_row == row {
9063 snapshot
9064 .buffer_snapshot
9065 .anchor_in_excerpt(enclosing_excerpt, *anchor)
9066 .map(|anchor| (anchor, bp.clone()))
9067 } else {
9068 None
9069 }
9070 })
9071 });
9072 bp
9073 }
9074
9075 pub fn edit_log_breakpoint(
9076 &mut self,
9077 _: &EditLogBreakpoint,
9078 window: &mut Window,
9079 cx: &mut Context<Self>,
9080 ) {
9081 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9082 let breakpoint = breakpoint.unwrap_or_else(|| Breakpoint {
9083 message: None,
9084 state: BreakpointState::Enabled,
9085 condition: None,
9086 hit_condition: None,
9087 });
9088
9089 self.add_edit_breakpoint_block(
9090 anchor,
9091 &breakpoint,
9092 BreakpointPromptEditAction::Log,
9093 window,
9094 cx,
9095 );
9096 }
9097 }
9098
9099 fn breakpoints_at_cursors(
9100 &self,
9101 window: &mut Window,
9102 cx: &mut Context<Self>,
9103 ) -> Vec<(Anchor, Option<Breakpoint>)> {
9104 let snapshot = self.snapshot(window, cx);
9105 let cursors = self
9106 .selections
9107 .disjoint_anchors()
9108 .into_iter()
9109 .map(|selection| {
9110 let cursor_position: Point = selection.head().to_point(&snapshot.buffer_snapshot);
9111
9112 let breakpoint_position = self
9113 .breakpoint_at_row(cursor_position.row, window, cx)
9114 .map(|bp| bp.0)
9115 .unwrap_or_else(|| {
9116 snapshot
9117 .display_snapshot
9118 .buffer_snapshot
9119 .anchor_after(Point::new(cursor_position.row, 0))
9120 });
9121
9122 let breakpoint = self
9123 .breakpoint_at_anchor(breakpoint_position, &snapshot, cx)
9124 .map(|(anchor, breakpoint)| (anchor, Some(breakpoint)));
9125
9126 breakpoint.unwrap_or_else(|| (breakpoint_position, None))
9127 })
9128 // There might be multiple cursors on the same line; all of them should have the same anchors though as their breakpoints positions, which makes it possible to sort and dedup the list.
9129 .collect::<HashMap<Anchor, _>>();
9130
9131 cursors.into_iter().collect()
9132 }
9133
9134 pub fn enable_breakpoint(
9135 &mut self,
9136 _: &crate::actions::EnableBreakpoint,
9137 window: &mut Window,
9138 cx: &mut Context<Self>,
9139 ) {
9140 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9141 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_disabled()) else {
9142 continue;
9143 };
9144 self.edit_breakpoint_at_anchor(
9145 anchor,
9146 breakpoint,
9147 BreakpointEditAction::InvertState,
9148 cx,
9149 );
9150 }
9151 }
9152
9153 pub fn disable_breakpoint(
9154 &mut self,
9155 _: &crate::actions::DisableBreakpoint,
9156 window: &mut Window,
9157 cx: &mut Context<Self>,
9158 ) {
9159 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9160 let Some(breakpoint) = breakpoint.filter(|breakpoint| breakpoint.is_enabled()) else {
9161 continue;
9162 };
9163 self.edit_breakpoint_at_anchor(
9164 anchor,
9165 breakpoint,
9166 BreakpointEditAction::InvertState,
9167 cx,
9168 );
9169 }
9170 }
9171
9172 pub fn toggle_breakpoint(
9173 &mut self,
9174 _: &crate::actions::ToggleBreakpoint,
9175 window: &mut Window,
9176 cx: &mut Context<Self>,
9177 ) {
9178 for (anchor, breakpoint) in self.breakpoints_at_cursors(window, cx) {
9179 if let Some(breakpoint) = breakpoint {
9180 self.edit_breakpoint_at_anchor(
9181 anchor,
9182 breakpoint,
9183 BreakpointEditAction::Toggle,
9184 cx,
9185 );
9186 } else {
9187 self.edit_breakpoint_at_anchor(
9188 anchor,
9189 Breakpoint::new_standard(),
9190 BreakpointEditAction::Toggle,
9191 cx,
9192 );
9193 }
9194 }
9195 }
9196
9197 pub fn edit_breakpoint_at_anchor(
9198 &mut self,
9199 breakpoint_position: Anchor,
9200 breakpoint: Breakpoint,
9201 edit_action: BreakpointEditAction,
9202 cx: &mut Context<Self>,
9203 ) {
9204 let Some(breakpoint_store) = &self.breakpoint_store else {
9205 return;
9206 };
9207
9208 let Some(buffer_id) = breakpoint_position.buffer_id.or_else(|| {
9209 if breakpoint_position == Anchor::min() {
9210 self.buffer()
9211 .read(cx)
9212 .excerpt_buffer_ids()
9213 .into_iter()
9214 .next()
9215 } else {
9216 None
9217 }
9218 }) else {
9219 return;
9220 };
9221
9222 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
9223 return;
9224 };
9225
9226 breakpoint_store.update(cx, |breakpoint_store, cx| {
9227 breakpoint_store.toggle_breakpoint(
9228 buffer,
9229 (breakpoint_position.text_anchor, breakpoint),
9230 edit_action,
9231 cx,
9232 );
9233 });
9234
9235 cx.notify();
9236 }
9237
9238 #[cfg(any(test, feature = "test-support"))]
9239 pub fn breakpoint_store(&self) -> Option<Entity<BreakpointStore>> {
9240 self.breakpoint_store.clone()
9241 }
9242
9243 pub fn prepare_restore_change(
9244 &self,
9245 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
9246 hunk: &MultiBufferDiffHunk,
9247 cx: &mut App,
9248 ) -> Option<()> {
9249 if hunk.is_created_file() {
9250 return None;
9251 }
9252 let buffer = self.buffer.read(cx);
9253 let diff = buffer.diff_for(hunk.buffer_id)?;
9254 let buffer = buffer.buffer(hunk.buffer_id)?;
9255 let buffer = buffer.read(cx);
9256 let original_text = diff
9257 .read(cx)
9258 .base_text()
9259 .as_rope()
9260 .slice(hunk.diff_base_byte_range.clone());
9261 let buffer_snapshot = buffer.snapshot();
9262 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
9263 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
9264 probe
9265 .0
9266 .start
9267 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
9268 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
9269 }) {
9270 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
9271 Some(())
9272 } else {
9273 None
9274 }
9275 }
9276
9277 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
9278 self.manipulate_lines(window, cx, |lines| lines.reverse())
9279 }
9280
9281 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
9282 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
9283 }
9284
9285 fn manipulate_lines<Fn>(
9286 &mut self,
9287 window: &mut Window,
9288 cx: &mut Context<Self>,
9289 mut callback: Fn,
9290 ) where
9291 Fn: FnMut(&mut Vec<&str>),
9292 {
9293 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9294
9295 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9296 let buffer = self.buffer.read(cx).snapshot(cx);
9297
9298 let mut edits = Vec::new();
9299
9300 let selections = self.selections.all::<Point>(cx);
9301 let mut selections = selections.iter().peekable();
9302 let mut contiguous_row_selections = Vec::new();
9303 let mut new_selections = Vec::new();
9304 let mut added_lines = 0;
9305 let mut removed_lines = 0;
9306
9307 while let Some(selection) = selections.next() {
9308 let (start_row, end_row) = consume_contiguous_rows(
9309 &mut contiguous_row_selections,
9310 selection,
9311 &display_map,
9312 &mut selections,
9313 );
9314
9315 let start_point = Point::new(start_row.0, 0);
9316 let end_point = Point::new(
9317 end_row.previous_row().0,
9318 buffer.line_len(end_row.previous_row()),
9319 );
9320 let text = buffer
9321 .text_for_range(start_point..end_point)
9322 .collect::<String>();
9323
9324 let mut lines = text.split('\n').collect_vec();
9325
9326 let lines_before = lines.len();
9327 callback(&mut lines);
9328 let lines_after = lines.len();
9329
9330 edits.push((start_point..end_point, lines.join("\n")));
9331
9332 // Selections must change based on added and removed line count
9333 let start_row =
9334 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
9335 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
9336 new_selections.push(Selection {
9337 id: selection.id,
9338 start: start_row,
9339 end: end_row,
9340 goal: SelectionGoal::None,
9341 reversed: selection.reversed,
9342 });
9343
9344 if lines_after > lines_before {
9345 added_lines += lines_after - lines_before;
9346 } else if lines_before > lines_after {
9347 removed_lines += lines_before - lines_after;
9348 }
9349 }
9350
9351 self.transact(window, cx, |this, window, cx| {
9352 let buffer = this.buffer.update(cx, |buffer, cx| {
9353 buffer.edit(edits, None, cx);
9354 buffer.snapshot(cx)
9355 });
9356
9357 // Recalculate offsets on newly edited buffer
9358 let new_selections = new_selections
9359 .iter()
9360 .map(|s| {
9361 let start_point = Point::new(s.start.0, 0);
9362 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
9363 Selection {
9364 id: s.id,
9365 start: buffer.point_to_offset(start_point),
9366 end: buffer.point_to_offset(end_point),
9367 goal: s.goal,
9368 reversed: s.reversed,
9369 }
9370 })
9371 .collect();
9372
9373 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9374 s.select(new_selections);
9375 });
9376
9377 this.request_autoscroll(Autoscroll::fit(), cx);
9378 });
9379 }
9380
9381 pub fn toggle_case(&mut self, _: &ToggleCase, window: &mut Window, cx: &mut Context<Self>) {
9382 self.manipulate_text(window, cx, |text| {
9383 let has_upper_case_characters = text.chars().any(|c| c.is_uppercase());
9384 if has_upper_case_characters {
9385 text.to_lowercase()
9386 } else {
9387 text.to_uppercase()
9388 }
9389 })
9390 }
9391
9392 pub fn convert_to_upper_case(
9393 &mut self,
9394 _: &ConvertToUpperCase,
9395 window: &mut Window,
9396 cx: &mut Context<Self>,
9397 ) {
9398 self.manipulate_text(window, cx, |text| text.to_uppercase())
9399 }
9400
9401 pub fn convert_to_lower_case(
9402 &mut self,
9403 _: &ConvertToLowerCase,
9404 window: &mut Window,
9405 cx: &mut Context<Self>,
9406 ) {
9407 self.manipulate_text(window, cx, |text| text.to_lowercase())
9408 }
9409
9410 pub fn convert_to_title_case(
9411 &mut self,
9412 _: &ConvertToTitleCase,
9413 window: &mut Window,
9414 cx: &mut Context<Self>,
9415 ) {
9416 self.manipulate_text(window, cx, |text| {
9417 text.split('\n')
9418 .map(|line| line.to_case(Case::Title))
9419 .join("\n")
9420 })
9421 }
9422
9423 pub fn convert_to_snake_case(
9424 &mut self,
9425 _: &ConvertToSnakeCase,
9426 window: &mut Window,
9427 cx: &mut Context<Self>,
9428 ) {
9429 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
9430 }
9431
9432 pub fn convert_to_kebab_case(
9433 &mut self,
9434 _: &ConvertToKebabCase,
9435 window: &mut Window,
9436 cx: &mut Context<Self>,
9437 ) {
9438 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
9439 }
9440
9441 pub fn convert_to_upper_camel_case(
9442 &mut self,
9443 _: &ConvertToUpperCamelCase,
9444 window: &mut Window,
9445 cx: &mut Context<Self>,
9446 ) {
9447 self.manipulate_text(window, cx, |text| {
9448 text.split('\n')
9449 .map(|line| line.to_case(Case::UpperCamel))
9450 .join("\n")
9451 })
9452 }
9453
9454 pub fn convert_to_lower_camel_case(
9455 &mut self,
9456 _: &ConvertToLowerCamelCase,
9457 window: &mut Window,
9458 cx: &mut Context<Self>,
9459 ) {
9460 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
9461 }
9462
9463 pub fn convert_to_opposite_case(
9464 &mut self,
9465 _: &ConvertToOppositeCase,
9466 window: &mut Window,
9467 cx: &mut Context<Self>,
9468 ) {
9469 self.manipulate_text(window, cx, |text| {
9470 text.chars()
9471 .fold(String::with_capacity(text.len()), |mut t, c| {
9472 if c.is_uppercase() {
9473 t.extend(c.to_lowercase());
9474 } else {
9475 t.extend(c.to_uppercase());
9476 }
9477 t
9478 })
9479 })
9480 }
9481
9482 pub fn convert_to_rot13(
9483 &mut self,
9484 _: &ConvertToRot13,
9485 window: &mut Window,
9486 cx: &mut Context<Self>,
9487 ) {
9488 self.manipulate_text(window, cx, |text| {
9489 text.chars()
9490 .map(|c| match c {
9491 'A'..='M' | 'a'..='m' => ((c as u8) + 13) as char,
9492 'N'..='Z' | 'n'..='z' => ((c as u8) - 13) as char,
9493 _ => c,
9494 })
9495 .collect()
9496 })
9497 }
9498
9499 pub fn convert_to_rot47(
9500 &mut self,
9501 _: &ConvertToRot47,
9502 window: &mut Window,
9503 cx: &mut Context<Self>,
9504 ) {
9505 self.manipulate_text(window, cx, |text| {
9506 text.chars()
9507 .map(|c| {
9508 let code_point = c as u32;
9509 if code_point >= 33 && code_point <= 126 {
9510 return char::from_u32(33 + ((code_point + 14) % 94)).unwrap();
9511 }
9512 c
9513 })
9514 .collect()
9515 })
9516 }
9517
9518 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
9519 where
9520 Fn: FnMut(&str) -> String,
9521 {
9522 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9523 let buffer = self.buffer.read(cx).snapshot(cx);
9524
9525 let mut new_selections = Vec::new();
9526 let mut edits = Vec::new();
9527 let mut selection_adjustment = 0i32;
9528
9529 for selection in self.selections.all::<usize>(cx) {
9530 let selection_is_empty = selection.is_empty();
9531
9532 let (start, end) = if selection_is_empty {
9533 let word_range = movement::surrounding_word(
9534 &display_map,
9535 selection.start.to_display_point(&display_map),
9536 );
9537 let start = word_range.start.to_offset(&display_map, Bias::Left);
9538 let end = word_range.end.to_offset(&display_map, Bias::Left);
9539 (start, end)
9540 } else {
9541 (selection.start, selection.end)
9542 };
9543
9544 let text = buffer.text_for_range(start..end).collect::<String>();
9545 let old_length = text.len() as i32;
9546 let text = callback(&text);
9547
9548 new_selections.push(Selection {
9549 start: (start as i32 - selection_adjustment) as usize,
9550 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
9551 goal: SelectionGoal::None,
9552 ..selection
9553 });
9554
9555 selection_adjustment += old_length - text.len() as i32;
9556
9557 edits.push((start..end, text));
9558 }
9559
9560 self.transact(window, cx, |this, window, cx| {
9561 this.buffer.update(cx, |buffer, cx| {
9562 buffer.edit(edits, None, cx);
9563 });
9564
9565 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9566 s.select(new_selections);
9567 });
9568
9569 this.request_autoscroll(Autoscroll::fit(), cx);
9570 });
9571 }
9572
9573 pub fn duplicate(
9574 &mut self,
9575 upwards: bool,
9576 whole_lines: bool,
9577 window: &mut Window,
9578 cx: &mut Context<Self>,
9579 ) {
9580 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9581
9582 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9583 let buffer = &display_map.buffer_snapshot;
9584 let selections = self.selections.all::<Point>(cx);
9585
9586 let mut edits = Vec::new();
9587 let mut selections_iter = selections.iter().peekable();
9588 while let Some(selection) = selections_iter.next() {
9589 let mut rows = selection.spanned_rows(false, &display_map);
9590 // duplicate line-wise
9591 if whole_lines || selection.start == selection.end {
9592 // Avoid duplicating the same lines twice.
9593 while let Some(next_selection) = selections_iter.peek() {
9594 let next_rows = next_selection.spanned_rows(false, &display_map);
9595 if next_rows.start < rows.end {
9596 rows.end = next_rows.end;
9597 selections_iter.next().unwrap();
9598 } else {
9599 break;
9600 }
9601 }
9602
9603 // Copy the text from the selected row region and splice it either at the start
9604 // or end of the region.
9605 let start = Point::new(rows.start.0, 0);
9606 let end = Point::new(
9607 rows.end.previous_row().0,
9608 buffer.line_len(rows.end.previous_row()),
9609 );
9610 let text = buffer
9611 .text_for_range(start..end)
9612 .chain(Some("\n"))
9613 .collect::<String>();
9614 let insert_location = if upwards {
9615 Point::new(rows.end.0, 0)
9616 } else {
9617 start
9618 };
9619 edits.push((insert_location..insert_location, text));
9620 } else {
9621 // duplicate character-wise
9622 let start = selection.start;
9623 let end = selection.end;
9624 let text = buffer.text_for_range(start..end).collect::<String>();
9625 edits.push((selection.end..selection.end, text));
9626 }
9627 }
9628
9629 self.transact(window, cx, |this, _, cx| {
9630 this.buffer.update(cx, |buffer, cx| {
9631 buffer.edit(edits, None, cx);
9632 });
9633
9634 this.request_autoscroll(Autoscroll::fit(), cx);
9635 });
9636 }
9637
9638 pub fn duplicate_line_up(
9639 &mut self,
9640 _: &DuplicateLineUp,
9641 window: &mut Window,
9642 cx: &mut Context<Self>,
9643 ) {
9644 self.duplicate(true, true, window, cx);
9645 }
9646
9647 pub fn duplicate_line_down(
9648 &mut self,
9649 _: &DuplicateLineDown,
9650 window: &mut Window,
9651 cx: &mut Context<Self>,
9652 ) {
9653 self.duplicate(false, true, window, cx);
9654 }
9655
9656 pub fn duplicate_selection(
9657 &mut self,
9658 _: &DuplicateSelection,
9659 window: &mut Window,
9660 cx: &mut Context<Self>,
9661 ) {
9662 self.duplicate(false, false, window, cx);
9663 }
9664
9665 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
9666 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9667
9668 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9669 let buffer = self.buffer.read(cx).snapshot(cx);
9670
9671 let mut edits = Vec::new();
9672 let mut unfold_ranges = Vec::new();
9673 let mut refold_creases = Vec::new();
9674
9675 let selections = self.selections.all::<Point>(cx);
9676 let mut selections = selections.iter().peekable();
9677 let mut contiguous_row_selections = Vec::new();
9678 let mut new_selections = Vec::new();
9679
9680 while let Some(selection) = selections.next() {
9681 // Find all the selections that span a contiguous row range
9682 let (start_row, end_row) = consume_contiguous_rows(
9683 &mut contiguous_row_selections,
9684 selection,
9685 &display_map,
9686 &mut selections,
9687 );
9688
9689 // Move the text spanned by the row range to be before the line preceding the row range
9690 if start_row.0 > 0 {
9691 let range_to_move = Point::new(
9692 start_row.previous_row().0,
9693 buffer.line_len(start_row.previous_row()),
9694 )
9695 ..Point::new(
9696 end_row.previous_row().0,
9697 buffer.line_len(end_row.previous_row()),
9698 );
9699 let insertion_point = display_map
9700 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
9701 .0;
9702
9703 // Don't move lines across excerpts
9704 if buffer
9705 .excerpt_containing(insertion_point..range_to_move.end)
9706 .is_some()
9707 {
9708 let text = buffer
9709 .text_for_range(range_to_move.clone())
9710 .flat_map(|s| s.chars())
9711 .skip(1)
9712 .chain(['\n'])
9713 .collect::<String>();
9714
9715 edits.push((
9716 buffer.anchor_after(range_to_move.start)
9717 ..buffer.anchor_before(range_to_move.end),
9718 String::new(),
9719 ));
9720 let insertion_anchor = buffer.anchor_after(insertion_point);
9721 edits.push((insertion_anchor..insertion_anchor, text));
9722
9723 let row_delta = range_to_move.start.row - insertion_point.row + 1;
9724
9725 // Move selections up
9726 new_selections.extend(contiguous_row_selections.drain(..).map(
9727 |mut selection| {
9728 selection.start.row -= row_delta;
9729 selection.end.row -= row_delta;
9730 selection
9731 },
9732 ));
9733
9734 // Move folds up
9735 unfold_ranges.push(range_to_move.clone());
9736 for fold in display_map.folds_in_range(
9737 buffer.anchor_before(range_to_move.start)
9738 ..buffer.anchor_after(range_to_move.end),
9739 ) {
9740 let mut start = fold.range.start.to_point(&buffer);
9741 let mut end = fold.range.end.to_point(&buffer);
9742 start.row -= row_delta;
9743 end.row -= row_delta;
9744 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9745 }
9746 }
9747 }
9748
9749 // If we didn't move line(s), preserve the existing selections
9750 new_selections.append(&mut contiguous_row_selections);
9751 }
9752
9753 self.transact(window, cx, |this, window, cx| {
9754 this.unfold_ranges(&unfold_ranges, true, true, cx);
9755 this.buffer.update(cx, |buffer, cx| {
9756 for (range, text) in edits {
9757 buffer.edit([(range, text)], None, cx);
9758 }
9759 });
9760 this.fold_creases(refold_creases, true, window, cx);
9761 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9762 s.select(new_selections);
9763 })
9764 });
9765 }
9766
9767 pub fn move_line_down(
9768 &mut self,
9769 _: &MoveLineDown,
9770 window: &mut Window,
9771 cx: &mut Context<Self>,
9772 ) {
9773 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9774
9775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9776 let buffer = self.buffer.read(cx).snapshot(cx);
9777
9778 let mut edits = Vec::new();
9779 let mut unfold_ranges = Vec::new();
9780 let mut refold_creases = Vec::new();
9781
9782 let selections = self.selections.all::<Point>(cx);
9783 let mut selections = selections.iter().peekable();
9784 let mut contiguous_row_selections = Vec::new();
9785 let mut new_selections = Vec::new();
9786
9787 while let Some(selection) = selections.next() {
9788 // Find all the selections that span a contiguous row range
9789 let (start_row, end_row) = consume_contiguous_rows(
9790 &mut contiguous_row_selections,
9791 selection,
9792 &display_map,
9793 &mut selections,
9794 );
9795
9796 // Move the text spanned by the row range to be after the last line of the row range
9797 if end_row.0 <= buffer.max_point().row {
9798 let range_to_move =
9799 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
9800 let insertion_point = display_map
9801 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
9802 .0;
9803
9804 // Don't move lines across excerpt boundaries
9805 if buffer
9806 .excerpt_containing(range_to_move.start..insertion_point)
9807 .is_some()
9808 {
9809 let mut text = String::from("\n");
9810 text.extend(buffer.text_for_range(range_to_move.clone()));
9811 text.pop(); // Drop trailing newline
9812 edits.push((
9813 buffer.anchor_after(range_to_move.start)
9814 ..buffer.anchor_before(range_to_move.end),
9815 String::new(),
9816 ));
9817 let insertion_anchor = buffer.anchor_after(insertion_point);
9818 edits.push((insertion_anchor..insertion_anchor, text));
9819
9820 let row_delta = insertion_point.row - range_to_move.end.row + 1;
9821
9822 // Move selections down
9823 new_selections.extend(contiguous_row_selections.drain(..).map(
9824 |mut selection| {
9825 selection.start.row += row_delta;
9826 selection.end.row += row_delta;
9827 selection
9828 },
9829 ));
9830
9831 // Move folds down
9832 unfold_ranges.push(range_to_move.clone());
9833 for fold in display_map.folds_in_range(
9834 buffer.anchor_before(range_to_move.start)
9835 ..buffer.anchor_after(range_to_move.end),
9836 ) {
9837 let mut start = fold.range.start.to_point(&buffer);
9838 let mut end = fold.range.end.to_point(&buffer);
9839 start.row += row_delta;
9840 end.row += row_delta;
9841 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
9842 }
9843 }
9844 }
9845
9846 // If we didn't move line(s), preserve the existing selections
9847 new_selections.append(&mut contiguous_row_selections);
9848 }
9849
9850 self.transact(window, cx, |this, window, cx| {
9851 this.unfold_ranges(&unfold_ranges, true, true, cx);
9852 this.buffer.update(cx, |buffer, cx| {
9853 for (range, text) in edits {
9854 buffer.edit([(range, text)], None, cx);
9855 }
9856 });
9857 this.fold_creases(refold_creases, true, window, cx);
9858 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9859 s.select(new_selections)
9860 });
9861 });
9862 }
9863
9864 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
9865 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9866 let text_layout_details = &self.text_layout_details(window);
9867 self.transact(window, cx, |this, window, cx| {
9868 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9869 let mut edits: Vec<(Range<usize>, String)> = Default::default();
9870 s.move_with(|display_map, selection| {
9871 if !selection.is_empty() {
9872 return;
9873 }
9874
9875 let mut head = selection.head();
9876 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
9877 if head.column() == display_map.line_len(head.row()) {
9878 transpose_offset = display_map
9879 .buffer_snapshot
9880 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9881 }
9882
9883 if transpose_offset == 0 {
9884 return;
9885 }
9886
9887 *head.column_mut() += 1;
9888 head = display_map.clip_point(head, Bias::Right);
9889 let goal = SelectionGoal::HorizontalPosition(
9890 display_map
9891 .x_for_display_point(head, text_layout_details)
9892 .into(),
9893 );
9894 selection.collapse_to(head, goal);
9895
9896 let transpose_start = display_map
9897 .buffer_snapshot
9898 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
9899 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
9900 let transpose_end = display_map
9901 .buffer_snapshot
9902 .clip_offset(transpose_offset + 1, Bias::Right);
9903 if let Some(ch) =
9904 display_map.buffer_snapshot.chars_at(transpose_start).next()
9905 {
9906 edits.push((transpose_start..transpose_offset, String::new()));
9907 edits.push((transpose_end..transpose_end, ch.to_string()));
9908 }
9909 }
9910 });
9911 edits
9912 });
9913 this.buffer
9914 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
9915 let selections = this.selections.all::<usize>(cx);
9916 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9917 s.select(selections);
9918 });
9919 });
9920 }
9921
9922 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
9923 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
9924 self.rewrap_impl(RewrapOptions::default(), cx)
9925 }
9926
9927 pub fn rewrap_impl(&mut self, options: RewrapOptions, cx: &mut Context<Self>) {
9928 let buffer = self.buffer.read(cx).snapshot(cx);
9929 let selections = self.selections.all::<Point>(cx);
9930 let mut selections = selections.iter().peekable();
9931
9932 let mut edits = Vec::new();
9933 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
9934
9935 while let Some(selection) = selections.next() {
9936 let mut start_row = selection.start.row;
9937 let mut end_row = selection.end.row;
9938
9939 // Skip selections that overlap with a range that has already been rewrapped.
9940 let selection_range = start_row..end_row;
9941 if rewrapped_row_ranges
9942 .iter()
9943 .any(|range| range.overlaps(&selection_range))
9944 {
9945 continue;
9946 }
9947
9948 let tab_size = buffer.language_settings_at(selection.head(), cx).tab_size;
9949
9950 // Since not all lines in the selection may be at the same indent
9951 // level, choose the indent size that is the most common between all
9952 // of the lines.
9953 //
9954 // If there is a tie, we use the deepest indent.
9955 let (indent_size, indent_end) = {
9956 let mut indent_size_occurrences = HashMap::default();
9957 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
9958
9959 for row in start_row..=end_row {
9960 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
9961 rows_by_indent_size.entry(indent).or_default().push(row);
9962 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
9963 }
9964
9965 let indent_size = indent_size_occurrences
9966 .into_iter()
9967 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
9968 .map(|(indent, _)| indent)
9969 .unwrap_or_default();
9970 let row = rows_by_indent_size[&indent_size][0];
9971 let indent_end = Point::new(row, indent_size.len);
9972
9973 (indent_size, indent_end)
9974 };
9975
9976 let mut line_prefix = indent_size.chars().collect::<String>();
9977
9978 let mut inside_comment = false;
9979 if let Some(comment_prefix) =
9980 buffer
9981 .language_scope_at(selection.head())
9982 .and_then(|language| {
9983 language
9984 .line_comment_prefixes()
9985 .iter()
9986 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
9987 .cloned()
9988 })
9989 {
9990 line_prefix.push_str(&comment_prefix);
9991 inside_comment = true;
9992 }
9993
9994 let language_settings = buffer.language_settings_at(selection.head(), cx);
9995 let allow_rewrap_based_on_language = match language_settings.allow_rewrap {
9996 RewrapBehavior::InComments => inside_comment,
9997 RewrapBehavior::InSelections => !selection.is_empty(),
9998 RewrapBehavior::Anywhere => true,
9999 };
10000
10001 let should_rewrap = options.override_language_settings
10002 || allow_rewrap_based_on_language
10003 || self.hard_wrap.is_some();
10004 if !should_rewrap {
10005 continue;
10006 }
10007
10008 if selection.is_empty() {
10009 'expand_upwards: while start_row > 0 {
10010 let prev_row = start_row - 1;
10011 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
10012 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
10013 {
10014 start_row = prev_row;
10015 } else {
10016 break 'expand_upwards;
10017 }
10018 }
10019
10020 'expand_downwards: while end_row < buffer.max_point().row {
10021 let next_row = end_row + 1;
10022 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
10023 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
10024 {
10025 end_row = next_row;
10026 } else {
10027 break 'expand_downwards;
10028 }
10029 }
10030 }
10031
10032 let start = Point::new(start_row, 0);
10033 let start_offset = start.to_offset(&buffer);
10034 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
10035 let selection_text = buffer.text_for_range(start..end).collect::<String>();
10036 let Some(lines_without_prefixes) = selection_text
10037 .lines()
10038 .map(|line| {
10039 line.strip_prefix(&line_prefix)
10040 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
10041 .ok_or_else(|| {
10042 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
10043 })
10044 })
10045 .collect::<Result<Vec<_>, _>>()
10046 .log_err()
10047 else {
10048 continue;
10049 };
10050
10051 let wrap_column = self.hard_wrap.unwrap_or_else(|| {
10052 buffer
10053 .language_settings_at(Point::new(start_row, 0), cx)
10054 .preferred_line_length as usize
10055 });
10056 let wrapped_text = wrap_with_prefix(
10057 line_prefix,
10058 lines_without_prefixes.join("\n"),
10059 wrap_column,
10060 tab_size,
10061 options.preserve_existing_whitespace,
10062 );
10063
10064 // TODO: should always use char-based diff while still supporting cursor behavior that
10065 // matches vim.
10066 let mut diff_options = DiffOptions::default();
10067 if options.override_language_settings {
10068 diff_options.max_word_diff_len = 0;
10069 diff_options.max_word_diff_line_count = 0;
10070 } else {
10071 diff_options.max_word_diff_len = usize::MAX;
10072 diff_options.max_word_diff_line_count = usize::MAX;
10073 }
10074
10075 for (old_range, new_text) in
10076 text_diff_with_options(&selection_text, &wrapped_text, diff_options)
10077 {
10078 let edit_start = buffer.anchor_after(start_offset + old_range.start);
10079 let edit_end = buffer.anchor_after(start_offset + old_range.end);
10080 edits.push((edit_start..edit_end, new_text));
10081 }
10082
10083 rewrapped_row_ranges.push(start_row..=end_row);
10084 }
10085
10086 self.buffer
10087 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
10088 }
10089
10090 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
10091 let mut text = String::new();
10092 let buffer = self.buffer.read(cx).snapshot(cx);
10093 let mut selections = self.selections.all::<Point>(cx);
10094 let mut clipboard_selections = Vec::with_capacity(selections.len());
10095 {
10096 let max_point = buffer.max_point();
10097 let mut is_first = true;
10098 for selection in &mut selections {
10099 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10100 if is_entire_line {
10101 selection.start = Point::new(selection.start.row, 0);
10102 if !selection.is_empty() && selection.end.column == 0 {
10103 selection.end = cmp::min(max_point, selection.end);
10104 } else {
10105 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
10106 }
10107 selection.goal = SelectionGoal::None;
10108 }
10109 if is_first {
10110 is_first = false;
10111 } else {
10112 text += "\n";
10113 }
10114 let mut len = 0;
10115 for chunk in buffer.text_for_range(selection.start..selection.end) {
10116 text.push_str(chunk);
10117 len += chunk.len();
10118 }
10119 clipboard_selections.push(ClipboardSelection {
10120 len,
10121 is_entire_line,
10122 first_line_indent: buffer
10123 .indent_size_for_line(MultiBufferRow(selection.start.row))
10124 .len,
10125 });
10126 }
10127 }
10128
10129 self.transact(window, cx, |this, window, cx| {
10130 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10131 s.select(selections);
10132 });
10133 this.insert("", window, cx);
10134 });
10135 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
10136 }
10137
10138 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
10139 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10140 let item = self.cut_common(window, cx);
10141 cx.write_to_clipboard(item);
10142 }
10143
10144 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
10145 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10146 self.change_selections(None, window, cx, |s| {
10147 s.move_with(|snapshot, sel| {
10148 if sel.is_empty() {
10149 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
10150 }
10151 });
10152 });
10153 let item = self.cut_common(window, cx);
10154 cx.set_global(KillRing(item))
10155 }
10156
10157 pub fn kill_ring_yank(
10158 &mut self,
10159 _: &KillRingYank,
10160 window: &mut Window,
10161 cx: &mut Context<Self>,
10162 ) {
10163 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10164 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
10165 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
10166 (kill_ring.text().to_string(), kill_ring.metadata_json())
10167 } else {
10168 return;
10169 }
10170 } else {
10171 return;
10172 };
10173 self.do_paste(&text, metadata, false, window, cx);
10174 }
10175
10176 pub fn copy_and_trim(&mut self, _: &CopyAndTrim, _: &mut Window, cx: &mut Context<Self>) {
10177 self.do_copy(true, cx);
10178 }
10179
10180 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
10181 self.do_copy(false, cx);
10182 }
10183
10184 fn do_copy(&self, strip_leading_indents: bool, cx: &mut Context<Self>) {
10185 let selections = self.selections.all::<Point>(cx);
10186 let buffer = self.buffer.read(cx).read(cx);
10187 let mut text = String::new();
10188
10189 let mut clipboard_selections = Vec::with_capacity(selections.len());
10190 {
10191 let max_point = buffer.max_point();
10192 let mut is_first = true;
10193 for selection in &selections {
10194 let mut start = selection.start;
10195 let mut end = selection.end;
10196 let is_entire_line = selection.is_empty() || self.selections.line_mode;
10197 if is_entire_line {
10198 start = Point::new(start.row, 0);
10199 end = cmp::min(max_point, Point::new(end.row + 1, 0));
10200 }
10201
10202 let mut trimmed_selections = Vec::new();
10203 if strip_leading_indents && end.row.saturating_sub(start.row) > 0 {
10204 let row = MultiBufferRow(start.row);
10205 let first_indent = buffer.indent_size_for_line(row);
10206 if first_indent.len == 0 || start.column > first_indent.len {
10207 trimmed_selections.push(start..end);
10208 } else {
10209 trimmed_selections.push(
10210 Point::new(row.0, first_indent.len)
10211 ..Point::new(row.0, buffer.line_len(row)),
10212 );
10213 for row in start.row + 1..=end.row {
10214 let mut line_len = buffer.line_len(MultiBufferRow(row));
10215 if row == end.row {
10216 line_len = end.column;
10217 }
10218 if line_len == 0 {
10219 trimmed_selections
10220 .push(Point::new(row, 0)..Point::new(row, line_len));
10221 continue;
10222 }
10223 let row_indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
10224 if row_indent_size.len >= first_indent.len {
10225 trimmed_selections.push(
10226 Point::new(row, first_indent.len)..Point::new(row, line_len),
10227 );
10228 } else {
10229 trimmed_selections.clear();
10230 trimmed_selections.push(start..end);
10231 break;
10232 }
10233 }
10234 }
10235 } else {
10236 trimmed_selections.push(start..end);
10237 }
10238
10239 for trimmed_range in trimmed_selections {
10240 if is_first {
10241 is_first = false;
10242 } else {
10243 text += "\n";
10244 }
10245 let mut len = 0;
10246 for chunk in buffer.text_for_range(trimmed_range.start..trimmed_range.end) {
10247 text.push_str(chunk);
10248 len += chunk.len();
10249 }
10250 clipboard_selections.push(ClipboardSelection {
10251 len,
10252 is_entire_line,
10253 first_line_indent: buffer
10254 .indent_size_for_line(MultiBufferRow(trimmed_range.start.row))
10255 .len,
10256 });
10257 }
10258 }
10259 }
10260
10261 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
10262 text,
10263 clipboard_selections,
10264 ));
10265 }
10266
10267 pub fn do_paste(
10268 &mut self,
10269 text: &String,
10270 clipboard_selections: Option<Vec<ClipboardSelection>>,
10271 handle_entire_lines: bool,
10272 window: &mut Window,
10273 cx: &mut Context<Self>,
10274 ) {
10275 if self.read_only(cx) {
10276 return;
10277 }
10278
10279 let clipboard_text = Cow::Borrowed(text);
10280
10281 self.transact(window, cx, |this, window, cx| {
10282 if let Some(mut clipboard_selections) = clipboard_selections {
10283 let old_selections = this.selections.all::<usize>(cx);
10284 let all_selections_were_entire_line =
10285 clipboard_selections.iter().all(|s| s.is_entire_line);
10286 let first_selection_indent_column =
10287 clipboard_selections.first().map(|s| s.first_line_indent);
10288 if clipboard_selections.len() != old_selections.len() {
10289 clipboard_selections.drain(..);
10290 }
10291 let cursor_offset = this.selections.last::<usize>(cx).head();
10292 let mut auto_indent_on_paste = true;
10293
10294 this.buffer.update(cx, |buffer, cx| {
10295 let snapshot = buffer.read(cx);
10296 auto_indent_on_paste = snapshot
10297 .language_settings_at(cursor_offset, cx)
10298 .auto_indent_on_paste;
10299
10300 let mut start_offset = 0;
10301 let mut edits = Vec::new();
10302 let mut original_indent_columns = Vec::new();
10303 for (ix, selection) in old_selections.iter().enumerate() {
10304 let to_insert;
10305 let entire_line;
10306 let original_indent_column;
10307 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
10308 let end_offset = start_offset + clipboard_selection.len;
10309 to_insert = &clipboard_text[start_offset..end_offset];
10310 entire_line = clipboard_selection.is_entire_line;
10311 start_offset = end_offset + 1;
10312 original_indent_column = Some(clipboard_selection.first_line_indent);
10313 } else {
10314 to_insert = clipboard_text.as_str();
10315 entire_line = all_selections_were_entire_line;
10316 original_indent_column = first_selection_indent_column
10317 }
10318
10319 // If the corresponding selection was empty when this slice of the
10320 // clipboard text was written, then the entire line containing the
10321 // selection was copied. If this selection is also currently empty,
10322 // then paste the line before the current line of the buffer.
10323 let range = if selection.is_empty() && handle_entire_lines && entire_line {
10324 let column = selection.start.to_point(&snapshot).column as usize;
10325 let line_start = selection.start - column;
10326 line_start..line_start
10327 } else {
10328 selection.range()
10329 };
10330
10331 edits.push((range, to_insert));
10332 original_indent_columns.push(original_indent_column);
10333 }
10334 drop(snapshot);
10335
10336 buffer.edit(
10337 edits,
10338 if auto_indent_on_paste {
10339 Some(AutoindentMode::Block {
10340 original_indent_columns,
10341 })
10342 } else {
10343 None
10344 },
10345 cx,
10346 );
10347 });
10348
10349 let selections = this.selections.all::<usize>(cx);
10350 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10351 s.select(selections)
10352 });
10353 } else {
10354 this.insert(&clipboard_text, window, cx);
10355 }
10356 });
10357 }
10358
10359 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
10360 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10361 if let Some(item) = cx.read_from_clipboard() {
10362 let entries = item.entries();
10363
10364 match entries.first() {
10365 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
10366 // of all the pasted entries.
10367 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
10368 .do_paste(
10369 clipboard_string.text(),
10370 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
10371 true,
10372 window,
10373 cx,
10374 ),
10375 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
10376 }
10377 }
10378 }
10379
10380 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
10381 if self.read_only(cx) {
10382 return;
10383 }
10384
10385 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10386
10387 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
10388 if let Some((selections, _)) =
10389 self.selection_history.transaction(transaction_id).cloned()
10390 {
10391 self.change_selections(None, window, cx, |s| {
10392 s.select_anchors(selections.to_vec());
10393 });
10394 } else {
10395 log::error!(
10396 "No entry in selection_history found for undo. \
10397 This may correspond to a bug where undo does not update the selection. \
10398 If this is occurring, please add details to \
10399 https://github.com/zed-industries/zed/issues/22692"
10400 );
10401 }
10402 self.request_autoscroll(Autoscroll::fit(), cx);
10403 self.unmark_text(window, cx);
10404 self.refresh_inline_completion(true, false, window, cx);
10405 cx.emit(EditorEvent::Edited { transaction_id });
10406 cx.emit(EditorEvent::TransactionUndone { transaction_id });
10407 }
10408 }
10409
10410 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
10411 if self.read_only(cx) {
10412 return;
10413 }
10414
10415 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10416
10417 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
10418 if let Some((_, Some(selections))) =
10419 self.selection_history.transaction(transaction_id).cloned()
10420 {
10421 self.change_selections(None, window, cx, |s| {
10422 s.select_anchors(selections.to_vec());
10423 });
10424 } else {
10425 log::error!(
10426 "No entry in selection_history found for redo. \
10427 This may correspond to a bug where undo does not update the selection. \
10428 If this is occurring, please add details to \
10429 https://github.com/zed-industries/zed/issues/22692"
10430 );
10431 }
10432 self.request_autoscroll(Autoscroll::fit(), cx);
10433 self.unmark_text(window, cx);
10434 self.refresh_inline_completion(true, false, window, cx);
10435 cx.emit(EditorEvent::Edited { transaction_id });
10436 }
10437 }
10438
10439 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
10440 self.buffer
10441 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
10442 }
10443
10444 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
10445 self.buffer
10446 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
10447 }
10448
10449 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
10450 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10451 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10452 s.move_with(|map, selection| {
10453 let cursor = if selection.is_empty() {
10454 movement::left(map, selection.start)
10455 } else {
10456 selection.start
10457 };
10458 selection.collapse_to(cursor, SelectionGoal::None);
10459 });
10460 })
10461 }
10462
10463 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
10464 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10465 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10466 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
10467 })
10468 }
10469
10470 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
10471 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10472 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10473 s.move_with(|map, selection| {
10474 let cursor = if selection.is_empty() {
10475 movement::right(map, selection.end)
10476 } else {
10477 selection.end
10478 };
10479 selection.collapse_to(cursor, SelectionGoal::None)
10480 });
10481 })
10482 }
10483
10484 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
10485 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10486 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10487 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
10488 })
10489 }
10490
10491 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
10492 if self.take_rename(true, window, cx).is_some() {
10493 return;
10494 }
10495
10496 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10497 cx.propagate();
10498 return;
10499 }
10500
10501 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10502
10503 let text_layout_details = &self.text_layout_details(window);
10504 let selection_count = self.selections.count();
10505 let first_selection = self.selections.first_anchor();
10506
10507 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10508 s.move_with(|map, selection| {
10509 if !selection.is_empty() {
10510 selection.goal = SelectionGoal::None;
10511 }
10512 let (cursor, goal) = movement::up(
10513 map,
10514 selection.start,
10515 selection.goal,
10516 false,
10517 text_layout_details,
10518 );
10519 selection.collapse_to(cursor, goal);
10520 });
10521 });
10522
10523 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10524 {
10525 cx.propagate();
10526 }
10527 }
10528
10529 pub fn move_up_by_lines(
10530 &mut self,
10531 action: &MoveUpByLines,
10532 window: &mut Window,
10533 cx: &mut Context<Self>,
10534 ) {
10535 if self.take_rename(true, window, cx).is_some() {
10536 return;
10537 }
10538
10539 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10540 cx.propagate();
10541 return;
10542 }
10543
10544 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10545
10546 let text_layout_details = &self.text_layout_details(window);
10547
10548 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10549 s.move_with(|map, selection| {
10550 if !selection.is_empty() {
10551 selection.goal = SelectionGoal::None;
10552 }
10553 let (cursor, goal) = movement::up_by_rows(
10554 map,
10555 selection.start,
10556 action.lines,
10557 selection.goal,
10558 false,
10559 text_layout_details,
10560 );
10561 selection.collapse_to(cursor, goal);
10562 });
10563 })
10564 }
10565
10566 pub fn move_down_by_lines(
10567 &mut self,
10568 action: &MoveDownByLines,
10569 window: &mut Window,
10570 cx: &mut Context<Self>,
10571 ) {
10572 if self.take_rename(true, window, cx).is_some() {
10573 return;
10574 }
10575
10576 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10577 cx.propagate();
10578 return;
10579 }
10580
10581 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10582
10583 let text_layout_details = &self.text_layout_details(window);
10584
10585 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10586 s.move_with(|map, selection| {
10587 if !selection.is_empty() {
10588 selection.goal = SelectionGoal::None;
10589 }
10590 let (cursor, goal) = movement::down_by_rows(
10591 map,
10592 selection.start,
10593 action.lines,
10594 selection.goal,
10595 false,
10596 text_layout_details,
10597 );
10598 selection.collapse_to(cursor, goal);
10599 });
10600 })
10601 }
10602
10603 pub fn select_down_by_lines(
10604 &mut self,
10605 action: &SelectDownByLines,
10606 window: &mut Window,
10607 cx: &mut Context<Self>,
10608 ) {
10609 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10610 let text_layout_details = &self.text_layout_details(window);
10611 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10612 s.move_heads_with(|map, head, goal| {
10613 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
10614 })
10615 })
10616 }
10617
10618 pub fn select_up_by_lines(
10619 &mut self,
10620 action: &SelectUpByLines,
10621 window: &mut Window,
10622 cx: &mut Context<Self>,
10623 ) {
10624 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10625 let text_layout_details = &self.text_layout_details(window);
10626 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10627 s.move_heads_with(|map, head, goal| {
10628 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
10629 })
10630 })
10631 }
10632
10633 pub fn select_page_up(
10634 &mut self,
10635 _: &SelectPageUp,
10636 window: &mut Window,
10637 cx: &mut Context<Self>,
10638 ) {
10639 let Some(row_count) = self.visible_row_count() else {
10640 return;
10641 };
10642
10643 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10644
10645 let text_layout_details = &self.text_layout_details(window);
10646
10647 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10648 s.move_heads_with(|map, head, goal| {
10649 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
10650 })
10651 })
10652 }
10653
10654 pub fn move_page_up(
10655 &mut self,
10656 action: &MovePageUp,
10657 window: &mut Window,
10658 cx: &mut Context<Self>,
10659 ) {
10660 if self.take_rename(true, window, cx).is_some() {
10661 return;
10662 }
10663
10664 if self
10665 .context_menu
10666 .borrow_mut()
10667 .as_mut()
10668 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
10669 .unwrap_or(false)
10670 {
10671 return;
10672 }
10673
10674 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10675 cx.propagate();
10676 return;
10677 }
10678
10679 let Some(row_count) = self.visible_row_count() else {
10680 return;
10681 };
10682
10683 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10684
10685 let autoscroll = if action.center_cursor {
10686 Autoscroll::center()
10687 } else {
10688 Autoscroll::fit()
10689 };
10690
10691 let text_layout_details = &self.text_layout_details(window);
10692
10693 self.change_selections(Some(autoscroll), window, cx, |s| {
10694 s.move_with(|map, selection| {
10695 if !selection.is_empty() {
10696 selection.goal = SelectionGoal::None;
10697 }
10698 let (cursor, goal) = movement::up_by_rows(
10699 map,
10700 selection.end,
10701 row_count,
10702 selection.goal,
10703 false,
10704 text_layout_details,
10705 );
10706 selection.collapse_to(cursor, goal);
10707 });
10708 });
10709 }
10710
10711 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
10712 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10713 let text_layout_details = &self.text_layout_details(window);
10714 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10715 s.move_heads_with(|map, head, goal| {
10716 movement::up(map, head, goal, false, text_layout_details)
10717 })
10718 })
10719 }
10720
10721 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
10722 self.take_rename(true, window, cx);
10723
10724 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10725 cx.propagate();
10726 return;
10727 }
10728
10729 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10730
10731 let text_layout_details = &self.text_layout_details(window);
10732 let selection_count = self.selections.count();
10733 let first_selection = self.selections.first_anchor();
10734
10735 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10736 s.move_with(|map, selection| {
10737 if !selection.is_empty() {
10738 selection.goal = SelectionGoal::None;
10739 }
10740 let (cursor, goal) = movement::down(
10741 map,
10742 selection.end,
10743 selection.goal,
10744 false,
10745 text_layout_details,
10746 );
10747 selection.collapse_to(cursor, goal);
10748 });
10749 });
10750
10751 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
10752 {
10753 cx.propagate();
10754 }
10755 }
10756
10757 pub fn select_page_down(
10758 &mut self,
10759 _: &SelectPageDown,
10760 window: &mut Window,
10761 cx: &mut Context<Self>,
10762 ) {
10763 let Some(row_count) = self.visible_row_count() else {
10764 return;
10765 };
10766
10767 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10768
10769 let text_layout_details = &self.text_layout_details(window);
10770
10771 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10772 s.move_heads_with(|map, head, goal| {
10773 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
10774 })
10775 })
10776 }
10777
10778 pub fn move_page_down(
10779 &mut self,
10780 action: &MovePageDown,
10781 window: &mut Window,
10782 cx: &mut Context<Self>,
10783 ) {
10784 if self.take_rename(true, window, cx).is_some() {
10785 return;
10786 }
10787
10788 if self
10789 .context_menu
10790 .borrow_mut()
10791 .as_mut()
10792 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
10793 .unwrap_or(false)
10794 {
10795 return;
10796 }
10797
10798 if matches!(self.mode, EditorMode::SingleLine { .. }) {
10799 cx.propagate();
10800 return;
10801 }
10802
10803 let Some(row_count) = self.visible_row_count() else {
10804 return;
10805 };
10806
10807 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10808
10809 let autoscroll = if action.center_cursor {
10810 Autoscroll::center()
10811 } else {
10812 Autoscroll::fit()
10813 };
10814
10815 let text_layout_details = &self.text_layout_details(window);
10816 self.change_selections(Some(autoscroll), window, cx, |s| {
10817 s.move_with(|map, selection| {
10818 if !selection.is_empty() {
10819 selection.goal = SelectionGoal::None;
10820 }
10821 let (cursor, goal) = movement::down_by_rows(
10822 map,
10823 selection.end,
10824 row_count,
10825 selection.goal,
10826 false,
10827 text_layout_details,
10828 );
10829 selection.collapse_to(cursor, goal);
10830 });
10831 });
10832 }
10833
10834 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
10835 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10836 let text_layout_details = &self.text_layout_details(window);
10837 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10838 s.move_heads_with(|map, head, goal| {
10839 movement::down(map, head, goal, false, text_layout_details)
10840 })
10841 });
10842 }
10843
10844 pub fn context_menu_first(
10845 &mut self,
10846 _: &ContextMenuFirst,
10847 _window: &mut Window,
10848 cx: &mut Context<Self>,
10849 ) {
10850 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10851 context_menu.select_first(self.completion_provider.as_deref(), cx);
10852 }
10853 }
10854
10855 pub fn context_menu_prev(
10856 &mut self,
10857 _: &ContextMenuPrevious,
10858 _window: &mut Window,
10859 cx: &mut Context<Self>,
10860 ) {
10861 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10862 context_menu.select_prev(self.completion_provider.as_deref(), cx);
10863 }
10864 }
10865
10866 pub fn context_menu_next(
10867 &mut self,
10868 _: &ContextMenuNext,
10869 _window: &mut Window,
10870 cx: &mut Context<Self>,
10871 ) {
10872 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10873 context_menu.select_next(self.completion_provider.as_deref(), cx);
10874 }
10875 }
10876
10877 pub fn context_menu_last(
10878 &mut self,
10879 _: &ContextMenuLast,
10880 _window: &mut Window,
10881 cx: &mut Context<Self>,
10882 ) {
10883 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
10884 context_menu.select_last(self.completion_provider.as_deref(), cx);
10885 }
10886 }
10887
10888 pub fn move_to_previous_word_start(
10889 &mut self,
10890 _: &MoveToPreviousWordStart,
10891 window: &mut Window,
10892 cx: &mut Context<Self>,
10893 ) {
10894 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10895 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10896 s.move_cursors_with(|map, head, _| {
10897 (
10898 movement::previous_word_start(map, head),
10899 SelectionGoal::None,
10900 )
10901 });
10902 })
10903 }
10904
10905 pub fn move_to_previous_subword_start(
10906 &mut self,
10907 _: &MoveToPreviousSubwordStart,
10908 window: &mut Window,
10909 cx: &mut Context<Self>,
10910 ) {
10911 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10912 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10913 s.move_cursors_with(|map, head, _| {
10914 (
10915 movement::previous_subword_start(map, head),
10916 SelectionGoal::None,
10917 )
10918 });
10919 })
10920 }
10921
10922 pub fn select_to_previous_word_start(
10923 &mut self,
10924 _: &SelectToPreviousWordStart,
10925 window: &mut Window,
10926 cx: &mut Context<Self>,
10927 ) {
10928 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10929 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10930 s.move_heads_with(|map, head, _| {
10931 (
10932 movement::previous_word_start(map, head),
10933 SelectionGoal::None,
10934 )
10935 });
10936 })
10937 }
10938
10939 pub fn select_to_previous_subword_start(
10940 &mut self,
10941 _: &SelectToPreviousSubwordStart,
10942 window: &mut Window,
10943 cx: &mut Context<Self>,
10944 ) {
10945 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
10946 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10947 s.move_heads_with(|map, head, _| {
10948 (
10949 movement::previous_subword_start(map, head),
10950 SelectionGoal::None,
10951 )
10952 });
10953 })
10954 }
10955
10956 pub fn delete_to_previous_word_start(
10957 &mut self,
10958 action: &DeleteToPreviousWordStart,
10959 window: &mut Window,
10960 cx: &mut Context<Self>,
10961 ) {
10962 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10963 self.transact(window, cx, |this, window, cx| {
10964 this.select_autoclose_pair(window, cx);
10965 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10966 s.move_with(|map, selection| {
10967 if selection.is_empty() {
10968 let cursor = if action.ignore_newlines {
10969 movement::previous_word_start(map, selection.head())
10970 } else {
10971 movement::previous_word_start_or_newline(map, selection.head())
10972 };
10973 selection.set_head(cursor, SelectionGoal::None);
10974 }
10975 });
10976 });
10977 this.insert("", window, cx);
10978 });
10979 }
10980
10981 pub fn delete_to_previous_subword_start(
10982 &mut self,
10983 _: &DeleteToPreviousSubwordStart,
10984 window: &mut Window,
10985 cx: &mut Context<Self>,
10986 ) {
10987 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
10988 self.transact(window, cx, |this, window, cx| {
10989 this.select_autoclose_pair(window, cx);
10990 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10991 s.move_with(|map, selection| {
10992 if selection.is_empty() {
10993 let cursor = movement::previous_subword_start(map, selection.head());
10994 selection.set_head(cursor, SelectionGoal::None);
10995 }
10996 });
10997 });
10998 this.insert("", window, cx);
10999 });
11000 }
11001
11002 pub fn move_to_next_word_end(
11003 &mut self,
11004 _: &MoveToNextWordEnd,
11005 window: &mut Window,
11006 cx: &mut Context<Self>,
11007 ) {
11008 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11009 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11010 s.move_cursors_with(|map, head, _| {
11011 (movement::next_word_end(map, head), SelectionGoal::None)
11012 });
11013 })
11014 }
11015
11016 pub fn move_to_next_subword_end(
11017 &mut self,
11018 _: &MoveToNextSubwordEnd,
11019 window: &mut Window,
11020 cx: &mut Context<Self>,
11021 ) {
11022 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11023 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11024 s.move_cursors_with(|map, head, _| {
11025 (movement::next_subword_end(map, head), SelectionGoal::None)
11026 });
11027 })
11028 }
11029
11030 pub fn select_to_next_word_end(
11031 &mut self,
11032 _: &SelectToNextWordEnd,
11033 window: &mut Window,
11034 cx: &mut Context<Self>,
11035 ) {
11036 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11037 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11038 s.move_heads_with(|map, head, _| {
11039 (movement::next_word_end(map, head), SelectionGoal::None)
11040 });
11041 })
11042 }
11043
11044 pub fn select_to_next_subword_end(
11045 &mut self,
11046 _: &SelectToNextSubwordEnd,
11047 window: &mut Window,
11048 cx: &mut Context<Self>,
11049 ) {
11050 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11051 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11052 s.move_heads_with(|map, head, _| {
11053 (movement::next_subword_end(map, head), SelectionGoal::None)
11054 });
11055 })
11056 }
11057
11058 pub fn delete_to_next_word_end(
11059 &mut self,
11060 action: &DeleteToNextWordEnd,
11061 window: &mut Window,
11062 cx: &mut Context<Self>,
11063 ) {
11064 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11065 self.transact(window, cx, |this, window, cx| {
11066 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11067 s.move_with(|map, selection| {
11068 if selection.is_empty() {
11069 let cursor = if action.ignore_newlines {
11070 movement::next_word_end(map, selection.head())
11071 } else {
11072 movement::next_word_end_or_newline(map, selection.head())
11073 };
11074 selection.set_head(cursor, SelectionGoal::None);
11075 }
11076 });
11077 });
11078 this.insert("", window, cx);
11079 });
11080 }
11081
11082 pub fn delete_to_next_subword_end(
11083 &mut self,
11084 _: &DeleteToNextSubwordEnd,
11085 window: &mut Window,
11086 cx: &mut Context<Self>,
11087 ) {
11088 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11089 self.transact(window, cx, |this, window, cx| {
11090 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11091 s.move_with(|map, selection| {
11092 if selection.is_empty() {
11093 let cursor = movement::next_subword_end(map, selection.head());
11094 selection.set_head(cursor, SelectionGoal::None);
11095 }
11096 });
11097 });
11098 this.insert("", window, cx);
11099 });
11100 }
11101
11102 pub fn move_to_beginning_of_line(
11103 &mut self,
11104 action: &MoveToBeginningOfLine,
11105 window: &mut Window,
11106 cx: &mut Context<Self>,
11107 ) {
11108 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11109 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11110 s.move_cursors_with(|map, head, _| {
11111 (
11112 movement::indented_line_beginning(
11113 map,
11114 head,
11115 action.stop_at_soft_wraps,
11116 action.stop_at_indent,
11117 ),
11118 SelectionGoal::None,
11119 )
11120 });
11121 })
11122 }
11123
11124 pub fn select_to_beginning_of_line(
11125 &mut self,
11126 action: &SelectToBeginningOfLine,
11127 window: &mut Window,
11128 cx: &mut Context<Self>,
11129 ) {
11130 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11131 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11132 s.move_heads_with(|map, head, _| {
11133 (
11134 movement::indented_line_beginning(
11135 map,
11136 head,
11137 action.stop_at_soft_wraps,
11138 action.stop_at_indent,
11139 ),
11140 SelectionGoal::None,
11141 )
11142 });
11143 });
11144 }
11145
11146 pub fn delete_to_beginning_of_line(
11147 &mut self,
11148 action: &DeleteToBeginningOfLine,
11149 window: &mut Window,
11150 cx: &mut Context<Self>,
11151 ) {
11152 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11153 self.transact(window, cx, |this, window, cx| {
11154 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11155 s.move_with(|_, selection| {
11156 selection.reversed = true;
11157 });
11158 });
11159
11160 this.select_to_beginning_of_line(
11161 &SelectToBeginningOfLine {
11162 stop_at_soft_wraps: false,
11163 stop_at_indent: action.stop_at_indent,
11164 },
11165 window,
11166 cx,
11167 );
11168 this.backspace(&Backspace, window, cx);
11169 });
11170 }
11171
11172 pub fn move_to_end_of_line(
11173 &mut self,
11174 action: &MoveToEndOfLine,
11175 window: &mut Window,
11176 cx: &mut Context<Self>,
11177 ) {
11178 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11179 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11180 s.move_cursors_with(|map, head, _| {
11181 (
11182 movement::line_end(map, head, action.stop_at_soft_wraps),
11183 SelectionGoal::None,
11184 )
11185 });
11186 })
11187 }
11188
11189 pub fn select_to_end_of_line(
11190 &mut self,
11191 action: &SelectToEndOfLine,
11192 window: &mut Window,
11193 cx: &mut Context<Self>,
11194 ) {
11195 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11196 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11197 s.move_heads_with(|map, head, _| {
11198 (
11199 movement::line_end(map, head, action.stop_at_soft_wraps),
11200 SelectionGoal::None,
11201 )
11202 });
11203 })
11204 }
11205
11206 pub fn delete_to_end_of_line(
11207 &mut self,
11208 _: &DeleteToEndOfLine,
11209 window: &mut Window,
11210 cx: &mut Context<Self>,
11211 ) {
11212 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11213 self.transact(window, cx, |this, window, cx| {
11214 this.select_to_end_of_line(
11215 &SelectToEndOfLine {
11216 stop_at_soft_wraps: false,
11217 },
11218 window,
11219 cx,
11220 );
11221 this.delete(&Delete, window, cx);
11222 });
11223 }
11224
11225 pub fn cut_to_end_of_line(
11226 &mut self,
11227 _: &CutToEndOfLine,
11228 window: &mut Window,
11229 cx: &mut Context<Self>,
11230 ) {
11231 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
11232 self.transact(window, cx, |this, window, cx| {
11233 this.select_to_end_of_line(
11234 &SelectToEndOfLine {
11235 stop_at_soft_wraps: false,
11236 },
11237 window,
11238 cx,
11239 );
11240 this.cut(&Cut, window, cx);
11241 });
11242 }
11243
11244 pub fn move_to_start_of_paragraph(
11245 &mut self,
11246 _: &MoveToStartOfParagraph,
11247 window: &mut Window,
11248 cx: &mut Context<Self>,
11249 ) {
11250 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11251 cx.propagate();
11252 return;
11253 }
11254 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11255 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11256 s.move_with(|map, selection| {
11257 selection.collapse_to(
11258 movement::start_of_paragraph(map, selection.head(), 1),
11259 SelectionGoal::None,
11260 )
11261 });
11262 })
11263 }
11264
11265 pub fn move_to_end_of_paragraph(
11266 &mut self,
11267 _: &MoveToEndOfParagraph,
11268 window: &mut Window,
11269 cx: &mut Context<Self>,
11270 ) {
11271 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11272 cx.propagate();
11273 return;
11274 }
11275 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11276 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11277 s.move_with(|map, selection| {
11278 selection.collapse_to(
11279 movement::end_of_paragraph(map, selection.head(), 1),
11280 SelectionGoal::None,
11281 )
11282 });
11283 })
11284 }
11285
11286 pub fn select_to_start_of_paragraph(
11287 &mut self,
11288 _: &SelectToStartOfParagraph,
11289 window: &mut Window,
11290 cx: &mut Context<Self>,
11291 ) {
11292 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11293 cx.propagate();
11294 return;
11295 }
11296 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11297 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11298 s.move_heads_with(|map, head, _| {
11299 (
11300 movement::start_of_paragraph(map, head, 1),
11301 SelectionGoal::None,
11302 )
11303 });
11304 })
11305 }
11306
11307 pub fn select_to_end_of_paragraph(
11308 &mut self,
11309 _: &SelectToEndOfParagraph,
11310 window: &mut Window,
11311 cx: &mut Context<Self>,
11312 ) {
11313 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11314 cx.propagate();
11315 return;
11316 }
11317 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11318 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11319 s.move_heads_with(|map, head, _| {
11320 (
11321 movement::end_of_paragraph(map, head, 1),
11322 SelectionGoal::None,
11323 )
11324 });
11325 })
11326 }
11327
11328 pub fn move_to_start_of_excerpt(
11329 &mut self,
11330 _: &MoveToStartOfExcerpt,
11331 window: &mut Window,
11332 cx: &mut Context<Self>,
11333 ) {
11334 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11335 cx.propagate();
11336 return;
11337 }
11338 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11339 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11340 s.move_with(|map, selection| {
11341 selection.collapse_to(
11342 movement::start_of_excerpt(
11343 map,
11344 selection.head(),
11345 workspace::searchable::Direction::Prev,
11346 ),
11347 SelectionGoal::None,
11348 )
11349 });
11350 })
11351 }
11352
11353 pub fn move_to_start_of_next_excerpt(
11354 &mut self,
11355 _: &MoveToStartOfNextExcerpt,
11356 window: &mut Window,
11357 cx: &mut Context<Self>,
11358 ) {
11359 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11360 cx.propagate();
11361 return;
11362 }
11363
11364 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11365 s.move_with(|map, selection| {
11366 selection.collapse_to(
11367 movement::start_of_excerpt(
11368 map,
11369 selection.head(),
11370 workspace::searchable::Direction::Next,
11371 ),
11372 SelectionGoal::None,
11373 )
11374 });
11375 })
11376 }
11377
11378 pub fn move_to_end_of_excerpt(
11379 &mut self,
11380 _: &MoveToEndOfExcerpt,
11381 window: &mut Window,
11382 cx: &mut Context<Self>,
11383 ) {
11384 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11385 cx.propagate();
11386 return;
11387 }
11388 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11389 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11390 s.move_with(|map, selection| {
11391 selection.collapse_to(
11392 movement::end_of_excerpt(
11393 map,
11394 selection.head(),
11395 workspace::searchable::Direction::Next,
11396 ),
11397 SelectionGoal::None,
11398 )
11399 });
11400 })
11401 }
11402
11403 pub fn move_to_end_of_previous_excerpt(
11404 &mut self,
11405 _: &MoveToEndOfPreviousExcerpt,
11406 window: &mut Window,
11407 cx: &mut Context<Self>,
11408 ) {
11409 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11410 cx.propagate();
11411 return;
11412 }
11413 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11414 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11415 s.move_with(|map, selection| {
11416 selection.collapse_to(
11417 movement::end_of_excerpt(
11418 map,
11419 selection.head(),
11420 workspace::searchable::Direction::Prev,
11421 ),
11422 SelectionGoal::None,
11423 )
11424 });
11425 })
11426 }
11427
11428 pub fn select_to_start_of_excerpt(
11429 &mut self,
11430 _: &SelectToStartOfExcerpt,
11431 window: &mut Window,
11432 cx: &mut Context<Self>,
11433 ) {
11434 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11435 cx.propagate();
11436 return;
11437 }
11438 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11439 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11440 s.move_heads_with(|map, head, _| {
11441 (
11442 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11443 SelectionGoal::None,
11444 )
11445 });
11446 })
11447 }
11448
11449 pub fn select_to_start_of_next_excerpt(
11450 &mut self,
11451 _: &SelectToStartOfNextExcerpt,
11452 window: &mut Window,
11453 cx: &mut Context<Self>,
11454 ) {
11455 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11456 cx.propagate();
11457 return;
11458 }
11459 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11460 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11461 s.move_heads_with(|map, head, _| {
11462 (
11463 movement::start_of_excerpt(map, head, workspace::searchable::Direction::Next),
11464 SelectionGoal::None,
11465 )
11466 });
11467 })
11468 }
11469
11470 pub fn select_to_end_of_excerpt(
11471 &mut self,
11472 _: &SelectToEndOfExcerpt,
11473 window: &mut Window,
11474 cx: &mut Context<Self>,
11475 ) {
11476 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11477 cx.propagate();
11478 return;
11479 }
11480 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11481 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11482 s.move_heads_with(|map, head, _| {
11483 (
11484 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Next),
11485 SelectionGoal::None,
11486 )
11487 });
11488 })
11489 }
11490
11491 pub fn select_to_end_of_previous_excerpt(
11492 &mut self,
11493 _: &SelectToEndOfPreviousExcerpt,
11494 window: &mut Window,
11495 cx: &mut Context<Self>,
11496 ) {
11497 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11498 cx.propagate();
11499 return;
11500 }
11501 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11502 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11503 s.move_heads_with(|map, head, _| {
11504 (
11505 movement::end_of_excerpt(map, head, workspace::searchable::Direction::Prev),
11506 SelectionGoal::None,
11507 )
11508 });
11509 })
11510 }
11511
11512 pub fn move_to_beginning(
11513 &mut self,
11514 _: &MoveToBeginning,
11515 window: &mut Window,
11516 cx: &mut Context<Self>,
11517 ) {
11518 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11519 cx.propagate();
11520 return;
11521 }
11522 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11523 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11524 s.select_ranges(vec![0..0]);
11525 });
11526 }
11527
11528 pub fn select_to_beginning(
11529 &mut self,
11530 _: &SelectToBeginning,
11531 window: &mut Window,
11532 cx: &mut Context<Self>,
11533 ) {
11534 let mut selection = self.selections.last::<Point>(cx);
11535 selection.set_head(Point::zero(), SelectionGoal::None);
11536 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11537 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11538 s.select(vec![selection]);
11539 });
11540 }
11541
11542 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
11543 if matches!(self.mode, EditorMode::SingleLine { .. }) {
11544 cx.propagate();
11545 return;
11546 }
11547 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11548 let cursor = self.buffer.read(cx).read(cx).len();
11549 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11550 s.select_ranges(vec![cursor..cursor])
11551 });
11552 }
11553
11554 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
11555 self.nav_history = nav_history;
11556 }
11557
11558 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
11559 self.nav_history.as_ref()
11560 }
11561
11562 pub fn create_nav_history_entry(&mut self, cx: &mut Context<Self>) {
11563 self.push_to_nav_history(self.selections.newest_anchor().head(), None, false, cx);
11564 }
11565
11566 fn push_to_nav_history(
11567 &mut self,
11568 cursor_anchor: Anchor,
11569 new_position: Option<Point>,
11570 is_deactivate: bool,
11571 cx: &mut Context<Self>,
11572 ) {
11573 if let Some(nav_history) = self.nav_history.as_mut() {
11574 let buffer = self.buffer.read(cx).read(cx);
11575 let cursor_position = cursor_anchor.to_point(&buffer);
11576 let scroll_state = self.scroll_manager.anchor();
11577 let scroll_top_row = scroll_state.top_row(&buffer);
11578 drop(buffer);
11579
11580 if let Some(new_position) = new_position {
11581 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
11582 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
11583 return;
11584 }
11585 }
11586
11587 nav_history.push(
11588 Some(NavigationData {
11589 cursor_anchor,
11590 cursor_position,
11591 scroll_anchor: scroll_state,
11592 scroll_top_row,
11593 }),
11594 cx,
11595 );
11596 cx.emit(EditorEvent::PushedToNavHistory {
11597 anchor: cursor_anchor,
11598 is_deactivate,
11599 })
11600 }
11601 }
11602
11603 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
11604 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11605 let buffer = self.buffer.read(cx).snapshot(cx);
11606 let mut selection = self.selections.first::<usize>(cx);
11607 selection.set_head(buffer.len(), SelectionGoal::None);
11608 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11609 s.select(vec![selection]);
11610 });
11611 }
11612
11613 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
11614 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11615 let end = self.buffer.read(cx).read(cx).len();
11616 self.change_selections(None, window, cx, |s| {
11617 s.select_ranges(vec![0..end]);
11618 });
11619 }
11620
11621 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
11622 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11623 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11624 let mut selections = self.selections.all::<Point>(cx);
11625 let max_point = display_map.buffer_snapshot.max_point();
11626 for selection in &mut selections {
11627 let rows = selection.spanned_rows(true, &display_map);
11628 selection.start = Point::new(rows.start.0, 0);
11629 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
11630 selection.reversed = false;
11631 }
11632 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11633 s.select(selections);
11634 });
11635 }
11636
11637 pub fn split_selection_into_lines(
11638 &mut self,
11639 _: &SplitSelectionIntoLines,
11640 window: &mut Window,
11641 cx: &mut Context<Self>,
11642 ) {
11643 let selections = self
11644 .selections
11645 .all::<Point>(cx)
11646 .into_iter()
11647 .map(|selection| selection.start..selection.end)
11648 .collect::<Vec<_>>();
11649 self.unfold_ranges(&selections, true, true, cx);
11650
11651 let mut new_selection_ranges = Vec::new();
11652 {
11653 let buffer = self.buffer.read(cx).read(cx);
11654 for selection in selections {
11655 for row in selection.start.row..selection.end.row {
11656 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
11657 new_selection_ranges.push(cursor..cursor);
11658 }
11659
11660 let is_multiline_selection = selection.start.row != selection.end.row;
11661 // Don't insert last one if it's a multi-line selection ending at the start of a line,
11662 // so this action feels more ergonomic when paired with other selection operations
11663 let should_skip_last = is_multiline_selection && selection.end.column == 0;
11664 if !should_skip_last {
11665 new_selection_ranges.push(selection.end..selection.end);
11666 }
11667 }
11668 }
11669 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11670 s.select_ranges(new_selection_ranges);
11671 });
11672 }
11673
11674 pub fn add_selection_above(
11675 &mut self,
11676 _: &AddSelectionAbove,
11677 window: &mut Window,
11678 cx: &mut Context<Self>,
11679 ) {
11680 self.add_selection(true, window, cx);
11681 }
11682
11683 pub fn add_selection_below(
11684 &mut self,
11685 _: &AddSelectionBelow,
11686 window: &mut Window,
11687 cx: &mut Context<Self>,
11688 ) {
11689 self.add_selection(false, window, cx);
11690 }
11691
11692 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
11693 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11694
11695 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11696 let mut selections = self.selections.all::<Point>(cx);
11697 let text_layout_details = self.text_layout_details(window);
11698 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
11699 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
11700 let range = oldest_selection.display_range(&display_map).sorted();
11701
11702 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
11703 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
11704 let positions = start_x.min(end_x)..start_x.max(end_x);
11705
11706 selections.clear();
11707 let mut stack = Vec::new();
11708 for row in range.start.row().0..=range.end.row().0 {
11709 if let Some(selection) = self.selections.build_columnar_selection(
11710 &display_map,
11711 DisplayRow(row),
11712 &positions,
11713 oldest_selection.reversed,
11714 &text_layout_details,
11715 ) {
11716 stack.push(selection.id);
11717 selections.push(selection);
11718 }
11719 }
11720
11721 if above {
11722 stack.reverse();
11723 }
11724
11725 AddSelectionsState { above, stack }
11726 });
11727
11728 let last_added_selection = *state.stack.last().unwrap();
11729 let mut new_selections = Vec::new();
11730 if above == state.above {
11731 let end_row = if above {
11732 DisplayRow(0)
11733 } else {
11734 display_map.max_point().row()
11735 };
11736
11737 'outer: for selection in selections {
11738 if selection.id == last_added_selection {
11739 let range = selection.display_range(&display_map).sorted();
11740 debug_assert_eq!(range.start.row(), range.end.row());
11741 let mut row = range.start.row();
11742 let positions =
11743 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
11744 px(start)..px(end)
11745 } else {
11746 let start_x =
11747 display_map.x_for_display_point(range.start, &text_layout_details);
11748 let end_x =
11749 display_map.x_for_display_point(range.end, &text_layout_details);
11750 start_x.min(end_x)..start_x.max(end_x)
11751 };
11752
11753 while row != end_row {
11754 if above {
11755 row.0 -= 1;
11756 } else {
11757 row.0 += 1;
11758 }
11759
11760 if let Some(new_selection) = self.selections.build_columnar_selection(
11761 &display_map,
11762 row,
11763 &positions,
11764 selection.reversed,
11765 &text_layout_details,
11766 ) {
11767 state.stack.push(new_selection.id);
11768 if above {
11769 new_selections.push(new_selection);
11770 new_selections.push(selection);
11771 } else {
11772 new_selections.push(selection);
11773 new_selections.push(new_selection);
11774 }
11775
11776 continue 'outer;
11777 }
11778 }
11779 }
11780
11781 new_selections.push(selection);
11782 }
11783 } else {
11784 new_selections = selections;
11785 new_selections.retain(|s| s.id != last_added_selection);
11786 state.stack.pop();
11787 }
11788
11789 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11790 s.select(new_selections);
11791 });
11792 if state.stack.len() > 1 {
11793 self.add_selections_state = Some(state);
11794 }
11795 }
11796
11797 pub fn select_next_match_internal(
11798 &mut self,
11799 display_map: &DisplaySnapshot,
11800 replace_newest: bool,
11801 autoscroll: Option<Autoscroll>,
11802 window: &mut Window,
11803 cx: &mut Context<Self>,
11804 ) -> Result<()> {
11805 fn select_next_match_ranges(
11806 this: &mut Editor,
11807 range: Range<usize>,
11808 replace_newest: bool,
11809 auto_scroll: Option<Autoscroll>,
11810 window: &mut Window,
11811 cx: &mut Context<Editor>,
11812 ) {
11813 this.unfold_ranges(&[range.clone()], false, auto_scroll.is_some(), cx);
11814 this.change_selections(auto_scroll, window, cx, |s| {
11815 if replace_newest {
11816 s.delete(s.newest_anchor().id);
11817 }
11818 s.insert_range(range.clone());
11819 });
11820 }
11821
11822 let buffer = &display_map.buffer_snapshot;
11823 let mut selections = self.selections.all::<usize>(cx);
11824 if let Some(mut select_next_state) = self.select_next_state.take() {
11825 let query = &select_next_state.query;
11826 if !select_next_state.done {
11827 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
11828 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
11829 let mut next_selected_range = None;
11830
11831 let bytes_after_last_selection =
11832 buffer.bytes_in_range(last_selection.end..buffer.len());
11833 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
11834 let query_matches = query
11835 .stream_find_iter(bytes_after_last_selection)
11836 .map(|result| (last_selection.end, result))
11837 .chain(
11838 query
11839 .stream_find_iter(bytes_before_first_selection)
11840 .map(|result| (0, result)),
11841 );
11842
11843 for (start_offset, query_match) in query_matches {
11844 let query_match = query_match.unwrap(); // can only fail due to I/O
11845 let offset_range =
11846 start_offset + query_match.start()..start_offset + query_match.end();
11847 let display_range = offset_range.start.to_display_point(display_map)
11848 ..offset_range.end.to_display_point(display_map);
11849
11850 if !select_next_state.wordwise
11851 || (!movement::is_inside_word(display_map, display_range.start)
11852 && !movement::is_inside_word(display_map, display_range.end))
11853 {
11854 // TODO: This is n^2, because we might check all the selections
11855 if !selections
11856 .iter()
11857 .any(|selection| selection.range().overlaps(&offset_range))
11858 {
11859 next_selected_range = Some(offset_range);
11860 break;
11861 }
11862 }
11863 }
11864
11865 if let Some(next_selected_range) = next_selected_range {
11866 select_next_match_ranges(
11867 self,
11868 next_selected_range,
11869 replace_newest,
11870 autoscroll,
11871 window,
11872 cx,
11873 );
11874 } else {
11875 select_next_state.done = true;
11876 }
11877 }
11878
11879 self.select_next_state = Some(select_next_state);
11880 } else {
11881 let mut only_carets = true;
11882 let mut same_text_selected = true;
11883 let mut selected_text = None;
11884
11885 let mut selections_iter = selections.iter().peekable();
11886 while let Some(selection) = selections_iter.next() {
11887 if selection.start != selection.end {
11888 only_carets = false;
11889 }
11890
11891 if same_text_selected {
11892 if selected_text.is_none() {
11893 selected_text =
11894 Some(buffer.text_for_range(selection.range()).collect::<String>());
11895 }
11896
11897 if let Some(next_selection) = selections_iter.peek() {
11898 if next_selection.range().len() == selection.range().len() {
11899 let next_selected_text = buffer
11900 .text_for_range(next_selection.range())
11901 .collect::<String>();
11902 if Some(next_selected_text) != selected_text {
11903 same_text_selected = false;
11904 selected_text = None;
11905 }
11906 } else {
11907 same_text_selected = false;
11908 selected_text = None;
11909 }
11910 }
11911 }
11912 }
11913
11914 if only_carets {
11915 for selection in &mut selections {
11916 let word_range = movement::surrounding_word(
11917 display_map,
11918 selection.start.to_display_point(display_map),
11919 );
11920 selection.start = word_range.start.to_offset(display_map, Bias::Left);
11921 selection.end = word_range.end.to_offset(display_map, Bias::Left);
11922 selection.goal = SelectionGoal::None;
11923 selection.reversed = false;
11924 select_next_match_ranges(
11925 self,
11926 selection.start..selection.end,
11927 replace_newest,
11928 autoscroll,
11929 window,
11930 cx,
11931 );
11932 }
11933
11934 if selections.len() == 1 {
11935 let selection = selections
11936 .last()
11937 .expect("ensured that there's only one selection");
11938 let query = buffer
11939 .text_for_range(selection.start..selection.end)
11940 .collect::<String>();
11941 let is_empty = query.is_empty();
11942 let select_state = SelectNextState {
11943 query: AhoCorasick::new(&[query])?,
11944 wordwise: true,
11945 done: is_empty,
11946 };
11947 self.select_next_state = Some(select_state);
11948 } else {
11949 self.select_next_state = None;
11950 }
11951 } else if let Some(selected_text) = selected_text {
11952 self.select_next_state = Some(SelectNextState {
11953 query: AhoCorasick::new(&[selected_text])?,
11954 wordwise: false,
11955 done: false,
11956 });
11957 self.select_next_match_internal(
11958 display_map,
11959 replace_newest,
11960 autoscroll,
11961 window,
11962 cx,
11963 )?;
11964 }
11965 }
11966 Ok(())
11967 }
11968
11969 pub fn select_all_matches(
11970 &mut self,
11971 _action: &SelectAllMatches,
11972 window: &mut Window,
11973 cx: &mut Context<Self>,
11974 ) -> Result<()> {
11975 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
11976
11977 self.push_to_selection_history();
11978 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11979
11980 self.select_next_match_internal(&display_map, false, None, window, cx)?;
11981 let Some(select_next_state) = self.select_next_state.as_mut() else {
11982 return Ok(());
11983 };
11984 if select_next_state.done {
11985 return Ok(());
11986 }
11987
11988 let mut new_selections = Vec::new();
11989
11990 let reversed = self.selections.oldest::<usize>(cx).reversed;
11991 let buffer = &display_map.buffer_snapshot;
11992 let query_matches = select_next_state
11993 .query
11994 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
11995
11996 for query_match in query_matches.into_iter() {
11997 let query_match = query_match.context("query match for select all action")?; // can only fail due to I/O
11998 let offset_range = if reversed {
11999 query_match.end()..query_match.start()
12000 } else {
12001 query_match.start()..query_match.end()
12002 };
12003 let display_range = offset_range.start.to_display_point(&display_map)
12004 ..offset_range.end.to_display_point(&display_map);
12005
12006 if !select_next_state.wordwise
12007 || (!movement::is_inside_word(&display_map, display_range.start)
12008 && !movement::is_inside_word(&display_map, display_range.end))
12009 {
12010 new_selections.push(offset_range.start..offset_range.end);
12011 }
12012 }
12013
12014 select_next_state.done = true;
12015 self.unfold_ranges(&new_selections.clone(), false, false, cx);
12016 self.change_selections(None, window, cx, |selections| {
12017 selections.select_ranges(new_selections)
12018 });
12019
12020 Ok(())
12021 }
12022
12023 pub fn select_next(
12024 &mut self,
12025 action: &SelectNext,
12026 window: &mut Window,
12027 cx: &mut Context<Self>,
12028 ) -> Result<()> {
12029 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12030 self.push_to_selection_history();
12031 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12032 self.select_next_match_internal(
12033 &display_map,
12034 action.replace_newest,
12035 Some(Autoscroll::newest()),
12036 window,
12037 cx,
12038 )?;
12039 Ok(())
12040 }
12041
12042 pub fn select_previous(
12043 &mut self,
12044 action: &SelectPrevious,
12045 window: &mut Window,
12046 cx: &mut Context<Self>,
12047 ) -> Result<()> {
12048 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12049 self.push_to_selection_history();
12050 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12051 let buffer = &display_map.buffer_snapshot;
12052 let mut selections = self.selections.all::<usize>(cx);
12053 if let Some(mut select_prev_state) = self.select_prev_state.take() {
12054 let query = &select_prev_state.query;
12055 if !select_prev_state.done {
12056 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
12057 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
12058 let mut next_selected_range = None;
12059 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
12060 let bytes_before_last_selection =
12061 buffer.reversed_bytes_in_range(0..last_selection.start);
12062 let bytes_after_first_selection =
12063 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
12064 let query_matches = query
12065 .stream_find_iter(bytes_before_last_selection)
12066 .map(|result| (last_selection.start, result))
12067 .chain(
12068 query
12069 .stream_find_iter(bytes_after_first_selection)
12070 .map(|result| (buffer.len(), result)),
12071 );
12072 for (end_offset, query_match) in query_matches {
12073 let query_match = query_match.unwrap(); // can only fail due to I/O
12074 let offset_range =
12075 end_offset - query_match.end()..end_offset - query_match.start();
12076 let display_range = offset_range.start.to_display_point(&display_map)
12077 ..offset_range.end.to_display_point(&display_map);
12078
12079 if !select_prev_state.wordwise
12080 || (!movement::is_inside_word(&display_map, display_range.start)
12081 && !movement::is_inside_word(&display_map, display_range.end))
12082 {
12083 next_selected_range = Some(offset_range);
12084 break;
12085 }
12086 }
12087
12088 if let Some(next_selected_range) = next_selected_range {
12089 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
12090 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12091 if action.replace_newest {
12092 s.delete(s.newest_anchor().id);
12093 }
12094 s.insert_range(next_selected_range);
12095 });
12096 } else {
12097 select_prev_state.done = true;
12098 }
12099 }
12100
12101 self.select_prev_state = Some(select_prev_state);
12102 } else {
12103 let mut only_carets = true;
12104 let mut same_text_selected = true;
12105 let mut selected_text = None;
12106
12107 let mut selections_iter = selections.iter().peekable();
12108 while let Some(selection) = selections_iter.next() {
12109 if selection.start != selection.end {
12110 only_carets = false;
12111 }
12112
12113 if same_text_selected {
12114 if selected_text.is_none() {
12115 selected_text =
12116 Some(buffer.text_for_range(selection.range()).collect::<String>());
12117 }
12118
12119 if let Some(next_selection) = selections_iter.peek() {
12120 if next_selection.range().len() == selection.range().len() {
12121 let next_selected_text = buffer
12122 .text_for_range(next_selection.range())
12123 .collect::<String>();
12124 if Some(next_selected_text) != selected_text {
12125 same_text_selected = false;
12126 selected_text = None;
12127 }
12128 } else {
12129 same_text_selected = false;
12130 selected_text = None;
12131 }
12132 }
12133 }
12134 }
12135
12136 if only_carets {
12137 for selection in &mut selections {
12138 let word_range = movement::surrounding_word(
12139 &display_map,
12140 selection.start.to_display_point(&display_map),
12141 );
12142 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
12143 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
12144 selection.goal = SelectionGoal::None;
12145 selection.reversed = false;
12146 }
12147 if selections.len() == 1 {
12148 let selection = selections
12149 .last()
12150 .expect("ensured that there's only one selection");
12151 let query = buffer
12152 .text_for_range(selection.start..selection.end)
12153 .collect::<String>();
12154 let is_empty = query.is_empty();
12155 let select_state = SelectNextState {
12156 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
12157 wordwise: true,
12158 done: is_empty,
12159 };
12160 self.select_prev_state = Some(select_state);
12161 } else {
12162 self.select_prev_state = None;
12163 }
12164
12165 self.unfold_ranges(
12166 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
12167 false,
12168 true,
12169 cx,
12170 );
12171 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
12172 s.select(selections);
12173 });
12174 } else if let Some(selected_text) = selected_text {
12175 self.select_prev_state = Some(SelectNextState {
12176 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
12177 wordwise: false,
12178 done: false,
12179 });
12180 self.select_previous(action, window, cx)?;
12181 }
12182 }
12183 Ok(())
12184 }
12185
12186 pub fn find_next_match(
12187 &mut self,
12188 _: &FindNextMatch,
12189 window: &mut Window,
12190 cx: &mut Context<Self>,
12191 ) -> Result<()> {
12192 let selections = self.selections.disjoint_anchors();
12193 match selections.first() {
12194 Some(first) if selections.len() >= 2 => {
12195 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12196 s.select_ranges([first.range()]);
12197 });
12198 }
12199 _ => self.select_next(
12200 &SelectNext {
12201 replace_newest: true,
12202 },
12203 window,
12204 cx,
12205 )?,
12206 }
12207 Ok(())
12208 }
12209
12210 pub fn find_previous_match(
12211 &mut self,
12212 _: &FindPreviousMatch,
12213 window: &mut Window,
12214 cx: &mut Context<Self>,
12215 ) -> Result<()> {
12216 let selections = self.selections.disjoint_anchors();
12217 match selections.last() {
12218 Some(last) if selections.len() >= 2 => {
12219 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12220 s.select_ranges([last.range()]);
12221 });
12222 }
12223 _ => self.select_previous(
12224 &SelectPrevious {
12225 replace_newest: true,
12226 },
12227 window,
12228 cx,
12229 )?,
12230 }
12231 Ok(())
12232 }
12233
12234 pub fn toggle_comments(
12235 &mut self,
12236 action: &ToggleComments,
12237 window: &mut Window,
12238 cx: &mut Context<Self>,
12239 ) {
12240 if self.read_only(cx) {
12241 return;
12242 }
12243 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
12244 let text_layout_details = &self.text_layout_details(window);
12245 self.transact(window, cx, |this, window, cx| {
12246 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
12247 let mut edits = Vec::new();
12248 let mut selection_edit_ranges = Vec::new();
12249 let mut last_toggled_row = None;
12250 let snapshot = this.buffer.read(cx).read(cx);
12251 let empty_str: Arc<str> = Arc::default();
12252 let mut suffixes_inserted = Vec::new();
12253 let ignore_indent = action.ignore_indent;
12254
12255 fn comment_prefix_range(
12256 snapshot: &MultiBufferSnapshot,
12257 row: MultiBufferRow,
12258 comment_prefix: &str,
12259 comment_prefix_whitespace: &str,
12260 ignore_indent: bool,
12261 ) -> Range<Point> {
12262 let indent_size = if ignore_indent {
12263 0
12264 } else {
12265 snapshot.indent_size_for_line(row).len
12266 };
12267
12268 let start = Point::new(row.0, indent_size);
12269
12270 let mut line_bytes = snapshot
12271 .bytes_in_range(start..snapshot.max_point())
12272 .flatten()
12273 .copied();
12274
12275 // If this line currently begins with the line comment prefix, then record
12276 // the range containing the prefix.
12277 if line_bytes
12278 .by_ref()
12279 .take(comment_prefix.len())
12280 .eq(comment_prefix.bytes())
12281 {
12282 // Include any whitespace that matches the comment prefix.
12283 let matching_whitespace_len = line_bytes
12284 .zip(comment_prefix_whitespace.bytes())
12285 .take_while(|(a, b)| a == b)
12286 .count() as u32;
12287 let end = Point::new(
12288 start.row,
12289 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
12290 );
12291 start..end
12292 } else {
12293 start..start
12294 }
12295 }
12296
12297 fn comment_suffix_range(
12298 snapshot: &MultiBufferSnapshot,
12299 row: MultiBufferRow,
12300 comment_suffix: &str,
12301 comment_suffix_has_leading_space: bool,
12302 ) -> Range<Point> {
12303 let end = Point::new(row.0, snapshot.line_len(row));
12304 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
12305
12306 let mut line_end_bytes = snapshot
12307 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
12308 .flatten()
12309 .copied();
12310
12311 let leading_space_len = if suffix_start_column > 0
12312 && line_end_bytes.next() == Some(b' ')
12313 && comment_suffix_has_leading_space
12314 {
12315 1
12316 } else {
12317 0
12318 };
12319
12320 // If this line currently begins with the line comment prefix, then record
12321 // the range containing the prefix.
12322 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
12323 let start = Point::new(end.row, suffix_start_column - leading_space_len);
12324 start..end
12325 } else {
12326 end..end
12327 }
12328 }
12329
12330 // TODO: Handle selections that cross excerpts
12331 for selection in &mut selections {
12332 let start_column = snapshot
12333 .indent_size_for_line(MultiBufferRow(selection.start.row))
12334 .len;
12335 let language = if let Some(language) =
12336 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
12337 {
12338 language
12339 } else {
12340 continue;
12341 };
12342
12343 selection_edit_ranges.clear();
12344
12345 // If multiple selections contain a given row, avoid processing that
12346 // row more than once.
12347 let mut start_row = MultiBufferRow(selection.start.row);
12348 if last_toggled_row == Some(start_row) {
12349 start_row = start_row.next_row();
12350 }
12351 let end_row =
12352 if selection.end.row > selection.start.row && selection.end.column == 0 {
12353 MultiBufferRow(selection.end.row - 1)
12354 } else {
12355 MultiBufferRow(selection.end.row)
12356 };
12357 last_toggled_row = Some(end_row);
12358
12359 if start_row > end_row {
12360 continue;
12361 }
12362
12363 // If the language has line comments, toggle those.
12364 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
12365
12366 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
12367 if ignore_indent {
12368 full_comment_prefixes = full_comment_prefixes
12369 .into_iter()
12370 .map(|s| Arc::from(s.trim_end()))
12371 .collect();
12372 }
12373
12374 if !full_comment_prefixes.is_empty() {
12375 let first_prefix = full_comment_prefixes
12376 .first()
12377 .expect("prefixes is non-empty");
12378 let prefix_trimmed_lengths = full_comment_prefixes
12379 .iter()
12380 .map(|p| p.trim_end_matches(' ').len())
12381 .collect::<SmallVec<[usize; 4]>>();
12382
12383 let mut all_selection_lines_are_comments = true;
12384
12385 for row in start_row.0..=end_row.0 {
12386 let row = MultiBufferRow(row);
12387 if start_row < end_row && snapshot.is_line_blank(row) {
12388 continue;
12389 }
12390
12391 let prefix_range = full_comment_prefixes
12392 .iter()
12393 .zip(prefix_trimmed_lengths.iter().copied())
12394 .map(|(prefix, trimmed_prefix_len)| {
12395 comment_prefix_range(
12396 snapshot.deref(),
12397 row,
12398 &prefix[..trimmed_prefix_len],
12399 &prefix[trimmed_prefix_len..],
12400 ignore_indent,
12401 )
12402 })
12403 .max_by_key(|range| range.end.column - range.start.column)
12404 .expect("prefixes is non-empty");
12405
12406 if prefix_range.is_empty() {
12407 all_selection_lines_are_comments = false;
12408 }
12409
12410 selection_edit_ranges.push(prefix_range);
12411 }
12412
12413 if all_selection_lines_are_comments {
12414 edits.extend(
12415 selection_edit_ranges
12416 .iter()
12417 .cloned()
12418 .map(|range| (range, empty_str.clone())),
12419 );
12420 } else {
12421 let min_column = selection_edit_ranges
12422 .iter()
12423 .map(|range| range.start.column)
12424 .min()
12425 .unwrap_or(0);
12426 edits.extend(selection_edit_ranges.iter().map(|range| {
12427 let position = Point::new(range.start.row, min_column);
12428 (position..position, first_prefix.clone())
12429 }));
12430 }
12431 } else if let Some((full_comment_prefix, comment_suffix)) =
12432 language.block_comment_delimiters()
12433 {
12434 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
12435 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
12436 let prefix_range = comment_prefix_range(
12437 snapshot.deref(),
12438 start_row,
12439 comment_prefix,
12440 comment_prefix_whitespace,
12441 ignore_indent,
12442 );
12443 let suffix_range = comment_suffix_range(
12444 snapshot.deref(),
12445 end_row,
12446 comment_suffix.trim_start_matches(' '),
12447 comment_suffix.starts_with(' '),
12448 );
12449
12450 if prefix_range.is_empty() || suffix_range.is_empty() {
12451 edits.push((
12452 prefix_range.start..prefix_range.start,
12453 full_comment_prefix.clone(),
12454 ));
12455 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
12456 suffixes_inserted.push((end_row, comment_suffix.len()));
12457 } else {
12458 edits.push((prefix_range, empty_str.clone()));
12459 edits.push((suffix_range, empty_str.clone()));
12460 }
12461 } else {
12462 continue;
12463 }
12464 }
12465
12466 drop(snapshot);
12467 this.buffer.update(cx, |buffer, cx| {
12468 buffer.edit(edits, None, cx);
12469 });
12470
12471 // Adjust selections so that they end before any comment suffixes that
12472 // were inserted.
12473 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
12474 let mut selections = this.selections.all::<Point>(cx);
12475 let snapshot = this.buffer.read(cx).read(cx);
12476 for selection in &mut selections {
12477 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
12478 match row.cmp(&MultiBufferRow(selection.end.row)) {
12479 Ordering::Less => {
12480 suffixes_inserted.next();
12481 continue;
12482 }
12483 Ordering::Greater => break,
12484 Ordering::Equal => {
12485 if selection.end.column == snapshot.line_len(row) {
12486 if selection.is_empty() {
12487 selection.start.column -= suffix_len as u32;
12488 }
12489 selection.end.column -= suffix_len as u32;
12490 }
12491 break;
12492 }
12493 }
12494 }
12495 }
12496
12497 drop(snapshot);
12498 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12499 s.select(selections)
12500 });
12501
12502 let selections = this.selections.all::<Point>(cx);
12503 let selections_on_single_row = selections.windows(2).all(|selections| {
12504 selections[0].start.row == selections[1].start.row
12505 && selections[0].end.row == selections[1].end.row
12506 && selections[0].start.row == selections[0].end.row
12507 });
12508 let selections_selecting = selections
12509 .iter()
12510 .any(|selection| selection.start != selection.end);
12511 let advance_downwards = action.advance_downwards
12512 && selections_on_single_row
12513 && !selections_selecting
12514 && !matches!(this.mode, EditorMode::SingleLine { .. });
12515
12516 if advance_downwards {
12517 let snapshot = this.buffer.read(cx).snapshot(cx);
12518
12519 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12520 s.move_cursors_with(|display_snapshot, display_point, _| {
12521 let mut point = display_point.to_point(display_snapshot);
12522 point.row += 1;
12523 point = snapshot.clip_point(point, Bias::Left);
12524 let display_point = point.to_display_point(display_snapshot);
12525 let goal = SelectionGoal::HorizontalPosition(
12526 display_snapshot
12527 .x_for_display_point(display_point, text_layout_details)
12528 .into(),
12529 );
12530 (display_point, goal)
12531 })
12532 });
12533 }
12534 });
12535 }
12536
12537 pub fn select_enclosing_symbol(
12538 &mut self,
12539 _: &SelectEnclosingSymbol,
12540 window: &mut Window,
12541 cx: &mut Context<Self>,
12542 ) {
12543 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12544
12545 let buffer = self.buffer.read(cx).snapshot(cx);
12546 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
12547
12548 fn update_selection(
12549 selection: &Selection<usize>,
12550 buffer_snap: &MultiBufferSnapshot,
12551 ) -> Option<Selection<usize>> {
12552 let cursor = selection.head();
12553 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
12554 for symbol in symbols.iter().rev() {
12555 let start = symbol.range.start.to_offset(buffer_snap);
12556 let end = symbol.range.end.to_offset(buffer_snap);
12557 let new_range = start..end;
12558 if start < selection.start || end > selection.end {
12559 return Some(Selection {
12560 id: selection.id,
12561 start: new_range.start,
12562 end: new_range.end,
12563 goal: SelectionGoal::None,
12564 reversed: selection.reversed,
12565 });
12566 }
12567 }
12568 None
12569 }
12570
12571 let mut selected_larger_symbol = false;
12572 let new_selections = old_selections
12573 .iter()
12574 .map(|selection| match update_selection(selection, &buffer) {
12575 Some(new_selection) => {
12576 if new_selection.range() != selection.range() {
12577 selected_larger_symbol = true;
12578 }
12579 new_selection
12580 }
12581 None => selection.clone(),
12582 })
12583 .collect::<Vec<_>>();
12584
12585 if selected_larger_symbol {
12586 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12587 s.select(new_selections);
12588 });
12589 }
12590 }
12591
12592 pub fn select_larger_syntax_node(
12593 &mut self,
12594 _: &SelectLargerSyntaxNode,
12595 window: &mut Window,
12596 cx: &mut Context<Self>,
12597 ) {
12598 let Some(visible_row_count) = self.visible_row_count() else {
12599 return;
12600 };
12601 let old_selections: Box<[_]> = self.selections.all::<usize>(cx).into();
12602 if old_selections.is_empty() {
12603 return;
12604 }
12605
12606 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12607
12608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12609 let buffer = self.buffer.read(cx).snapshot(cx);
12610
12611 let mut selected_larger_node = false;
12612 let mut new_selections = old_selections
12613 .iter()
12614 .map(|selection| {
12615 let old_range = selection.start..selection.end;
12616
12617 if let Some((node, _)) = buffer.syntax_ancestor(old_range.clone()) {
12618 // manually select word at selection
12619 if ["string_content", "inline"].contains(&node.kind()) {
12620 let word_range = {
12621 let display_point = buffer
12622 .offset_to_point(old_range.start)
12623 .to_display_point(&display_map);
12624 let Range { start, end } =
12625 movement::surrounding_word(&display_map, display_point);
12626 start.to_point(&display_map).to_offset(&buffer)
12627 ..end.to_point(&display_map).to_offset(&buffer)
12628 };
12629 // ignore if word is already selected
12630 if !word_range.is_empty() && old_range != word_range {
12631 let last_word_range = {
12632 let display_point = buffer
12633 .offset_to_point(old_range.end)
12634 .to_display_point(&display_map);
12635 let Range { start, end } =
12636 movement::surrounding_word(&display_map, display_point);
12637 start.to_point(&display_map).to_offset(&buffer)
12638 ..end.to_point(&display_map).to_offset(&buffer)
12639 };
12640 // only select word if start and end point belongs to same word
12641 if word_range == last_word_range {
12642 selected_larger_node = true;
12643 return Selection {
12644 id: selection.id,
12645 start: word_range.start,
12646 end: word_range.end,
12647 goal: SelectionGoal::None,
12648 reversed: selection.reversed,
12649 };
12650 }
12651 }
12652 }
12653 }
12654
12655 let mut new_range = old_range.clone();
12656 let mut new_node = None;
12657 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
12658 {
12659 new_node = Some(node);
12660 new_range = match containing_range {
12661 MultiOrSingleBufferOffsetRange::Single(_) => break,
12662 MultiOrSingleBufferOffsetRange::Multi(range) => range,
12663 };
12664 if !display_map.intersects_fold(new_range.start)
12665 && !display_map.intersects_fold(new_range.end)
12666 {
12667 break;
12668 }
12669 }
12670
12671 if let Some(node) = new_node {
12672 // Log the ancestor, to support using this action as a way to explore TreeSitter
12673 // nodes. Parent and grandparent are also logged because this operation will not
12674 // visit nodes that have the same range as their parent.
12675 log::info!("Node: {node:?}");
12676 let parent = node.parent();
12677 log::info!("Parent: {parent:?}");
12678 let grandparent = parent.and_then(|x| x.parent());
12679 log::info!("Grandparent: {grandparent:?}");
12680 }
12681
12682 selected_larger_node |= new_range != old_range;
12683 Selection {
12684 id: selection.id,
12685 start: new_range.start,
12686 end: new_range.end,
12687 goal: SelectionGoal::None,
12688 reversed: selection.reversed,
12689 }
12690 })
12691 .collect::<Vec<_>>();
12692
12693 if !selected_larger_node {
12694 return; // don't put this call in the history
12695 }
12696
12697 // scroll based on transformation done to the last selection created by the user
12698 let (last_old, last_new) = old_selections
12699 .last()
12700 .zip(new_selections.last().cloned())
12701 .expect("old_selections isn't empty");
12702
12703 // revert selection
12704 let is_selection_reversed = {
12705 let should_newest_selection_be_reversed = last_old.start != last_new.start;
12706 new_selections.last_mut().expect("checked above").reversed =
12707 should_newest_selection_be_reversed;
12708 should_newest_selection_be_reversed
12709 };
12710
12711 if selected_larger_node {
12712 self.select_syntax_node_history.disable_clearing = true;
12713 self.change_selections(None, window, cx, |s| {
12714 s.select(new_selections.clone());
12715 });
12716 self.select_syntax_node_history.disable_clearing = false;
12717 }
12718
12719 let start_row = last_new.start.to_display_point(&display_map).row().0;
12720 let end_row = last_new.end.to_display_point(&display_map).row().0;
12721 let selection_height = end_row - start_row + 1;
12722 let scroll_margin_rows = self.vertical_scroll_margin() as u32;
12723
12724 let fits_on_the_screen = visible_row_count >= selection_height + scroll_margin_rows * 2;
12725 let scroll_behavior = if fits_on_the_screen {
12726 self.request_autoscroll(Autoscroll::fit(), cx);
12727 SelectSyntaxNodeScrollBehavior::FitSelection
12728 } else if is_selection_reversed {
12729 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12730 SelectSyntaxNodeScrollBehavior::CursorTop
12731 } else {
12732 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12733 SelectSyntaxNodeScrollBehavior::CursorBottom
12734 };
12735
12736 self.select_syntax_node_history.push((
12737 old_selections,
12738 scroll_behavior,
12739 is_selection_reversed,
12740 ));
12741 }
12742
12743 pub fn select_smaller_syntax_node(
12744 &mut self,
12745 _: &SelectSmallerSyntaxNode,
12746 window: &mut Window,
12747 cx: &mut Context<Self>,
12748 ) {
12749 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12750
12751 if let Some((mut selections, scroll_behavior, is_selection_reversed)) =
12752 self.select_syntax_node_history.pop()
12753 {
12754 if let Some(selection) = selections.last_mut() {
12755 selection.reversed = is_selection_reversed;
12756 }
12757
12758 self.select_syntax_node_history.disable_clearing = true;
12759 self.change_selections(None, window, cx, |s| {
12760 s.select(selections.to_vec());
12761 });
12762 self.select_syntax_node_history.disable_clearing = false;
12763
12764 match scroll_behavior {
12765 SelectSyntaxNodeScrollBehavior::CursorTop => {
12766 self.scroll_cursor_top(&ScrollCursorTop, window, cx);
12767 }
12768 SelectSyntaxNodeScrollBehavior::FitSelection => {
12769 self.request_autoscroll(Autoscroll::fit(), cx);
12770 }
12771 SelectSyntaxNodeScrollBehavior::CursorBottom => {
12772 self.scroll_cursor_bottom(&ScrollCursorBottom, window, cx);
12773 }
12774 }
12775 }
12776 }
12777
12778 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
12779 if !EditorSettings::get_global(cx).gutter.runnables {
12780 self.clear_tasks();
12781 return Task::ready(());
12782 }
12783 let project = self.project.as_ref().map(Entity::downgrade);
12784 let task_sources = self.lsp_task_sources(cx);
12785 cx.spawn_in(window, async move |editor, cx| {
12786 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
12787 let Some(project) = project.and_then(|p| p.upgrade()) else {
12788 return;
12789 };
12790 let Ok(display_snapshot) = editor.update(cx, |this, cx| {
12791 this.display_map.update(cx, |map, cx| map.snapshot(cx))
12792 }) else {
12793 return;
12794 };
12795
12796 let hide_runnables = project
12797 .update(cx, |project, cx| {
12798 // Do not display any test indicators in non-dev server remote projects.
12799 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
12800 })
12801 .unwrap_or(true);
12802 if hide_runnables {
12803 return;
12804 }
12805 let new_rows =
12806 cx.background_spawn({
12807 let snapshot = display_snapshot.clone();
12808 async move {
12809 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
12810 }
12811 })
12812 .await;
12813 let Ok(lsp_tasks) =
12814 cx.update(|_, cx| crate::lsp_tasks(project.clone(), &task_sources, None, cx))
12815 else {
12816 return;
12817 };
12818 let lsp_tasks = lsp_tasks.await;
12819
12820 let Ok(mut lsp_tasks_by_rows) = cx.update(|_, cx| {
12821 lsp_tasks
12822 .into_iter()
12823 .flat_map(|(kind, tasks)| {
12824 tasks.into_iter().filter_map(move |(location, task)| {
12825 Some((kind.clone(), location?, task))
12826 })
12827 })
12828 .fold(HashMap::default(), |mut acc, (kind, location, task)| {
12829 let buffer = location.target.buffer;
12830 let buffer_snapshot = buffer.read(cx).snapshot();
12831 let offset = display_snapshot.buffer_snapshot.excerpts().find_map(
12832 |(excerpt_id, snapshot, _)| {
12833 if snapshot.remote_id() == buffer_snapshot.remote_id() {
12834 display_snapshot
12835 .buffer_snapshot
12836 .anchor_in_excerpt(excerpt_id, location.target.range.start)
12837 } else {
12838 None
12839 }
12840 },
12841 );
12842 if let Some(offset) = offset {
12843 let task_buffer_range =
12844 location.target.range.to_point(&buffer_snapshot);
12845 let context_buffer_range =
12846 task_buffer_range.to_offset(&buffer_snapshot);
12847 let context_range = BufferOffset(context_buffer_range.start)
12848 ..BufferOffset(context_buffer_range.end);
12849
12850 acc.entry((buffer_snapshot.remote_id(), task_buffer_range.start.row))
12851 .or_insert_with(|| RunnableTasks {
12852 templates: Vec::new(),
12853 offset,
12854 column: task_buffer_range.start.column,
12855 extra_variables: HashMap::default(),
12856 context_range,
12857 })
12858 .templates
12859 .push((kind, task.original_task().clone()));
12860 }
12861
12862 acc
12863 })
12864 }) else {
12865 return;
12866 };
12867
12868 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
12869 editor
12870 .update(cx, |editor, _| {
12871 editor.clear_tasks();
12872 for (key, mut value) in rows {
12873 if let Some(lsp_tasks) = lsp_tasks_by_rows.remove(&key) {
12874 value.templates.extend(lsp_tasks.templates);
12875 }
12876
12877 editor.insert_tasks(key, value);
12878 }
12879 for (key, value) in lsp_tasks_by_rows {
12880 editor.insert_tasks(key, value);
12881 }
12882 })
12883 .ok();
12884 })
12885 }
12886 fn fetch_runnable_ranges(
12887 snapshot: &DisplaySnapshot,
12888 range: Range<Anchor>,
12889 ) -> Vec<language::RunnableRange> {
12890 snapshot.buffer_snapshot.runnable_ranges(range).collect()
12891 }
12892
12893 fn runnable_rows(
12894 project: Entity<Project>,
12895 snapshot: DisplaySnapshot,
12896 runnable_ranges: Vec<RunnableRange>,
12897 mut cx: AsyncWindowContext,
12898 ) -> Vec<((BufferId, BufferRow), RunnableTasks)> {
12899 runnable_ranges
12900 .into_iter()
12901 .filter_map(|mut runnable| {
12902 let tasks = cx
12903 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
12904 .ok()?;
12905 if tasks.is_empty() {
12906 return None;
12907 }
12908
12909 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
12910
12911 let row = snapshot
12912 .buffer_snapshot
12913 .buffer_line_for_row(MultiBufferRow(point.row))?
12914 .1
12915 .start
12916 .row;
12917
12918 let context_range =
12919 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
12920 Some((
12921 (runnable.buffer_id, row),
12922 RunnableTasks {
12923 templates: tasks,
12924 offset: snapshot
12925 .buffer_snapshot
12926 .anchor_before(runnable.run_range.start),
12927 context_range,
12928 column: point.column,
12929 extra_variables: runnable.extra_captures,
12930 },
12931 ))
12932 })
12933 .collect()
12934 }
12935
12936 fn templates_with_tags(
12937 project: &Entity<Project>,
12938 runnable: &mut Runnable,
12939 cx: &mut App,
12940 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
12941 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
12942 let (worktree_id, file) = project
12943 .buffer_for_id(runnable.buffer, cx)
12944 .and_then(|buffer| buffer.read(cx).file())
12945 .map(|file| (file.worktree_id(cx), file.clone()))
12946 .unzip();
12947
12948 (
12949 project.task_store().read(cx).task_inventory().cloned(),
12950 worktree_id,
12951 file,
12952 )
12953 });
12954
12955 let mut templates_with_tags = mem::take(&mut runnable.tags)
12956 .into_iter()
12957 .flat_map(|RunnableTag(tag)| {
12958 inventory
12959 .as_ref()
12960 .into_iter()
12961 .flat_map(|inventory| {
12962 inventory.read(cx).list_tasks(
12963 file.clone(),
12964 Some(runnable.language.clone()),
12965 worktree_id,
12966 cx,
12967 )
12968 })
12969 .filter(move |(_, template)| {
12970 template.tags.iter().any(|source_tag| source_tag == &tag)
12971 })
12972 })
12973 .sorted_by_key(|(kind, _)| kind.to_owned())
12974 .collect::<Vec<_>>();
12975 if let Some((leading_tag_source, _)) = templates_with_tags.first() {
12976 // Strongest source wins; if we have worktree tag binding, prefer that to
12977 // global and language bindings;
12978 // if we have a global binding, prefer that to language binding.
12979 let first_mismatch = templates_with_tags
12980 .iter()
12981 .position(|(tag_source, _)| tag_source != leading_tag_source);
12982 if let Some(index) = first_mismatch {
12983 templates_with_tags.truncate(index);
12984 }
12985 }
12986
12987 templates_with_tags
12988 }
12989
12990 pub fn move_to_enclosing_bracket(
12991 &mut self,
12992 _: &MoveToEnclosingBracket,
12993 window: &mut Window,
12994 cx: &mut Context<Self>,
12995 ) {
12996 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
12997 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
12998 s.move_offsets_with(|snapshot, selection| {
12999 let Some(enclosing_bracket_ranges) =
13000 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
13001 else {
13002 return;
13003 };
13004
13005 let mut best_length = usize::MAX;
13006 let mut best_inside = false;
13007 let mut best_in_bracket_range = false;
13008 let mut best_destination = None;
13009 for (open, close) in enclosing_bracket_ranges {
13010 let close = close.to_inclusive();
13011 let length = close.end() - open.start;
13012 let inside = selection.start >= open.end && selection.end <= *close.start();
13013 let in_bracket_range = open.to_inclusive().contains(&selection.head())
13014 || close.contains(&selection.head());
13015
13016 // If best is next to a bracket and current isn't, skip
13017 if !in_bracket_range && best_in_bracket_range {
13018 continue;
13019 }
13020
13021 // Prefer smaller lengths unless best is inside and current isn't
13022 if length > best_length && (best_inside || !inside) {
13023 continue;
13024 }
13025
13026 best_length = length;
13027 best_inside = inside;
13028 best_in_bracket_range = in_bracket_range;
13029 best_destination = Some(
13030 if close.contains(&selection.start) && close.contains(&selection.end) {
13031 if inside { open.end } else { open.start }
13032 } else if inside {
13033 *close.start()
13034 } else {
13035 *close.end()
13036 },
13037 );
13038 }
13039
13040 if let Some(destination) = best_destination {
13041 selection.collapse_to(destination, SelectionGoal::None);
13042 }
13043 })
13044 });
13045 }
13046
13047 pub fn undo_selection(
13048 &mut self,
13049 _: &UndoSelection,
13050 window: &mut Window,
13051 cx: &mut Context<Self>,
13052 ) {
13053 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13054 self.end_selection(window, cx);
13055 self.selection_history.mode = SelectionHistoryMode::Undoing;
13056 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
13057 self.change_selections(None, window, cx, |s| {
13058 s.select_anchors(entry.selections.to_vec())
13059 });
13060 self.select_next_state = entry.select_next_state;
13061 self.select_prev_state = entry.select_prev_state;
13062 self.add_selections_state = entry.add_selections_state;
13063 self.request_autoscroll(Autoscroll::newest(), cx);
13064 }
13065 self.selection_history.mode = SelectionHistoryMode::Normal;
13066 }
13067
13068 pub fn redo_selection(
13069 &mut self,
13070 _: &RedoSelection,
13071 window: &mut Window,
13072 cx: &mut Context<Self>,
13073 ) {
13074 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13075 self.end_selection(window, cx);
13076 self.selection_history.mode = SelectionHistoryMode::Redoing;
13077 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
13078 self.change_selections(None, window, cx, |s| {
13079 s.select_anchors(entry.selections.to_vec())
13080 });
13081 self.select_next_state = entry.select_next_state;
13082 self.select_prev_state = entry.select_prev_state;
13083 self.add_selections_state = entry.add_selections_state;
13084 self.request_autoscroll(Autoscroll::newest(), cx);
13085 }
13086 self.selection_history.mode = SelectionHistoryMode::Normal;
13087 }
13088
13089 pub fn expand_excerpts(
13090 &mut self,
13091 action: &ExpandExcerpts,
13092 _: &mut Window,
13093 cx: &mut Context<Self>,
13094 ) {
13095 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
13096 }
13097
13098 pub fn expand_excerpts_down(
13099 &mut self,
13100 action: &ExpandExcerptsDown,
13101 _: &mut Window,
13102 cx: &mut Context<Self>,
13103 ) {
13104 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
13105 }
13106
13107 pub fn expand_excerpts_up(
13108 &mut self,
13109 action: &ExpandExcerptsUp,
13110 _: &mut Window,
13111 cx: &mut Context<Self>,
13112 ) {
13113 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
13114 }
13115
13116 pub fn expand_excerpts_for_direction(
13117 &mut self,
13118 lines: u32,
13119 direction: ExpandExcerptDirection,
13120
13121 cx: &mut Context<Self>,
13122 ) {
13123 let selections = self.selections.disjoint_anchors();
13124
13125 let lines = if lines == 0 {
13126 EditorSettings::get_global(cx).expand_excerpt_lines
13127 } else {
13128 lines
13129 };
13130
13131 self.buffer.update(cx, |buffer, cx| {
13132 let snapshot = buffer.snapshot(cx);
13133 let mut excerpt_ids = selections
13134 .iter()
13135 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
13136 .collect::<Vec<_>>();
13137 excerpt_ids.sort();
13138 excerpt_ids.dedup();
13139 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
13140 })
13141 }
13142
13143 pub fn expand_excerpt(
13144 &mut self,
13145 excerpt: ExcerptId,
13146 direction: ExpandExcerptDirection,
13147 window: &mut Window,
13148 cx: &mut Context<Self>,
13149 ) {
13150 let current_scroll_position = self.scroll_position(cx);
13151 let lines_to_expand = EditorSettings::get_global(cx).expand_excerpt_lines;
13152 let mut should_scroll_up = false;
13153
13154 if direction == ExpandExcerptDirection::Down {
13155 let multi_buffer = self.buffer.read(cx);
13156 let snapshot = multi_buffer.snapshot(cx);
13157 if let Some(buffer_id) = snapshot.buffer_id_for_excerpt(excerpt) {
13158 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13159 if let Some(excerpt_range) = snapshot.buffer_range_for_excerpt(excerpt) {
13160 let buffer_snapshot = buffer.read(cx).snapshot();
13161 let excerpt_end_row =
13162 Point::from_anchor(&excerpt_range.end, &buffer_snapshot).row;
13163 let last_row = buffer_snapshot.max_point().row;
13164 let lines_below = last_row.saturating_sub(excerpt_end_row);
13165 should_scroll_up = lines_below >= lines_to_expand;
13166 }
13167 }
13168 }
13169 }
13170
13171 self.buffer.update(cx, |buffer, cx| {
13172 buffer.expand_excerpts([excerpt], lines_to_expand, direction, cx)
13173 });
13174
13175 if should_scroll_up {
13176 let new_scroll_position =
13177 current_scroll_position + gpui::Point::new(0.0, lines_to_expand as f32);
13178 self.set_scroll_position(new_scroll_position, window, cx);
13179 }
13180 }
13181
13182 pub fn go_to_singleton_buffer_point(
13183 &mut self,
13184 point: Point,
13185 window: &mut Window,
13186 cx: &mut Context<Self>,
13187 ) {
13188 self.go_to_singleton_buffer_range(point..point, window, cx);
13189 }
13190
13191 pub fn go_to_singleton_buffer_range(
13192 &mut self,
13193 range: Range<Point>,
13194 window: &mut Window,
13195 cx: &mut Context<Self>,
13196 ) {
13197 let multibuffer = self.buffer().read(cx);
13198 let Some(buffer) = multibuffer.as_singleton() else {
13199 return;
13200 };
13201 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
13202 return;
13203 };
13204 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
13205 return;
13206 };
13207 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
13208 s.select_anchor_ranges([start..end])
13209 });
13210 }
13211
13212 pub fn go_to_diagnostic(
13213 &mut self,
13214 _: &GoToDiagnostic,
13215 window: &mut Window,
13216 cx: &mut Context<Self>,
13217 ) {
13218 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13219 self.go_to_diagnostic_impl(Direction::Next, window, cx)
13220 }
13221
13222 pub fn go_to_prev_diagnostic(
13223 &mut self,
13224 _: &GoToPreviousDiagnostic,
13225 window: &mut Window,
13226 cx: &mut Context<Self>,
13227 ) {
13228 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13229 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
13230 }
13231
13232 pub fn go_to_diagnostic_impl(
13233 &mut self,
13234 direction: Direction,
13235 window: &mut Window,
13236 cx: &mut Context<Self>,
13237 ) {
13238 let buffer = self.buffer.read(cx).snapshot(cx);
13239 let selection = self.selections.newest::<usize>(cx);
13240
13241 let mut active_group_id = None;
13242 if let ActiveDiagnostic::Group(active_group) = &self.active_diagnostics {
13243 if active_group.active_range.start.to_offset(&buffer) == selection.start {
13244 active_group_id = Some(active_group.group_id);
13245 }
13246 }
13247
13248 fn filtered(
13249 snapshot: EditorSnapshot,
13250 diagnostics: impl Iterator<Item = DiagnosticEntry<usize>>,
13251 ) -> impl Iterator<Item = DiagnosticEntry<usize>> {
13252 diagnostics
13253 .filter(|entry| entry.range.start != entry.range.end)
13254 .filter(|entry| !entry.diagnostic.is_unnecessary)
13255 .filter(move |entry| !snapshot.intersects_fold(entry.range.start))
13256 }
13257
13258 let snapshot = self.snapshot(window, cx);
13259 let before = filtered(
13260 snapshot.clone(),
13261 buffer
13262 .diagnostics_in_range(0..selection.start)
13263 .filter(|entry| entry.range.start <= selection.start),
13264 );
13265 let after = filtered(
13266 snapshot,
13267 buffer
13268 .diagnostics_in_range(selection.start..buffer.len())
13269 .filter(|entry| entry.range.start >= selection.start),
13270 );
13271
13272 let mut found: Option<DiagnosticEntry<usize>> = None;
13273 if direction == Direction::Prev {
13274 'outer: for prev_diagnostics in [before.collect::<Vec<_>>(), after.collect::<Vec<_>>()]
13275 {
13276 for diagnostic in prev_diagnostics.into_iter().rev() {
13277 if diagnostic.range.start != selection.start
13278 || active_group_id
13279 .is_some_and(|active| diagnostic.diagnostic.group_id < active)
13280 {
13281 found = Some(diagnostic);
13282 break 'outer;
13283 }
13284 }
13285 }
13286 } else {
13287 for diagnostic in after.chain(before) {
13288 if diagnostic.range.start != selection.start
13289 || active_group_id.is_some_and(|active| diagnostic.diagnostic.group_id > active)
13290 {
13291 found = Some(diagnostic);
13292 break;
13293 }
13294 }
13295 }
13296 let Some(next_diagnostic) = found else {
13297 return;
13298 };
13299
13300 let Some(buffer_id) = buffer.anchor_after(next_diagnostic.range.start).buffer_id else {
13301 return;
13302 };
13303 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13304 s.select_ranges(vec![
13305 next_diagnostic.range.start..next_diagnostic.range.start,
13306 ])
13307 });
13308 self.activate_diagnostics(buffer_id, next_diagnostic, window, cx);
13309 self.refresh_inline_completion(false, true, window, cx);
13310 }
13311
13312 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
13313 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13314 let snapshot = self.snapshot(window, cx);
13315 let selection = self.selections.newest::<Point>(cx);
13316 self.go_to_hunk_before_or_after_position(
13317 &snapshot,
13318 selection.head(),
13319 Direction::Next,
13320 window,
13321 cx,
13322 );
13323 }
13324
13325 pub fn go_to_hunk_before_or_after_position(
13326 &mut self,
13327 snapshot: &EditorSnapshot,
13328 position: Point,
13329 direction: Direction,
13330 window: &mut Window,
13331 cx: &mut Context<Editor>,
13332 ) {
13333 let row = if direction == Direction::Next {
13334 self.hunk_after_position(snapshot, position)
13335 .map(|hunk| hunk.row_range.start)
13336 } else {
13337 self.hunk_before_position(snapshot, position)
13338 };
13339
13340 if let Some(row) = row {
13341 let destination = Point::new(row.0, 0);
13342 let autoscroll = Autoscroll::center();
13343
13344 self.unfold_ranges(&[destination..destination], false, false, cx);
13345 self.change_selections(Some(autoscroll), window, cx, |s| {
13346 s.select_ranges([destination..destination]);
13347 });
13348 }
13349 }
13350
13351 fn hunk_after_position(
13352 &mut self,
13353 snapshot: &EditorSnapshot,
13354 position: Point,
13355 ) -> Option<MultiBufferDiffHunk> {
13356 snapshot
13357 .buffer_snapshot
13358 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
13359 .find(|hunk| hunk.row_range.start.0 > position.row)
13360 .or_else(|| {
13361 snapshot
13362 .buffer_snapshot
13363 .diff_hunks_in_range(Point::zero()..position)
13364 .find(|hunk| hunk.row_range.end.0 < position.row)
13365 })
13366 }
13367
13368 fn go_to_prev_hunk(
13369 &mut self,
13370 _: &GoToPreviousHunk,
13371 window: &mut Window,
13372 cx: &mut Context<Self>,
13373 ) {
13374 self.hide_mouse_cursor(&HideMouseCursorOrigin::MovementAction);
13375 let snapshot = self.snapshot(window, cx);
13376 let selection = self.selections.newest::<Point>(cx);
13377 self.go_to_hunk_before_or_after_position(
13378 &snapshot,
13379 selection.head(),
13380 Direction::Prev,
13381 window,
13382 cx,
13383 );
13384 }
13385
13386 fn hunk_before_position(
13387 &mut self,
13388 snapshot: &EditorSnapshot,
13389 position: Point,
13390 ) -> Option<MultiBufferRow> {
13391 snapshot
13392 .buffer_snapshot
13393 .diff_hunk_before(position)
13394 .or_else(|| snapshot.buffer_snapshot.diff_hunk_before(Point::MAX))
13395 }
13396
13397 fn go_to_next_change(
13398 &mut self,
13399 _: &GoToNextChange,
13400 window: &mut Window,
13401 cx: &mut Context<Self>,
13402 ) {
13403 if let Some(selections) = self
13404 .change_list
13405 .next_change(1, Direction::Next)
13406 .map(|s| s.to_vec())
13407 {
13408 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13409 let map = s.display_map();
13410 s.select_display_ranges(selections.iter().map(|a| {
13411 let point = a.to_display_point(&map);
13412 point..point
13413 }))
13414 })
13415 }
13416 }
13417
13418 fn go_to_previous_change(
13419 &mut self,
13420 _: &GoToPreviousChange,
13421 window: &mut Window,
13422 cx: &mut Context<Self>,
13423 ) {
13424 if let Some(selections) = self
13425 .change_list
13426 .next_change(1, Direction::Prev)
13427 .map(|s| s.to_vec())
13428 {
13429 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
13430 let map = s.display_map();
13431 s.select_display_ranges(selections.iter().map(|a| {
13432 let point = a.to_display_point(&map);
13433 point..point
13434 }))
13435 })
13436 }
13437 }
13438
13439 fn go_to_line<T: 'static>(
13440 &mut self,
13441 position: Anchor,
13442 highlight_color: Option<Hsla>,
13443 window: &mut Window,
13444 cx: &mut Context<Self>,
13445 ) {
13446 let snapshot = self.snapshot(window, cx).display_snapshot;
13447 let position = position.to_point(&snapshot.buffer_snapshot);
13448 let start = snapshot
13449 .buffer_snapshot
13450 .clip_point(Point::new(position.row, 0), Bias::Left);
13451 let end = start + Point::new(1, 0);
13452 let start = snapshot.buffer_snapshot.anchor_before(start);
13453 let end = snapshot.buffer_snapshot.anchor_before(end);
13454
13455 self.highlight_rows::<T>(
13456 start..end,
13457 highlight_color
13458 .unwrap_or_else(|| cx.theme().colors().editor_highlighted_line_background),
13459 false,
13460 cx,
13461 );
13462 self.request_autoscroll(Autoscroll::center().for_anchor(start), cx);
13463 }
13464
13465 pub fn go_to_definition(
13466 &mut self,
13467 _: &GoToDefinition,
13468 window: &mut Window,
13469 cx: &mut Context<Self>,
13470 ) -> Task<Result<Navigated>> {
13471 let definition =
13472 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
13473 let fallback_strategy = EditorSettings::get_global(cx).go_to_definition_fallback;
13474 cx.spawn_in(window, async move |editor, cx| {
13475 if definition.await? == Navigated::Yes {
13476 return Ok(Navigated::Yes);
13477 }
13478 match fallback_strategy {
13479 GoToDefinitionFallback::None => Ok(Navigated::No),
13480 GoToDefinitionFallback::FindAllReferences => {
13481 match editor.update_in(cx, |editor, window, cx| {
13482 editor.find_all_references(&FindAllReferences, window, cx)
13483 })? {
13484 Some(references) => references.await,
13485 None => Ok(Navigated::No),
13486 }
13487 }
13488 }
13489 })
13490 }
13491
13492 pub fn go_to_declaration(
13493 &mut self,
13494 _: &GoToDeclaration,
13495 window: &mut Window,
13496 cx: &mut Context<Self>,
13497 ) -> Task<Result<Navigated>> {
13498 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
13499 }
13500
13501 pub fn go_to_declaration_split(
13502 &mut self,
13503 _: &GoToDeclaration,
13504 window: &mut Window,
13505 cx: &mut Context<Self>,
13506 ) -> Task<Result<Navigated>> {
13507 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
13508 }
13509
13510 pub fn go_to_implementation(
13511 &mut self,
13512 _: &GoToImplementation,
13513 window: &mut Window,
13514 cx: &mut Context<Self>,
13515 ) -> Task<Result<Navigated>> {
13516 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
13517 }
13518
13519 pub fn go_to_implementation_split(
13520 &mut self,
13521 _: &GoToImplementationSplit,
13522 window: &mut Window,
13523 cx: &mut Context<Self>,
13524 ) -> Task<Result<Navigated>> {
13525 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
13526 }
13527
13528 pub fn go_to_type_definition(
13529 &mut self,
13530 _: &GoToTypeDefinition,
13531 window: &mut Window,
13532 cx: &mut Context<Self>,
13533 ) -> Task<Result<Navigated>> {
13534 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
13535 }
13536
13537 pub fn go_to_definition_split(
13538 &mut self,
13539 _: &GoToDefinitionSplit,
13540 window: &mut Window,
13541 cx: &mut Context<Self>,
13542 ) -> Task<Result<Navigated>> {
13543 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
13544 }
13545
13546 pub fn go_to_type_definition_split(
13547 &mut self,
13548 _: &GoToTypeDefinitionSplit,
13549 window: &mut Window,
13550 cx: &mut Context<Self>,
13551 ) -> Task<Result<Navigated>> {
13552 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
13553 }
13554
13555 fn go_to_definition_of_kind(
13556 &mut self,
13557 kind: GotoDefinitionKind,
13558 split: bool,
13559 window: &mut Window,
13560 cx: &mut Context<Self>,
13561 ) -> Task<Result<Navigated>> {
13562 let Some(provider) = self.semantics_provider.clone() else {
13563 return Task::ready(Ok(Navigated::No));
13564 };
13565 let head = self.selections.newest::<usize>(cx).head();
13566 let buffer = self.buffer.read(cx);
13567 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
13568 text_anchor
13569 } else {
13570 return Task::ready(Ok(Navigated::No));
13571 };
13572
13573 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
13574 return Task::ready(Ok(Navigated::No));
13575 };
13576
13577 cx.spawn_in(window, async move |editor, cx| {
13578 let definitions = definitions.await?;
13579 let navigated = editor
13580 .update_in(cx, |editor, window, cx| {
13581 editor.navigate_to_hover_links(
13582 Some(kind),
13583 definitions
13584 .into_iter()
13585 .filter(|location| {
13586 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
13587 })
13588 .map(HoverLink::Text)
13589 .collect::<Vec<_>>(),
13590 split,
13591 window,
13592 cx,
13593 )
13594 })?
13595 .await?;
13596 anyhow::Ok(navigated)
13597 })
13598 }
13599
13600 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
13601 let selection = self.selections.newest_anchor();
13602 let head = selection.head();
13603 let tail = selection.tail();
13604
13605 let Some((buffer, start_position)) =
13606 self.buffer.read(cx).text_anchor_for_position(head, cx)
13607 else {
13608 return;
13609 };
13610
13611 let end_position = if head != tail {
13612 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
13613 return;
13614 };
13615 Some(pos)
13616 } else {
13617 None
13618 };
13619
13620 let url_finder = cx.spawn_in(window, async move |editor, cx| {
13621 let url = if let Some(end_pos) = end_position {
13622 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
13623 } else {
13624 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
13625 };
13626
13627 if let Some(url) = url {
13628 editor.update(cx, |_, cx| {
13629 cx.open_url(&url);
13630 })
13631 } else {
13632 Ok(())
13633 }
13634 });
13635
13636 url_finder.detach();
13637 }
13638
13639 pub fn open_selected_filename(
13640 &mut self,
13641 _: &OpenSelectedFilename,
13642 window: &mut Window,
13643 cx: &mut Context<Self>,
13644 ) {
13645 let Some(workspace) = self.workspace() else {
13646 return;
13647 };
13648
13649 let position = self.selections.newest_anchor().head();
13650
13651 let Some((buffer, buffer_position)) =
13652 self.buffer.read(cx).text_anchor_for_position(position, cx)
13653 else {
13654 return;
13655 };
13656
13657 let project = self.project.clone();
13658
13659 cx.spawn_in(window, async move |_, cx| {
13660 let result = find_file(&buffer, project, buffer_position, cx).await;
13661
13662 if let Some((_, path)) = result {
13663 workspace
13664 .update_in(cx, |workspace, window, cx| {
13665 workspace.open_resolved_path(path, window, cx)
13666 })?
13667 .await?;
13668 }
13669 anyhow::Ok(())
13670 })
13671 .detach();
13672 }
13673
13674 pub(crate) fn navigate_to_hover_links(
13675 &mut self,
13676 kind: Option<GotoDefinitionKind>,
13677 mut definitions: Vec<HoverLink>,
13678 split: bool,
13679 window: &mut Window,
13680 cx: &mut Context<Editor>,
13681 ) -> Task<Result<Navigated>> {
13682 // If there is one definition, just open it directly
13683 if definitions.len() == 1 {
13684 let definition = definitions.pop().unwrap();
13685
13686 enum TargetTaskResult {
13687 Location(Option<Location>),
13688 AlreadyNavigated,
13689 }
13690
13691 let target_task = match definition {
13692 HoverLink::Text(link) => {
13693 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
13694 }
13695 HoverLink::InlayHint(lsp_location, server_id) => {
13696 let computation =
13697 self.compute_target_location(lsp_location, server_id, window, cx);
13698 cx.background_spawn(async move {
13699 let location = computation.await?;
13700 Ok(TargetTaskResult::Location(location))
13701 })
13702 }
13703 HoverLink::Url(url) => {
13704 cx.open_url(&url);
13705 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
13706 }
13707 HoverLink::File(path) => {
13708 if let Some(workspace) = self.workspace() {
13709 cx.spawn_in(window, async move |_, cx| {
13710 workspace
13711 .update_in(cx, |workspace, window, cx| {
13712 workspace.open_resolved_path(path, window, cx)
13713 })?
13714 .await
13715 .map(|_| TargetTaskResult::AlreadyNavigated)
13716 })
13717 } else {
13718 Task::ready(Ok(TargetTaskResult::Location(None)))
13719 }
13720 }
13721 };
13722 cx.spawn_in(window, async move |editor, cx| {
13723 let target = match target_task.await.context("target resolution task")? {
13724 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
13725 TargetTaskResult::Location(None) => return Ok(Navigated::No),
13726 TargetTaskResult::Location(Some(target)) => target,
13727 };
13728
13729 editor.update_in(cx, |editor, window, cx| {
13730 let Some(workspace) = editor.workspace() else {
13731 return Navigated::No;
13732 };
13733 let pane = workspace.read(cx).active_pane().clone();
13734
13735 let range = target.range.to_point(target.buffer.read(cx));
13736 let range = editor.range_for_match(&range);
13737 let range = collapse_multiline_range(range);
13738
13739 if !split
13740 && Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref()
13741 {
13742 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
13743 } else {
13744 window.defer(cx, move |window, cx| {
13745 let target_editor: Entity<Self> =
13746 workspace.update(cx, |workspace, cx| {
13747 let pane = if split {
13748 workspace.adjacent_pane(window, cx)
13749 } else {
13750 workspace.active_pane().clone()
13751 };
13752
13753 workspace.open_project_item(
13754 pane,
13755 target.buffer.clone(),
13756 true,
13757 true,
13758 window,
13759 cx,
13760 )
13761 });
13762 target_editor.update(cx, |target_editor, cx| {
13763 // When selecting a definition in a different buffer, disable the nav history
13764 // to avoid creating a history entry at the previous cursor location.
13765 pane.update(cx, |pane, _| pane.disable_history());
13766 target_editor.go_to_singleton_buffer_range(range, window, cx);
13767 pane.update(cx, |pane, _| pane.enable_history());
13768 });
13769 });
13770 }
13771 Navigated::Yes
13772 })
13773 })
13774 } else if !definitions.is_empty() {
13775 cx.spawn_in(window, async move |editor, cx| {
13776 let (title, location_tasks, workspace) = editor
13777 .update_in(cx, |editor, window, cx| {
13778 let tab_kind = match kind {
13779 Some(GotoDefinitionKind::Implementation) => "Implementations",
13780 _ => "Definitions",
13781 };
13782 let title = definitions
13783 .iter()
13784 .find_map(|definition| match definition {
13785 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
13786 let buffer = origin.buffer.read(cx);
13787 format!(
13788 "{} for {}",
13789 tab_kind,
13790 buffer
13791 .text_for_range(origin.range.clone())
13792 .collect::<String>()
13793 )
13794 }),
13795 HoverLink::InlayHint(_, _) => None,
13796 HoverLink::Url(_) => None,
13797 HoverLink::File(_) => None,
13798 })
13799 .unwrap_or(tab_kind.to_string());
13800 let location_tasks = definitions
13801 .into_iter()
13802 .map(|definition| match definition {
13803 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
13804 HoverLink::InlayHint(lsp_location, server_id) => editor
13805 .compute_target_location(lsp_location, server_id, window, cx),
13806 HoverLink::Url(_) => Task::ready(Ok(None)),
13807 HoverLink::File(_) => Task::ready(Ok(None)),
13808 })
13809 .collect::<Vec<_>>();
13810 (title, location_tasks, editor.workspace().clone())
13811 })
13812 .context("location tasks preparation")?;
13813
13814 let locations = future::join_all(location_tasks)
13815 .await
13816 .into_iter()
13817 .filter_map(|location| location.transpose())
13818 .collect::<Result<_>>()
13819 .context("location tasks")?;
13820
13821 let Some(workspace) = workspace else {
13822 return Ok(Navigated::No);
13823 };
13824 let opened = workspace
13825 .update_in(cx, |workspace, window, cx| {
13826 Self::open_locations_in_multibuffer(
13827 workspace,
13828 locations,
13829 title,
13830 split,
13831 MultibufferSelectionMode::First,
13832 window,
13833 cx,
13834 )
13835 })
13836 .ok();
13837
13838 anyhow::Ok(Navigated::from_bool(opened.is_some()))
13839 })
13840 } else {
13841 Task::ready(Ok(Navigated::No))
13842 }
13843 }
13844
13845 fn compute_target_location(
13846 &self,
13847 lsp_location: lsp::Location,
13848 server_id: LanguageServerId,
13849 window: &mut Window,
13850 cx: &mut Context<Self>,
13851 ) -> Task<anyhow::Result<Option<Location>>> {
13852 let Some(project) = self.project.clone() else {
13853 return Task::ready(Ok(None));
13854 };
13855
13856 cx.spawn_in(window, async move |editor, cx| {
13857 let location_task = editor.update(cx, |_, cx| {
13858 project.update(cx, |project, cx| {
13859 let language_server_name = project
13860 .language_server_statuses(cx)
13861 .find(|(id, _)| server_id == *id)
13862 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
13863 language_server_name.map(|language_server_name| {
13864 project.open_local_buffer_via_lsp(
13865 lsp_location.uri.clone(),
13866 server_id,
13867 language_server_name,
13868 cx,
13869 )
13870 })
13871 })
13872 })?;
13873 let location = match location_task {
13874 Some(task) => Some({
13875 let target_buffer_handle = task.await.context("open local buffer")?;
13876 let range = target_buffer_handle.update(cx, |target_buffer, _| {
13877 let target_start = target_buffer
13878 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
13879 let target_end = target_buffer
13880 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
13881 target_buffer.anchor_after(target_start)
13882 ..target_buffer.anchor_before(target_end)
13883 })?;
13884 Location {
13885 buffer: target_buffer_handle,
13886 range,
13887 }
13888 }),
13889 None => None,
13890 };
13891 Ok(location)
13892 })
13893 }
13894
13895 pub fn find_all_references(
13896 &mut self,
13897 _: &FindAllReferences,
13898 window: &mut Window,
13899 cx: &mut Context<Self>,
13900 ) -> Option<Task<Result<Navigated>>> {
13901 let selection = self.selections.newest::<usize>(cx);
13902 let multi_buffer = self.buffer.read(cx);
13903 let head = selection.head();
13904
13905 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13906 let head_anchor = multi_buffer_snapshot.anchor_at(
13907 head,
13908 if head < selection.tail() {
13909 Bias::Right
13910 } else {
13911 Bias::Left
13912 },
13913 );
13914
13915 match self
13916 .find_all_references_task_sources
13917 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13918 {
13919 Ok(_) => {
13920 log::info!(
13921 "Ignoring repeated FindAllReferences invocation with the position of already running task"
13922 );
13923 return None;
13924 }
13925 Err(i) => {
13926 self.find_all_references_task_sources.insert(i, head_anchor);
13927 }
13928 }
13929
13930 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
13931 let workspace = self.workspace()?;
13932 let project = workspace.read(cx).project().clone();
13933 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
13934 Some(cx.spawn_in(window, async move |editor, cx| {
13935 let _cleanup = cx.on_drop(&editor, move |editor, _| {
13936 if let Ok(i) = editor
13937 .find_all_references_task_sources
13938 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
13939 {
13940 editor.find_all_references_task_sources.remove(i);
13941 }
13942 });
13943
13944 let locations = references.await?;
13945 if locations.is_empty() {
13946 return anyhow::Ok(Navigated::No);
13947 }
13948
13949 workspace.update_in(cx, |workspace, window, cx| {
13950 let title = locations
13951 .first()
13952 .as_ref()
13953 .map(|location| {
13954 let buffer = location.buffer.read(cx);
13955 format!(
13956 "References to `{}`",
13957 buffer
13958 .text_for_range(location.range.clone())
13959 .collect::<String>()
13960 )
13961 })
13962 .unwrap();
13963 Self::open_locations_in_multibuffer(
13964 workspace,
13965 locations,
13966 title,
13967 false,
13968 MultibufferSelectionMode::First,
13969 window,
13970 cx,
13971 );
13972 Navigated::Yes
13973 })
13974 }))
13975 }
13976
13977 /// Opens a multibuffer with the given project locations in it
13978 pub fn open_locations_in_multibuffer(
13979 workspace: &mut Workspace,
13980 mut locations: Vec<Location>,
13981 title: String,
13982 split: bool,
13983 multibuffer_selection_mode: MultibufferSelectionMode,
13984 window: &mut Window,
13985 cx: &mut Context<Workspace>,
13986 ) {
13987 // If there are multiple definitions, open them in a multibuffer
13988 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
13989 let mut locations = locations.into_iter().peekable();
13990 let mut ranges: Vec<Range<Anchor>> = Vec::new();
13991 let capability = workspace.project().read(cx).capability();
13992
13993 let excerpt_buffer = cx.new(|cx| {
13994 let mut multibuffer = MultiBuffer::new(capability);
13995 while let Some(location) = locations.next() {
13996 let buffer = location.buffer.read(cx);
13997 let mut ranges_for_buffer = Vec::new();
13998 let range = location.range.to_point(buffer);
13999 ranges_for_buffer.push(range.clone());
14000
14001 while let Some(next_location) = locations.peek() {
14002 if next_location.buffer == location.buffer {
14003 ranges_for_buffer.push(next_location.range.to_point(buffer));
14004 locations.next();
14005 } else {
14006 break;
14007 }
14008 }
14009
14010 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
14011 let (new_ranges, _) = multibuffer.set_excerpts_for_path(
14012 PathKey::for_buffer(&location.buffer, cx),
14013 location.buffer.clone(),
14014 ranges_for_buffer,
14015 DEFAULT_MULTIBUFFER_CONTEXT,
14016 cx,
14017 );
14018 ranges.extend(new_ranges)
14019 }
14020
14021 multibuffer.with_title(title)
14022 });
14023
14024 let editor = cx.new(|cx| {
14025 Editor::for_multibuffer(
14026 excerpt_buffer,
14027 Some(workspace.project().clone()),
14028 window,
14029 cx,
14030 )
14031 });
14032 editor.update(cx, |editor, cx| {
14033 match multibuffer_selection_mode {
14034 MultibufferSelectionMode::First => {
14035 if let Some(first_range) = ranges.first() {
14036 editor.change_selections(None, window, cx, |selections| {
14037 selections.clear_disjoint();
14038 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
14039 });
14040 }
14041 editor.highlight_background::<Self>(
14042 &ranges,
14043 |theme| theme.editor_highlighted_line_background,
14044 cx,
14045 );
14046 }
14047 MultibufferSelectionMode::All => {
14048 editor.change_selections(None, window, cx, |selections| {
14049 selections.clear_disjoint();
14050 selections.select_anchor_ranges(ranges);
14051 });
14052 }
14053 }
14054 editor.register_buffers_with_language_servers(cx);
14055 });
14056
14057 let item = Box::new(editor);
14058 let item_id = item.item_id();
14059
14060 if split {
14061 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
14062 } else {
14063 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
14064 let (preview_item_id, preview_item_idx) =
14065 workspace.active_pane().update(cx, |pane, _| {
14066 (pane.preview_item_id(), pane.preview_item_idx())
14067 });
14068
14069 workspace.add_item_to_active_pane(item.clone(), preview_item_idx, true, window, cx);
14070
14071 if let Some(preview_item_id) = preview_item_id {
14072 workspace.active_pane().update(cx, |pane, cx| {
14073 pane.remove_item(preview_item_id, false, false, window, cx);
14074 });
14075 }
14076 } else {
14077 workspace.add_item_to_active_pane(item.clone(), None, true, window, cx);
14078 }
14079 }
14080 workspace.active_pane().update(cx, |pane, cx| {
14081 pane.set_preview_item_id(Some(item_id), cx);
14082 });
14083 }
14084
14085 pub fn rename(
14086 &mut self,
14087 _: &Rename,
14088 window: &mut Window,
14089 cx: &mut Context<Self>,
14090 ) -> Option<Task<Result<()>>> {
14091 use language::ToOffset as _;
14092
14093 let provider = self.semantics_provider.clone()?;
14094 let selection = self.selections.newest_anchor().clone();
14095 let (cursor_buffer, cursor_buffer_position) = self
14096 .buffer
14097 .read(cx)
14098 .text_anchor_for_position(selection.head(), cx)?;
14099 let (tail_buffer, cursor_buffer_position_end) = self
14100 .buffer
14101 .read(cx)
14102 .text_anchor_for_position(selection.tail(), cx)?;
14103 if tail_buffer != cursor_buffer {
14104 return None;
14105 }
14106
14107 let snapshot = cursor_buffer.read(cx).snapshot();
14108 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
14109 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
14110 let prepare_rename = provider
14111 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
14112 .unwrap_or_else(|| Task::ready(Ok(None)));
14113 drop(snapshot);
14114
14115 Some(cx.spawn_in(window, async move |this, cx| {
14116 let rename_range = if let Some(range) = prepare_rename.await? {
14117 Some(range)
14118 } else {
14119 this.update(cx, |this, cx| {
14120 let buffer = this.buffer.read(cx).snapshot(cx);
14121 let mut buffer_highlights = this
14122 .document_highlights_for_position(selection.head(), &buffer)
14123 .filter(|highlight| {
14124 highlight.start.excerpt_id == selection.head().excerpt_id
14125 && highlight.end.excerpt_id == selection.head().excerpt_id
14126 });
14127 buffer_highlights
14128 .next()
14129 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
14130 })?
14131 };
14132 if let Some(rename_range) = rename_range {
14133 this.update_in(cx, |this, window, cx| {
14134 let snapshot = cursor_buffer.read(cx).snapshot();
14135 let rename_buffer_range = rename_range.to_offset(&snapshot);
14136 let cursor_offset_in_rename_range =
14137 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
14138 let cursor_offset_in_rename_range_end =
14139 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
14140
14141 this.take_rename(false, window, cx);
14142 let buffer = this.buffer.read(cx).read(cx);
14143 let cursor_offset = selection.head().to_offset(&buffer);
14144 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
14145 let rename_end = rename_start + rename_buffer_range.len();
14146 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
14147 let mut old_highlight_id = None;
14148 let old_name: Arc<str> = buffer
14149 .chunks(rename_start..rename_end, true)
14150 .map(|chunk| {
14151 if old_highlight_id.is_none() {
14152 old_highlight_id = chunk.syntax_highlight_id;
14153 }
14154 chunk.text
14155 })
14156 .collect::<String>()
14157 .into();
14158
14159 drop(buffer);
14160
14161 // Position the selection in the rename editor so that it matches the current selection.
14162 this.show_local_selections = false;
14163 let rename_editor = cx.new(|cx| {
14164 let mut editor = Editor::single_line(window, cx);
14165 editor.buffer.update(cx, |buffer, cx| {
14166 buffer.edit([(0..0, old_name.clone())], None, cx)
14167 });
14168 let rename_selection_range = match cursor_offset_in_rename_range
14169 .cmp(&cursor_offset_in_rename_range_end)
14170 {
14171 Ordering::Equal => {
14172 editor.select_all(&SelectAll, window, cx);
14173 return editor;
14174 }
14175 Ordering::Less => {
14176 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
14177 }
14178 Ordering::Greater => {
14179 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
14180 }
14181 };
14182 if rename_selection_range.end > old_name.len() {
14183 editor.select_all(&SelectAll, window, cx);
14184 } else {
14185 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
14186 s.select_ranges([rename_selection_range]);
14187 });
14188 }
14189 editor
14190 });
14191 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
14192 if e == &EditorEvent::Focused {
14193 cx.emit(EditorEvent::FocusedIn)
14194 }
14195 })
14196 .detach();
14197
14198 let write_highlights =
14199 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
14200 let read_highlights =
14201 this.clear_background_highlights::<DocumentHighlightRead>(cx);
14202 let ranges = write_highlights
14203 .iter()
14204 .flat_map(|(_, ranges)| ranges.iter())
14205 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
14206 .cloned()
14207 .collect();
14208
14209 this.highlight_text::<Rename>(
14210 ranges,
14211 HighlightStyle {
14212 fade_out: Some(0.6),
14213 ..Default::default()
14214 },
14215 cx,
14216 );
14217 let rename_focus_handle = rename_editor.focus_handle(cx);
14218 window.focus(&rename_focus_handle);
14219 let block_id = this.insert_blocks(
14220 [BlockProperties {
14221 style: BlockStyle::Flex,
14222 placement: BlockPlacement::Below(range.start),
14223 height: Some(1),
14224 render: Arc::new({
14225 let rename_editor = rename_editor.clone();
14226 move |cx: &mut BlockContext| {
14227 let mut text_style = cx.editor_style.text.clone();
14228 if let Some(highlight_style) = old_highlight_id
14229 .and_then(|h| h.style(&cx.editor_style.syntax))
14230 {
14231 text_style = text_style.highlight(highlight_style);
14232 }
14233 div()
14234 .block_mouse_down()
14235 .pl(cx.anchor_x)
14236 .child(EditorElement::new(
14237 &rename_editor,
14238 EditorStyle {
14239 background: cx.theme().system().transparent,
14240 local_player: cx.editor_style.local_player,
14241 text: text_style,
14242 scrollbar_width: cx.editor_style.scrollbar_width,
14243 syntax: cx.editor_style.syntax.clone(),
14244 status: cx.editor_style.status.clone(),
14245 inlay_hints_style: HighlightStyle {
14246 font_weight: Some(FontWeight::BOLD),
14247 ..make_inlay_hints_style(cx.app)
14248 },
14249 inline_completion_styles: make_suggestion_styles(
14250 cx.app,
14251 ),
14252 ..EditorStyle::default()
14253 },
14254 ))
14255 .into_any_element()
14256 }
14257 }),
14258 priority: 0,
14259 }],
14260 Some(Autoscroll::fit()),
14261 cx,
14262 )[0];
14263 this.pending_rename = Some(RenameState {
14264 range,
14265 old_name,
14266 editor: rename_editor,
14267 block_id,
14268 });
14269 })?;
14270 }
14271
14272 Ok(())
14273 }))
14274 }
14275
14276 pub fn confirm_rename(
14277 &mut self,
14278 _: &ConfirmRename,
14279 window: &mut Window,
14280 cx: &mut Context<Self>,
14281 ) -> Option<Task<Result<()>>> {
14282 let rename = self.take_rename(false, window, cx)?;
14283 let workspace = self.workspace()?.downgrade();
14284 let (buffer, start) = self
14285 .buffer
14286 .read(cx)
14287 .text_anchor_for_position(rename.range.start, cx)?;
14288 let (end_buffer, _) = self
14289 .buffer
14290 .read(cx)
14291 .text_anchor_for_position(rename.range.end, cx)?;
14292 if buffer != end_buffer {
14293 return None;
14294 }
14295
14296 let old_name = rename.old_name;
14297 let new_name = rename.editor.read(cx).text(cx);
14298
14299 let rename = self.semantics_provider.as_ref()?.perform_rename(
14300 &buffer,
14301 start,
14302 new_name.clone(),
14303 cx,
14304 )?;
14305
14306 Some(cx.spawn_in(window, async move |editor, cx| {
14307 let project_transaction = rename.await?;
14308 Self::open_project_transaction(
14309 &editor,
14310 workspace,
14311 project_transaction,
14312 format!("Rename: {} → {}", old_name, new_name),
14313 cx,
14314 )
14315 .await?;
14316
14317 editor.update(cx, |editor, cx| {
14318 editor.refresh_document_highlights(cx);
14319 })?;
14320 Ok(())
14321 }))
14322 }
14323
14324 fn take_rename(
14325 &mut self,
14326 moving_cursor: bool,
14327 window: &mut Window,
14328 cx: &mut Context<Self>,
14329 ) -> Option<RenameState> {
14330 let rename = self.pending_rename.take()?;
14331 if rename.editor.focus_handle(cx).is_focused(window) {
14332 window.focus(&self.focus_handle);
14333 }
14334
14335 self.remove_blocks(
14336 [rename.block_id].into_iter().collect(),
14337 Some(Autoscroll::fit()),
14338 cx,
14339 );
14340 self.clear_highlights::<Rename>(cx);
14341 self.show_local_selections = true;
14342
14343 if moving_cursor {
14344 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
14345 editor.selections.newest::<usize>(cx).head()
14346 });
14347
14348 // Update the selection to match the position of the selection inside
14349 // the rename editor.
14350 let snapshot = self.buffer.read(cx).read(cx);
14351 let rename_range = rename.range.to_offset(&snapshot);
14352 let cursor_in_editor = snapshot
14353 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
14354 .min(rename_range.end);
14355 drop(snapshot);
14356
14357 self.change_selections(None, window, cx, |s| {
14358 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
14359 });
14360 } else {
14361 self.refresh_document_highlights(cx);
14362 }
14363
14364 Some(rename)
14365 }
14366
14367 pub fn pending_rename(&self) -> Option<&RenameState> {
14368 self.pending_rename.as_ref()
14369 }
14370
14371 fn format(
14372 &mut self,
14373 _: &Format,
14374 window: &mut Window,
14375 cx: &mut Context<Self>,
14376 ) -> Option<Task<Result<()>>> {
14377 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14378
14379 let project = match &self.project {
14380 Some(project) => project.clone(),
14381 None => return None,
14382 };
14383
14384 Some(self.perform_format(
14385 project,
14386 FormatTrigger::Manual,
14387 FormatTarget::Buffers,
14388 window,
14389 cx,
14390 ))
14391 }
14392
14393 fn format_selections(
14394 &mut self,
14395 _: &FormatSelections,
14396 window: &mut Window,
14397 cx: &mut Context<Self>,
14398 ) -> Option<Task<Result<()>>> {
14399 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14400
14401 let project = match &self.project {
14402 Some(project) => project.clone(),
14403 None => return None,
14404 };
14405
14406 let ranges = self
14407 .selections
14408 .all_adjusted(cx)
14409 .into_iter()
14410 .map(|selection| selection.range())
14411 .collect_vec();
14412
14413 Some(self.perform_format(
14414 project,
14415 FormatTrigger::Manual,
14416 FormatTarget::Ranges(ranges),
14417 window,
14418 cx,
14419 ))
14420 }
14421
14422 fn perform_format(
14423 &mut self,
14424 project: Entity<Project>,
14425 trigger: FormatTrigger,
14426 target: FormatTarget,
14427 window: &mut Window,
14428 cx: &mut Context<Self>,
14429 ) -> Task<Result<()>> {
14430 let buffer = self.buffer.clone();
14431 let (buffers, target) = match target {
14432 FormatTarget::Buffers => {
14433 let mut buffers = buffer.read(cx).all_buffers();
14434 if trigger == FormatTrigger::Save {
14435 buffers.retain(|buffer| buffer.read(cx).is_dirty());
14436 }
14437 (buffers, LspFormatTarget::Buffers)
14438 }
14439 FormatTarget::Ranges(selection_ranges) => {
14440 let multi_buffer = buffer.read(cx);
14441 let snapshot = multi_buffer.read(cx);
14442 let mut buffers = HashSet::default();
14443 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
14444 BTreeMap::new();
14445 for selection_range in selection_ranges {
14446 for (buffer, buffer_range, _) in
14447 snapshot.range_to_buffer_ranges(selection_range)
14448 {
14449 let buffer_id = buffer.remote_id();
14450 let start = buffer.anchor_before(buffer_range.start);
14451 let end = buffer.anchor_after(buffer_range.end);
14452 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
14453 buffer_id_to_ranges
14454 .entry(buffer_id)
14455 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
14456 .or_insert_with(|| vec![start..end]);
14457 }
14458 }
14459 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
14460 }
14461 };
14462
14463 let transaction_id_prev = buffer.read_with(cx, |b, cx| b.last_transaction_id(cx));
14464 let selections_prev = transaction_id_prev
14465 .and_then(|transaction_id_prev| {
14466 // default to selections as they were after the last edit, if we have them,
14467 // instead of how they are now.
14468 // This will make it so that editing, moving somewhere else, formatting, then undoing the format
14469 // will take you back to where you made the last edit, instead of staying where you scrolled
14470 self.selection_history
14471 .transaction(transaction_id_prev)
14472 .map(|t| t.0.clone())
14473 })
14474 .unwrap_or_else(|| {
14475 log::info!("Failed to determine selections from before format. Falling back to selections when format was initiated");
14476 self.selections.disjoint_anchors()
14477 });
14478
14479 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
14480 let format = project.update(cx, |project, cx| {
14481 project.format(buffers, target, true, trigger, cx)
14482 });
14483
14484 cx.spawn_in(window, async move |editor, cx| {
14485 let transaction = futures::select_biased! {
14486 transaction = format.log_err().fuse() => transaction,
14487 () = timeout => {
14488 log::warn!("timed out waiting for formatting");
14489 None
14490 }
14491 };
14492
14493 buffer
14494 .update(cx, |buffer, cx| {
14495 if let Some(transaction) = transaction {
14496 if !buffer.is_singleton() {
14497 buffer.push_transaction(&transaction.0, cx);
14498 }
14499 }
14500 cx.notify();
14501 })
14502 .ok();
14503
14504 if let Some(transaction_id_now) =
14505 buffer.read_with(cx, |b, cx| b.last_transaction_id(cx))?
14506 {
14507 let has_new_transaction = transaction_id_prev != Some(transaction_id_now);
14508 if has_new_transaction {
14509 _ = editor.update(cx, |editor, _| {
14510 editor
14511 .selection_history
14512 .insert_transaction(transaction_id_now, selections_prev);
14513 });
14514 }
14515 }
14516
14517 Ok(())
14518 })
14519 }
14520
14521 fn organize_imports(
14522 &mut self,
14523 _: &OrganizeImports,
14524 window: &mut Window,
14525 cx: &mut Context<Self>,
14526 ) -> Option<Task<Result<()>>> {
14527 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
14528 let project = match &self.project {
14529 Some(project) => project.clone(),
14530 None => return None,
14531 };
14532 Some(self.perform_code_action_kind(
14533 project,
14534 CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
14535 window,
14536 cx,
14537 ))
14538 }
14539
14540 fn perform_code_action_kind(
14541 &mut self,
14542 project: Entity<Project>,
14543 kind: CodeActionKind,
14544 window: &mut Window,
14545 cx: &mut Context<Self>,
14546 ) -> Task<Result<()>> {
14547 let buffer = self.buffer.clone();
14548 let buffers = buffer.read(cx).all_buffers();
14549 let mut timeout = cx.background_executor().timer(CODE_ACTION_TIMEOUT).fuse();
14550 let apply_action = project.update(cx, |project, cx| {
14551 project.apply_code_action_kind(buffers, kind, true, cx)
14552 });
14553 cx.spawn_in(window, async move |_, cx| {
14554 let transaction = futures::select_biased! {
14555 () = timeout => {
14556 log::warn!("timed out waiting for executing code action");
14557 None
14558 }
14559 transaction = apply_action.log_err().fuse() => transaction,
14560 };
14561 buffer
14562 .update(cx, |buffer, cx| {
14563 // check if we need this
14564 if let Some(transaction) = transaction {
14565 if !buffer.is_singleton() {
14566 buffer.push_transaction(&transaction.0, cx);
14567 }
14568 }
14569 cx.notify();
14570 })
14571 .ok();
14572 Ok(())
14573 })
14574 }
14575
14576 fn restart_language_server(
14577 &mut self,
14578 _: &RestartLanguageServer,
14579 _: &mut Window,
14580 cx: &mut Context<Self>,
14581 ) {
14582 if let Some(project) = self.project.clone() {
14583 self.buffer.update(cx, |multi_buffer, cx| {
14584 project.update(cx, |project, cx| {
14585 project.restart_language_servers_for_buffers(
14586 multi_buffer.all_buffers().into_iter().collect(),
14587 cx,
14588 );
14589 });
14590 })
14591 }
14592 }
14593
14594 fn stop_language_server(
14595 &mut self,
14596 _: &StopLanguageServer,
14597 _: &mut Window,
14598 cx: &mut Context<Self>,
14599 ) {
14600 if let Some(project) = self.project.clone() {
14601 self.buffer.update(cx, |multi_buffer, cx| {
14602 project.update(cx, |project, cx| {
14603 project.stop_language_servers_for_buffers(
14604 multi_buffer.all_buffers().into_iter().collect(),
14605 cx,
14606 );
14607 cx.emit(project::Event::RefreshInlayHints);
14608 });
14609 });
14610 }
14611 }
14612
14613 fn cancel_language_server_work(
14614 workspace: &mut Workspace,
14615 _: &actions::CancelLanguageServerWork,
14616 _: &mut Window,
14617 cx: &mut Context<Workspace>,
14618 ) {
14619 let project = workspace.project();
14620 let buffers = workspace
14621 .active_item(cx)
14622 .and_then(|item| item.act_as::<Editor>(cx))
14623 .map_or(HashSet::default(), |editor| {
14624 editor.read(cx).buffer.read(cx).all_buffers()
14625 });
14626 project.update(cx, |project, cx| {
14627 project.cancel_language_server_work_for_buffers(buffers, cx);
14628 });
14629 }
14630
14631 fn show_character_palette(
14632 &mut self,
14633 _: &ShowCharacterPalette,
14634 window: &mut Window,
14635 _: &mut Context<Self>,
14636 ) {
14637 window.show_character_palette();
14638 }
14639
14640 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
14641 if let ActiveDiagnostic::Group(active_diagnostics) = &mut self.active_diagnostics {
14642 let buffer = self.buffer.read(cx).snapshot(cx);
14643 let primary_range_start = active_diagnostics.active_range.start.to_offset(&buffer);
14644 let primary_range_end = active_diagnostics.active_range.end.to_offset(&buffer);
14645 let is_valid = buffer
14646 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
14647 .any(|entry| {
14648 entry.diagnostic.is_primary
14649 && !entry.range.is_empty()
14650 && entry.range.start == primary_range_start
14651 && entry.diagnostic.message == active_diagnostics.active_message
14652 });
14653
14654 if !is_valid {
14655 self.dismiss_diagnostics(cx);
14656 }
14657 }
14658 }
14659
14660 pub fn active_diagnostic_group(&self) -> Option<&ActiveDiagnosticGroup> {
14661 match &self.active_diagnostics {
14662 ActiveDiagnostic::Group(group) => Some(group),
14663 _ => None,
14664 }
14665 }
14666
14667 pub fn set_all_diagnostics_active(&mut self, cx: &mut Context<Self>) {
14668 self.dismiss_diagnostics(cx);
14669 self.active_diagnostics = ActiveDiagnostic::All;
14670 }
14671
14672 fn activate_diagnostics(
14673 &mut self,
14674 buffer_id: BufferId,
14675 diagnostic: DiagnosticEntry<usize>,
14676 window: &mut Window,
14677 cx: &mut Context<Self>,
14678 ) {
14679 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14680 return;
14681 }
14682 self.dismiss_diagnostics(cx);
14683 let snapshot = self.snapshot(window, cx);
14684 let Some(diagnostic_renderer) = cx
14685 .try_global::<GlobalDiagnosticRenderer>()
14686 .map(|g| g.0.clone())
14687 else {
14688 return;
14689 };
14690 let buffer = self.buffer.read(cx).snapshot(cx);
14691
14692 let diagnostic_group = buffer
14693 .diagnostic_group(buffer_id, diagnostic.diagnostic.group_id)
14694 .collect::<Vec<_>>();
14695
14696 let blocks = diagnostic_renderer.render_group(
14697 diagnostic_group,
14698 buffer_id,
14699 snapshot,
14700 cx.weak_entity(),
14701 cx,
14702 );
14703
14704 let blocks = self.display_map.update(cx, |display_map, cx| {
14705 display_map.insert_blocks(blocks, cx).into_iter().collect()
14706 });
14707 self.active_diagnostics = ActiveDiagnostic::Group(ActiveDiagnosticGroup {
14708 active_range: buffer.anchor_before(diagnostic.range.start)
14709 ..buffer.anchor_after(diagnostic.range.end),
14710 active_message: diagnostic.diagnostic.message.clone(),
14711 group_id: diagnostic.diagnostic.group_id,
14712 blocks,
14713 });
14714 cx.notify();
14715 }
14716
14717 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
14718 if matches!(self.active_diagnostics, ActiveDiagnostic::All) {
14719 return;
14720 };
14721
14722 let prev = mem::replace(&mut self.active_diagnostics, ActiveDiagnostic::None);
14723 if let ActiveDiagnostic::Group(group) = prev {
14724 self.display_map.update(cx, |display_map, cx| {
14725 display_map.remove_blocks(group.blocks, cx);
14726 });
14727 cx.notify();
14728 }
14729 }
14730
14731 /// Disable inline diagnostics rendering for this editor.
14732 pub fn disable_inline_diagnostics(&mut self) {
14733 self.inline_diagnostics_enabled = false;
14734 self.inline_diagnostics_update = Task::ready(());
14735 self.inline_diagnostics.clear();
14736 }
14737
14738 pub fn inline_diagnostics_enabled(&self) -> bool {
14739 self.inline_diagnostics_enabled
14740 }
14741
14742 pub fn show_inline_diagnostics(&self) -> bool {
14743 self.show_inline_diagnostics
14744 }
14745
14746 pub fn toggle_inline_diagnostics(
14747 &mut self,
14748 _: &ToggleInlineDiagnostics,
14749 window: &mut Window,
14750 cx: &mut Context<Editor>,
14751 ) {
14752 self.show_inline_diagnostics = !self.show_inline_diagnostics;
14753 self.refresh_inline_diagnostics(false, window, cx);
14754 }
14755
14756 fn refresh_inline_diagnostics(
14757 &mut self,
14758 debounce: bool,
14759 window: &mut Window,
14760 cx: &mut Context<Self>,
14761 ) {
14762 if !self.inline_diagnostics_enabled || !self.show_inline_diagnostics {
14763 self.inline_diagnostics_update = Task::ready(());
14764 self.inline_diagnostics.clear();
14765 return;
14766 }
14767
14768 let debounce_ms = ProjectSettings::get_global(cx)
14769 .diagnostics
14770 .inline
14771 .update_debounce_ms;
14772 let debounce = if debounce && debounce_ms > 0 {
14773 Some(Duration::from_millis(debounce_ms))
14774 } else {
14775 None
14776 };
14777 self.inline_diagnostics_update = cx.spawn_in(window, async move |editor, cx| {
14778 let editor = editor.upgrade().unwrap();
14779
14780 if let Some(debounce) = debounce {
14781 cx.background_executor().timer(debounce).await;
14782 }
14783 let Some(snapshot) = editor
14784 .update(cx, |editor, cx| editor.buffer().read(cx).snapshot(cx))
14785 .ok()
14786 else {
14787 return;
14788 };
14789
14790 let new_inline_diagnostics = cx
14791 .background_spawn(async move {
14792 let mut inline_diagnostics = Vec::<(Anchor, InlineDiagnostic)>::new();
14793 for diagnostic_entry in snapshot.diagnostics_in_range(0..snapshot.len()) {
14794 let message = diagnostic_entry
14795 .diagnostic
14796 .message
14797 .split_once('\n')
14798 .map(|(line, _)| line)
14799 .map(SharedString::new)
14800 .unwrap_or_else(|| {
14801 SharedString::from(diagnostic_entry.diagnostic.message)
14802 });
14803 let start_anchor = snapshot.anchor_before(diagnostic_entry.range.start);
14804 let (Ok(i) | Err(i)) = inline_diagnostics
14805 .binary_search_by(|(probe, _)| probe.cmp(&start_anchor, &snapshot));
14806 inline_diagnostics.insert(
14807 i,
14808 (
14809 start_anchor,
14810 InlineDiagnostic {
14811 message,
14812 group_id: diagnostic_entry.diagnostic.group_id,
14813 start: diagnostic_entry.range.start.to_point(&snapshot),
14814 is_primary: diagnostic_entry.diagnostic.is_primary,
14815 severity: diagnostic_entry.diagnostic.severity,
14816 },
14817 ),
14818 );
14819 }
14820 inline_diagnostics
14821 })
14822 .await;
14823
14824 editor
14825 .update(cx, |editor, cx| {
14826 editor.inline_diagnostics = new_inline_diagnostics;
14827 cx.notify();
14828 })
14829 .ok();
14830 });
14831 }
14832
14833 pub fn set_selections_from_remote(
14834 &mut self,
14835 selections: Vec<Selection<Anchor>>,
14836 pending_selection: Option<Selection<Anchor>>,
14837 window: &mut Window,
14838 cx: &mut Context<Self>,
14839 ) {
14840 let old_cursor_position = self.selections.newest_anchor().head();
14841 self.selections.change_with(cx, |s| {
14842 s.select_anchors(selections);
14843 if let Some(pending_selection) = pending_selection {
14844 s.set_pending(pending_selection, SelectMode::Character);
14845 } else {
14846 s.clear_pending();
14847 }
14848 });
14849 self.selections_did_change(false, &old_cursor_position, true, window, cx);
14850 }
14851
14852 fn push_to_selection_history(&mut self) {
14853 self.selection_history.push(SelectionHistoryEntry {
14854 selections: self.selections.disjoint_anchors(),
14855 select_next_state: self.select_next_state.clone(),
14856 select_prev_state: self.select_prev_state.clone(),
14857 add_selections_state: self.add_selections_state.clone(),
14858 });
14859 }
14860
14861 pub fn transact(
14862 &mut self,
14863 window: &mut Window,
14864 cx: &mut Context<Self>,
14865 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
14866 ) -> Option<TransactionId> {
14867 self.start_transaction_at(Instant::now(), window, cx);
14868 update(self, window, cx);
14869 self.end_transaction_at(Instant::now(), cx)
14870 }
14871
14872 pub fn start_transaction_at(
14873 &mut self,
14874 now: Instant,
14875 window: &mut Window,
14876 cx: &mut Context<Self>,
14877 ) {
14878 self.end_selection(window, cx);
14879 if let Some(tx_id) = self
14880 .buffer
14881 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
14882 {
14883 self.selection_history
14884 .insert_transaction(tx_id, self.selections.disjoint_anchors());
14885 cx.emit(EditorEvent::TransactionBegun {
14886 transaction_id: tx_id,
14887 })
14888 }
14889 }
14890
14891 pub fn end_transaction_at(
14892 &mut self,
14893 now: Instant,
14894 cx: &mut Context<Self>,
14895 ) -> Option<TransactionId> {
14896 if let Some(transaction_id) = self
14897 .buffer
14898 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
14899 {
14900 if let Some((_, end_selections)) =
14901 self.selection_history.transaction_mut(transaction_id)
14902 {
14903 *end_selections = Some(self.selections.disjoint_anchors());
14904 } else {
14905 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
14906 }
14907
14908 cx.emit(EditorEvent::Edited { transaction_id });
14909 Some(transaction_id)
14910 } else {
14911 None
14912 }
14913 }
14914
14915 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
14916 if self.selection_mark_mode {
14917 self.change_selections(None, window, cx, |s| {
14918 s.move_with(|_, sel| {
14919 sel.collapse_to(sel.head(), SelectionGoal::None);
14920 });
14921 })
14922 }
14923 self.selection_mark_mode = true;
14924 cx.notify();
14925 }
14926
14927 pub fn swap_selection_ends(
14928 &mut self,
14929 _: &actions::SwapSelectionEnds,
14930 window: &mut Window,
14931 cx: &mut Context<Self>,
14932 ) {
14933 self.change_selections(None, window, cx, |s| {
14934 s.move_with(|_, sel| {
14935 if sel.start != sel.end {
14936 sel.reversed = !sel.reversed
14937 }
14938 });
14939 });
14940 self.request_autoscroll(Autoscroll::newest(), cx);
14941 cx.notify();
14942 }
14943
14944 pub fn toggle_fold(
14945 &mut self,
14946 _: &actions::ToggleFold,
14947 window: &mut Window,
14948 cx: &mut Context<Self>,
14949 ) {
14950 if self.is_singleton(cx) {
14951 let selection = self.selections.newest::<Point>(cx);
14952
14953 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14954 let range = if selection.is_empty() {
14955 let point = selection.head().to_display_point(&display_map);
14956 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
14957 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
14958 .to_point(&display_map);
14959 start..end
14960 } else {
14961 selection.range()
14962 };
14963 if display_map.folds_in_range(range).next().is_some() {
14964 self.unfold_lines(&Default::default(), window, cx)
14965 } else {
14966 self.fold(&Default::default(), window, cx)
14967 }
14968 } else {
14969 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14970 let buffer_ids: HashSet<_> = self
14971 .selections
14972 .disjoint_anchor_ranges()
14973 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
14974 .collect();
14975
14976 let should_unfold = buffer_ids
14977 .iter()
14978 .any(|buffer_id| self.is_buffer_folded(*buffer_id, cx));
14979
14980 for buffer_id in buffer_ids {
14981 if should_unfold {
14982 self.unfold_buffer(buffer_id, cx);
14983 } else {
14984 self.fold_buffer(buffer_id, cx);
14985 }
14986 }
14987 }
14988 }
14989
14990 pub fn toggle_fold_recursive(
14991 &mut self,
14992 _: &actions::ToggleFoldRecursive,
14993 window: &mut Window,
14994 cx: &mut Context<Self>,
14995 ) {
14996 let selection = self.selections.newest::<Point>(cx);
14997
14998 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
14999 let range = if selection.is_empty() {
15000 let point = selection.head().to_display_point(&display_map);
15001 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
15002 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
15003 .to_point(&display_map);
15004 start..end
15005 } else {
15006 selection.range()
15007 };
15008 if display_map.folds_in_range(range).next().is_some() {
15009 self.unfold_recursive(&Default::default(), window, cx)
15010 } else {
15011 self.fold_recursive(&Default::default(), window, cx)
15012 }
15013 }
15014
15015 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
15016 if self.is_singleton(cx) {
15017 let mut to_fold = Vec::new();
15018 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15019 let selections = self.selections.all_adjusted(cx);
15020
15021 for selection in selections {
15022 let range = selection.range().sorted();
15023 let buffer_start_row = range.start.row;
15024
15025 if range.start.row != range.end.row {
15026 let mut found = false;
15027 let mut row = range.start.row;
15028 while row <= range.end.row {
15029 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
15030 {
15031 found = true;
15032 row = crease.range().end.row + 1;
15033 to_fold.push(crease);
15034 } else {
15035 row += 1
15036 }
15037 }
15038 if found {
15039 continue;
15040 }
15041 }
15042
15043 for row in (0..=range.start.row).rev() {
15044 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15045 if crease.range().end.row >= buffer_start_row {
15046 to_fold.push(crease);
15047 if row <= range.start.row {
15048 break;
15049 }
15050 }
15051 }
15052 }
15053 }
15054
15055 self.fold_creases(to_fold, true, window, cx);
15056 } else {
15057 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15058 let buffer_ids = self
15059 .selections
15060 .disjoint_anchor_ranges()
15061 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15062 .collect::<HashSet<_>>();
15063 for buffer_id in buffer_ids {
15064 self.fold_buffer(buffer_id, cx);
15065 }
15066 }
15067 }
15068
15069 fn fold_at_level(
15070 &mut self,
15071 fold_at: &FoldAtLevel,
15072 window: &mut Window,
15073 cx: &mut Context<Self>,
15074 ) {
15075 if !self.buffer.read(cx).is_singleton() {
15076 return;
15077 }
15078
15079 let fold_at_level = fold_at.0;
15080 let snapshot = self.buffer.read(cx).snapshot(cx);
15081 let mut to_fold = Vec::new();
15082 let mut stack = vec![(0, snapshot.max_row().0, 1)];
15083
15084 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
15085 while start_row < end_row {
15086 match self
15087 .snapshot(window, cx)
15088 .crease_for_buffer_row(MultiBufferRow(start_row))
15089 {
15090 Some(crease) => {
15091 let nested_start_row = crease.range().start.row + 1;
15092 let nested_end_row = crease.range().end.row;
15093
15094 if current_level < fold_at_level {
15095 stack.push((nested_start_row, nested_end_row, current_level + 1));
15096 } else if current_level == fold_at_level {
15097 to_fold.push(crease);
15098 }
15099
15100 start_row = nested_end_row + 1;
15101 }
15102 None => start_row += 1,
15103 }
15104 }
15105 }
15106
15107 self.fold_creases(to_fold, true, window, cx);
15108 }
15109
15110 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
15111 if self.buffer.read(cx).is_singleton() {
15112 let mut fold_ranges = Vec::new();
15113 let snapshot = self.buffer.read(cx).snapshot(cx);
15114
15115 for row in 0..snapshot.max_row().0 {
15116 if let Some(foldable_range) = self
15117 .snapshot(window, cx)
15118 .crease_for_buffer_row(MultiBufferRow(row))
15119 {
15120 fold_ranges.push(foldable_range);
15121 }
15122 }
15123
15124 self.fold_creases(fold_ranges, true, window, cx);
15125 } else {
15126 self.toggle_fold_multiple_buffers = cx.spawn_in(window, async move |editor, cx| {
15127 editor
15128 .update_in(cx, |editor, _, cx| {
15129 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15130 editor.fold_buffer(buffer_id, cx);
15131 }
15132 })
15133 .ok();
15134 });
15135 }
15136 }
15137
15138 pub fn fold_function_bodies(
15139 &mut self,
15140 _: &actions::FoldFunctionBodies,
15141 window: &mut Window,
15142 cx: &mut Context<Self>,
15143 ) {
15144 let snapshot = self.buffer.read(cx).snapshot(cx);
15145
15146 let ranges = snapshot
15147 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
15148 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
15149 .collect::<Vec<_>>();
15150
15151 let creases = ranges
15152 .into_iter()
15153 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
15154 .collect();
15155
15156 self.fold_creases(creases, true, window, cx);
15157 }
15158
15159 pub fn fold_recursive(
15160 &mut self,
15161 _: &actions::FoldRecursive,
15162 window: &mut Window,
15163 cx: &mut Context<Self>,
15164 ) {
15165 let mut to_fold = Vec::new();
15166 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15167 let selections = self.selections.all_adjusted(cx);
15168
15169 for selection in selections {
15170 let range = selection.range().sorted();
15171 let buffer_start_row = range.start.row;
15172
15173 if range.start.row != range.end.row {
15174 let mut found = false;
15175 for row in range.start.row..=range.end.row {
15176 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15177 found = true;
15178 to_fold.push(crease);
15179 }
15180 }
15181 if found {
15182 continue;
15183 }
15184 }
15185
15186 for row in (0..=range.start.row).rev() {
15187 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
15188 if crease.range().end.row >= buffer_start_row {
15189 to_fold.push(crease);
15190 } else {
15191 break;
15192 }
15193 }
15194 }
15195 }
15196
15197 self.fold_creases(to_fold, true, window, cx);
15198 }
15199
15200 pub fn fold_at(
15201 &mut self,
15202 buffer_row: MultiBufferRow,
15203 window: &mut Window,
15204 cx: &mut Context<Self>,
15205 ) {
15206 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15207
15208 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
15209 let autoscroll = self
15210 .selections
15211 .all::<Point>(cx)
15212 .iter()
15213 .any(|selection| crease.range().overlaps(&selection.range()));
15214
15215 self.fold_creases(vec![crease], autoscroll, window, cx);
15216 }
15217 }
15218
15219 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
15220 if self.is_singleton(cx) {
15221 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15222 let buffer = &display_map.buffer_snapshot;
15223 let selections = self.selections.all::<Point>(cx);
15224 let ranges = selections
15225 .iter()
15226 .map(|s| {
15227 let range = s.display_range(&display_map).sorted();
15228 let mut start = range.start.to_point(&display_map);
15229 let mut end = range.end.to_point(&display_map);
15230 start.column = 0;
15231 end.column = buffer.line_len(MultiBufferRow(end.row));
15232 start..end
15233 })
15234 .collect::<Vec<_>>();
15235
15236 self.unfold_ranges(&ranges, true, true, cx);
15237 } else {
15238 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
15239 let buffer_ids = self
15240 .selections
15241 .disjoint_anchor_ranges()
15242 .flat_map(|range| multi_buffer_snapshot.buffer_ids_for_range(range))
15243 .collect::<HashSet<_>>();
15244 for buffer_id in buffer_ids {
15245 self.unfold_buffer(buffer_id, cx);
15246 }
15247 }
15248 }
15249
15250 pub fn unfold_recursive(
15251 &mut self,
15252 _: &UnfoldRecursive,
15253 _window: &mut Window,
15254 cx: &mut Context<Self>,
15255 ) {
15256 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15257 let selections = self.selections.all::<Point>(cx);
15258 let ranges = selections
15259 .iter()
15260 .map(|s| {
15261 let mut range = s.display_range(&display_map).sorted();
15262 *range.start.column_mut() = 0;
15263 *range.end.column_mut() = display_map.line_len(range.end.row());
15264 let start = range.start.to_point(&display_map);
15265 let end = range.end.to_point(&display_map);
15266 start..end
15267 })
15268 .collect::<Vec<_>>();
15269
15270 self.unfold_ranges(&ranges, true, true, cx);
15271 }
15272
15273 pub fn unfold_at(
15274 &mut self,
15275 buffer_row: MultiBufferRow,
15276 _window: &mut Window,
15277 cx: &mut Context<Self>,
15278 ) {
15279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15280
15281 let intersection_range = Point::new(buffer_row.0, 0)
15282 ..Point::new(
15283 buffer_row.0,
15284 display_map.buffer_snapshot.line_len(buffer_row),
15285 );
15286
15287 let autoscroll = self
15288 .selections
15289 .all::<Point>(cx)
15290 .iter()
15291 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
15292
15293 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
15294 }
15295
15296 pub fn unfold_all(
15297 &mut self,
15298 _: &actions::UnfoldAll,
15299 _window: &mut Window,
15300 cx: &mut Context<Self>,
15301 ) {
15302 if self.buffer.read(cx).is_singleton() {
15303 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15304 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
15305 } else {
15306 self.toggle_fold_multiple_buffers = cx.spawn(async move |editor, cx| {
15307 editor
15308 .update(cx, |editor, cx| {
15309 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
15310 editor.unfold_buffer(buffer_id, cx);
15311 }
15312 })
15313 .ok();
15314 });
15315 }
15316 }
15317
15318 pub fn fold_selected_ranges(
15319 &mut self,
15320 _: &FoldSelectedRanges,
15321 window: &mut Window,
15322 cx: &mut Context<Self>,
15323 ) {
15324 let selections = self.selections.all_adjusted(cx);
15325 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15326 let ranges = selections
15327 .into_iter()
15328 .map(|s| Crease::simple(s.range(), display_map.fold_placeholder.clone()))
15329 .collect::<Vec<_>>();
15330 self.fold_creases(ranges, true, window, cx);
15331 }
15332
15333 pub fn fold_ranges<T: ToOffset + Clone>(
15334 &mut self,
15335 ranges: Vec<Range<T>>,
15336 auto_scroll: bool,
15337 window: &mut Window,
15338 cx: &mut Context<Self>,
15339 ) {
15340 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
15341 let ranges = ranges
15342 .into_iter()
15343 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
15344 .collect::<Vec<_>>();
15345 self.fold_creases(ranges, auto_scroll, window, cx);
15346 }
15347
15348 pub fn fold_creases<T: ToOffset + Clone>(
15349 &mut self,
15350 creases: Vec<Crease<T>>,
15351 auto_scroll: bool,
15352 _window: &mut Window,
15353 cx: &mut Context<Self>,
15354 ) {
15355 if creases.is_empty() {
15356 return;
15357 }
15358
15359 let mut buffers_affected = HashSet::default();
15360 let multi_buffer = self.buffer().read(cx);
15361 for crease in &creases {
15362 if let Some((_, buffer, _)) =
15363 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
15364 {
15365 buffers_affected.insert(buffer.read(cx).remote_id());
15366 };
15367 }
15368
15369 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
15370
15371 if auto_scroll {
15372 self.request_autoscroll(Autoscroll::fit(), cx);
15373 }
15374
15375 cx.notify();
15376
15377 self.scrollbar_marker_state.dirty = true;
15378 self.folds_did_change(cx);
15379 }
15380
15381 /// Removes any folds whose ranges intersect any of the given ranges.
15382 pub fn unfold_ranges<T: ToOffset + Clone>(
15383 &mut self,
15384 ranges: &[Range<T>],
15385 inclusive: bool,
15386 auto_scroll: bool,
15387 cx: &mut Context<Self>,
15388 ) {
15389 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15390 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
15391 });
15392 self.folds_did_change(cx);
15393 }
15394
15395 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15396 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
15397 return;
15398 }
15399 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15400 self.display_map.update(cx, |display_map, cx| {
15401 display_map.fold_buffers([buffer_id], cx)
15402 });
15403 cx.emit(EditorEvent::BufferFoldToggled {
15404 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
15405 folded: true,
15406 });
15407 cx.notify();
15408 }
15409
15410 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15411 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
15412 return;
15413 }
15414 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
15415 self.display_map.update(cx, |display_map, cx| {
15416 display_map.unfold_buffers([buffer_id], cx);
15417 });
15418 cx.emit(EditorEvent::BufferFoldToggled {
15419 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
15420 folded: false,
15421 });
15422 cx.notify();
15423 }
15424
15425 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
15426 self.display_map.read(cx).is_buffer_folded(buffer)
15427 }
15428
15429 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
15430 self.display_map.read(cx).folded_buffers()
15431 }
15432
15433 pub fn disable_header_for_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
15434 self.display_map.update(cx, |display_map, cx| {
15435 display_map.disable_header_for_buffer(buffer_id, cx);
15436 });
15437 cx.notify();
15438 }
15439
15440 /// Removes any folds with the given ranges.
15441 pub fn remove_folds_with_type<T: ToOffset + Clone>(
15442 &mut self,
15443 ranges: &[Range<T>],
15444 type_id: TypeId,
15445 auto_scroll: bool,
15446 cx: &mut Context<Self>,
15447 ) {
15448 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
15449 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
15450 });
15451 self.folds_did_change(cx);
15452 }
15453
15454 fn remove_folds_with<T: ToOffset + Clone>(
15455 &mut self,
15456 ranges: &[Range<T>],
15457 auto_scroll: bool,
15458 cx: &mut Context<Self>,
15459 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
15460 ) {
15461 if ranges.is_empty() {
15462 return;
15463 }
15464
15465 let mut buffers_affected = HashSet::default();
15466 let multi_buffer = self.buffer().read(cx);
15467 for range in ranges {
15468 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
15469 buffers_affected.insert(buffer.read(cx).remote_id());
15470 };
15471 }
15472
15473 self.display_map.update(cx, update);
15474
15475 if auto_scroll {
15476 self.request_autoscroll(Autoscroll::fit(), cx);
15477 }
15478
15479 cx.notify();
15480 self.scrollbar_marker_state.dirty = true;
15481 self.active_indent_guides_state.dirty = true;
15482 }
15483
15484 pub fn update_fold_widths(
15485 &mut self,
15486 widths: impl IntoIterator<Item = (FoldId, Pixels)>,
15487 cx: &mut Context<Self>,
15488 ) -> bool {
15489 self.display_map
15490 .update(cx, |map, cx| map.update_fold_widths(widths, cx))
15491 }
15492
15493 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
15494 self.display_map.read(cx).fold_placeholder.clone()
15495 }
15496
15497 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
15498 self.buffer.update(cx, |buffer, cx| {
15499 buffer.set_all_diff_hunks_expanded(cx);
15500 });
15501 }
15502
15503 pub fn expand_all_diff_hunks(
15504 &mut self,
15505 _: &ExpandAllDiffHunks,
15506 _window: &mut Window,
15507 cx: &mut Context<Self>,
15508 ) {
15509 self.buffer.update(cx, |buffer, cx| {
15510 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
15511 });
15512 }
15513
15514 pub fn toggle_selected_diff_hunks(
15515 &mut self,
15516 _: &ToggleSelectedDiffHunks,
15517 _window: &mut Window,
15518 cx: &mut Context<Self>,
15519 ) {
15520 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15521 self.toggle_diff_hunks_in_ranges(ranges, cx);
15522 }
15523
15524 pub fn diff_hunks_in_ranges<'a>(
15525 &'a self,
15526 ranges: &'a [Range<Anchor>],
15527 buffer: &'a MultiBufferSnapshot,
15528 ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
15529 ranges.iter().flat_map(move |range| {
15530 let end_excerpt_id = range.end.excerpt_id;
15531 let range = range.to_point(buffer);
15532 let mut peek_end = range.end;
15533 if range.end.row < buffer.max_row().0 {
15534 peek_end = Point::new(range.end.row + 1, 0);
15535 }
15536 buffer
15537 .diff_hunks_in_range(range.start..peek_end)
15538 .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
15539 })
15540 }
15541
15542 pub fn has_stageable_diff_hunks_in_ranges(
15543 &self,
15544 ranges: &[Range<Anchor>],
15545 snapshot: &MultiBufferSnapshot,
15546 ) -> bool {
15547 let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
15548 hunks.any(|hunk| hunk.status().has_secondary_hunk())
15549 }
15550
15551 pub fn toggle_staged_selected_diff_hunks(
15552 &mut self,
15553 _: &::git::ToggleStaged,
15554 _: &mut Window,
15555 cx: &mut Context<Self>,
15556 ) {
15557 let snapshot = self.buffer.read(cx).snapshot(cx);
15558 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15559 let stage = self.has_stageable_diff_hunks_in_ranges(&ranges, &snapshot);
15560 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15561 }
15562
15563 pub fn set_render_diff_hunk_controls(
15564 &mut self,
15565 render_diff_hunk_controls: RenderDiffHunkControlsFn,
15566 cx: &mut Context<Self>,
15567 ) {
15568 self.render_diff_hunk_controls = render_diff_hunk_controls;
15569 cx.notify();
15570 }
15571
15572 pub fn stage_and_next(
15573 &mut self,
15574 _: &::git::StageAndNext,
15575 window: &mut Window,
15576 cx: &mut Context<Self>,
15577 ) {
15578 self.do_stage_or_unstage_and_next(true, window, cx);
15579 }
15580
15581 pub fn unstage_and_next(
15582 &mut self,
15583 _: &::git::UnstageAndNext,
15584 window: &mut Window,
15585 cx: &mut Context<Self>,
15586 ) {
15587 self.do_stage_or_unstage_and_next(false, window, cx);
15588 }
15589
15590 pub fn stage_or_unstage_diff_hunks(
15591 &mut self,
15592 stage: bool,
15593 ranges: Vec<Range<Anchor>>,
15594 cx: &mut Context<Self>,
15595 ) {
15596 let task = self.save_buffers_for_ranges_if_needed(&ranges, cx);
15597 cx.spawn(async move |this, cx| {
15598 task.await?;
15599 this.update(cx, |this, cx| {
15600 let snapshot = this.buffer.read(cx).snapshot(cx);
15601 let chunk_by = this
15602 .diff_hunks_in_ranges(&ranges, &snapshot)
15603 .chunk_by(|hunk| hunk.buffer_id);
15604 for (buffer_id, hunks) in &chunk_by {
15605 this.do_stage_or_unstage(stage, buffer_id, hunks, cx);
15606 }
15607 })
15608 })
15609 .detach_and_log_err(cx);
15610 }
15611
15612 fn save_buffers_for_ranges_if_needed(
15613 &mut self,
15614 ranges: &[Range<Anchor>],
15615 cx: &mut Context<Editor>,
15616 ) -> Task<Result<()>> {
15617 let multibuffer = self.buffer.read(cx);
15618 let snapshot = multibuffer.read(cx);
15619 let buffer_ids: HashSet<_> = ranges
15620 .iter()
15621 .flat_map(|range| snapshot.buffer_ids_for_range(range.clone()))
15622 .collect();
15623 drop(snapshot);
15624
15625 let mut buffers = HashSet::default();
15626 for buffer_id in buffer_ids {
15627 if let Some(buffer_entity) = multibuffer.buffer(buffer_id) {
15628 let buffer = buffer_entity.read(cx);
15629 if buffer.file().is_some_and(|file| file.disk_state().exists()) && buffer.is_dirty()
15630 {
15631 buffers.insert(buffer_entity);
15632 }
15633 }
15634 }
15635
15636 if let Some(project) = &self.project {
15637 project.update(cx, |project, cx| project.save_buffers(buffers, cx))
15638 } else {
15639 Task::ready(Ok(()))
15640 }
15641 }
15642
15643 fn do_stage_or_unstage_and_next(
15644 &mut self,
15645 stage: bool,
15646 window: &mut Window,
15647 cx: &mut Context<Self>,
15648 ) {
15649 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
15650
15651 if ranges.iter().any(|range| range.start != range.end) {
15652 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15653 return;
15654 }
15655
15656 self.stage_or_unstage_diff_hunks(stage, ranges, cx);
15657 let snapshot = self.snapshot(window, cx);
15658 let position = self.selections.newest::<Point>(cx).head();
15659 let mut row = snapshot
15660 .buffer_snapshot
15661 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
15662 .find(|hunk| hunk.row_range.start.0 > position.row)
15663 .map(|hunk| hunk.row_range.start);
15664
15665 let all_diff_hunks_expanded = self.buffer().read(cx).all_diff_hunks_expanded();
15666 // Outside of the project diff editor, wrap around to the beginning.
15667 if !all_diff_hunks_expanded {
15668 row = row.or_else(|| {
15669 snapshot
15670 .buffer_snapshot
15671 .diff_hunks_in_range(Point::zero()..position)
15672 .find(|hunk| hunk.row_range.end.0 < position.row)
15673 .map(|hunk| hunk.row_range.start)
15674 });
15675 }
15676
15677 if let Some(row) = row {
15678 let destination = Point::new(row.0, 0);
15679 let autoscroll = Autoscroll::center();
15680
15681 self.unfold_ranges(&[destination..destination], false, false, cx);
15682 self.change_selections(Some(autoscroll), window, cx, |s| {
15683 s.select_ranges([destination..destination]);
15684 });
15685 }
15686 }
15687
15688 fn do_stage_or_unstage(
15689 &self,
15690 stage: bool,
15691 buffer_id: BufferId,
15692 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
15693 cx: &mut App,
15694 ) -> Option<()> {
15695 let project = self.project.as_ref()?;
15696 let buffer = project.read(cx).buffer_for_id(buffer_id, cx)?;
15697 let diff = self.buffer.read(cx).diff_for(buffer_id)?;
15698 let buffer_snapshot = buffer.read(cx).snapshot();
15699 let file_exists = buffer_snapshot
15700 .file()
15701 .is_some_and(|file| file.disk_state().exists());
15702 diff.update(cx, |diff, cx| {
15703 diff.stage_or_unstage_hunks(
15704 stage,
15705 &hunks
15706 .map(|hunk| buffer_diff::DiffHunk {
15707 buffer_range: hunk.buffer_range,
15708 diff_base_byte_range: hunk.diff_base_byte_range,
15709 secondary_status: hunk.secondary_status,
15710 range: Point::zero()..Point::zero(), // unused
15711 })
15712 .collect::<Vec<_>>(),
15713 &buffer_snapshot,
15714 file_exists,
15715 cx,
15716 )
15717 });
15718 None
15719 }
15720
15721 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
15722 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
15723 self.buffer
15724 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
15725 }
15726
15727 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
15728 self.buffer.update(cx, |buffer, cx| {
15729 let ranges = vec![Anchor::min()..Anchor::max()];
15730 if !buffer.all_diff_hunks_expanded()
15731 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
15732 {
15733 buffer.collapse_diff_hunks(ranges, cx);
15734 true
15735 } else {
15736 false
15737 }
15738 })
15739 }
15740
15741 fn toggle_diff_hunks_in_ranges(
15742 &mut self,
15743 ranges: Vec<Range<Anchor>>,
15744 cx: &mut Context<Editor>,
15745 ) {
15746 self.buffer.update(cx, |buffer, cx| {
15747 let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
15748 buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
15749 })
15750 }
15751
15752 fn toggle_single_diff_hunk(&mut self, range: Range<Anchor>, cx: &mut Context<Self>) {
15753 self.buffer.update(cx, |buffer, cx| {
15754 let snapshot = buffer.snapshot(cx);
15755 let excerpt_id = range.end.excerpt_id;
15756 let point_range = range.to_point(&snapshot);
15757 let expand = !buffer.single_hunk_is_expanded(range, cx);
15758 buffer.expand_or_collapse_diff_hunks_inner([(point_range, excerpt_id)], expand, cx);
15759 })
15760 }
15761
15762 pub(crate) fn apply_all_diff_hunks(
15763 &mut self,
15764 _: &ApplyAllDiffHunks,
15765 window: &mut Window,
15766 cx: &mut Context<Self>,
15767 ) {
15768 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15769
15770 let buffers = self.buffer.read(cx).all_buffers();
15771 for branch_buffer in buffers {
15772 branch_buffer.update(cx, |branch_buffer, cx| {
15773 branch_buffer.merge_into_base(Vec::new(), cx);
15774 });
15775 }
15776
15777 if let Some(project) = self.project.clone() {
15778 self.save(true, project, window, cx).detach_and_log_err(cx);
15779 }
15780 }
15781
15782 pub(crate) fn apply_selected_diff_hunks(
15783 &mut self,
15784 _: &ApplyDiffHunk,
15785 window: &mut Window,
15786 cx: &mut Context<Self>,
15787 ) {
15788 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
15789 let snapshot = self.snapshot(window, cx);
15790 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx));
15791 let mut ranges_by_buffer = HashMap::default();
15792 self.transact(window, cx, |editor, _window, cx| {
15793 for hunk in hunks {
15794 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
15795 ranges_by_buffer
15796 .entry(buffer.clone())
15797 .or_insert_with(Vec::new)
15798 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
15799 }
15800 }
15801
15802 for (buffer, ranges) in ranges_by_buffer {
15803 buffer.update(cx, |buffer, cx| {
15804 buffer.merge_into_base(ranges, cx);
15805 });
15806 }
15807 });
15808
15809 if let Some(project) = self.project.clone() {
15810 self.save(true, project, window, cx).detach_and_log_err(cx);
15811 }
15812 }
15813
15814 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
15815 if hovered != self.gutter_hovered {
15816 self.gutter_hovered = hovered;
15817 cx.notify();
15818 }
15819 }
15820
15821 pub fn insert_blocks(
15822 &mut self,
15823 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
15824 autoscroll: Option<Autoscroll>,
15825 cx: &mut Context<Self>,
15826 ) -> Vec<CustomBlockId> {
15827 let blocks = self
15828 .display_map
15829 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
15830 if let Some(autoscroll) = autoscroll {
15831 self.request_autoscroll(autoscroll, cx);
15832 }
15833 cx.notify();
15834 blocks
15835 }
15836
15837 pub fn resize_blocks(
15838 &mut self,
15839 heights: HashMap<CustomBlockId, u32>,
15840 autoscroll: Option<Autoscroll>,
15841 cx: &mut Context<Self>,
15842 ) {
15843 self.display_map
15844 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
15845 if let Some(autoscroll) = autoscroll {
15846 self.request_autoscroll(autoscroll, cx);
15847 }
15848 cx.notify();
15849 }
15850
15851 pub fn replace_blocks(
15852 &mut self,
15853 renderers: HashMap<CustomBlockId, RenderBlock>,
15854 autoscroll: Option<Autoscroll>,
15855 cx: &mut Context<Self>,
15856 ) {
15857 self.display_map
15858 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
15859 if let Some(autoscroll) = autoscroll {
15860 self.request_autoscroll(autoscroll, cx);
15861 }
15862 cx.notify();
15863 }
15864
15865 pub fn remove_blocks(
15866 &mut self,
15867 block_ids: HashSet<CustomBlockId>,
15868 autoscroll: Option<Autoscroll>,
15869 cx: &mut Context<Self>,
15870 ) {
15871 self.display_map.update(cx, |display_map, cx| {
15872 display_map.remove_blocks(block_ids, cx)
15873 });
15874 if let Some(autoscroll) = autoscroll {
15875 self.request_autoscroll(autoscroll, cx);
15876 }
15877 cx.notify();
15878 }
15879
15880 pub fn row_for_block(
15881 &self,
15882 block_id: CustomBlockId,
15883 cx: &mut Context<Self>,
15884 ) -> Option<DisplayRow> {
15885 self.display_map
15886 .update(cx, |map, cx| map.row_for_block(block_id, cx))
15887 }
15888
15889 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
15890 self.focused_block = Some(focused_block);
15891 }
15892
15893 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
15894 self.focused_block.take()
15895 }
15896
15897 pub fn insert_creases(
15898 &mut self,
15899 creases: impl IntoIterator<Item = Crease<Anchor>>,
15900 cx: &mut Context<Self>,
15901 ) -> Vec<CreaseId> {
15902 self.display_map
15903 .update(cx, |map, cx| map.insert_creases(creases, cx))
15904 }
15905
15906 pub fn remove_creases(
15907 &mut self,
15908 ids: impl IntoIterator<Item = CreaseId>,
15909 cx: &mut Context<Self>,
15910 ) {
15911 self.display_map
15912 .update(cx, |map, cx| map.remove_creases(ids, cx));
15913 }
15914
15915 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
15916 self.display_map
15917 .update(cx, |map, cx| map.snapshot(cx))
15918 .longest_row()
15919 }
15920
15921 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
15922 self.display_map
15923 .update(cx, |map, cx| map.snapshot(cx))
15924 .max_point()
15925 }
15926
15927 pub fn text(&self, cx: &App) -> String {
15928 self.buffer.read(cx).read(cx).text()
15929 }
15930
15931 pub fn is_empty(&self, cx: &App) -> bool {
15932 self.buffer.read(cx).read(cx).is_empty()
15933 }
15934
15935 pub fn text_option(&self, cx: &App) -> Option<String> {
15936 let text = self.text(cx);
15937 let text = text.trim();
15938
15939 if text.is_empty() {
15940 return None;
15941 }
15942
15943 Some(text.to_string())
15944 }
15945
15946 pub fn set_text(
15947 &mut self,
15948 text: impl Into<Arc<str>>,
15949 window: &mut Window,
15950 cx: &mut Context<Self>,
15951 ) {
15952 self.transact(window, cx, |this, _, cx| {
15953 this.buffer
15954 .read(cx)
15955 .as_singleton()
15956 .expect("you can only call set_text on editors for singleton buffers")
15957 .update(cx, |buffer, cx| buffer.set_text(text, cx));
15958 });
15959 }
15960
15961 pub fn display_text(&self, cx: &mut App) -> String {
15962 self.display_map
15963 .update(cx, |map, cx| map.snapshot(cx))
15964 .text()
15965 }
15966
15967 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
15968 let mut wrap_guides = smallvec::smallvec![];
15969
15970 if self.show_wrap_guides == Some(false) {
15971 return wrap_guides;
15972 }
15973
15974 let settings = self.buffer.read(cx).language_settings(cx);
15975 if settings.show_wrap_guides {
15976 match self.soft_wrap_mode(cx) {
15977 SoftWrap::Column(soft_wrap) => {
15978 wrap_guides.push((soft_wrap as usize, true));
15979 }
15980 SoftWrap::Bounded(soft_wrap) => {
15981 wrap_guides.push((soft_wrap as usize, true));
15982 }
15983 SoftWrap::GitDiff | SoftWrap::None | SoftWrap::EditorWidth => {}
15984 }
15985 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
15986 }
15987
15988 wrap_guides
15989 }
15990
15991 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
15992 let settings = self.buffer.read(cx).language_settings(cx);
15993 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
15994 match mode {
15995 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
15996 SoftWrap::None
15997 }
15998 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
15999 language_settings::SoftWrap::PreferredLineLength => {
16000 SoftWrap::Column(settings.preferred_line_length)
16001 }
16002 language_settings::SoftWrap::Bounded => {
16003 SoftWrap::Bounded(settings.preferred_line_length)
16004 }
16005 }
16006 }
16007
16008 pub fn set_soft_wrap_mode(
16009 &mut self,
16010 mode: language_settings::SoftWrap,
16011
16012 cx: &mut Context<Self>,
16013 ) {
16014 self.soft_wrap_mode_override = Some(mode);
16015 cx.notify();
16016 }
16017
16018 pub fn set_hard_wrap(&mut self, hard_wrap: Option<usize>, cx: &mut Context<Self>) {
16019 self.hard_wrap = hard_wrap;
16020 cx.notify();
16021 }
16022
16023 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
16024 self.text_style_refinement = Some(style);
16025 }
16026
16027 /// called by the Element so we know what style we were most recently rendered with.
16028 pub(crate) fn set_style(
16029 &mut self,
16030 style: EditorStyle,
16031 window: &mut Window,
16032 cx: &mut Context<Self>,
16033 ) {
16034 let rem_size = window.rem_size();
16035 self.display_map.update(cx, |map, cx| {
16036 map.set_font(
16037 style.text.font(),
16038 style.text.font_size.to_pixels(rem_size),
16039 cx,
16040 )
16041 });
16042 self.style = Some(style);
16043 }
16044
16045 pub fn style(&self) -> Option<&EditorStyle> {
16046 self.style.as_ref()
16047 }
16048
16049 // Called by the element. This method is not designed to be called outside of the editor
16050 // element's layout code because it does not notify when rewrapping is computed synchronously.
16051 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
16052 self.display_map
16053 .update(cx, |map, cx| map.set_wrap_width(width, cx))
16054 }
16055
16056 pub fn set_soft_wrap(&mut self) {
16057 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
16058 }
16059
16060 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
16061 if self.soft_wrap_mode_override.is_some() {
16062 self.soft_wrap_mode_override.take();
16063 } else {
16064 let soft_wrap = match self.soft_wrap_mode(cx) {
16065 SoftWrap::GitDiff => return,
16066 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
16067 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
16068 language_settings::SoftWrap::None
16069 }
16070 };
16071 self.soft_wrap_mode_override = Some(soft_wrap);
16072 }
16073 cx.notify();
16074 }
16075
16076 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
16077 let Some(workspace) = self.workspace() else {
16078 return;
16079 };
16080 let fs = workspace.read(cx).app_state().fs.clone();
16081 let current_show = TabBarSettings::get_global(cx).show;
16082 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
16083 setting.show = Some(!current_show);
16084 });
16085 }
16086
16087 pub fn toggle_indent_guides(
16088 &mut self,
16089 _: &ToggleIndentGuides,
16090 _: &mut Window,
16091 cx: &mut Context<Self>,
16092 ) {
16093 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
16094 self.buffer
16095 .read(cx)
16096 .language_settings(cx)
16097 .indent_guides
16098 .enabled
16099 });
16100 self.show_indent_guides = Some(!currently_enabled);
16101 cx.notify();
16102 }
16103
16104 fn should_show_indent_guides(&self) -> Option<bool> {
16105 self.show_indent_guides
16106 }
16107
16108 pub fn toggle_line_numbers(
16109 &mut self,
16110 _: &ToggleLineNumbers,
16111 _: &mut Window,
16112 cx: &mut Context<Self>,
16113 ) {
16114 let mut editor_settings = EditorSettings::get_global(cx).clone();
16115 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
16116 EditorSettings::override_global(editor_settings, cx);
16117 }
16118
16119 pub fn line_numbers_enabled(&self, cx: &App) -> bool {
16120 if let Some(show_line_numbers) = self.show_line_numbers {
16121 return show_line_numbers;
16122 }
16123 EditorSettings::get_global(cx).gutter.line_numbers
16124 }
16125
16126 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
16127 self.use_relative_line_numbers
16128 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
16129 }
16130
16131 pub fn toggle_relative_line_numbers(
16132 &mut self,
16133 _: &ToggleRelativeLineNumbers,
16134 _: &mut Window,
16135 cx: &mut Context<Self>,
16136 ) {
16137 let is_relative = self.should_use_relative_line_numbers(cx);
16138 self.set_relative_line_number(Some(!is_relative), cx)
16139 }
16140
16141 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
16142 self.use_relative_line_numbers = is_relative;
16143 cx.notify();
16144 }
16145
16146 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
16147 self.show_gutter = show_gutter;
16148 cx.notify();
16149 }
16150
16151 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
16152 self.show_scrollbars = show_scrollbars;
16153 cx.notify();
16154 }
16155
16156 pub fn disable_scrolling(&mut self, cx: &mut Context<Self>) {
16157 self.disable_scrolling = true;
16158 cx.notify();
16159 }
16160
16161 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
16162 self.show_line_numbers = Some(show_line_numbers);
16163 cx.notify();
16164 }
16165
16166 pub fn disable_expand_excerpt_buttons(&mut self, cx: &mut Context<Self>) {
16167 self.disable_expand_excerpt_buttons = true;
16168 cx.notify();
16169 }
16170
16171 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
16172 self.show_git_diff_gutter = Some(show_git_diff_gutter);
16173 cx.notify();
16174 }
16175
16176 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
16177 self.show_code_actions = Some(show_code_actions);
16178 cx.notify();
16179 }
16180
16181 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
16182 self.show_runnables = Some(show_runnables);
16183 cx.notify();
16184 }
16185
16186 pub fn set_show_breakpoints(&mut self, show_breakpoints: bool, cx: &mut Context<Self>) {
16187 self.show_breakpoints = Some(show_breakpoints);
16188 cx.notify();
16189 }
16190
16191 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
16192 if self.display_map.read(cx).masked != masked {
16193 self.display_map.update(cx, |map, _| map.masked = masked);
16194 }
16195 cx.notify()
16196 }
16197
16198 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
16199 self.show_wrap_guides = Some(show_wrap_guides);
16200 cx.notify();
16201 }
16202
16203 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
16204 self.show_indent_guides = Some(show_indent_guides);
16205 cx.notify();
16206 }
16207
16208 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
16209 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
16210 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
16211 if let Some(dir) = file.abs_path(cx).parent() {
16212 return Some(dir.to_owned());
16213 }
16214 }
16215
16216 if let Some(project_path) = buffer.read(cx).project_path(cx) {
16217 return Some(project_path.path.to_path_buf());
16218 }
16219 }
16220
16221 None
16222 }
16223
16224 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
16225 self.active_excerpt(cx)?
16226 .1
16227 .read(cx)
16228 .file()
16229 .and_then(|f| f.as_local())
16230 }
16231
16232 pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16233 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16234 let buffer = buffer.read(cx);
16235 if let Some(project_path) = buffer.project_path(cx) {
16236 let project = self.project.as_ref()?.read(cx);
16237 project.absolute_path(&project_path, cx)
16238 } else {
16239 buffer
16240 .file()
16241 .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
16242 }
16243 })
16244 }
16245
16246 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
16247 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
16248 let project_path = buffer.read(cx).project_path(cx)?;
16249 let project = self.project.as_ref()?.read(cx);
16250 let entry = project.entry_for_path(&project_path, cx)?;
16251 let path = entry.path.to_path_buf();
16252 Some(path)
16253 })
16254 }
16255
16256 pub fn reveal_in_finder(
16257 &mut self,
16258 _: &RevealInFileManager,
16259 _window: &mut Window,
16260 cx: &mut Context<Self>,
16261 ) {
16262 if let Some(target) = self.target_file(cx) {
16263 cx.reveal_path(&target.abs_path(cx));
16264 }
16265 }
16266
16267 pub fn copy_path(
16268 &mut self,
16269 _: &zed_actions::workspace::CopyPath,
16270 _window: &mut Window,
16271 cx: &mut Context<Self>,
16272 ) {
16273 if let Some(path) = self.target_file_abs_path(cx) {
16274 if let Some(path) = path.to_str() {
16275 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16276 }
16277 }
16278 }
16279
16280 pub fn copy_relative_path(
16281 &mut self,
16282 _: &zed_actions::workspace::CopyRelativePath,
16283 _window: &mut Window,
16284 cx: &mut Context<Self>,
16285 ) {
16286 if let Some(path) = self.target_file_path(cx) {
16287 if let Some(path) = path.to_str() {
16288 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
16289 }
16290 }
16291 }
16292
16293 pub fn project_path(&self, cx: &App) -> Option<ProjectPath> {
16294 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
16295 buffer.read(cx).project_path(cx)
16296 } else {
16297 None
16298 }
16299 }
16300
16301 // Returns true if the editor handled a go-to-line request
16302 pub fn go_to_active_debug_line(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
16303 maybe!({
16304 let breakpoint_store = self.breakpoint_store.as_ref()?;
16305
16306 let Some((_, _, active_position)) =
16307 breakpoint_store.read(cx).active_position().cloned()
16308 else {
16309 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16310 return None;
16311 };
16312
16313 let snapshot = self
16314 .project
16315 .as_ref()?
16316 .read(cx)
16317 .buffer_for_id(active_position.buffer_id?, cx)?
16318 .read(cx)
16319 .snapshot();
16320
16321 let mut handled = false;
16322 for (id, ExcerptRange { context, .. }) in self
16323 .buffer
16324 .read(cx)
16325 .excerpts_for_buffer(active_position.buffer_id?, cx)
16326 {
16327 if context.start.cmp(&active_position, &snapshot).is_ge()
16328 || context.end.cmp(&active_position, &snapshot).is_lt()
16329 {
16330 continue;
16331 }
16332 let snapshot = self.buffer.read(cx).snapshot(cx);
16333 let multibuffer_anchor = snapshot.anchor_in_excerpt(id, active_position)?;
16334
16335 handled = true;
16336 self.clear_row_highlights::<DebugCurrentRowHighlight>();
16337 self.go_to_line::<DebugCurrentRowHighlight>(
16338 multibuffer_anchor,
16339 Some(cx.theme().colors().editor_debugger_active_line_background),
16340 window,
16341 cx,
16342 );
16343
16344 cx.notify();
16345 }
16346 handled.then_some(())
16347 })
16348 .is_some()
16349 }
16350
16351 pub fn copy_file_name_without_extension(
16352 &mut self,
16353 _: &CopyFileNameWithoutExtension,
16354 _: &mut Window,
16355 cx: &mut Context<Self>,
16356 ) {
16357 if let Some(file) = self.target_file(cx) {
16358 if let Some(file_stem) = file.path().file_stem() {
16359 if let Some(name) = file_stem.to_str() {
16360 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16361 }
16362 }
16363 }
16364 }
16365
16366 pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
16367 if let Some(file) = self.target_file(cx) {
16368 if let Some(file_name) = file.path().file_name() {
16369 if let Some(name) = file_name.to_str() {
16370 cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
16371 }
16372 }
16373 }
16374 }
16375
16376 pub fn toggle_git_blame(
16377 &mut self,
16378 _: &::git::Blame,
16379 window: &mut Window,
16380 cx: &mut Context<Self>,
16381 ) {
16382 self.show_git_blame_gutter = !self.show_git_blame_gutter;
16383
16384 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
16385 self.start_git_blame(true, window, cx);
16386 }
16387
16388 cx.notify();
16389 }
16390
16391 pub fn toggle_git_blame_inline(
16392 &mut self,
16393 _: &ToggleGitBlameInline,
16394 window: &mut Window,
16395 cx: &mut Context<Self>,
16396 ) {
16397 self.toggle_git_blame_inline_internal(true, window, cx);
16398 cx.notify();
16399 }
16400
16401 pub fn open_git_blame_commit(
16402 &mut self,
16403 _: &OpenGitBlameCommit,
16404 window: &mut Window,
16405 cx: &mut Context<Self>,
16406 ) {
16407 self.open_git_blame_commit_internal(window, cx);
16408 }
16409
16410 fn open_git_blame_commit_internal(
16411 &mut self,
16412 window: &mut Window,
16413 cx: &mut Context<Self>,
16414 ) -> Option<()> {
16415 let blame = self.blame.as_ref()?;
16416 let snapshot = self.snapshot(window, cx);
16417 let cursor = self.selections.newest::<Point>(cx).head();
16418 let (buffer, point, _) = snapshot.buffer_snapshot.point_to_buffer_point(cursor)?;
16419 let blame_entry = blame
16420 .update(cx, |blame, cx| {
16421 blame
16422 .blame_for_rows(
16423 &[RowInfo {
16424 buffer_id: Some(buffer.remote_id()),
16425 buffer_row: Some(point.row),
16426 ..Default::default()
16427 }],
16428 cx,
16429 )
16430 .next()
16431 })
16432 .flatten()?;
16433 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
16434 let repo = blame.read(cx).repository(cx)?;
16435 let workspace = self.workspace()?.downgrade();
16436 renderer.open_blame_commit(blame_entry, repo, workspace, window, cx);
16437 None
16438 }
16439
16440 pub fn git_blame_inline_enabled(&self) -> bool {
16441 self.git_blame_inline_enabled
16442 }
16443
16444 pub fn toggle_selection_menu(
16445 &mut self,
16446 _: &ToggleSelectionMenu,
16447 _: &mut Window,
16448 cx: &mut Context<Self>,
16449 ) {
16450 self.show_selection_menu = self
16451 .show_selection_menu
16452 .map(|show_selections_menu| !show_selections_menu)
16453 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
16454
16455 cx.notify();
16456 }
16457
16458 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
16459 self.show_selection_menu
16460 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
16461 }
16462
16463 fn start_git_blame(
16464 &mut self,
16465 user_triggered: bool,
16466 window: &mut Window,
16467 cx: &mut Context<Self>,
16468 ) {
16469 if let Some(project) = self.project.as_ref() {
16470 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
16471 return;
16472 };
16473
16474 if buffer.read(cx).file().is_none() {
16475 return;
16476 }
16477
16478 let focused = self.focus_handle(cx).contains_focused(window, cx);
16479
16480 let project = project.clone();
16481 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
16482 self.blame_subscription =
16483 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
16484 self.blame = Some(blame);
16485 }
16486 }
16487
16488 fn toggle_git_blame_inline_internal(
16489 &mut self,
16490 user_triggered: bool,
16491 window: &mut Window,
16492 cx: &mut Context<Self>,
16493 ) {
16494 if self.git_blame_inline_enabled {
16495 self.git_blame_inline_enabled = false;
16496 self.show_git_blame_inline = false;
16497 self.show_git_blame_inline_delay_task.take();
16498 } else {
16499 self.git_blame_inline_enabled = true;
16500 self.start_git_blame_inline(user_triggered, window, cx);
16501 }
16502
16503 cx.notify();
16504 }
16505
16506 fn start_git_blame_inline(
16507 &mut self,
16508 user_triggered: bool,
16509 window: &mut Window,
16510 cx: &mut Context<Self>,
16511 ) {
16512 self.start_git_blame(user_triggered, window, cx);
16513
16514 if ProjectSettings::get_global(cx)
16515 .git
16516 .inline_blame_delay()
16517 .is_some()
16518 {
16519 self.start_inline_blame_timer(window, cx);
16520 } else {
16521 self.show_git_blame_inline = true
16522 }
16523 }
16524
16525 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
16526 self.blame.as_ref()
16527 }
16528
16529 pub fn show_git_blame_gutter(&self) -> bool {
16530 self.show_git_blame_gutter
16531 }
16532
16533 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
16534 self.show_git_blame_gutter && self.has_blame_entries(cx)
16535 }
16536
16537 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
16538 self.show_git_blame_inline
16539 && (self.focus_handle.is_focused(window)
16540 || self
16541 .git_blame_inline_tooltip
16542 .as_ref()
16543 .and_then(|t| t.upgrade())
16544 .is_some())
16545 && !self.newest_selection_head_on_empty_line(cx)
16546 && self.has_blame_entries(cx)
16547 }
16548
16549 fn has_blame_entries(&self, cx: &App) -> bool {
16550 self.blame()
16551 .map_or(false, |blame| blame.read(cx).has_generated_entries())
16552 }
16553
16554 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
16555 let cursor_anchor = self.selections.newest_anchor().head();
16556
16557 let snapshot = self.buffer.read(cx).snapshot(cx);
16558 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
16559
16560 snapshot.line_len(buffer_row) == 0
16561 }
16562
16563 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
16564 let buffer_and_selection = maybe!({
16565 let selection = self.selections.newest::<Point>(cx);
16566 let selection_range = selection.range();
16567
16568 let multi_buffer = self.buffer().read(cx);
16569 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
16570 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
16571
16572 let (buffer, range, _) = if selection.reversed {
16573 buffer_ranges.first()
16574 } else {
16575 buffer_ranges.last()
16576 }?;
16577
16578 let selection = text::ToPoint::to_point(&range.start, &buffer).row
16579 ..text::ToPoint::to_point(&range.end, &buffer).row;
16580 Some((
16581 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
16582 selection,
16583 ))
16584 });
16585
16586 let Some((buffer, selection)) = buffer_and_selection else {
16587 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
16588 };
16589
16590 let Some(project) = self.project.as_ref() else {
16591 return Task::ready(Err(anyhow!("editor does not have project")));
16592 };
16593
16594 project.update(cx, |project, cx| {
16595 project.get_permalink_to_line(&buffer, selection, cx)
16596 })
16597 }
16598
16599 pub fn copy_permalink_to_line(
16600 &mut self,
16601 _: &CopyPermalinkToLine,
16602 window: &mut Window,
16603 cx: &mut Context<Self>,
16604 ) {
16605 let permalink_task = self.get_permalink_to_line(cx);
16606 let workspace = self.workspace();
16607
16608 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16609 Ok(permalink) => {
16610 cx.update(|_, cx| {
16611 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
16612 })
16613 .ok();
16614 }
16615 Err(err) => {
16616 let message = format!("Failed to copy permalink: {err}");
16617
16618 Err::<(), anyhow::Error>(err).log_err();
16619
16620 if let Some(workspace) = workspace {
16621 workspace
16622 .update_in(cx, |workspace, _, cx| {
16623 struct CopyPermalinkToLine;
16624
16625 workspace.show_toast(
16626 Toast::new(
16627 NotificationId::unique::<CopyPermalinkToLine>(),
16628 message,
16629 ),
16630 cx,
16631 )
16632 })
16633 .ok();
16634 }
16635 }
16636 })
16637 .detach();
16638 }
16639
16640 pub fn copy_file_location(
16641 &mut self,
16642 _: &CopyFileLocation,
16643 _: &mut Window,
16644 cx: &mut Context<Self>,
16645 ) {
16646 let selection = self.selections.newest::<Point>(cx).start.row + 1;
16647 if let Some(file) = self.target_file(cx) {
16648 if let Some(path) = file.path().to_str() {
16649 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
16650 }
16651 }
16652 }
16653
16654 pub fn open_permalink_to_line(
16655 &mut self,
16656 _: &OpenPermalinkToLine,
16657 window: &mut Window,
16658 cx: &mut Context<Self>,
16659 ) {
16660 let permalink_task = self.get_permalink_to_line(cx);
16661 let workspace = self.workspace();
16662
16663 cx.spawn_in(window, async move |_, cx| match permalink_task.await {
16664 Ok(permalink) => {
16665 cx.update(|_, cx| {
16666 cx.open_url(permalink.as_ref());
16667 })
16668 .ok();
16669 }
16670 Err(err) => {
16671 let message = format!("Failed to open permalink: {err}");
16672
16673 Err::<(), anyhow::Error>(err).log_err();
16674
16675 if let Some(workspace) = workspace {
16676 workspace
16677 .update(cx, |workspace, cx| {
16678 struct OpenPermalinkToLine;
16679
16680 workspace.show_toast(
16681 Toast::new(
16682 NotificationId::unique::<OpenPermalinkToLine>(),
16683 message,
16684 ),
16685 cx,
16686 )
16687 })
16688 .ok();
16689 }
16690 }
16691 })
16692 .detach();
16693 }
16694
16695 pub fn insert_uuid_v4(
16696 &mut self,
16697 _: &InsertUuidV4,
16698 window: &mut Window,
16699 cx: &mut Context<Self>,
16700 ) {
16701 self.insert_uuid(UuidVersion::V4, window, cx);
16702 }
16703
16704 pub fn insert_uuid_v7(
16705 &mut self,
16706 _: &InsertUuidV7,
16707 window: &mut Window,
16708 cx: &mut Context<Self>,
16709 ) {
16710 self.insert_uuid(UuidVersion::V7, window, cx);
16711 }
16712
16713 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
16714 self.hide_mouse_cursor(&HideMouseCursorOrigin::TypingAction);
16715 self.transact(window, cx, |this, window, cx| {
16716 let edits = this
16717 .selections
16718 .all::<Point>(cx)
16719 .into_iter()
16720 .map(|selection| {
16721 let uuid = match version {
16722 UuidVersion::V4 => uuid::Uuid::new_v4(),
16723 UuidVersion::V7 => uuid::Uuid::now_v7(),
16724 };
16725
16726 (selection.range(), uuid.to_string())
16727 });
16728 this.edit(edits, cx);
16729 this.refresh_inline_completion(true, false, window, cx);
16730 });
16731 }
16732
16733 pub fn open_selections_in_multibuffer(
16734 &mut self,
16735 _: &OpenSelectionsInMultibuffer,
16736 window: &mut Window,
16737 cx: &mut Context<Self>,
16738 ) {
16739 let multibuffer = self.buffer.read(cx);
16740
16741 let Some(buffer) = multibuffer.as_singleton() else {
16742 return;
16743 };
16744
16745 let Some(workspace) = self.workspace() else {
16746 return;
16747 };
16748
16749 let locations = self
16750 .selections
16751 .disjoint_anchors()
16752 .iter()
16753 .map(|range| Location {
16754 buffer: buffer.clone(),
16755 range: range.start.text_anchor..range.end.text_anchor,
16756 })
16757 .collect::<Vec<_>>();
16758
16759 let title = multibuffer.title(cx).to_string();
16760
16761 cx.spawn_in(window, async move |_, cx| {
16762 workspace.update_in(cx, |workspace, window, cx| {
16763 Self::open_locations_in_multibuffer(
16764 workspace,
16765 locations,
16766 format!("Selections for '{title}'"),
16767 false,
16768 MultibufferSelectionMode::All,
16769 window,
16770 cx,
16771 );
16772 })
16773 })
16774 .detach();
16775 }
16776
16777 /// Adds a row highlight for the given range. If a row has multiple highlights, the
16778 /// last highlight added will be used.
16779 ///
16780 /// If the range ends at the beginning of a line, then that line will not be highlighted.
16781 pub fn highlight_rows<T: 'static>(
16782 &mut self,
16783 range: Range<Anchor>,
16784 color: Hsla,
16785 should_autoscroll: bool,
16786 cx: &mut Context<Self>,
16787 ) {
16788 let snapshot = self.buffer().read(cx).snapshot(cx);
16789 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16790 let ix = row_highlights.binary_search_by(|highlight| {
16791 Ordering::Equal
16792 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
16793 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
16794 });
16795
16796 if let Err(mut ix) = ix {
16797 let index = post_inc(&mut self.highlight_order);
16798
16799 // If this range intersects with the preceding highlight, then merge it with
16800 // the preceding highlight. Otherwise insert a new highlight.
16801 let mut merged = false;
16802 if ix > 0 {
16803 let prev_highlight = &mut row_highlights[ix - 1];
16804 if prev_highlight
16805 .range
16806 .end
16807 .cmp(&range.start, &snapshot)
16808 .is_ge()
16809 {
16810 ix -= 1;
16811 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
16812 prev_highlight.range.end = range.end;
16813 }
16814 merged = true;
16815 prev_highlight.index = index;
16816 prev_highlight.color = color;
16817 prev_highlight.should_autoscroll = should_autoscroll;
16818 }
16819 }
16820
16821 if !merged {
16822 row_highlights.insert(
16823 ix,
16824 RowHighlight {
16825 range: range.clone(),
16826 index,
16827 color,
16828 should_autoscroll,
16829 },
16830 );
16831 }
16832
16833 // If any of the following highlights intersect with this one, merge them.
16834 while let Some(next_highlight) = row_highlights.get(ix + 1) {
16835 let highlight = &row_highlights[ix];
16836 if next_highlight
16837 .range
16838 .start
16839 .cmp(&highlight.range.end, &snapshot)
16840 .is_le()
16841 {
16842 if next_highlight
16843 .range
16844 .end
16845 .cmp(&highlight.range.end, &snapshot)
16846 .is_gt()
16847 {
16848 row_highlights[ix].range.end = next_highlight.range.end;
16849 }
16850 row_highlights.remove(ix + 1);
16851 } else {
16852 break;
16853 }
16854 }
16855 }
16856 }
16857
16858 /// Remove any highlighted row ranges of the given type that intersect the
16859 /// given ranges.
16860 pub fn remove_highlighted_rows<T: 'static>(
16861 &mut self,
16862 ranges_to_remove: Vec<Range<Anchor>>,
16863 cx: &mut Context<Self>,
16864 ) {
16865 let snapshot = self.buffer().read(cx).snapshot(cx);
16866 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
16867 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
16868 row_highlights.retain(|highlight| {
16869 while let Some(range_to_remove) = ranges_to_remove.peek() {
16870 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
16871 Ordering::Less | Ordering::Equal => {
16872 ranges_to_remove.next();
16873 }
16874 Ordering::Greater => {
16875 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
16876 Ordering::Less | Ordering::Equal => {
16877 return false;
16878 }
16879 Ordering::Greater => break,
16880 }
16881 }
16882 }
16883 }
16884
16885 true
16886 })
16887 }
16888
16889 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
16890 pub fn clear_row_highlights<T: 'static>(&mut self) {
16891 self.highlighted_rows.remove(&TypeId::of::<T>());
16892 }
16893
16894 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
16895 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
16896 self.highlighted_rows
16897 .get(&TypeId::of::<T>())
16898 .map_or(&[] as &[_], |vec| vec.as_slice())
16899 .iter()
16900 .map(|highlight| (highlight.range.clone(), highlight.color))
16901 }
16902
16903 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
16904 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
16905 /// Allows to ignore certain kinds of highlights.
16906 pub fn highlighted_display_rows(
16907 &self,
16908 window: &mut Window,
16909 cx: &mut App,
16910 ) -> BTreeMap<DisplayRow, LineHighlight> {
16911 let snapshot = self.snapshot(window, cx);
16912 let mut used_highlight_orders = HashMap::default();
16913 self.highlighted_rows
16914 .iter()
16915 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
16916 .fold(
16917 BTreeMap::<DisplayRow, LineHighlight>::new(),
16918 |mut unique_rows, highlight| {
16919 let start = highlight.range.start.to_display_point(&snapshot);
16920 let end = highlight.range.end.to_display_point(&snapshot);
16921 let start_row = start.row().0;
16922 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
16923 && end.column() == 0
16924 {
16925 end.row().0.saturating_sub(1)
16926 } else {
16927 end.row().0
16928 };
16929 for row in start_row..=end_row {
16930 let used_index =
16931 used_highlight_orders.entry(row).or_insert(highlight.index);
16932 if highlight.index >= *used_index {
16933 *used_index = highlight.index;
16934 unique_rows.insert(DisplayRow(row), highlight.color.into());
16935 }
16936 }
16937 unique_rows
16938 },
16939 )
16940 }
16941
16942 pub fn highlighted_display_row_for_autoscroll(
16943 &self,
16944 snapshot: &DisplaySnapshot,
16945 ) -> Option<DisplayRow> {
16946 self.highlighted_rows
16947 .values()
16948 .flat_map(|highlighted_rows| highlighted_rows.iter())
16949 .filter_map(|highlight| {
16950 if highlight.should_autoscroll {
16951 Some(highlight.range.start.to_display_point(snapshot).row())
16952 } else {
16953 None
16954 }
16955 })
16956 .min()
16957 }
16958
16959 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
16960 self.highlight_background::<SearchWithinRange>(
16961 ranges,
16962 |colors| colors.editor_document_highlight_read_background,
16963 cx,
16964 )
16965 }
16966
16967 pub fn set_breadcrumb_header(&mut self, new_header: String) {
16968 self.breadcrumb_header = Some(new_header);
16969 }
16970
16971 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
16972 self.clear_background_highlights::<SearchWithinRange>(cx);
16973 }
16974
16975 pub fn highlight_background<T: 'static>(
16976 &mut self,
16977 ranges: &[Range<Anchor>],
16978 color_fetcher: fn(&ThemeColors) -> Hsla,
16979 cx: &mut Context<Self>,
16980 ) {
16981 self.background_highlights
16982 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
16983 self.scrollbar_marker_state.dirty = true;
16984 cx.notify();
16985 }
16986
16987 pub fn clear_background_highlights<T: 'static>(
16988 &mut self,
16989 cx: &mut Context<Self>,
16990 ) -> Option<BackgroundHighlight> {
16991 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
16992 if !text_highlights.1.is_empty() {
16993 self.scrollbar_marker_state.dirty = true;
16994 cx.notify();
16995 }
16996 Some(text_highlights)
16997 }
16998
16999 pub fn highlight_gutter<T: 'static>(
17000 &mut self,
17001 ranges: &[Range<Anchor>],
17002 color_fetcher: fn(&App) -> Hsla,
17003 cx: &mut Context<Self>,
17004 ) {
17005 self.gutter_highlights
17006 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
17007 cx.notify();
17008 }
17009
17010 pub fn clear_gutter_highlights<T: 'static>(
17011 &mut self,
17012 cx: &mut Context<Self>,
17013 ) -> Option<GutterHighlight> {
17014 cx.notify();
17015 self.gutter_highlights.remove(&TypeId::of::<T>())
17016 }
17017
17018 #[cfg(feature = "test-support")]
17019 pub fn all_text_background_highlights(
17020 &self,
17021 window: &mut Window,
17022 cx: &mut Context<Self>,
17023 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17024 let snapshot = self.snapshot(window, cx);
17025 let buffer = &snapshot.buffer_snapshot;
17026 let start = buffer.anchor_before(0);
17027 let end = buffer.anchor_after(buffer.len());
17028 let theme = cx.theme().colors();
17029 self.background_highlights_in_range(start..end, &snapshot, theme)
17030 }
17031
17032 #[cfg(feature = "test-support")]
17033 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
17034 let snapshot = self.buffer().read(cx).snapshot(cx);
17035
17036 let highlights = self
17037 .background_highlights
17038 .get(&TypeId::of::<items::BufferSearchHighlights>());
17039
17040 if let Some((_color, ranges)) = highlights {
17041 ranges
17042 .iter()
17043 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
17044 .collect_vec()
17045 } else {
17046 vec![]
17047 }
17048 }
17049
17050 fn document_highlights_for_position<'a>(
17051 &'a self,
17052 position: Anchor,
17053 buffer: &'a MultiBufferSnapshot,
17054 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
17055 let read_highlights = self
17056 .background_highlights
17057 .get(&TypeId::of::<DocumentHighlightRead>())
17058 .map(|h| &h.1);
17059 let write_highlights = self
17060 .background_highlights
17061 .get(&TypeId::of::<DocumentHighlightWrite>())
17062 .map(|h| &h.1);
17063 let left_position = position.bias_left(buffer);
17064 let right_position = position.bias_right(buffer);
17065 read_highlights
17066 .into_iter()
17067 .chain(write_highlights)
17068 .flat_map(move |ranges| {
17069 let start_ix = match ranges.binary_search_by(|probe| {
17070 let cmp = probe.end.cmp(&left_position, buffer);
17071 if cmp.is_ge() {
17072 Ordering::Greater
17073 } else {
17074 Ordering::Less
17075 }
17076 }) {
17077 Ok(i) | Err(i) => i,
17078 };
17079
17080 ranges[start_ix..]
17081 .iter()
17082 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
17083 })
17084 }
17085
17086 pub fn has_background_highlights<T: 'static>(&self) -> bool {
17087 self.background_highlights
17088 .get(&TypeId::of::<T>())
17089 .map_or(false, |(_, highlights)| !highlights.is_empty())
17090 }
17091
17092 pub fn background_highlights_in_range(
17093 &self,
17094 search_range: Range<Anchor>,
17095 display_snapshot: &DisplaySnapshot,
17096 theme: &ThemeColors,
17097 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17098 let mut results = Vec::new();
17099 for (color_fetcher, ranges) in self.background_highlights.values() {
17100 let color = color_fetcher(theme);
17101 let start_ix = match ranges.binary_search_by(|probe| {
17102 let cmp = probe
17103 .end
17104 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17105 if cmp.is_gt() {
17106 Ordering::Greater
17107 } else {
17108 Ordering::Less
17109 }
17110 }) {
17111 Ok(i) | Err(i) => i,
17112 };
17113 for range in &ranges[start_ix..] {
17114 if range
17115 .start
17116 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17117 .is_ge()
17118 {
17119 break;
17120 }
17121
17122 let start = range.start.to_display_point(display_snapshot);
17123 let end = range.end.to_display_point(display_snapshot);
17124 results.push((start..end, color))
17125 }
17126 }
17127 results
17128 }
17129
17130 pub fn background_highlight_row_ranges<T: 'static>(
17131 &self,
17132 search_range: Range<Anchor>,
17133 display_snapshot: &DisplaySnapshot,
17134 count: usize,
17135 ) -> Vec<RangeInclusive<DisplayPoint>> {
17136 let mut results = Vec::new();
17137 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
17138 return vec![];
17139 };
17140
17141 let start_ix = match ranges.binary_search_by(|probe| {
17142 let cmp = probe
17143 .end
17144 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17145 if cmp.is_gt() {
17146 Ordering::Greater
17147 } else {
17148 Ordering::Less
17149 }
17150 }) {
17151 Ok(i) | Err(i) => i,
17152 };
17153 let mut push_region = |start: Option<Point>, end: Option<Point>| {
17154 if let (Some(start_display), Some(end_display)) = (start, end) {
17155 results.push(
17156 start_display.to_display_point(display_snapshot)
17157 ..=end_display.to_display_point(display_snapshot),
17158 );
17159 }
17160 };
17161 let mut start_row: Option<Point> = None;
17162 let mut end_row: Option<Point> = None;
17163 if ranges.len() > count {
17164 return Vec::new();
17165 }
17166 for range in &ranges[start_ix..] {
17167 if range
17168 .start
17169 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17170 .is_ge()
17171 {
17172 break;
17173 }
17174 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
17175 if let Some(current_row) = &end_row {
17176 if end.row == current_row.row {
17177 continue;
17178 }
17179 }
17180 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
17181 if start_row.is_none() {
17182 assert_eq!(end_row, None);
17183 start_row = Some(start);
17184 end_row = Some(end);
17185 continue;
17186 }
17187 if let Some(current_end) = end_row.as_mut() {
17188 if start.row > current_end.row + 1 {
17189 push_region(start_row, end_row);
17190 start_row = Some(start);
17191 end_row = Some(end);
17192 } else {
17193 // Merge two hunks.
17194 *current_end = end;
17195 }
17196 } else {
17197 unreachable!();
17198 }
17199 }
17200 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
17201 push_region(start_row, end_row);
17202 results
17203 }
17204
17205 pub fn gutter_highlights_in_range(
17206 &self,
17207 search_range: Range<Anchor>,
17208 display_snapshot: &DisplaySnapshot,
17209 cx: &App,
17210 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
17211 let mut results = Vec::new();
17212 for (color_fetcher, ranges) in self.gutter_highlights.values() {
17213 let color = color_fetcher(cx);
17214 let start_ix = match ranges.binary_search_by(|probe| {
17215 let cmp = probe
17216 .end
17217 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
17218 if cmp.is_gt() {
17219 Ordering::Greater
17220 } else {
17221 Ordering::Less
17222 }
17223 }) {
17224 Ok(i) | Err(i) => i,
17225 };
17226 for range in &ranges[start_ix..] {
17227 if range
17228 .start
17229 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
17230 .is_ge()
17231 {
17232 break;
17233 }
17234
17235 let start = range.start.to_display_point(display_snapshot);
17236 let end = range.end.to_display_point(display_snapshot);
17237 results.push((start..end, color))
17238 }
17239 }
17240 results
17241 }
17242
17243 /// Get the text ranges corresponding to the redaction query
17244 pub fn redacted_ranges(
17245 &self,
17246 search_range: Range<Anchor>,
17247 display_snapshot: &DisplaySnapshot,
17248 cx: &App,
17249 ) -> Vec<Range<DisplayPoint>> {
17250 display_snapshot
17251 .buffer_snapshot
17252 .redacted_ranges(search_range, |file| {
17253 if let Some(file) = file {
17254 file.is_private()
17255 && EditorSettings::get(
17256 Some(SettingsLocation {
17257 worktree_id: file.worktree_id(cx),
17258 path: file.path().as_ref(),
17259 }),
17260 cx,
17261 )
17262 .redact_private_values
17263 } else {
17264 false
17265 }
17266 })
17267 .map(|range| {
17268 range.start.to_display_point(display_snapshot)
17269 ..range.end.to_display_point(display_snapshot)
17270 })
17271 .collect()
17272 }
17273
17274 pub fn highlight_text<T: 'static>(
17275 &mut self,
17276 ranges: Vec<Range<Anchor>>,
17277 style: HighlightStyle,
17278 cx: &mut Context<Self>,
17279 ) {
17280 self.display_map.update(cx, |map, _| {
17281 map.highlight_text(TypeId::of::<T>(), ranges, style)
17282 });
17283 cx.notify();
17284 }
17285
17286 pub(crate) fn highlight_inlays<T: 'static>(
17287 &mut self,
17288 highlights: Vec<InlayHighlight>,
17289 style: HighlightStyle,
17290 cx: &mut Context<Self>,
17291 ) {
17292 self.display_map.update(cx, |map, _| {
17293 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
17294 });
17295 cx.notify();
17296 }
17297
17298 pub fn text_highlights<'a, T: 'static>(
17299 &'a self,
17300 cx: &'a App,
17301 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
17302 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
17303 }
17304
17305 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
17306 let cleared = self
17307 .display_map
17308 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
17309 if cleared {
17310 cx.notify();
17311 }
17312 }
17313
17314 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
17315 (self.read_only(cx) || self.blink_manager.read(cx).visible())
17316 && self.focus_handle.is_focused(window)
17317 }
17318
17319 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
17320 self.show_cursor_when_unfocused = is_enabled;
17321 cx.notify();
17322 }
17323
17324 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
17325 cx.notify();
17326 }
17327
17328 fn on_buffer_event(
17329 &mut self,
17330 multibuffer: &Entity<MultiBuffer>,
17331 event: &multi_buffer::Event,
17332 window: &mut Window,
17333 cx: &mut Context<Self>,
17334 ) {
17335 match event {
17336 multi_buffer::Event::Edited {
17337 singleton_buffer_edited,
17338 edited_buffer: buffer_edited,
17339 } => {
17340 self.scrollbar_marker_state.dirty = true;
17341 self.active_indent_guides_state.dirty = true;
17342 self.refresh_active_diagnostics(cx);
17343 self.refresh_code_actions(window, cx);
17344 if self.has_active_inline_completion() {
17345 self.update_visible_inline_completion(window, cx);
17346 }
17347 if let Some(buffer) = buffer_edited {
17348 let buffer_id = buffer.read(cx).remote_id();
17349 if !self.registered_buffers.contains_key(&buffer_id) {
17350 if let Some(project) = self.project.as_ref() {
17351 project.update(cx, |project, cx| {
17352 self.registered_buffers.insert(
17353 buffer_id,
17354 project.register_buffer_with_language_servers(&buffer, cx),
17355 );
17356 })
17357 }
17358 }
17359 }
17360 cx.emit(EditorEvent::BufferEdited);
17361 cx.emit(SearchEvent::MatchesInvalidated);
17362 if *singleton_buffer_edited {
17363 if let Some(project) = &self.project {
17364 #[allow(clippy::mutable_key_type)]
17365 let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
17366 multibuffer
17367 .all_buffers()
17368 .into_iter()
17369 .filter_map(|buffer| {
17370 buffer.update(cx, |buffer, cx| {
17371 let language = buffer.language()?;
17372 let should_discard = project.update(cx, |project, cx| {
17373 project.is_local()
17374 && !project.has_language_servers_for(buffer, cx)
17375 });
17376 should_discard.not().then_some(language.clone())
17377 })
17378 })
17379 .collect::<HashSet<_>>()
17380 });
17381 if !languages_affected.is_empty() {
17382 self.refresh_inlay_hints(
17383 InlayHintRefreshReason::BufferEdited(languages_affected),
17384 cx,
17385 );
17386 }
17387 }
17388 }
17389
17390 let Some(project) = &self.project else { return };
17391 let (telemetry, is_via_ssh) = {
17392 let project = project.read(cx);
17393 let telemetry = project.client().telemetry().clone();
17394 let is_via_ssh = project.is_via_ssh();
17395 (telemetry, is_via_ssh)
17396 };
17397 refresh_linked_ranges(self, window, cx);
17398 telemetry.log_edit_event("editor", is_via_ssh);
17399 }
17400 multi_buffer::Event::ExcerptsAdded {
17401 buffer,
17402 predecessor,
17403 excerpts,
17404 } => {
17405 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17406 let buffer_id = buffer.read(cx).remote_id();
17407 if self.buffer.read(cx).diff_for(buffer_id).is_none() {
17408 if let Some(project) = &self.project {
17409 get_uncommitted_diff_for_buffer(
17410 project,
17411 [buffer.clone()],
17412 self.buffer.clone(),
17413 cx,
17414 )
17415 .detach();
17416 }
17417 }
17418 cx.emit(EditorEvent::ExcerptsAdded {
17419 buffer: buffer.clone(),
17420 predecessor: *predecessor,
17421 excerpts: excerpts.clone(),
17422 });
17423 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17424 }
17425 multi_buffer::Event::ExcerptsRemoved { ids } => {
17426 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
17427 let buffer = self.buffer.read(cx);
17428 self.registered_buffers
17429 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
17430 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17431 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
17432 }
17433 multi_buffer::Event::ExcerptsEdited {
17434 excerpt_ids,
17435 buffer_ids,
17436 } => {
17437 self.display_map.update(cx, |map, cx| {
17438 map.unfold_buffers(buffer_ids.iter().copied(), cx)
17439 });
17440 cx.emit(EditorEvent::ExcerptsEdited {
17441 ids: excerpt_ids.clone(),
17442 })
17443 }
17444 multi_buffer::Event::ExcerptsExpanded { ids } => {
17445 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
17446 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
17447 }
17448 multi_buffer::Event::Reparsed(buffer_id) => {
17449 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17450 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17451
17452 cx.emit(EditorEvent::Reparsed(*buffer_id));
17453 }
17454 multi_buffer::Event::DiffHunksToggled => {
17455 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17456 }
17457 multi_buffer::Event::LanguageChanged(buffer_id) => {
17458 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
17459 jsx_tag_auto_close::refresh_enabled_in_any_buffer(self, multibuffer, cx);
17460 cx.emit(EditorEvent::Reparsed(*buffer_id));
17461 cx.notify();
17462 }
17463 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
17464 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
17465 multi_buffer::Event::FileHandleChanged
17466 | multi_buffer::Event::Reloaded
17467 | multi_buffer::Event::BufferDiffChanged => cx.emit(EditorEvent::TitleChanged),
17468 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
17469 multi_buffer::Event::DiagnosticsUpdated => {
17470 self.refresh_active_diagnostics(cx);
17471 self.refresh_inline_diagnostics(true, window, cx);
17472 self.scrollbar_marker_state.dirty = true;
17473 cx.notify();
17474 }
17475 _ => {}
17476 };
17477 }
17478
17479 fn on_display_map_changed(
17480 &mut self,
17481 _: Entity<DisplayMap>,
17482 _: &mut Window,
17483 cx: &mut Context<Self>,
17484 ) {
17485 cx.notify();
17486 }
17487
17488 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
17489 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
17490 self.update_edit_prediction_settings(cx);
17491 self.refresh_inline_completion(true, false, window, cx);
17492 self.refresh_inlay_hints(
17493 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
17494 self.selections.newest_anchor().head(),
17495 &self.buffer.read(cx).snapshot(cx),
17496 cx,
17497 )),
17498 cx,
17499 );
17500
17501 let old_cursor_shape = self.cursor_shape;
17502
17503 {
17504 let editor_settings = EditorSettings::get_global(cx);
17505 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
17506 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
17507 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
17508 self.hide_mouse_mode = editor_settings.hide_mouse.unwrap_or_default();
17509 }
17510
17511 if old_cursor_shape != self.cursor_shape {
17512 cx.emit(EditorEvent::CursorShapeChanged);
17513 }
17514
17515 let project_settings = ProjectSettings::get_global(cx);
17516 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
17517
17518 if self.mode.is_full() {
17519 let show_inline_diagnostics = project_settings.diagnostics.inline.enabled;
17520 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
17521 if self.show_inline_diagnostics != show_inline_diagnostics {
17522 self.show_inline_diagnostics = show_inline_diagnostics;
17523 self.refresh_inline_diagnostics(false, window, cx);
17524 }
17525
17526 if self.git_blame_inline_enabled != inline_blame_enabled {
17527 self.toggle_git_blame_inline_internal(false, window, cx);
17528 }
17529 }
17530
17531 cx.notify();
17532 }
17533
17534 pub fn set_searchable(&mut self, searchable: bool) {
17535 self.searchable = searchable;
17536 }
17537
17538 pub fn searchable(&self) -> bool {
17539 self.searchable
17540 }
17541
17542 fn open_proposed_changes_editor(
17543 &mut self,
17544 _: &OpenProposedChangesEditor,
17545 window: &mut Window,
17546 cx: &mut Context<Self>,
17547 ) {
17548 let Some(workspace) = self.workspace() else {
17549 cx.propagate();
17550 return;
17551 };
17552
17553 let selections = self.selections.all::<usize>(cx);
17554 let multi_buffer = self.buffer.read(cx);
17555 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
17556 let mut new_selections_by_buffer = HashMap::default();
17557 for selection in selections {
17558 for (buffer, range, _) in
17559 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
17560 {
17561 let mut range = range.to_point(buffer);
17562 range.start.column = 0;
17563 range.end.column = buffer.line_len(range.end.row);
17564 new_selections_by_buffer
17565 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
17566 .or_insert(Vec::new())
17567 .push(range)
17568 }
17569 }
17570
17571 let proposed_changes_buffers = new_selections_by_buffer
17572 .into_iter()
17573 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
17574 .collect::<Vec<_>>();
17575 let proposed_changes_editor = cx.new(|cx| {
17576 ProposedChangesEditor::new(
17577 "Proposed changes",
17578 proposed_changes_buffers,
17579 self.project.clone(),
17580 window,
17581 cx,
17582 )
17583 });
17584
17585 window.defer(cx, move |window, cx| {
17586 workspace.update(cx, |workspace, cx| {
17587 workspace.active_pane().update(cx, |pane, cx| {
17588 pane.add_item(
17589 Box::new(proposed_changes_editor),
17590 true,
17591 true,
17592 None,
17593 window,
17594 cx,
17595 );
17596 });
17597 });
17598 });
17599 }
17600
17601 pub fn open_excerpts_in_split(
17602 &mut self,
17603 _: &OpenExcerptsSplit,
17604 window: &mut Window,
17605 cx: &mut Context<Self>,
17606 ) {
17607 self.open_excerpts_common(None, true, window, cx)
17608 }
17609
17610 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
17611 self.open_excerpts_common(None, false, window, cx)
17612 }
17613
17614 fn open_excerpts_common(
17615 &mut self,
17616 jump_data: Option<JumpData>,
17617 split: bool,
17618 window: &mut Window,
17619 cx: &mut Context<Self>,
17620 ) {
17621 let Some(workspace) = self.workspace() else {
17622 cx.propagate();
17623 return;
17624 };
17625
17626 if self.buffer.read(cx).is_singleton() {
17627 cx.propagate();
17628 return;
17629 }
17630
17631 let mut new_selections_by_buffer = HashMap::default();
17632 match &jump_data {
17633 Some(JumpData::MultiBufferPoint {
17634 excerpt_id,
17635 position,
17636 anchor,
17637 line_offset_from_top,
17638 }) => {
17639 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
17640 if let Some(buffer) = multi_buffer_snapshot
17641 .buffer_id_for_excerpt(*excerpt_id)
17642 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
17643 {
17644 let buffer_snapshot = buffer.read(cx).snapshot();
17645 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
17646 language::ToPoint::to_point(anchor, &buffer_snapshot)
17647 } else {
17648 buffer_snapshot.clip_point(*position, Bias::Left)
17649 };
17650 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
17651 new_selections_by_buffer.insert(
17652 buffer,
17653 (
17654 vec![jump_to_offset..jump_to_offset],
17655 Some(*line_offset_from_top),
17656 ),
17657 );
17658 }
17659 }
17660 Some(JumpData::MultiBufferRow {
17661 row,
17662 line_offset_from_top,
17663 }) => {
17664 let point = MultiBufferPoint::new(row.0, 0);
17665 if let Some((buffer, buffer_point, _)) =
17666 self.buffer.read(cx).point_to_buffer_point(point, cx)
17667 {
17668 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
17669 new_selections_by_buffer
17670 .entry(buffer)
17671 .or_insert((Vec::new(), Some(*line_offset_from_top)))
17672 .0
17673 .push(buffer_offset..buffer_offset)
17674 }
17675 }
17676 None => {
17677 let selections = self.selections.all::<usize>(cx);
17678 let multi_buffer = self.buffer.read(cx);
17679 for selection in selections {
17680 for (snapshot, range, _, anchor) in multi_buffer
17681 .snapshot(cx)
17682 .range_to_buffer_ranges_with_deleted_hunks(selection.range())
17683 {
17684 if let Some(anchor) = anchor {
17685 // selection is in a deleted hunk
17686 let Some(buffer_id) = anchor.buffer_id else {
17687 continue;
17688 };
17689 let Some(buffer_handle) = multi_buffer.buffer(buffer_id) else {
17690 continue;
17691 };
17692 let offset = text::ToOffset::to_offset(
17693 &anchor.text_anchor,
17694 &buffer_handle.read(cx).snapshot(),
17695 );
17696 let range = offset..offset;
17697 new_selections_by_buffer
17698 .entry(buffer_handle)
17699 .or_insert((Vec::new(), None))
17700 .0
17701 .push(range)
17702 } else {
17703 let Some(buffer_handle) = multi_buffer.buffer(snapshot.remote_id())
17704 else {
17705 continue;
17706 };
17707 new_selections_by_buffer
17708 .entry(buffer_handle)
17709 .or_insert((Vec::new(), None))
17710 .0
17711 .push(range)
17712 }
17713 }
17714 }
17715 }
17716 }
17717
17718 new_selections_by_buffer
17719 .retain(|buffer, _| Self::can_open_excerpts_in_file(buffer.read(cx).file()));
17720
17721 if new_selections_by_buffer.is_empty() {
17722 return;
17723 }
17724
17725 // We defer the pane interaction because we ourselves are a workspace item
17726 // and activating a new item causes the pane to call a method on us reentrantly,
17727 // which panics if we're on the stack.
17728 window.defer(cx, move |window, cx| {
17729 workspace.update(cx, |workspace, cx| {
17730 let pane = if split {
17731 workspace.adjacent_pane(window, cx)
17732 } else {
17733 workspace.active_pane().clone()
17734 };
17735
17736 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
17737 let editor = buffer
17738 .read(cx)
17739 .file()
17740 .is_none()
17741 .then(|| {
17742 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
17743 // so `workspace.open_project_item` will never find them, always opening a new editor.
17744 // Instead, we try to activate the existing editor in the pane first.
17745 let (editor, pane_item_index) =
17746 pane.read(cx).items().enumerate().find_map(|(i, item)| {
17747 let editor = item.downcast::<Editor>()?;
17748 let singleton_buffer =
17749 editor.read(cx).buffer().read(cx).as_singleton()?;
17750 if singleton_buffer == buffer {
17751 Some((editor, i))
17752 } else {
17753 None
17754 }
17755 })?;
17756 pane.update(cx, |pane, cx| {
17757 pane.activate_item(pane_item_index, true, true, window, cx)
17758 });
17759 Some(editor)
17760 })
17761 .flatten()
17762 .unwrap_or_else(|| {
17763 workspace.open_project_item::<Self>(
17764 pane.clone(),
17765 buffer,
17766 true,
17767 true,
17768 window,
17769 cx,
17770 )
17771 });
17772
17773 editor.update(cx, |editor, cx| {
17774 let autoscroll = match scroll_offset {
17775 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
17776 None => Autoscroll::newest(),
17777 };
17778 let nav_history = editor.nav_history.take();
17779 editor.change_selections(Some(autoscroll), window, cx, |s| {
17780 s.select_ranges(ranges);
17781 });
17782 editor.nav_history = nav_history;
17783 });
17784 }
17785 })
17786 });
17787 }
17788
17789 // For now, don't allow opening excerpts in buffers that aren't backed by
17790 // regular project files.
17791 fn can_open_excerpts_in_file(file: Option<&Arc<dyn language::File>>) -> bool {
17792 file.map_or(true, |file| project::File::from_dyn(Some(file)).is_some())
17793 }
17794
17795 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
17796 let snapshot = self.buffer.read(cx).read(cx);
17797 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
17798 Some(
17799 ranges
17800 .iter()
17801 .map(move |range| {
17802 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
17803 })
17804 .collect(),
17805 )
17806 }
17807
17808 fn selection_replacement_ranges(
17809 &self,
17810 range: Range<OffsetUtf16>,
17811 cx: &mut App,
17812 ) -> Vec<Range<OffsetUtf16>> {
17813 let selections = self.selections.all::<OffsetUtf16>(cx);
17814 let newest_selection = selections
17815 .iter()
17816 .max_by_key(|selection| selection.id)
17817 .unwrap();
17818 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
17819 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
17820 let snapshot = self.buffer.read(cx).read(cx);
17821 selections
17822 .into_iter()
17823 .map(|mut selection| {
17824 selection.start.0 =
17825 (selection.start.0 as isize).saturating_add(start_delta) as usize;
17826 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
17827 snapshot.clip_offset_utf16(selection.start, Bias::Left)
17828 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
17829 })
17830 .collect()
17831 }
17832
17833 fn report_editor_event(
17834 &self,
17835 event_type: &'static str,
17836 file_extension: Option<String>,
17837 cx: &App,
17838 ) {
17839 if cfg!(any(test, feature = "test-support")) {
17840 return;
17841 }
17842
17843 let Some(project) = &self.project else { return };
17844
17845 // If None, we are in a file without an extension
17846 let file = self
17847 .buffer
17848 .read(cx)
17849 .as_singleton()
17850 .and_then(|b| b.read(cx).file());
17851 let file_extension = file_extension.or(file
17852 .as_ref()
17853 .and_then(|file| Path::new(file.file_name(cx)).extension())
17854 .and_then(|e| e.to_str())
17855 .map(|a| a.to_string()));
17856
17857 let vim_mode = vim_enabled(cx);
17858
17859 let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
17860 let copilot_enabled = edit_predictions_provider
17861 == language::language_settings::EditPredictionProvider::Copilot;
17862 let copilot_enabled_for_language = self
17863 .buffer
17864 .read(cx)
17865 .language_settings(cx)
17866 .show_edit_predictions;
17867
17868 let project = project.read(cx);
17869 telemetry::event!(
17870 event_type,
17871 file_extension,
17872 vim_mode,
17873 copilot_enabled,
17874 copilot_enabled_for_language,
17875 edit_predictions_provider,
17876 is_via_ssh = project.is_via_ssh(),
17877 );
17878 }
17879
17880 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
17881 /// with each line being an array of {text, highlight} objects.
17882 fn copy_highlight_json(
17883 &mut self,
17884 _: &CopyHighlightJson,
17885 window: &mut Window,
17886 cx: &mut Context<Self>,
17887 ) {
17888 #[derive(Serialize)]
17889 struct Chunk<'a> {
17890 text: String,
17891 highlight: Option<&'a str>,
17892 }
17893
17894 let snapshot = self.buffer.read(cx).snapshot(cx);
17895 let range = self
17896 .selected_text_range(false, window, cx)
17897 .and_then(|selection| {
17898 if selection.range.is_empty() {
17899 None
17900 } else {
17901 Some(selection.range)
17902 }
17903 })
17904 .unwrap_or_else(|| 0..snapshot.len());
17905
17906 let chunks = snapshot.chunks(range, true);
17907 let mut lines = Vec::new();
17908 let mut line: VecDeque<Chunk> = VecDeque::new();
17909
17910 let Some(style) = self.style.as_ref() else {
17911 return;
17912 };
17913
17914 for chunk in chunks {
17915 let highlight = chunk
17916 .syntax_highlight_id
17917 .and_then(|id| id.name(&style.syntax));
17918 let mut chunk_lines = chunk.text.split('\n').peekable();
17919 while let Some(text) = chunk_lines.next() {
17920 let mut merged_with_last_token = false;
17921 if let Some(last_token) = line.back_mut() {
17922 if last_token.highlight == highlight {
17923 last_token.text.push_str(text);
17924 merged_with_last_token = true;
17925 }
17926 }
17927
17928 if !merged_with_last_token {
17929 line.push_back(Chunk {
17930 text: text.into(),
17931 highlight,
17932 });
17933 }
17934
17935 if chunk_lines.peek().is_some() {
17936 if line.len() > 1 && line.front().unwrap().text.is_empty() {
17937 line.pop_front();
17938 }
17939 if line.len() > 1 && line.back().unwrap().text.is_empty() {
17940 line.pop_back();
17941 }
17942
17943 lines.push(mem::take(&mut line));
17944 }
17945 }
17946 }
17947
17948 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
17949 return;
17950 };
17951 cx.write_to_clipboard(ClipboardItem::new_string(lines));
17952 }
17953
17954 pub fn open_context_menu(
17955 &mut self,
17956 _: &OpenContextMenu,
17957 window: &mut Window,
17958 cx: &mut Context<Self>,
17959 ) {
17960 self.request_autoscroll(Autoscroll::newest(), cx);
17961 let position = self.selections.newest_display(cx).start;
17962 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
17963 }
17964
17965 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
17966 &self.inlay_hint_cache
17967 }
17968
17969 pub fn replay_insert_event(
17970 &mut self,
17971 text: &str,
17972 relative_utf16_range: Option<Range<isize>>,
17973 window: &mut Window,
17974 cx: &mut Context<Self>,
17975 ) {
17976 if !self.input_enabled {
17977 cx.emit(EditorEvent::InputIgnored { text: text.into() });
17978 return;
17979 }
17980 if let Some(relative_utf16_range) = relative_utf16_range {
17981 let selections = self.selections.all::<OffsetUtf16>(cx);
17982 self.change_selections(None, window, cx, |s| {
17983 let new_ranges = selections.into_iter().map(|range| {
17984 let start = OffsetUtf16(
17985 range
17986 .head()
17987 .0
17988 .saturating_add_signed(relative_utf16_range.start),
17989 );
17990 let end = OffsetUtf16(
17991 range
17992 .head()
17993 .0
17994 .saturating_add_signed(relative_utf16_range.end),
17995 );
17996 start..end
17997 });
17998 s.select_ranges(new_ranges);
17999 });
18000 }
18001
18002 self.handle_input(text, window, cx);
18003 }
18004
18005 pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
18006 let Some(provider) = self.semantics_provider.as_ref() else {
18007 return false;
18008 };
18009
18010 let mut supports = false;
18011 self.buffer().update(cx, |this, cx| {
18012 this.for_each_buffer(|buffer| {
18013 supports |= provider.supports_inlay_hints(buffer, cx);
18014 });
18015 });
18016
18017 supports
18018 }
18019
18020 pub fn is_focused(&self, window: &Window) -> bool {
18021 self.focus_handle.is_focused(window)
18022 }
18023
18024 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18025 cx.emit(EditorEvent::Focused);
18026
18027 if let Some(descendant) = self
18028 .last_focused_descendant
18029 .take()
18030 .and_then(|descendant| descendant.upgrade())
18031 {
18032 window.focus(&descendant);
18033 } else {
18034 if let Some(blame) = self.blame.as_ref() {
18035 blame.update(cx, GitBlame::focus)
18036 }
18037
18038 self.blink_manager.update(cx, BlinkManager::enable);
18039 self.show_cursor_names(window, cx);
18040 self.buffer.update(cx, |buffer, cx| {
18041 buffer.finalize_last_transaction(cx);
18042 if self.leader_peer_id.is_none() {
18043 buffer.set_active_selections(
18044 &self.selections.disjoint_anchors(),
18045 self.selections.line_mode,
18046 self.cursor_shape,
18047 cx,
18048 );
18049 }
18050 });
18051 }
18052 }
18053
18054 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
18055 cx.emit(EditorEvent::FocusedIn)
18056 }
18057
18058 fn handle_focus_out(
18059 &mut self,
18060 event: FocusOutEvent,
18061 _window: &mut Window,
18062 cx: &mut Context<Self>,
18063 ) {
18064 if event.blurred != self.focus_handle {
18065 self.last_focused_descendant = Some(event.blurred);
18066 }
18067 self.refresh_inlay_hints(InlayHintRefreshReason::ModifiersChanged(false), cx);
18068 }
18069
18070 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
18071 self.blink_manager.update(cx, BlinkManager::disable);
18072 self.buffer
18073 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
18074
18075 if let Some(blame) = self.blame.as_ref() {
18076 blame.update(cx, GitBlame::blur)
18077 }
18078 if !self.hover_state.focused(window, cx) {
18079 hide_hover(self, cx);
18080 }
18081 if !self
18082 .context_menu
18083 .borrow()
18084 .as_ref()
18085 .is_some_and(|context_menu| context_menu.focused(window, cx))
18086 {
18087 self.hide_context_menu(window, cx);
18088 }
18089 self.discard_inline_completion(false, cx);
18090 cx.emit(EditorEvent::Blurred);
18091 cx.notify();
18092 }
18093
18094 pub fn register_action<A: Action>(
18095 &mut self,
18096 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
18097 ) -> Subscription {
18098 let id = self.next_editor_action_id.post_inc();
18099 let listener = Arc::new(listener);
18100 self.editor_actions.borrow_mut().insert(
18101 id,
18102 Box::new(move |window, _| {
18103 let listener = listener.clone();
18104 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
18105 let action = action.downcast_ref().unwrap();
18106 if phase == DispatchPhase::Bubble {
18107 listener(action, window, cx)
18108 }
18109 })
18110 }),
18111 );
18112
18113 let editor_actions = self.editor_actions.clone();
18114 Subscription::new(move || {
18115 editor_actions.borrow_mut().remove(&id);
18116 })
18117 }
18118
18119 pub fn file_header_size(&self) -> u32 {
18120 FILE_HEADER_HEIGHT
18121 }
18122
18123 pub fn restore(
18124 &mut self,
18125 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
18126 window: &mut Window,
18127 cx: &mut Context<Self>,
18128 ) {
18129 let workspace = self.workspace();
18130 let project = self.project.as_ref();
18131 let save_tasks = self.buffer().update(cx, |multi_buffer, cx| {
18132 let mut tasks = Vec::new();
18133 for (buffer_id, changes) in revert_changes {
18134 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
18135 buffer.update(cx, |buffer, cx| {
18136 buffer.edit(
18137 changes
18138 .into_iter()
18139 .map(|(range, text)| (range, text.to_string())),
18140 None,
18141 cx,
18142 );
18143 });
18144
18145 if let Some(project) =
18146 project.filter(|_| multi_buffer.all_diff_hunks_expanded())
18147 {
18148 project.update(cx, |project, cx| {
18149 tasks.push((buffer.clone(), project.save_buffer(buffer, cx)));
18150 })
18151 }
18152 }
18153 }
18154 tasks
18155 });
18156 cx.spawn_in(window, async move |_, cx| {
18157 for (buffer, task) in save_tasks {
18158 let result = task.await;
18159 if result.is_err() {
18160 let Some(path) = buffer
18161 .read_with(cx, |buffer, cx| buffer.project_path(cx))
18162 .ok()
18163 else {
18164 continue;
18165 };
18166 if let Some((workspace, path)) = workspace.as_ref().zip(path) {
18167 let Some(task) = cx
18168 .update_window_entity(&workspace, |workspace, window, cx| {
18169 workspace
18170 .open_path_preview(path, None, false, false, false, window, cx)
18171 })
18172 .ok()
18173 else {
18174 continue;
18175 };
18176 task.await.log_err();
18177 }
18178 }
18179 }
18180 })
18181 .detach();
18182 self.change_selections(None, window, cx, |selections| selections.refresh());
18183 }
18184
18185 pub fn to_pixel_point(
18186 &self,
18187 source: multi_buffer::Anchor,
18188 editor_snapshot: &EditorSnapshot,
18189 window: &mut Window,
18190 ) -> Option<gpui::Point<Pixels>> {
18191 let source_point = source.to_display_point(editor_snapshot);
18192 self.display_to_pixel_point(source_point, editor_snapshot, window)
18193 }
18194
18195 pub fn display_to_pixel_point(
18196 &self,
18197 source: DisplayPoint,
18198 editor_snapshot: &EditorSnapshot,
18199 window: &mut Window,
18200 ) -> Option<gpui::Point<Pixels>> {
18201 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
18202 let text_layout_details = self.text_layout_details(window);
18203 let scroll_top = text_layout_details
18204 .scroll_anchor
18205 .scroll_position(editor_snapshot)
18206 .y;
18207
18208 if source.row().as_f32() < scroll_top.floor() {
18209 return None;
18210 }
18211 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
18212 let source_y = line_height * (source.row().as_f32() - scroll_top);
18213 Some(gpui::Point::new(source_x, source_y))
18214 }
18215
18216 pub fn has_visible_completions_menu(&self) -> bool {
18217 !self.edit_prediction_preview_is_active()
18218 && self.context_menu.borrow().as_ref().map_or(false, |menu| {
18219 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
18220 })
18221 }
18222
18223 pub fn register_addon<T: Addon>(&mut self, instance: T) {
18224 self.addons
18225 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
18226 }
18227
18228 pub fn unregister_addon<T: Addon>(&mut self) {
18229 self.addons.remove(&std::any::TypeId::of::<T>());
18230 }
18231
18232 pub fn addon<T: Addon>(&self) -> Option<&T> {
18233 let type_id = std::any::TypeId::of::<T>();
18234 self.addons
18235 .get(&type_id)
18236 .and_then(|item| item.to_any().downcast_ref::<T>())
18237 }
18238
18239 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
18240 let text_layout_details = self.text_layout_details(window);
18241 let style = &text_layout_details.editor_style;
18242 let font_id = window.text_system().resolve_font(&style.text.font());
18243 let font_size = style.text.font_size.to_pixels(window.rem_size());
18244 let line_height = style.text.line_height_in_pixels(window.rem_size());
18245 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
18246
18247 gpui::Size::new(em_width, line_height)
18248 }
18249
18250 pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
18251 self.load_diff_task.clone()
18252 }
18253
18254 fn read_metadata_from_db(
18255 &mut self,
18256 item_id: u64,
18257 workspace_id: WorkspaceId,
18258 window: &mut Window,
18259 cx: &mut Context<Editor>,
18260 ) {
18261 if self.is_singleton(cx)
18262 && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
18263 {
18264 let buffer_snapshot = OnceCell::new();
18265
18266 if let Some(folds) = DB.get_editor_folds(item_id, workspace_id).log_err() {
18267 if !folds.is_empty() {
18268 let snapshot =
18269 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18270 self.fold_ranges(
18271 folds
18272 .into_iter()
18273 .map(|(start, end)| {
18274 snapshot.clip_offset(start, Bias::Left)
18275 ..snapshot.clip_offset(end, Bias::Right)
18276 })
18277 .collect(),
18278 false,
18279 window,
18280 cx,
18281 );
18282 }
18283 }
18284
18285 if let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() {
18286 if !selections.is_empty() {
18287 let snapshot =
18288 buffer_snapshot.get_or_init(|| self.buffer.read(cx).snapshot(cx));
18289 self.change_selections(None, window, cx, |s| {
18290 s.select_ranges(selections.into_iter().map(|(start, end)| {
18291 snapshot.clip_offset(start, Bias::Left)
18292 ..snapshot.clip_offset(end, Bias::Right)
18293 }));
18294 });
18295 }
18296 };
18297 }
18298
18299 self.read_scroll_position_from_db(item_id, workspace_id, window, cx);
18300 }
18301}
18302
18303fn vim_enabled(cx: &App) -> bool {
18304 cx.global::<SettingsStore>()
18305 .raw_user_settings()
18306 .get("vim_mode")
18307 == Some(&serde_json::Value::Bool(true))
18308}
18309
18310// Consider user intent and default settings
18311fn choose_completion_range(
18312 completion: &Completion,
18313 intent: CompletionIntent,
18314 buffer: &Entity<Buffer>,
18315 cx: &mut Context<Editor>,
18316) -> Range<usize> {
18317 fn should_replace(
18318 completion: &Completion,
18319 insert_range: &Range<text::Anchor>,
18320 intent: CompletionIntent,
18321 completion_mode_setting: LspInsertMode,
18322 buffer: &Buffer,
18323 ) -> bool {
18324 // specific actions take precedence over settings
18325 match intent {
18326 CompletionIntent::CompleteWithInsert => return false,
18327 CompletionIntent::CompleteWithReplace => return true,
18328 CompletionIntent::Complete | CompletionIntent::Compose => {}
18329 }
18330
18331 match completion_mode_setting {
18332 LspInsertMode::Insert => false,
18333 LspInsertMode::Replace => true,
18334 LspInsertMode::ReplaceSubsequence => {
18335 let mut text_to_replace = buffer.chars_for_range(
18336 buffer.anchor_before(completion.replace_range.start)
18337 ..buffer.anchor_after(completion.replace_range.end),
18338 );
18339 let mut completion_text = completion.new_text.chars();
18340
18341 // is `text_to_replace` a subsequence of `completion_text`
18342 text_to_replace
18343 .all(|needle_ch| completion_text.any(|haystack_ch| haystack_ch == needle_ch))
18344 }
18345 LspInsertMode::ReplaceSuffix => {
18346 let range_after_cursor = insert_range.end..completion.replace_range.end;
18347
18348 let text_after_cursor = buffer
18349 .text_for_range(
18350 buffer.anchor_before(range_after_cursor.start)
18351 ..buffer.anchor_after(range_after_cursor.end),
18352 )
18353 .collect::<String>();
18354 completion.new_text.ends_with(&text_after_cursor)
18355 }
18356 }
18357 }
18358
18359 let buffer = buffer.read(cx);
18360
18361 if let CompletionSource::Lsp {
18362 insert_range: Some(insert_range),
18363 ..
18364 } = &completion.source
18365 {
18366 let completion_mode_setting =
18367 language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx)
18368 .completions
18369 .lsp_insert_mode;
18370
18371 if !should_replace(
18372 completion,
18373 &insert_range,
18374 intent,
18375 completion_mode_setting,
18376 buffer,
18377 ) {
18378 return insert_range.to_offset(buffer);
18379 }
18380 }
18381
18382 completion.replace_range.to_offset(buffer)
18383}
18384
18385fn insert_extra_newline_brackets(
18386 buffer: &MultiBufferSnapshot,
18387 range: Range<usize>,
18388 language: &language::LanguageScope,
18389) -> bool {
18390 let leading_whitespace_len = buffer
18391 .reversed_chars_at(range.start)
18392 .take_while(|c| c.is_whitespace() && *c != '\n')
18393 .map(|c| c.len_utf8())
18394 .sum::<usize>();
18395 let trailing_whitespace_len = buffer
18396 .chars_at(range.end)
18397 .take_while(|c| c.is_whitespace() && *c != '\n')
18398 .map(|c| c.len_utf8())
18399 .sum::<usize>();
18400 let range = range.start - leading_whitespace_len..range.end + trailing_whitespace_len;
18401
18402 language.brackets().any(|(pair, enabled)| {
18403 let pair_start = pair.start.trim_end();
18404 let pair_end = pair.end.trim_start();
18405
18406 enabled
18407 && pair.newline
18408 && buffer.contains_str_at(range.end, pair_end)
18409 && buffer.contains_str_at(range.start.saturating_sub(pair_start.len()), pair_start)
18410 })
18411}
18412
18413fn insert_extra_newline_tree_sitter(buffer: &MultiBufferSnapshot, range: Range<usize>) -> bool {
18414 let (buffer, range) = match buffer.range_to_buffer_ranges(range).as_slice() {
18415 [(buffer, range, _)] => (*buffer, range.clone()),
18416 _ => return false,
18417 };
18418 let pair = {
18419 let mut result: Option<BracketMatch> = None;
18420
18421 for pair in buffer
18422 .all_bracket_ranges(range.clone())
18423 .filter(move |pair| {
18424 pair.open_range.start <= range.start && pair.close_range.end >= range.end
18425 })
18426 {
18427 let len = pair.close_range.end - pair.open_range.start;
18428
18429 if let Some(existing) = &result {
18430 let existing_len = existing.close_range.end - existing.open_range.start;
18431 if len > existing_len {
18432 continue;
18433 }
18434 }
18435
18436 result = Some(pair);
18437 }
18438
18439 result
18440 };
18441 let Some(pair) = pair else {
18442 return false;
18443 };
18444 pair.newline_only
18445 && buffer
18446 .chars_for_range(pair.open_range.end..range.start)
18447 .chain(buffer.chars_for_range(range.end..pair.close_range.start))
18448 .all(|c| c.is_whitespace() && c != '\n')
18449}
18450
18451fn get_uncommitted_diff_for_buffer(
18452 project: &Entity<Project>,
18453 buffers: impl IntoIterator<Item = Entity<Buffer>>,
18454 buffer: Entity<MultiBuffer>,
18455 cx: &mut App,
18456) -> Task<()> {
18457 let mut tasks = Vec::new();
18458 project.update(cx, |project, cx| {
18459 for buffer in buffers {
18460 if project::File::from_dyn(buffer.read(cx).file()).is_some() {
18461 tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
18462 }
18463 }
18464 });
18465 cx.spawn(async move |cx| {
18466 let diffs = future::join_all(tasks).await;
18467 buffer
18468 .update(cx, |buffer, cx| {
18469 for diff in diffs.into_iter().flatten() {
18470 buffer.add_diff(diff, cx);
18471 }
18472 })
18473 .ok();
18474 })
18475}
18476
18477fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
18478 let tab_size = tab_size.get() as usize;
18479 let mut width = offset;
18480
18481 for ch in text.chars() {
18482 width += if ch == '\t' {
18483 tab_size - (width % tab_size)
18484 } else {
18485 1
18486 };
18487 }
18488
18489 width - offset
18490}
18491
18492#[cfg(test)]
18493mod tests {
18494 use super::*;
18495
18496 #[test]
18497 fn test_string_size_with_expanded_tabs() {
18498 let nz = |val| NonZeroU32::new(val).unwrap();
18499 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
18500 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
18501 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
18502 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
18503 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
18504 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
18505 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
18506 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
18507 }
18508}
18509
18510/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
18511struct WordBreakingTokenizer<'a> {
18512 input: &'a str,
18513}
18514
18515impl<'a> WordBreakingTokenizer<'a> {
18516 fn new(input: &'a str) -> Self {
18517 Self { input }
18518 }
18519}
18520
18521fn is_char_ideographic(ch: char) -> bool {
18522 use unicode_script::Script::*;
18523 use unicode_script::UnicodeScript;
18524 matches!(ch.script(), Han | Tangut | Yi)
18525}
18526
18527fn is_grapheme_ideographic(text: &str) -> bool {
18528 text.chars().any(is_char_ideographic)
18529}
18530
18531fn is_grapheme_whitespace(text: &str) -> bool {
18532 text.chars().any(|x| x.is_whitespace())
18533}
18534
18535fn should_stay_with_preceding_ideograph(text: &str) -> bool {
18536 text.chars().next().map_or(false, |ch| {
18537 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
18538 })
18539}
18540
18541#[derive(PartialEq, Eq, Debug, Clone, Copy)]
18542enum WordBreakToken<'a> {
18543 Word { token: &'a str, grapheme_len: usize },
18544 InlineWhitespace { token: &'a str, grapheme_len: usize },
18545 Newline,
18546}
18547
18548impl<'a> Iterator for WordBreakingTokenizer<'a> {
18549 /// Yields a span, the count of graphemes in the token, and whether it was
18550 /// whitespace. Note that it also breaks at word boundaries.
18551 type Item = WordBreakToken<'a>;
18552
18553 fn next(&mut self) -> Option<Self::Item> {
18554 use unicode_segmentation::UnicodeSegmentation;
18555 if self.input.is_empty() {
18556 return None;
18557 }
18558
18559 let mut iter = self.input.graphemes(true).peekable();
18560 let mut offset = 0;
18561 let mut grapheme_len = 0;
18562 if let Some(first_grapheme) = iter.next() {
18563 let is_newline = first_grapheme == "\n";
18564 let is_whitespace = is_grapheme_whitespace(first_grapheme);
18565 offset += first_grapheme.len();
18566 grapheme_len += 1;
18567 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
18568 if let Some(grapheme) = iter.peek().copied() {
18569 if should_stay_with_preceding_ideograph(grapheme) {
18570 offset += grapheme.len();
18571 grapheme_len += 1;
18572 }
18573 }
18574 } else {
18575 let mut words = self.input[offset..].split_word_bound_indices().peekable();
18576 let mut next_word_bound = words.peek().copied();
18577 if next_word_bound.map_or(false, |(i, _)| i == 0) {
18578 next_word_bound = words.next();
18579 }
18580 while let Some(grapheme) = iter.peek().copied() {
18581 if next_word_bound.map_or(false, |(i, _)| i == offset) {
18582 break;
18583 };
18584 if is_grapheme_whitespace(grapheme) != is_whitespace
18585 || (grapheme == "\n") != is_newline
18586 {
18587 break;
18588 };
18589 offset += grapheme.len();
18590 grapheme_len += 1;
18591 iter.next();
18592 }
18593 }
18594 let token = &self.input[..offset];
18595 self.input = &self.input[offset..];
18596 if token == "\n" {
18597 Some(WordBreakToken::Newline)
18598 } else if is_whitespace {
18599 Some(WordBreakToken::InlineWhitespace {
18600 token,
18601 grapheme_len,
18602 })
18603 } else {
18604 Some(WordBreakToken::Word {
18605 token,
18606 grapheme_len,
18607 })
18608 }
18609 } else {
18610 None
18611 }
18612 }
18613}
18614
18615#[test]
18616fn test_word_breaking_tokenizer() {
18617 let tests: &[(&str, &[WordBreakToken<'static>])] = &[
18618 ("", &[]),
18619 (" ", &[whitespace(" ", 2)]),
18620 ("Ʒ", &[word("Ʒ", 1)]),
18621 ("Ǽ", &[word("Ǽ", 1)]),
18622 ("⋑", &[word("⋑", 1)]),
18623 ("⋑⋑", &[word("⋑⋑", 2)]),
18624 (
18625 "原理,进而",
18626 &[word("原", 1), word("理,", 2), word("进", 1), word("而", 1)],
18627 ),
18628 (
18629 "hello world",
18630 &[word("hello", 5), whitespace(" ", 1), word("world", 5)],
18631 ),
18632 (
18633 "hello, world",
18634 &[word("hello,", 6), whitespace(" ", 1), word("world", 5)],
18635 ),
18636 (
18637 " hello world",
18638 &[
18639 whitespace(" ", 2),
18640 word("hello", 5),
18641 whitespace(" ", 1),
18642 word("world", 5),
18643 ],
18644 ),
18645 (
18646 "这是什么 \n 钢笔",
18647 &[
18648 word("这", 1),
18649 word("是", 1),
18650 word("什", 1),
18651 word("么", 1),
18652 whitespace(" ", 1),
18653 newline(),
18654 whitespace(" ", 1),
18655 word("钢", 1),
18656 word("笔", 1),
18657 ],
18658 ),
18659 (" mutton", &[whitespace(" ", 1), word("mutton", 6)]),
18660 ];
18661
18662 fn word(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18663 WordBreakToken::Word {
18664 token,
18665 grapheme_len,
18666 }
18667 }
18668
18669 fn whitespace(token: &'static str, grapheme_len: usize) -> WordBreakToken<'static> {
18670 WordBreakToken::InlineWhitespace {
18671 token,
18672 grapheme_len,
18673 }
18674 }
18675
18676 fn newline() -> WordBreakToken<'static> {
18677 WordBreakToken::Newline
18678 }
18679
18680 for (input, result) in tests {
18681 assert_eq!(
18682 WordBreakingTokenizer::new(input)
18683 .collect::<Vec<_>>()
18684 .as_slice(),
18685 *result,
18686 );
18687 }
18688}
18689
18690fn wrap_with_prefix(
18691 line_prefix: String,
18692 unwrapped_text: String,
18693 wrap_column: usize,
18694 tab_size: NonZeroU32,
18695 preserve_existing_whitespace: bool,
18696) -> String {
18697 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
18698 let mut wrapped_text = String::new();
18699 let mut current_line = line_prefix.clone();
18700
18701 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
18702 let mut current_line_len = line_prefix_len;
18703 let mut in_whitespace = false;
18704 for token in tokenizer {
18705 let have_preceding_whitespace = in_whitespace;
18706 match token {
18707 WordBreakToken::Word {
18708 token,
18709 grapheme_len,
18710 } => {
18711 in_whitespace = false;
18712 if current_line_len + grapheme_len > wrap_column
18713 && current_line_len != line_prefix_len
18714 {
18715 wrapped_text.push_str(current_line.trim_end());
18716 wrapped_text.push('\n');
18717 current_line.truncate(line_prefix.len());
18718 current_line_len = line_prefix_len;
18719 }
18720 current_line.push_str(token);
18721 current_line_len += grapheme_len;
18722 }
18723 WordBreakToken::InlineWhitespace {
18724 mut token,
18725 mut grapheme_len,
18726 } => {
18727 in_whitespace = true;
18728 if have_preceding_whitespace && !preserve_existing_whitespace {
18729 continue;
18730 }
18731 if !preserve_existing_whitespace {
18732 token = " ";
18733 grapheme_len = 1;
18734 }
18735 if current_line_len + grapheme_len > wrap_column {
18736 wrapped_text.push_str(current_line.trim_end());
18737 wrapped_text.push('\n');
18738 current_line.truncate(line_prefix.len());
18739 current_line_len = line_prefix_len;
18740 } else if current_line_len != line_prefix_len || preserve_existing_whitespace {
18741 current_line.push_str(token);
18742 current_line_len += grapheme_len;
18743 }
18744 }
18745 WordBreakToken::Newline => {
18746 in_whitespace = true;
18747 if preserve_existing_whitespace {
18748 wrapped_text.push_str(current_line.trim_end());
18749 wrapped_text.push('\n');
18750 current_line.truncate(line_prefix.len());
18751 current_line_len = line_prefix_len;
18752 } else if have_preceding_whitespace {
18753 continue;
18754 } else if current_line_len + 1 > wrap_column && current_line_len != line_prefix_len
18755 {
18756 wrapped_text.push_str(current_line.trim_end());
18757 wrapped_text.push('\n');
18758 current_line.truncate(line_prefix.len());
18759 current_line_len = line_prefix_len;
18760 } else if current_line_len != line_prefix_len {
18761 current_line.push(' ');
18762 current_line_len += 1;
18763 }
18764 }
18765 }
18766 }
18767
18768 if !current_line.is_empty() {
18769 wrapped_text.push_str(¤t_line);
18770 }
18771 wrapped_text
18772}
18773
18774#[test]
18775fn test_wrap_with_prefix() {
18776 assert_eq!(
18777 wrap_with_prefix(
18778 "# ".to_string(),
18779 "abcdefg".to_string(),
18780 4,
18781 NonZeroU32::new(4).unwrap(),
18782 false,
18783 ),
18784 "# abcdefg"
18785 );
18786 assert_eq!(
18787 wrap_with_prefix(
18788 "".to_string(),
18789 "\thello world".to_string(),
18790 8,
18791 NonZeroU32::new(4).unwrap(),
18792 false,
18793 ),
18794 "hello\nworld"
18795 );
18796 assert_eq!(
18797 wrap_with_prefix(
18798 "// ".to_string(),
18799 "xx \nyy zz aa bb cc".to_string(),
18800 12,
18801 NonZeroU32::new(4).unwrap(),
18802 false,
18803 ),
18804 "// xx yy zz\n// aa bb cc"
18805 );
18806 assert_eq!(
18807 wrap_with_prefix(
18808 String::new(),
18809 "这是什么 \n 钢笔".to_string(),
18810 3,
18811 NonZeroU32::new(4).unwrap(),
18812 false,
18813 ),
18814 "这是什\n么 钢\n笔"
18815 );
18816}
18817
18818pub trait CollaborationHub {
18819 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
18820 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
18821 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
18822}
18823
18824impl CollaborationHub for Entity<Project> {
18825 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
18826 self.read(cx).collaborators()
18827 }
18828
18829 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
18830 self.read(cx).user_store().read(cx).participant_indices()
18831 }
18832
18833 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
18834 let this = self.read(cx);
18835 let user_ids = this.collaborators().values().map(|c| c.user_id);
18836 this.user_store().read_with(cx, |user_store, cx| {
18837 user_store.participant_names(user_ids, cx)
18838 })
18839 }
18840}
18841
18842pub trait SemanticsProvider {
18843 fn hover(
18844 &self,
18845 buffer: &Entity<Buffer>,
18846 position: text::Anchor,
18847 cx: &mut App,
18848 ) -> Option<Task<Vec<project::Hover>>>;
18849
18850 fn inlay_hints(
18851 &self,
18852 buffer_handle: Entity<Buffer>,
18853 range: Range<text::Anchor>,
18854 cx: &mut App,
18855 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
18856
18857 fn resolve_inlay_hint(
18858 &self,
18859 hint: InlayHint,
18860 buffer_handle: Entity<Buffer>,
18861 server_id: LanguageServerId,
18862 cx: &mut App,
18863 ) -> Option<Task<anyhow::Result<InlayHint>>>;
18864
18865 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
18866
18867 fn document_highlights(
18868 &self,
18869 buffer: &Entity<Buffer>,
18870 position: text::Anchor,
18871 cx: &mut App,
18872 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
18873
18874 fn definitions(
18875 &self,
18876 buffer: &Entity<Buffer>,
18877 position: text::Anchor,
18878 kind: GotoDefinitionKind,
18879 cx: &mut App,
18880 ) -> Option<Task<Result<Vec<LocationLink>>>>;
18881
18882 fn range_for_rename(
18883 &self,
18884 buffer: &Entity<Buffer>,
18885 position: text::Anchor,
18886 cx: &mut App,
18887 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
18888
18889 fn perform_rename(
18890 &self,
18891 buffer: &Entity<Buffer>,
18892 position: text::Anchor,
18893 new_name: String,
18894 cx: &mut App,
18895 ) -> Option<Task<Result<ProjectTransaction>>>;
18896}
18897
18898pub trait CompletionProvider {
18899 fn completions(
18900 &self,
18901 excerpt_id: ExcerptId,
18902 buffer: &Entity<Buffer>,
18903 buffer_position: text::Anchor,
18904 trigger: CompletionContext,
18905 window: &mut Window,
18906 cx: &mut Context<Editor>,
18907 ) -> Task<Result<Option<Vec<Completion>>>>;
18908
18909 fn resolve_completions(
18910 &self,
18911 buffer: Entity<Buffer>,
18912 completion_indices: Vec<usize>,
18913 completions: Rc<RefCell<Box<[Completion]>>>,
18914 cx: &mut Context<Editor>,
18915 ) -> Task<Result<bool>>;
18916
18917 fn apply_additional_edits_for_completion(
18918 &self,
18919 _buffer: Entity<Buffer>,
18920 _completions: Rc<RefCell<Box<[Completion]>>>,
18921 _completion_index: usize,
18922 _push_to_history: bool,
18923 _cx: &mut Context<Editor>,
18924 ) -> Task<Result<Option<language::Transaction>>> {
18925 Task::ready(Ok(None))
18926 }
18927
18928 fn is_completion_trigger(
18929 &self,
18930 buffer: &Entity<Buffer>,
18931 position: language::Anchor,
18932 text: &str,
18933 trigger_in_words: bool,
18934 cx: &mut Context<Editor>,
18935 ) -> bool;
18936
18937 fn sort_completions(&self) -> bool {
18938 true
18939 }
18940
18941 fn filter_completions(&self) -> bool {
18942 true
18943 }
18944}
18945
18946pub trait CodeActionProvider {
18947 fn id(&self) -> Arc<str>;
18948
18949 fn code_actions(
18950 &self,
18951 buffer: &Entity<Buffer>,
18952 range: Range<text::Anchor>,
18953 window: &mut Window,
18954 cx: &mut App,
18955 ) -> Task<Result<Vec<CodeAction>>>;
18956
18957 fn apply_code_action(
18958 &self,
18959 buffer_handle: Entity<Buffer>,
18960 action: CodeAction,
18961 excerpt_id: ExcerptId,
18962 push_to_history: bool,
18963 window: &mut Window,
18964 cx: &mut App,
18965 ) -> Task<Result<ProjectTransaction>>;
18966}
18967
18968impl CodeActionProvider for Entity<Project> {
18969 fn id(&self) -> Arc<str> {
18970 "project".into()
18971 }
18972
18973 fn code_actions(
18974 &self,
18975 buffer: &Entity<Buffer>,
18976 range: Range<text::Anchor>,
18977 _window: &mut Window,
18978 cx: &mut App,
18979 ) -> Task<Result<Vec<CodeAction>>> {
18980 self.update(cx, |project, cx| {
18981 let code_lens = project.code_lens(buffer, range.clone(), cx);
18982 let code_actions = project.code_actions(buffer, range, None, cx);
18983 cx.background_spawn(async move {
18984 let (code_lens, code_actions) = join(code_lens, code_actions).await;
18985 Ok(code_lens
18986 .context("code lens fetch")?
18987 .into_iter()
18988 .chain(code_actions.context("code action fetch")?)
18989 .collect())
18990 })
18991 })
18992 }
18993
18994 fn apply_code_action(
18995 &self,
18996 buffer_handle: Entity<Buffer>,
18997 action: CodeAction,
18998 _excerpt_id: ExcerptId,
18999 push_to_history: bool,
19000 _window: &mut Window,
19001 cx: &mut App,
19002 ) -> Task<Result<ProjectTransaction>> {
19003 self.update(cx, |project, cx| {
19004 project.apply_code_action(buffer_handle, action, push_to_history, cx)
19005 })
19006 }
19007}
19008
19009fn snippet_completions(
19010 project: &Project,
19011 buffer: &Entity<Buffer>,
19012 buffer_position: text::Anchor,
19013 cx: &mut App,
19014) -> Task<Result<Vec<Completion>>> {
19015 let languages = buffer.read(cx).languages_at(buffer_position);
19016 let snippet_store = project.snippets().read(cx);
19017
19018 let scopes: Vec<_> = languages
19019 .iter()
19020 .filter_map(|language| {
19021 let language_name = language.lsp_id();
19022 let snippets = snippet_store.snippets_for(Some(language_name), cx);
19023
19024 if snippets.is_empty() {
19025 None
19026 } else {
19027 Some((language.default_scope(), snippets))
19028 }
19029 })
19030 .collect();
19031
19032 if scopes.is_empty() {
19033 return Task::ready(Ok(vec![]));
19034 }
19035
19036 let snapshot = buffer.read(cx).text_snapshot();
19037 let chars: String = snapshot
19038 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
19039 .collect();
19040 let executor = cx.background_executor().clone();
19041
19042 cx.background_spawn(async move {
19043 let mut all_results: Vec<Completion> = Vec::new();
19044 for (scope, snippets) in scopes.into_iter() {
19045 let classifier = CharClassifier::new(Some(scope)).for_completion(true);
19046 let mut last_word = chars
19047 .chars()
19048 .take_while(|c| classifier.is_word(*c))
19049 .collect::<String>();
19050 last_word = last_word.chars().rev().collect();
19051
19052 if last_word.is_empty() {
19053 return Ok(vec![]);
19054 }
19055
19056 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
19057 let to_lsp = |point: &text::Anchor| {
19058 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
19059 point_to_lsp(end)
19060 };
19061 let lsp_end = to_lsp(&buffer_position);
19062
19063 let candidates = snippets
19064 .iter()
19065 .enumerate()
19066 .flat_map(|(ix, snippet)| {
19067 snippet
19068 .prefix
19069 .iter()
19070 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
19071 })
19072 .collect::<Vec<StringMatchCandidate>>();
19073
19074 let mut matches = fuzzy::match_strings(
19075 &candidates,
19076 &last_word,
19077 last_word.chars().any(|c| c.is_uppercase()),
19078 100,
19079 &Default::default(),
19080 executor.clone(),
19081 )
19082 .await;
19083
19084 // Remove all candidates where the query's start does not match the start of any word in the candidate
19085 if let Some(query_start) = last_word.chars().next() {
19086 matches.retain(|string_match| {
19087 split_words(&string_match.string).any(|word| {
19088 // Check that the first codepoint of the word as lowercase matches the first
19089 // codepoint of the query as lowercase
19090 word.chars()
19091 .flat_map(|codepoint| codepoint.to_lowercase())
19092 .zip(query_start.to_lowercase())
19093 .all(|(word_cp, query_cp)| word_cp == query_cp)
19094 })
19095 });
19096 }
19097
19098 let matched_strings = matches
19099 .into_iter()
19100 .map(|m| m.string)
19101 .collect::<HashSet<_>>();
19102
19103 let mut result: Vec<Completion> = snippets
19104 .iter()
19105 .filter_map(|snippet| {
19106 let matching_prefix = snippet
19107 .prefix
19108 .iter()
19109 .find(|prefix| matched_strings.contains(*prefix))?;
19110 let start = as_offset - last_word.len();
19111 let start = snapshot.anchor_before(start);
19112 let range = start..buffer_position;
19113 let lsp_start = to_lsp(&start);
19114 let lsp_range = lsp::Range {
19115 start: lsp_start,
19116 end: lsp_end,
19117 };
19118 Some(Completion {
19119 replace_range: range,
19120 new_text: snippet.body.clone(),
19121 source: CompletionSource::Lsp {
19122 insert_range: None,
19123 server_id: LanguageServerId(usize::MAX),
19124 resolved: true,
19125 lsp_completion: Box::new(lsp::CompletionItem {
19126 label: snippet.prefix.first().unwrap().clone(),
19127 kind: Some(CompletionItemKind::SNIPPET),
19128 label_details: snippet.description.as_ref().map(|description| {
19129 lsp::CompletionItemLabelDetails {
19130 detail: Some(description.clone()),
19131 description: None,
19132 }
19133 }),
19134 insert_text_format: Some(InsertTextFormat::SNIPPET),
19135 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19136 lsp::InsertReplaceEdit {
19137 new_text: snippet.body.clone(),
19138 insert: lsp_range,
19139 replace: lsp_range,
19140 },
19141 )),
19142 filter_text: Some(snippet.body.clone()),
19143 sort_text: Some(char::MAX.to_string()),
19144 ..lsp::CompletionItem::default()
19145 }),
19146 lsp_defaults: None,
19147 },
19148 label: CodeLabel {
19149 text: matching_prefix.clone(),
19150 runs: Vec::new(),
19151 filter_range: 0..matching_prefix.len(),
19152 },
19153 icon_path: None,
19154 documentation: snippet.description.clone().map(|description| {
19155 CompletionDocumentation::SingleLine(description.into())
19156 }),
19157 insert_text_mode: None,
19158 confirm: None,
19159 })
19160 })
19161 .collect();
19162
19163 all_results.append(&mut result);
19164 }
19165
19166 Ok(all_results)
19167 })
19168}
19169
19170impl CompletionProvider for Entity<Project> {
19171 fn completions(
19172 &self,
19173 _excerpt_id: ExcerptId,
19174 buffer: &Entity<Buffer>,
19175 buffer_position: text::Anchor,
19176 options: CompletionContext,
19177 _window: &mut Window,
19178 cx: &mut Context<Editor>,
19179 ) -> Task<Result<Option<Vec<Completion>>>> {
19180 self.update(cx, |project, cx| {
19181 let snippets = snippet_completions(project, buffer, buffer_position, cx);
19182 let project_completions = project.completions(buffer, buffer_position, options, cx);
19183 cx.background_spawn(async move {
19184 let snippets_completions = snippets.await?;
19185 match project_completions.await? {
19186 Some(mut completions) => {
19187 completions.extend(snippets_completions);
19188 Ok(Some(completions))
19189 }
19190 None => {
19191 if snippets_completions.is_empty() {
19192 Ok(None)
19193 } else {
19194 Ok(Some(snippets_completions))
19195 }
19196 }
19197 }
19198 })
19199 })
19200 }
19201
19202 fn resolve_completions(
19203 &self,
19204 buffer: Entity<Buffer>,
19205 completion_indices: Vec<usize>,
19206 completions: Rc<RefCell<Box<[Completion]>>>,
19207 cx: &mut Context<Editor>,
19208 ) -> Task<Result<bool>> {
19209 self.update(cx, |project, cx| {
19210 project.lsp_store().update(cx, |lsp_store, cx| {
19211 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
19212 })
19213 })
19214 }
19215
19216 fn apply_additional_edits_for_completion(
19217 &self,
19218 buffer: Entity<Buffer>,
19219 completions: Rc<RefCell<Box<[Completion]>>>,
19220 completion_index: usize,
19221 push_to_history: bool,
19222 cx: &mut Context<Editor>,
19223 ) -> Task<Result<Option<language::Transaction>>> {
19224 self.update(cx, |project, cx| {
19225 project.lsp_store().update(cx, |lsp_store, cx| {
19226 lsp_store.apply_additional_edits_for_completion(
19227 buffer,
19228 completions,
19229 completion_index,
19230 push_to_history,
19231 cx,
19232 )
19233 })
19234 })
19235 }
19236
19237 fn is_completion_trigger(
19238 &self,
19239 buffer: &Entity<Buffer>,
19240 position: language::Anchor,
19241 text: &str,
19242 trigger_in_words: bool,
19243 cx: &mut Context<Editor>,
19244 ) -> bool {
19245 let mut chars = text.chars();
19246 let char = if let Some(char) = chars.next() {
19247 char
19248 } else {
19249 return false;
19250 };
19251 if chars.next().is_some() {
19252 return false;
19253 }
19254
19255 let buffer = buffer.read(cx);
19256 let snapshot = buffer.snapshot();
19257 if !snapshot.settings_at(position, cx).show_completions_on_input {
19258 return false;
19259 }
19260 let classifier = snapshot.char_classifier_at(position).for_completion(true);
19261 if trigger_in_words && classifier.is_word(char) {
19262 return true;
19263 }
19264
19265 buffer.completion_triggers().contains(text)
19266 }
19267}
19268
19269impl SemanticsProvider for Entity<Project> {
19270 fn hover(
19271 &self,
19272 buffer: &Entity<Buffer>,
19273 position: text::Anchor,
19274 cx: &mut App,
19275 ) -> Option<Task<Vec<project::Hover>>> {
19276 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
19277 }
19278
19279 fn document_highlights(
19280 &self,
19281 buffer: &Entity<Buffer>,
19282 position: text::Anchor,
19283 cx: &mut App,
19284 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
19285 Some(self.update(cx, |project, cx| {
19286 project.document_highlights(buffer, position, cx)
19287 }))
19288 }
19289
19290 fn definitions(
19291 &self,
19292 buffer: &Entity<Buffer>,
19293 position: text::Anchor,
19294 kind: GotoDefinitionKind,
19295 cx: &mut App,
19296 ) -> Option<Task<Result<Vec<LocationLink>>>> {
19297 Some(self.update(cx, |project, cx| match kind {
19298 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
19299 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
19300 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
19301 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
19302 }))
19303 }
19304
19305 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
19306 // TODO: make this work for remote projects
19307 self.update(cx, |this, cx| {
19308 buffer.update(cx, |buffer, cx| {
19309 this.any_language_server_supports_inlay_hints(buffer, cx)
19310 })
19311 })
19312 }
19313
19314 fn inlay_hints(
19315 &self,
19316 buffer_handle: Entity<Buffer>,
19317 range: Range<text::Anchor>,
19318 cx: &mut App,
19319 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
19320 Some(self.update(cx, |project, cx| {
19321 project.inlay_hints(buffer_handle, range, cx)
19322 }))
19323 }
19324
19325 fn resolve_inlay_hint(
19326 &self,
19327 hint: InlayHint,
19328 buffer_handle: Entity<Buffer>,
19329 server_id: LanguageServerId,
19330 cx: &mut App,
19331 ) -> Option<Task<anyhow::Result<InlayHint>>> {
19332 Some(self.update(cx, |project, cx| {
19333 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
19334 }))
19335 }
19336
19337 fn range_for_rename(
19338 &self,
19339 buffer: &Entity<Buffer>,
19340 position: text::Anchor,
19341 cx: &mut App,
19342 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
19343 Some(self.update(cx, |project, cx| {
19344 let buffer = buffer.clone();
19345 let task = project.prepare_rename(buffer.clone(), position, cx);
19346 cx.spawn(async move |_, cx| {
19347 Ok(match task.await? {
19348 PrepareRenameResponse::Success(range) => Some(range),
19349 PrepareRenameResponse::InvalidPosition => None,
19350 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
19351 // Fallback on using TreeSitter info to determine identifier range
19352 buffer.update(cx, |buffer, _| {
19353 let snapshot = buffer.snapshot();
19354 let (range, kind) = snapshot.surrounding_word(position);
19355 if kind != Some(CharKind::Word) {
19356 return None;
19357 }
19358 Some(
19359 snapshot.anchor_before(range.start)
19360 ..snapshot.anchor_after(range.end),
19361 )
19362 })?
19363 }
19364 })
19365 })
19366 }))
19367 }
19368
19369 fn perform_rename(
19370 &self,
19371 buffer: &Entity<Buffer>,
19372 position: text::Anchor,
19373 new_name: String,
19374 cx: &mut App,
19375 ) -> Option<Task<Result<ProjectTransaction>>> {
19376 Some(self.update(cx, |project, cx| {
19377 project.perform_rename(buffer.clone(), position, new_name, cx)
19378 }))
19379 }
19380}
19381
19382fn inlay_hint_settings(
19383 location: Anchor,
19384 snapshot: &MultiBufferSnapshot,
19385 cx: &mut Context<Editor>,
19386) -> InlayHintSettings {
19387 let file = snapshot.file_at(location);
19388 let language = snapshot.language_at(location).map(|l| l.name());
19389 language_settings(language, file, cx).inlay_hints
19390}
19391
19392fn consume_contiguous_rows(
19393 contiguous_row_selections: &mut Vec<Selection<Point>>,
19394 selection: &Selection<Point>,
19395 display_map: &DisplaySnapshot,
19396 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
19397) -> (MultiBufferRow, MultiBufferRow) {
19398 contiguous_row_selections.push(selection.clone());
19399 let start_row = MultiBufferRow(selection.start.row);
19400 let mut end_row = ending_row(selection, display_map);
19401
19402 while let Some(next_selection) = selections.peek() {
19403 if next_selection.start.row <= end_row.0 {
19404 end_row = ending_row(next_selection, display_map);
19405 contiguous_row_selections.push(selections.next().unwrap().clone());
19406 } else {
19407 break;
19408 }
19409 }
19410 (start_row, end_row)
19411}
19412
19413fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
19414 if next_selection.end.column > 0 || next_selection.is_empty() {
19415 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
19416 } else {
19417 MultiBufferRow(next_selection.end.row)
19418 }
19419}
19420
19421impl EditorSnapshot {
19422 pub fn remote_selections_in_range<'a>(
19423 &'a self,
19424 range: &'a Range<Anchor>,
19425 collaboration_hub: &dyn CollaborationHub,
19426 cx: &'a App,
19427 ) -> impl 'a + Iterator<Item = RemoteSelection> {
19428 let participant_names = collaboration_hub.user_names(cx);
19429 let participant_indices = collaboration_hub.user_participant_indices(cx);
19430 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
19431 let collaborators_by_replica_id = collaborators_by_peer_id
19432 .iter()
19433 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
19434 .collect::<HashMap<_, _>>();
19435 self.buffer_snapshot
19436 .selections_in_range(range, false)
19437 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
19438 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
19439 let participant_index = participant_indices.get(&collaborator.user_id).copied();
19440 let user_name = participant_names.get(&collaborator.user_id).cloned();
19441 Some(RemoteSelection {
19442 replica_id,
19443 selection,
19444 cursor_shape,
19445 line_mode,
19446 participant_index,
19447 peer_id: collaborator.peer_id,
19448 user_name,
19449 })
19450 })
19451 }
19452
19453 pub fn hunks_for_ranges(
19454 &self,
19455 ranges: impl IntoIterator<Item = Range<Point>>,
19456 ) -> Vec<MultiBufferDiffHunk> {
19457 let mut hunks = Vec::new();
19458 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
19459 HashMap::default();
19460 for query_range in ranges {
19461 let query_rows =
19462 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
19463 for hunk in self.buffer_snapshot.diff_hunks_in_range(
19464 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
19465 ) {
19466 // Include deleted hunks that are adjacent to the query range, because
19467 // otherwise they would be missed.
19468 let mut intersects_range = hunk.row_range.overlaps(&query_rows);
19469 if hunk.status().is_deleted() {
19470 intersects_range |= hunk.row_range.start == query_rows.end;
19471 intersects_range |= hunk.row_range.end == query_rows.start;
19472 }
19473 if intersects_range {
19474 if !processed_buffer_rows
19475 .entry(hunk.buffer_id)
19476 .or_default()
19477 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
19478 {
19479 continue;
19480 }
19481 hunks.push(hunk);
19482 }
19483 }
19484 }
19485
19486 hunks
19487 }
19488
19489 fn display_diff_hunks_for_rows<'a>(
19490 &'a self,
19491 display_rows: Range<DisplayRow>,
19492 folded_buffers: &'a HashSet<BufferId>,
19493 ) -> impl 'a + Iterator<Item = DisplayDiffHunk> {
19494 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(self);
19495 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(self);
19496
19497 self.buffer_snapshot
19498 .diff_hunks_in_range(buffer_start..buffer_end)
19499 .filter_map(|hunk| {
19500 if folded_buffers.contains(&hunk.buffer_id) {
19501 return None;
19502 }
19503
19504 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
19505 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
19506
19507 let hunk_display_start = self.point_to_display_point(hunk_start_point, Bias::Left);
19508 let hunk_display_end = self.point_to_display_point(hunk_end_point, Bias::Right);
19509
19510 let display_hunk = if hunk_display_start.column() != 0 {
19511 DisplayDiffHunk::Folded {
19512 display_row: hunk_display_start.row(),
19513 }
19514 } else {
19515 let mut end_row = hunk_display_end.row();
19516 if hunk_display_end.column() > 0 {
19517 end_row.0 += 1;
19518 }
19519 let is_created_file = hunk.is_created_file();
19520 DisplayDiffHunk::Unfolded {
19521 status: hunk.status(),
19522 diff_base_byte_range: hunk.diff_base_byte_range,
19523 display_row_range: hunk_display_start.row()..end_row,
19524 multi_buffer_range: Anchor::range_in_buffer(
19525 hunk.excerpt_id,
19526 hunk.buffer_id,
19527 hunk.buffer_range,
19528 ),
19529 is_created_file,
19530 }
19531 };
19532
19533 Some(display_hunk)
19534 })
19535 }
19536
19537 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
19538 self.display_snapshot.buffer_snapshot.language_at(position)
19539 }
19540
19541 pub fn is_focused(&self) -> bool {
19542 self.is_focused
19543 }
19544
19545 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
19546 self.placeholder_text.as_ref()
19547 }
19548
19549 pub fn scroll_position(&self) -> gpui::Point<f32> {
19550 self.scroll_anchor.scroll_position(&self.display_snapshot)
19551 }
19552
19553 fn gutter_dimensions(
19554 &self,
19555 font_id: FontId,
19556 font_size: Pixels,
19557 max_line_number_width: Pixels,
19558 cx: &App,
19559 ) -> Option<GutterDimensions> {
19560 if !self.show_gutter {
19561 return None;
19562 }
19563
19564 let descent = cx.text_system().descent(font_id, font_size);
19565 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
19566 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
19567
19568 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
19569 matches!(
19570 ProjectSettings::get_global(cx).git.git_gutter,
19571 Some(GitGutterSetting::TrackedFiles)
19572 )
19573 });
19574 let gutter_settings = EditorSettings::get_global(cx).gutter;
19575 let show_line_numbers = self
19576 .show_line_numbers
19577 .unwrap_or(gutter_settings.line_numbers);
19578 let line_gutter_width = if show_line_numbers {
19579 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
19580 let min_width_for_number_on_gutter = em_advance * MIN_LINE_NUMBER_DIGITS as f32;
19581 max_line_number_width.max(min_width_for_number_on_gutter)
19582 } else {
19583 0.0.into()
19584 };
19585
19586 let show_code_actions = self
19587 .show_code_actions
19588 .unwrap_or(gutter_settings.code_actions);
19589
19590 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
19591 let show_breakpoints = self.show_breakpoints.unwrap_or(gutter_settings.breakpoints);
19592
19593 let git_blame_entries_width =
19594 self.git_blame_gutter_max_author_length
19595 .map(|max_author_length| {
19596 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
19597 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
19598
19599 /// The number of characters to dedicate to gaps and margins.
19600 const SPACING_WIDTH: usize = 4;
19601
19602 let max_char_count = max_author_length.min(renderer.max_author_length())
19603 + ::git::SHORT_SHA_LENGTH
19604 + MAX_RELATIVE_TIMESTAMP.len()
19605 + SPACING_WIDTH;
19606
19607 em_advance * max_char_count
19608 });
19609
19610 let is_singleton = self.buffer_snapshot.is_singleton();
19611
19612 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
19613 left_padding += if !is_singleton {
19614 em_width * 4.0
19615 } else if show_code_actions || show_runnables || show_breakpoints {
19616 em_width * 3.0
19617 } else if show_git_gutter && show_line_numbers {
19618 em_width * 2.0
19619 } else if show_git_gutter || show_line_numbers {
19620 em_width
19621 } else {
19622 px(0.)
19623 };
19624
19625 let shows_folds = is_singleton && gutter_settings.folds;
19626
19627 let right_padding = if shows_folds && show_line_numbers {
19628 em_width * 4.0
19629 } else if shows_folds || (!is_singleton && show_line_numbers) {
19630 em_width * 3.0
19631 } else if show_line_numbers {
19632 em_width
19633 } else {
19634 px(0.)
19635 };
19636
19637 Some(GutterDimensions {
19638 left_padding,
19639 right_padding,
19640 width: line_gutter_width + left_padding + right_padding,
19641 margin: -descent,
19642 git_blame_entries_width,
19643 })
19644 }
19645
19646 pub fn render_crease_toggle(
19647 &self,
19648 buffer_row: MultiBufferRow,
19649 row_contains_cursor: bool,
19650 editor: Entity<Editor>,
19651 window: &mut Window,
19652 cx: &mut App,
19653 ) -> Option<AnyElement> {
19654 let folded = self.is_line_folded(buffer_row);
19655 let mut is_foldable = false;
19656
19657 if let Some(crease) = self
19658 .crease_snapshot
19659 .query_row(buffer_row, &self.buffer_snapshot)
19660 {
19661 is_foldable = true;
19662 match crease {
19663 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
19664 if let Some(render_toggle) = render_toggle {
19665 let toggle_callback =
19666 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
19667 if folded {
19668 editor.update(cx, |editor, cx| {
19669 editor.fold_at(buffer_row, window, cx)
19670 });
19671 } else {
19672 editor.update(cx, |editor, cx| {
19673 editor.unfold_at(buffer_row, window, cx)
19674 });
19675 }
19676 });
19677 return Some((render_toggle)(
19678 buffer_row,
19679 folded,
19680 toggle_callback,
19681 window,
19682 cx,
19683 ));
19684 }
19685 }
19686 }
19687 }
19688
19689 is_foldable |= self.starts_indent(buffer_row);
19690
19691 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
19692 Some(
19693 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
19694 .toggle_state(folded)
19695 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
19696 if folded {
19697 this.unfold_at(buffer_row, window, cx);
19698 } else {
19699 this.fold_at(buffer_row, window, cx);
19700 }
19701 }))
19702 .into_any_element(),
19703 )
19704 } else {
19705 None
19706 }
19707 }
19708
19709 pub fn render_crease_trailer(
19710 &self,
19711 buffer_row: MultiBufferRow,
19712 window: &mut Window,
19713 cx: &mut App,
19714 ) -> Option<AnyElement> {
19715 let folded = self.is_line_folded(buffer_row);
19716 if let Crease::Inline { render_trailer, .. } = self
19717 .crease_snapshot
19718 .query_row(buffer_row, &self.buffer_snapshot)?
19719 {
19720 let render_trailer = render_trailer.as_ref()?;
19721 Some(render_trailer(buffer_row, folded, window, cx))
19722 } else {
19723 None
19724 }
19725 }
19726}
19727
19728impl Deref for EditorSnapshot {
19729 type Target = DisplaySnapshot;
19730
19731 fn deref(&self) -> &Self::Target {
19732 &self.display_snapshot
19733 }
19734}
19735
19736#[derive(Clone, Debug, PartialEq, Eq)]
19737pub enum EditorEvent {
19738 InputIgnored {
19739 text: Arc<str>,
19740 },
19741 InputHandled {
19742 utf16_range_to_replace: Option<Range<isize>>,
19743 text: Arc<str>,
19744 },
19745 ExcerptsAdded {
19746 buffer: Entity<Buffer>,
19747 predecessor: ExcerptId,
19748 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
19749 },
19750 ExcerptsRemoved {
19751 ids: Vec<ExcerptId>,
19752 },
19753 BufferFoldToggled {
19754 ids: Vec<ExcerptId>,
19755 folded: bool,
19756 },
19757 ExcerptsEdited {
19758 ids: Vec<ExcerptId>,
19759 },
19760 ExcerptsExpanded {
19761 ids: Vec<ExcerptId>,
19762 },
19763 BufferEdited,
19764 Edited {
19765 transaction_id: clock::Lamport,
19766 },
19767 Reparsed(BufferId),
19768 Focused,
19769 FocusedIn,
19770 Blurred,
19771 DirtyChanged,
19772 Saved,
19773 TitleChanged,
19774 DiffBaseChanged,
19775 SelectionsChanged {
19776 local: bool,
19777 },
19778 ScrollPositionChanged {
19779 local: bool,
19780 autoscroll: bool,
19781 },
19782 Closed,
19783 TransactionUndone {
19784 transaction_id: clock::Lamport,
19785 },
19786 TransactionBegun {
19787 transaction_id: clock::Lamport,
19788 },
19789 Reloaded,
19790 CursorShapeChanged,
19791 PushedToNavHistory {
19792 anchor: Anchor,
19793 is_deactivate: bool,
19794 },
19795}
19796
19797impl EventEmitter<EditorEvent> for Editor {}
19798
19799impl Focusable for Editor {
19800 fn focus_handle(&self, _cx: &App) -> FocusHandle {
19801 self.focus_handle.clone()
19802 }
19803}
19804
19805impl Render for Editor {
19806 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
19807 let settings = ThemeSettings::get_global(cx);
19808
19809 let mut text_style = match self.mode {
19810 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
19811 color: cx.theme().colors().editor_foreground,
19812 font_family: settings.ui_font.family.clone(),
19813 font_features: settings.ui_font.features.clone(),
19814 font_fallbacks: settings.ui_font.fallbacks.clone(),
19815 font_size: rems(0.875).into(),
19816 font_weight: settings.ui_font.weight,
19817 line_height: relative(settings.buffer_line_height.value()),
19818 ..Default::default()
19819 },
19820 EditorMode::Full { .. } => TextStyle {
19821 color: cx.theme().colors().editor_foreground,
19822 font_family: settings.buffer_font.family.clone(),
19823 font_features: settings.buffer_font.features.clone(),
19824 font_fallbacks: settings.buffer_font.fallbacks.clone(),
19825 font_size: settings.buffer_font_size(cx).into(),
19826 font_weight: settings.buffer_font.weight,
19827 line_height: relative(settings.buffer_line_height.value()),
19828 ..Default::default()
19829 },
19830 };
19831 if let Some(text_style_refinement) = &self.text_style_refinement {
19832 text_style.refine(text_style_refinement)
19833 }
19834
19835 let background = match self.mode {
19836 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
19837 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
19838 EditorMode::Full { .. } => cx.theme().colors().editor_background,
19839 };
19840
19841 EditorElement::new(
19842 &cx.entity(),
19843 EditorStyle {
19844 background,
19845 local_player: cx.theme().players().local(),
19846 text: text_style,
19847 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
19848 syntax: cx.theme().syntax().clone(),
19849 status: cx.theme().status().clone(),
19850 inlay_hints_style: make_inlay_hints_style(cx),
19851 inline_completion_styles: make_suggestion_styles(cx),
19852 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
19853 },
19854 )
19855 }
19856}
19857
19858impl EntityInputHandler for Editor {
19859 fn text_for_range(
19860 &mut self,
19861 range_utf16: Range<usize>,
19862 adjusted_range: &mut Option<Range<usize>>,
19863 _: &mut Window,
19864 cx: &mut Context<Self>,
19865 ) -> Option<String> {
19866 let snapshot = self.buffer.read(cx).read(cx);
19867 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
19868 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
19869 if (start.0..end.0) != range_utf16 {
19870 adjusted_range.replace(start.0..end.0);
19871 }
19872 Some(snapshot.text_for_range(start..end).collect())
19873 }
19874
19875 fn selected_text_range(
19876 &mut self,
19877 ignore_disabled_input: bool,
19878 _: &mut Window,
19879 cx: &mut Context<Self>,
19880 ) -> Option<UTF16Selection> {
19881 // Prevent the IME menu from appearing when holding down an alphabetic key
19882 // while input is disabled.
19883 if !ignore_disabled_input && !self.input_enabled {
19884 return None;
19885 }
19886
19887 let selection = self.selections.newest::<OffsetUtf16>(cx);
19888 let range = selection.range();
19889
19890 Some(UTF16Selection {
19891 range: range.start.0..range.end.0,
19892 reversed: selection.reversed,
19893 })
19894 }
19895
19896 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
19897 let snapshot = self.buffer.read(cx).read(cx);
19898 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
19899 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
19900 }
19901
19902 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
19903 self.clear_highlights::<InputComposition>(cx);
19904 self.ime_transaction.take();
19905 }
19906
19907 fn replace_text_in_range(
19908 &mut self,
19909 range_utf16: Option<Range<usize>>,
19910 text: &str,
19911 window: &mut Window,
19912 cx: &mut Context<Self>,
19913 ) {
19914 if !self.input_enabled {
19915 cx.emit(EditorEvent::InputIgnored { text: text.into() });
19916 return;
19917 }
19918
19919 self.transact(window, cx, |this, window, cx| {
19920 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
19921 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19922 Some(this.selection_replacement_ranges(range_utf16, cx))
19923 } else {
19924 this.marked_text_ranges(cx)
19925 };
19926
19927 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
19928 let newest_selection_id = this.selections.newest_anchor().id;
19929 this.selections
19930 .all::<OffsetUtf16>(cx)
19931 .iter()
19932 .zip(ranges_to_replace.iter())
19933 .find_map(|(selection, range)| {
19934 if selection.id == newest_selection_id {
19935 Some(
19936 (range.start.0 as isize - selection.head().0 as isize)
19937 ..(range.end.0 as isize - selection.head().0 as isize),
19938 )
19939 } else {
19940 None
19941 }
19942 })
19943 });
19944
19945 cx.emit(EditorEvent::InputHandled {
19946 utf16_range_to_replace: range_to_replace,
19947 text: text.into(),
19948 });
19949
19950 if let Some(new_selected_ranges) = new_selected_ranges {
19951 this.change_selections(None, window, cx, |selections| {
19952 selections.select_ranges(new_selected_ranges)
19953 });
19954 this.backspace(&Default::default(), window, cx);
19955 }
19956
19957 this.handle_input(text, window, cx);
19958 });
19959
19960 if let Some(transaction) = self.ime_transaction {
19961 self.buffer.update(cx, |buffer, cx| {
19962 buffer.group_until_transaction(transaction, cx);
19963 });
19964 }
19965
19966 self.unmark_text(window, cx);
19967 }
19968
19969 fn replace_and_mark_text_in_range(
19970 &mut self,
19971 range_utf16: Option<Range<usize>>,
19972 text: &str,
19973 new_selected_range_utf16: Option<Range<usize>>,
19974 window: &mut Window,
19975 cx: &mut Context<Self>,
19976 ) {
19977 if !self.input_enabled {
19978 return;
19979 }
19980
19981 let transaction = self.transact(window, cx, |this, window, cx| {
19982 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
19983 let snapshot = this.buffer.read(cx).read(cx);
19984 if let Some(relative_range_utf16) = range_utf16.as_ref() {
19985 for marked_range in &mut marked_ranges {
19986 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
19987 marked_range.start.0 += relative_range_utf16.start;
19988 marked_range.start =
19989 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
19990 marked_range.end =
19991 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
19992 }
19993 }
19994 Some(marked_ranges)
19995 } else if let Some(range_utf16) = range_utf16 {
19996 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
19997 Some(this.selection_replacement_ranges(range_utf16, cx))
19998 } else {
19999 None
20000 };
20001
20002 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
20003 let newest_selection_id = this.selections.newest_anchor().id;
20004 this.selections
20005 .all::<OffsetUtf16>(cx)
20006 .iter()
20007 .zip(ranges_to_replace.iter())
20008 .find_map(|(selection, range)| {
20009 if selection.id == newest_selection_id {
20010 Some(
20011 (range.start.0 as isize - selection.head().0 as isize)
20012 ..(range.end.0 as isize - selection.head().0 as isize),
20013 )
20014 } else {
20015 None
20016 }
20017 })
20018 });
20019
20020 cx.emit(EditorEvent::InputHandled {
20021 utf16_range_to_replace: range_to_replace,
20022 text: text.into(),
20023 });
20024
20025 if let Some(ranges) = ranges_to_replace {
20026 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
20027 }
20028
20029 let marked_ranges = {
20030 let snapshot = this.buffer.read(cx).read(cx);
20031 this.selections
20032 .disjoint_anchors()
20033 .iter()
20034 .map(|selection| {
20035 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
20036 })
20037 .collect::<Vec<_>>()
20038 };
20039
20040 if text.is_empty() {
20041 this.unmark_text(window, cx);
20042 } else {
20043 this.highlight_text::<InputComposition>(
20044 marked_ranges.clone(),
20045 HighlightStyle {
20046 underline: Some(UnderlineStyle {
20047 thickness: px(1.),
20048 color: None,
20049 wavy: false,
20050 }),
20051 ..Default::default()
20052 },
20053 cx,
20054 );
20055 }
20056
20057 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
20058 let use_autoclose = this.use_autoclose;
20059 let use_auto_surround = this.use_auto_surround;
20060 this.set_use_autoclose(false);
20061 this.set_use_auto_surround(false);
20062 this.handle_input(text, window, cx);
20063 this.set_use_autoclose(use_autoclose);
20064 this.set_use_auto_surround(use_auto_surround);
20065
20066 if let Some(new_selected_range) = new_selected_range_utf16 {
20067 let snapshot = this.buffer.read(cx).read(cx);
20068 let new_selected_ranges = marked_ranges
20069 .into_iter()
20070 .map(|marked_range| {
20071 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
20072 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
20073 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
20074 snapshot.clip_offset_utf16(new_start, Bias::Left)
20075 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
20076 })
20077 .collect::<Vec<_>>();
20078
20079 drop(snapshot);
20080 this.change_selections(None, window, cx, |selections| {
20081 selections.select_ranges(new_selected_ranges)
20082 });
20083 }
20084 });
20085
20086 self.ime_transaction = self.ime_transaction.or(transaction);
20087 if let Some(transaction) = self.ime_transaction {
20088 self.buffer.update(cx, |buffer, cx| {
20089 buffer.group_until_transaction(transaction, cx);
20090 });
20091 }
20092
20093 if self.text_highlights::<InputComposition>(cx).is_none() {
20094 self.ime_transaction.take();
20095 }
20096 }
20097
20098 fn bounds_for_range(
20099 &mut self,
20100 range_utf16: Range<usize>,
20101 element_bounds: gpui::Bounds<Pixels>,
20102 window: &mut Window,
20103 cx: &mut Context<Self>,
20104 ) -> Option<gpui::Bounds<Pixels>> {
20105 let text_layout_details = self.text_layout_details(window);
20106 let gpui::Size {
20107 width: em_width,
20108 height: line_height,
20109 } = self.character_size(window);
20110
20111 let snapshot = self.snapshot(window, cx);
20112 let scroll_position = snapshot.scroll_position();
20113 let scroll_left = scroll_position.x * em_width;
20114
20115 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
20116 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
20117 + self.gutter_dimensions.width
20118 + self.gutter_dimensions.margin;
20119 let y = line_height * (start.row().as_f32() - scroll_position.y);
20120
20121 Some(Bounds {
20122 origin: element_bounds.origin + point(x, y),
20123 size: size(em_width, line_height),
20124 })
20125 }
20126
20127 fn character_index_for_point(
20128 &mut self,
20129 point: gpui::Point<Pixels>,
20130 _window: &mut Window,
20131 _cx: &mut Context<Self>,
20132 ) -> Option<usize> {
20133 let position_map = self.last_position_map.as_ref()?;
20134 if !position_map.text_hitbox.contains(&point) {
20135 return None;
20136 }
20137 let display_point = position_map.point_for_position(point).previous_valid;
20138 let anchor = position_map
20139 .snapshot
20140 .display_point_to_anchor(display_point, Bias::Left);
20141 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
20142 Some(utf16_offset.0)
20143 }
20144}
20145
20146trait SelectionExt {
20147 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
20148 fn spanned_rows(
20149 &self,
20150 include_end_if_at_line_start: bool,
20151 map: &DisplaySnapshot,
20152 ) -> Range<MultiBufferRow>;
20153}
20154
20155impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
20156 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
20157 let start = self
20158 .start
20159 .to_point(&map.buffer_snapshot)
20160 .to_display_point(map);
20161 let end = self
20162 .end
20163 .to_point(&map.buffer_snapshot)
20164 .to_display_point(map);
20165 if self.reversed {
20166 end..start
20167 } else {
20168 start..end
20169 }
20170 }
20171
20172 fn spanned_rows(
20173 &self,
20174 include_end_if_at_line_start: bool,
20175 map: &DisplaySnapshot,
20176 ) -> Range<MultiBufferRow> {
20177 let start = self.start.to_point(&map.buffer_snapshot);
20178 let mut end = self.end.to_point(&map.buffer_snapshot);
20179 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
20180 end.row -= 1;
20181 }
20182
20183 let buffer_start = map.prev_line_boundary(start).0;
20184 let buffer_end = map.next_line_boundary(end).0;
20185 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
20186 }
20187}
20188
20189impl<T: InvalidationRegion> InvalidationStack<T> {
20190 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
20191 where
20192 S: Clone + ToOffset,
20193 {
20194 while let Some(region) = self.last() {
20195 let all_selections_inside_invalidation_ranges =
20196 if selections.len() == region.ranges().len() {
20197 selections
20198 .iter()
20199 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
20200 .all(|(selection, invalidation_range)| {
20201 let head = selection.head().to_offset(buffer);
20202 invalidation_range.start <= head && invalidation_range.end >= head
20203 })
20204 } else {
20205 false
20206 };
20207
20208 if all_selections_inside_invalidation_ranges {
20209 break;
20210 } else {
20211 self.pop();
20212 }
20213 }
20214 }
20215}
20216
20217impl<T> Default for InvalidationStack<T> {
20218 fn default() -> Self {
20219 Self(Default::default())
20220 }
20221}
20222
20223impl<T> Deref for InvalidationStack<T> {
20224 type Target = Vec<T>;
20225
20226 fn deref(&self) -> &Self::Target {
20227 &self.0
20228 }
20229}
20230
20231impl<T> DerefMut for InvalidationStack<T> {
20232 fn deref_mut(&mut self) -> &mut Self::Target {
20233 &mut self.0
20234 }
20235}
20236
20237impl InvalidationRegion for SnippetState {
20238 fn ranges(&self) -> &[Range<Anchor>] {
20239 &self.ranges[self.active_index]
20240 }
20241}
20242
20243fn inline_completion_edit_text(
20244 current_snapshot: &BufferSnapshot,
20245 edits: &[(Range<Anchor>, String)],
20246 edit_preview: &EditPreview,
20247 include_deletions: bool,
20248 cx: &App,
20249) -> HighlightedText {
20250 let edits = edits
20251 .iter()
20252 .map(|(anchor, text)| {
20253 (
20254 anchor.start.text_anchor..anchor.end.text_anchor,
20255 text.clone(),
20256 )
20257 })
20258 .collect::<Vec<_>>();
20259
20260 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
20261}
20262
20263pub fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
20264 match severity {
20265 DiagnosticSeverity::ERROR => colors.error,
20266 DiagnosticSeverity::WARNING => colors.warning,
20267 DiagnosticSeverity::INFORMATION => colors.info,
20268 DiagnosticSeverity::HINT => colors.info,
20269 _ => colors.ignored,
20270 }
20271}
20272
20273pub fn styled_runs_for_code_label<'a>(
20274 label: &'a CodeLabel,
20275 syntax_theme: &'a theme::SyntaxTheme,
20276) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
20277 let fade_out = HighlightStyle {
20278 fade_out: Some(0.35),
20279 ..Default::default()
20280 };
20281
20282 let mut prev_end = label.filter_range.end;
20283 label
20284 .runs
20285 .iter()
20286 .enumerate()
20287 .flat_map(move |(ix, (range, highlight_id))| {
20288 let style = if let Some(style) = highlight_id.style(syntax_theme) {
20289 style
20290 } else {
20291 return Default::default();
20292 };
20293 let mut muted_style = style;
20294 muted_style.highlight(fade_out);
20295
20296 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
20297 if range.start >= label.filter_range.end {
20298 if range.start > prev_end {
20299 runs.push((prev_end..range.start, fade_out));
20300 }
20301 runs.push((range.clone(), muted_style));
20302 } else if range.end <= label.filter_range.end {
20303 runs.push((range.clone(), style));
20304 } else {
20305 runs.push((range.start..label.filter_range.end, style));
20306 runs.push((label.filter_range.end..range.end, muted_style));
20307 }
20308 prev_end = cmp::max(prev_end, range.end);
20309
20310 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
20311 runs.push((prev_end..label.text.len(), fade_out));
20312 }
20313
20314 runs
20315 })
20316}
20317
20318pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
20319 let mut prev_index = 0;
20320 let mut prev_codepoint: Option<char> = None;
20321 text.char_indices()
20322 .chain([(text.len(), '\0')])
20323 .filter_map(move |(index, codepoint)| {
20324 let prev_codepoint = prev_codepoint.replace(codepoint)?;
20325 let is_boundary = index == text.len()
20326 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
20327 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
20328 if is_boundary {
20329 let chunk = &text[prev_index..index];
20330 prev_index = index;
20331 Some(chunk)
20332 } else {
20333 None
20334 }
20335 })
20336}
20337
20338pub trait RangeToAnchorExt: Sized {
20339 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
20340
20341 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
20342 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
20343 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
20344 }
20345}
20346
20347impl<T: ToOffset> RangeToAnchorExt for Range<T> {
20348 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
20349 let start_offset = self.start.to_offset(snapshot);
20350 let end_offset = self.end.to_offset(snapshot);
20351 if start_offset == end_offset {
20352 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
20353 } else {
20354 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
20355 }
20356 }
20357}
20358
20359pub trait RowExt {
20360 fn as_f32(&self) -> f32;
20361
20362 fn next_row(&self) -> Self;
20363
20364 fn previous_row(&self) -> Self;
20365
20366 fn minus(&self, other: Self) -> u32;
20367}
20368
20369impl RowExt for DisplayRow {
20370 fn as_f32(&self) -> f32 {
20371 self.0 as f32
20372 }
20373
20374 fn next_row(&self) -> Self {
20375 Self(self.0 + 1)
20376 }
20377
20378 fn previous_row(&self) -> Self {
20379 Self(self.0.saturating_sub(1))
20380 }
20381
20382 fn minus(&self, other: Self) -> u32 {
20383 self.0 - other.0
20384 }
20385}
20386
20387impl RowExt for MultiBufferRow {
20388 fn as_f32(&self) -> f32 {
20389 self.0 as f32
20390 }
20391
20392 fn next_row(&self) -> Self {
20393 Self(self.0 + 1)
20394 }
20395
20396 fn previous_row(&self) -> Self {
20397 Self(self.0.saturating_sub(1))
20398 }
20399
20400 fn minus(&self, other: Self) -> u32 {
20401 self.0 - other.0
20402 }
20403}
20404
20405trait RowRangeExt {
20406 type Row;
20407
20408 fn len(&self) -> usize;
20409
20410 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
20411}
20412
20413impl RowRangeExt for Range<MultiBufferRow> {
20414 type Row = MultiBufferRow;
20415
20416 fn len(&self) -> usize {
20417 (self.end.0 - self.start.0) as usize
20418 }
20419
20420 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
20421 (self.start.0..self.end.0).map(MultiBufferRow)
20422 }
20423}
20424
20425impl RowRangeExt for Range<DisplayRow> {
20426 type Row = DisplayRow;
20427
20428 fn len(&self) -> usize {
20429 (self.end.0 - self.start.0) as usize
20430 }
20431
20432 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
20433 (self.start.0..self.end.0).map(DisplayRow)
20434 }
20435}
20436
20437/// If select range has more than one line, we
20438/// just point the cursor to range.start.
20439fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
20440 if range.start.row == range.end.row {
20441 range
20442 } else {
20443 range.start..range.start
20444 }
20445}
20446pub struct KillRing(ClipboardItem);
20447impl Global for KillRing {}
20448
20449const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
20450
20451enum BreakpointPromptEditAction {
20452 Log,
20453 Condition,
20454 HitCondition,
20455}
20456
20457struct BreakpointPromptEditor {
20458 pub(crate) prompt: Entity<Editor>,
20459 editor: WeakEntity<Editor>,
20460 breakpoint_anchor: Anchor,
20461 breakpoint: Breakpoint,
20462 edit_action: BreakpointPromptEditAction,
20463 block_ids: HashSet<CustomBlockId>,
20464 gutter_dimensions: Arc<Mutex<GutterDimensions>>,
20465 _subscriptions: Vec<Subscription>,
20466}
20467
20468impl BreakpointPromptEditor {
20469 const MAX_LINES: u8 = 4;
20470
20471 fn new(
20472 editor: WeakEntity<Editor>,
20473 breakpoint_anchor: Anchor,
20474 breakpoint: Breakpoint,
20475 edit_action: BreakpointPromptEditAction,
20476 window: &mut Window,
20477 cx: &mut Context<Self>,
20478 ) -> Self {
20479 let base_text = match edit_action {
20480 BreakpointPromptEditAction::Log => breakpoint.message.as_ref(),
20481 BreakpointPromptEditAction::Condition => breakpoint.condition.as_ref(),
20482 BreakpointPromptEditAction::HitCondition => breakpoint.hit_condition.as_ref(),
20483 }
20484 .map(|msg| msg.to_string())
20485 .unwrap_or_default();
20486
20487 let buffer = cx.new(|cx| Buffer::local(base_text, cx));
20488 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
20489
20490 let prompt = cx.new(|cx| {
20491 let mut prompt = Editor::new(
20492 EditorMode::AutoHeight {
20493 max_lines: Self::MAX_LINES as usize,
20494 },
20495 buffer,
20496 None,
20497 window,
20498 cx,
20499 );
20500 prompt.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
20501 prompt.set_show_cursor_when_unfocused(false, cx);
20502 prompt.set_placeholder_text(
20503 match edit_action {
20504 BreakpointPromptEditAction::Log => "Message to log when a breakpoint is hit. Expressions within {} are interpolated.",
20505 BreakpointPromptEditAction::Condition => "Condition when a breakpoint is hit. Expressions within {} are interpolated.",
20506 BreakpointPromptEditAction::HitCondition => "How many breakpoint hits to ignore",
20507 },
20508 cx,
20509 );
20510
20511 prompt
20512 });
20513
20514 Self {
20515 prompt,
20516 editor,
20517 breakpoint_anchor,
20518 breakpoint,
20519 edit_action,
20520 gutter_dimensions: Arc::new(Mutex::new(GutterDimensions::default())),
20521 block_ids: Default::default(),
20522 _subscriptions: vec![],
20523 }
20524 }
20525
20526 pub(crate) fn add_block_ids(&mut self, block_ids: Vec<CustomBlockId>) {
20527 self.block_ids.extend(block_ids)
20528 }
20529
20530 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
20531 if let Some(editor) = self.editor.upgrade() {
20532 let message = self
20533 .prompt
20534 .read(cx)
20535 .buffer
20536 .read(cx)
20537 .as_singleton()
20538 .expect("A multi buffer in breakpoint prompt isn't possible")
20539 .read(cx)
20540 .as_rope()
20541 .to_string();
20542
20543 editor.update(cx, |editor, cx| {
20544 editor.edit_breakpoint_at_anchor(
20545 self.breakpoint_anchor,
20546 self.breakpoint.clone(),
20547 match self.edit_action {
20548 BreakpointPromptEditAction::Log => {
20549 BreakpointEditAction::EditLogMessage(message.into())
20550 }
20551 BreakpointPromptEditAction::Condition => {
20552 BreakpointEditAction::EditCondition(message.into())
20553 }
20554 BreakpointPromptEditAction::HitCondition => {
20555 BreakpointEditAction::EditHitCondition(message.into())
20556 }
20557 },
20558 cx,
20559 );
20560
20561 editor.remove_blocks(self.block_ids.clone(), None, cx);
20562 cx.focus_self(window);
20563 });
20564 }
20565 }
20566
20567 fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
20568 self.editor
20569 .update(cx, |editor, cx| {
20570 editor.remove_blocks(self.block_ids.clone(), None, cx);
20571 window.focus(&editor.focus_handle);
20572 })
20573 .log_err();
20574 }
20575
20576 fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
20577 let settings = ThemeSettings::get_global(cx);
20578 let text_style = TextStyle {
20579 color: if self.prompt.read(cx).read_only(cx) {
20580 cx.theme().colors().text_disabled
20581 } else {
20582 cx.theme().colors().text
20583 },
20584 font_family: settings.buffer_font.family.clone(),
20585 font_fallbacks: settings.buffer_font.fallbacks.clone(),
20586 font_size: settings.buffer_font_size(cx).into(),
20587 font_weight: settings.buffer_font.weight,
20588 line_height: relative(settings.buffer_line_height.value()),
20589 ..Default::default()
20590 };
20591 EditorElement::new(
20592 &self.prompt,
20593 EditorStyle {
20594 background: cx.theme().colors().editor_background,
20595 local_player: cx.theme().players().local(),
20596 text: text_style,
20597 ..Default::default()
20598 },
20599 )
20600 }
20601}
20602
20603impl Render for BreakpointPromptEditor {
20604 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20605 let gutter_dimensions = *self.gutter_dimensions.lock();
20606 h_flex()
20607 .key_context("Editor")
20608 .bg(cx.theme().colors().editor_background)
20609 .border_y_1()
20610 .border_color(cx.theme().status().info_border)
20611 .size_full()
20612 .py(window.line_height() / 2.5)
20613 .on_action(cx.listener(Self::confirm))
20614 .on_action(cx.listener(Self::cancel))
20615 .child(h_flex().w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0)))
20616 .child(div().flex_1().child(self.render_prompt_editor(cx)))
20617 }
20618}
20619
20620impl Focusable for BreakpointPromptEditor {
20621 fn focus_handle(&self, cx: &App) -> FocusHandle {
20622 self.prompt.focus_handle(cx)
20623 }
20624}
20625
20626fn all_edits_insertions_or_deletions(
20627 edits: &Vec<(Range<Anchor>, String)>,
20628 snapshot: &MultiBufferSnapshot,
20629) -> bool {
20630 let mut all_insertions = true;
20631 let mut all_deletions = true;
20632
20633 for (range, new_text) in edits.iter() {
20634 let range_is_empty = range.to_offset(&snapshot).is_empty();
20635 let text_is_empty = new_text.is_empty();
20636
20637 if range_is_empty != text_is_empty {
20638 if range_is_empty {
20639 all_deletions = false;
20640 } else {
20641 all_insertions = false;
20642 }
20643 } else {
20644 return false;
20645 }
20646
20647 if !all_insertions && !all_deletions {
20648 return false;
20649 }
20650 }
20651 all_insertions || all_deletions
20652}
20653
20654struct MissingEditPredictionKeybindingTooltip;
20655
20656impl Render for MissingEditPredictionKeybindingTooltip {
20657 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
20658 ui::tooltip_container(window, cx, |container, _, cx| {
20659 container
20660 .flex_shrink_0()
20661 .max_w_80()
20662 .min_h(rems_from_px(124.))
20663 .justify_between()
20664 .child(
20665 v_flex()
20666 .flex_1()
20667 .text_ui_sm(cx)
20668 .child(Label::new("Conflict with Accept Keybinding"))
20669 .child("Your keymap currently overrides the default accept keybinding. To continue, assign one keybinding for the `editor::AcceptEditPrediction` action.")
20670 )
20671 .child(
20672 h_flex()
20673 .pb_1()
20674 .gap_1()
20675 .items_end()
20676 .w_full()
20677 .child(Button::new("open-keymap", "Assign Keybinding").size(ButtonSize::Compact).on_click(|_ev, window, cx| {
20678 window.dispatch_action(zed_actions::OpenKeymap.boxed_clone(), cx)
20679 }))
20680 .child(Button::new("see-docs", "See Docs").size(ButtonSize::Compact).on_click(|_ev, _window, cx| {
20681 cx.open_url("https://zed.dev/docs/completions#edit-predictions-missing-keybinding");
20682 })),
20683 )
20684 })
20685 }
20686}
20687
20688#[derive(Debug, Clone, Copy, PartialEq)]
20689pub struct LineHighlight {
20690 pub background: Background,
20691 pub border: Option<gpui::Hsla>,
20692}
20693
20694impl From<Hsla> for LineHighlight {
20695 fn from(hsla: Hsla) -> Self {
20696 Self {
20697 background: hsla.into(),
20698 border: None,
20699 }
20700 }
20701}
20702
20703impl From<Background> for LineHighlight {
20704 fn from(background: Background) -> Self {
20705 Self {
20706 background,
20707 border: None,
20708 }
20709 }
20710}
20711
20712fn render_diff_hunk_controls(
20713 row: u32,
20714 status: &DiffHunkStatus,
20715 hunk_range: Range<Anchor>,
20716 is_created_file: bool,
20717 line_height: Pixels,
20718 editor: &Entity<Editor>,
20719 _window: &mut Window,
20720 cx: &mut App,
20721) -> AnyElement {
20722 h_flex()
20723 .h(line_height)
20724 .mr_1()
20725 .gap_1()
20726 .px_0p5()
20727 .pb_1()
20728 .border_x_1()
20729 .border_b_1()
20730 .border_color(cx.theme().colors().border_variant)
20731 .rounded_b_lg()
20732 .bg(cx.theme().colors().editor_background)
20733 .gap_1()
20734 .occlude()
20735 .shadow_md()
20736 .child(if status.has_secondary_hunk() {
20737 Button::new(("stage", row as u64), "Stage")
20738 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20739 .tooltip({
20740 let focus_handle = editor.focus_handle(cx);
20741 move |window, cx| {
20742 Tooltip::for_action_in(
20743 "Stage Hunk",
20744 &::git::ToggleStaged,
20745 &focus_handle,
20746 window,
20747 cx,
20748 )
20749 }
20750 })
20751 .on_click({
20752 let editor = editor.clone();
20753 move |_event, _window, cx| {
20754 editor.update(cx, |editor, cx| {
20755 editor.stage_or_unstage_diff_hunks(
20756 true,
20757 vec![hunk_range.start..hunk_range.start],
20758 cx,
20759 );
20760 });
20761 }
20762 })
20763 } else {
20764 Button::new(("unstage", row as u64), "Unstage")
20765 .alpha(if status.is_pending() { 0.66 } else { 1.0 })
20766 .tooltip({
20767 let focus_handle = editor.focus_handle(cx);
20768 move |window, cx| {
20769 Tooltip::for_action_in(
20770 "Unstage Hunk",
20771 &::git::ToggleStaged,
20772 &focus_handle,
20773 window,
20774 cx,
20775 )
20776 }
20777 })
20778 .on_click({
20779 let editor = editor.clone();
20780 move |_event, _window, cx| {
20781 editor.update(cx, |editor, cx| {
20782 editor.stage_or_unstage_diff_hunks(
20783 false,
20784 vec![hunk_range.start..hunk_range.start],
20785 cx,
20786 );
20787 });
20788 }
20789 })
20790 })
20791 .child(
20792 Button::new(("restore", row as u64), "Restore")
20793 .tooltip({
20794 let focus_handle = editor.focus_handle(cx);
20795 move |window, cx| {
20796 Tooltip::for_action_in(
20797 "Restore Hunk",
20798 &::git::Restore,
20799 &focus_handle,
20800 window,
20801 cx,
20802 )
20803 }
20804 })
20805 .on_click({
20806 let editor = editor.clone();
20807 move |_event, window, cx| {
20808 editor.update(cx, |editor, cx| {
20809 let snapshot = editor.snapshot(window, cx);
20810 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
20811 editor.restore_hunks_in_ranges(vec![point..point], window, cx);
20812 });
20813 }
20814 })
20815 .disabled(is_created_file),
20816 )
20817 .when(
20818 !editor.read(cx).buffer().read(cx).all_diff_hunks_expanded(),
20819 |el| {
20820 el.child(
20821 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
20822 .shape(IconButtonShape::Square)
20823 .icon_size(IconSize::Small)
20824 // .disabled(!has_multiple_hunks)
20825 .tooltip({
20826 let focus_handle = editor.focus_handle(cx);
20827 move |window, cx| {
20828 Tooltip::for_action_in(
20829 "Next Hunk",
20830 &GoToHunk,
20831 &focus_handle,
20832 window,
20833 cx,
20834 )
20835 }
20836 })
20837 .on_click({
20838 let editor = editor.clone();
20839 move |_event, window, cx| {
20840 editor.update(cx, |editor, cx| {
20841 let snapshot = editor.snapshot(window, cx);
20842 let position =
20843 hunk_range.end.to_point(&snapshot.buffer_snapshot);
20844 editor.go_to_hunk_before_or_after_position(
20845 &snapshot,
20846 position,
20847 Direction::Next,
20848 window,
20849 cx,
20850 );
20851 editor.expand_selected_diff_hunks(cx);
20852 });
20853 }
20854 }),
20855 )
20856 .child(
20857 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
20858 .shape(IconButtonShape::Square)
20859 .icon_size(IconSize::Small)
20860 // .disabled(!has_multiple_hunks)
20861 .tooltip({
20862 let focus_handle = editor.focus_handle(cx);
20863 move |window, cx| {
20864 Tooltip::for_action_in(
20865 "Previous Hunk",
20866 &GoToPreviousHunk,
20867 &focus_handle,
20868 window,
20869 cx,
20870 )
20871 }
20872 })
20873 .on_click({
20874 let editor = editor.clone();
20875 move |_event, window, cx| {
20876 editor.update(cx, |editor, cx| {
20877 let snapshot = editor.snapshot(window, cx);
20878 let point =
20879 hunk_range.start.to_point(&snapshot.buffer_snapshot);
20880 editor.go_to_hunk_before_or_after_position(
20881 &snapshot,
20882 point,
20883 Direction::Prev,
20884 window,
20885 cx,
20886 );
20887 editor.expand_selected_diff_hunks(cx);
20888 });
20889 }
20890 }),
20891 )
20892 },
20893 )
20894 .into_any_element()
20895}