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 behaviour.
15pub mod actions;
16mod blink_manager;
17pub mod display_map;
18mod editor_settings;
19mod element;
20mod inlay_hint_cache;
21
22mod debounced_delay;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26mod hover_popover;
27mod inline_completion_provider;
28pub mod items;
29mod mouse_context_menu;
30pub mod movement;
31mod persistence;
32mod rust_analyzer_ext;
33pub mod scroll;
34mod selections_collection;
35
36#[cfg(test)]
37mod editor_tests;
38#[cfg(any(test, feature = "test-support"))]
39pub mod test;
40use ::git::diff::{DiffHunk, DiffHunkStatus};
41use ::git::permalink::{build_permalink, BuildPermalinkParams};
42pub(crate) use actions::*;
43use aho_corasick::AhoCorasick;
44use anyhow::{anyhow, Context as _, Result};
45use blink_manager::BlinkManager;
46use client::{Collaborator, ParticipantIndex};
47use clock::ReplicaId;
48use collections::{hash_map, BTreeMap, Bound, HashMap, HashSet, VecDeque};
49use convert_case::{Case, Casing};
50use debounced_delay::DebouncedDelay;
51pub use display_map::DisplayPoint;
52use display_map::*;
53pub use editor_settings::EditorSettings;
54use element::LineWithInvisibles;
55pub use element::{
56 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
57};
58use futures::FutureExt;
59use fuzzy::{StringMatch, StringMatchCandidate};
60use git::blame::GitBlame;
61use git::diff_hunk_to_display;
62use gpui::{
63 div, impl_actions, point, prelude::*, px, relative, rems, size, uniform_list, Action,
64 AnyElement, AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds,
65 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView,
66 FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext, Model,
67 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, StrikethroughStyle,
68 Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle, UniformListScrollHandle,
69 View, ViewContext, ViewInputHandler, VisualContext, WeakView, WhiteSpace, WindowContext,
70};
71use highlight_matching_bracket::refresh_matching_bracket_highlights;
72use hover_popover::{hide_hover, HoverState};
73use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
74pub use inline_completion_provider::*;
75pub use items::MAX_TAB_TITLE_LEN;
76use itertools::Itertools;
77use language::{
78 char_kind,
79 language_settings::{self, all_language_settings, InlayHintSettings},
80 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
81 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
82 Point, Selection, SelectionGoal, TransactionId,
83};
84
85use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
86use lsp::{DiagnosticSeverity, LanguageServerId};
87use mouse_context_menu::MouseContextMenu;
88use movement::TextLayoutDetails;
89use multi_buffer::ToOffsetUtf16;
90pub use multi_buffer::{
91 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
92 ToPoint,
93};
94use ordered_float::OrderedFloat;
95use parking_lot::{Mutex, RwLock};
96use project::project_settings::{GitGutterSetting, ProjectSettings};
97use project::{
98 CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath, ProjectTransaction,
99};
100use rand::prelude::*;
101use rpc::proto::*;
102use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
103use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
104use serde::{Deserialize, Serialize};
105use settings::{Settings, SettingsStore};
106use smallvec::SmallVec;
107use snippet::Snippet;
108use std::ops::Not as _;
109use std::{
110 any::TypeId,
111 borrow::Cow,
112 cmp::{self, Ordering, Reverse},
113 mem,
114 num::NonZeroU32,
115 ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
116 path::Path,
117 sync::Arc,
118 time::{Duration, Instant},
119};
120pub use sum_tree::Bias;
121use sum_tree::TreeMap;
122use text::{BufferId, OffsetUtf16, Rope};
123use theme::{
124 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
125 ThemeColors, ThemeSettings,
126};
127use ui::{
128 h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
129 Tooltip,
130};
131use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
132use workspace::item::ItemHandle;
133use workspace::notifications::NotificationId;
134use workspace::Toast;
135use workspace::{
136 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
137};
138
139use crate::hover_links::find_url;
140
141const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
142const MAX_LINE_LEN: usize = 1024;
143const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
144const MAX_SELECTION_HISTORY_LEN: usize = 1024;
145pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
146#[doc(hidden)]
147pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
148#[doc(hidden)]
149pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
150
151pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
152
153pub fn render_parsed_markdown(
154 element_id: impl Into<ElementId>,
155 parsed: &language::ParsedMarkdown,
156 editor_style: &EditorStyle,
157 workspace: Option<WeakView<Workspace>>,
158 cx: &mut ViewContext<Editor>,
159) -> InteractiveText {
160 let code_span_background_color = cx
161 .theme()
162 .colors()
163 .editor_document_highlight_read_background;
164
165 let highlights = gpui::combine_highlights(
166 parsed.highlights.iter().filter_map(|(range, highlight)| {
167 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
168 Some((range.clone(), highlight))
169 }),
170 parsed
171 .regions
172 .iter()
173 .zip(&parsed.region_ranges)
174 .filter_map(|(region, range)| {
175 if region.code {
176 Some((
177 range.clone(),
178 HighlightStyle {
179 background_color: Some(code_span_background_color),
180 ..Default::default()
181 },
182 ))
183 } else {
184 None
185 }
186 }),
187 );
188
189 let mut links = Vec::new();
190 let mut link_ranges = Vec::new();
191 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
192 if let Some(link) = region.link.clone() {
193 links.push(link);
194 link_ranges.push(range.clone());
195 }
196 }
197
198 InteractiveText::new(
199 element_id,
200 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
201 )
202 .on_click(link_ranges, move |clicked_range_ix, cx| {
203 match &links[clicked_range_ix] {
204 markdown::Link::Web { url } => cx.open_url(url),
205 markdown::Link::Path { path } => {
206 if let Some(workspace) = &workspace {
207 _ = workspace.update(cx, |workspace, cx| {
208 workspace.open_abs_path(path.clone(), false, cx).detach();
209 });
210 }
211 }
212 }
213 })
214}
215
216#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
217pub(crate) enum InlayId {
218 Suggestion(usize),
219 Hint(usize),
220}
221
222impl InlayId {
223 fn id(&self) -> usize {
224 match self {
225 Self::Suggestion(id) => *id,
226 Self::Hint(id) => *id,
227 }
228 }
229}
230
231enum DocumentHighlightRead {}
232enum DocumentHighlightWrite {}
233enum InputComposition {}
234
235#[derive(Copy, Clone, PartialEq, Eq)]
236pub enum Direction {
237 Prev,
238 Next,
239}
240
241pub fn init_settings(cx: &mut AppContext) {
242 EditorSettings::register(cx);
243}
244
245pub fn init(cx: &mut AppContext) {
246 init_settings(cx);
247
248 workspace::register_project_item::<Editor>(cx);
249 workspace::register_followable_item::<Editor>(cx);
250 workspace::register_deserializable_item::<Editor>(cx);
251 cx.observe_new_views(
252 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
253 workspace.register_action(Editor::new_file);
254 workspace.register_action(Editor::new_file_in_direction);
255 },
256 )
257 .detach();
258
259 cx.on_action(move |_: &workspace::NewFile, cx| {
260 let app_state = workspace::AppState::global(cx);
261 if let Some(app_state) = app_state.upgrade() {
262 workspace::open_new(app_state, cx, |workspace, cx| {
263 Editor::new_file(workspace, &Default::default(), cx)
264 })
265 .detach();
266 }
267 });
268 cx.on_action(move |_: &workspace::NewWindow, cx| {
269 let app_state = workspace::AppState::global(cx);
270 if let Some(app_state) = app_state.upgrade() {
271 workspace::open_new(app_state, cx, |workspace, cx| {
272 Editor::new_file(workspace, &Default::default(), cx)
273 })
274 .detach();
275 }
276 });
277}
278
279trait InvalidationRegion {
280 fn ranges(&self) -> &[Range<Anchor>];
281}
282
283#[derive(Clone, Debug, PartialEq)]
284pub enum SelectPhase {
285 Begin {
286 position: DisplayPoint,
287 add: bool,
288 click_count: usize,
289 },
290 BeginColumnar {
291 position: DisplayPoint,
292 goal_column: u32,
293 },
294 Extend {
295 position: DisplayPoint,
296 click_count: usize,
297 },
298 Update {
299 position: DisplayPoint,
300 goal_column: u32,
301 scroll_delta: gpui::Point<f32>,
302 },
303 End,
304}
305
306#[derive(Clone, Debug)]
307pub enum SelectMode {
308 Character,
309 Word(Range<Anchor>),
310 Line(Range<Anchor>),
311 All,
312}
313
314#[derive(Copy, Clone, PartialEq, Eq, Debug)]
315pub enum EditorMode {
316 SingleLine,
317 AutoHeight { max_lines: usize },
318 Full,
319}
320
321#[derive(Clone, Debug)]
322pub enum SoftWrap {
323 None,
324 EditorWidth,
325 Column(u32),
326}
327
328#[derive(Clone)]
329pub struct EditorStyle {
330 pub background: Hsla,
331 pub local_player: PlayerColor,
332 pub text: TextStyle,
333 pub scrollbar_width: Pixels,
334 pub syntax: Arc<SyntaxTheme>,
335 pub status: StatusColors,
336 pub inlay_hints_style: HighlightStyle,
337 pub suggestions_style: HighlightStyle,
338}
339
340impl Default for EditorStyle {
341 fn default() -> Self {
342 Self {
343 background: Hsla::default(),
344 local_player: PlayerColor::default(),
345 text: TextStyle::default(),
346 scrollbar_width: Pixels::default(),
347 syntax: Default::default(),
348 // HACK: Status colors don't have a real default.
349 // We should look into removing the status colors from the editor
350 // style and retrieve them directly from the theme.
351 status: StatusColors::dark(),
352 inlay_hints_style: HighlightStyle::default(),
353 suggestions_style: HighlightStyle::default(),
354 }
355 }
356}
357
358type CompletionId = usize;
359
360// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
361// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
362
363type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
364
365struct ScrollbarMarkerState {
366 scrollbar_size: Size<Pixels>,
367 dirty: bool,
368 markers: Arc<[PaintQuad]>,
369 pending_refresh: Option<Task<Result<()>>>,
370}
371
372impl ScrollbarMarkerState {
373 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
374 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
375 }
376}
377
378impl Default for ScrollbarMarkerState {
379 fn default() -> Self {
380 Self {
381 scrollbar_size: Size::default(),
382 dirty: false,
383 markers: Arc::from([]),
384 pending_refresh: None,
385 }
386 }
387}
388
389/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
390///
391/// See the [module level documentation](self) for more information.
392pub struct Editor {
393 focus_handle: FocusHandle,
394 /// The text buffer being edited
395 buffer: Model<MultiBuffer>,
396 /// Map of how text in the buffer should be displayed.
397 /// Handles soft wraps, folds, fake inlay text insertions, etc.
398 pub display_map: Model<DisplayMap>,
399 pub selections: SelectionsCollection,
400 pub scroll_manager: ScrollManager,
401 columnar_selection_tail: Option<Anchor>,
402 add_selections_state: Option<AddSelectionsState>,
403 select_next_state: Option<SelectNextState>,
404 select_prev_state: Option<SelectNextState>,
405 selection_history: SelectionHistory,
406 autoclose_regions: Vec<AutocloseRegion>,
407 snippet_stack: InvalidationStack<SnippetState>,
408 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
409 ime_transaction: Option<TransactionId>,
410 active_diagnostics: Option<ActiveDiagnosticGroup>,
411 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
412 project: Option<Model<Project>>,
413 completion_provider: Option<Box<dyn CompletionProvider>>,
414 collaboration_hub: Option<Box<dyn CollaborationHub>>,
415 blink_manager: Model<BlinkManager>,
416 show_cursor_names: bool,
417 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
418 pub show_local_selections: bool,
419 mode: EditorMode,
420 show_breadcrumbs: bool,
421 show_gutter: bool,
422 show_wrap_guides: Option<bool>,
423 placeholder_text: Option<Arc<str>>,
424 highlight_order: usize,
425 highlighted_rows: HashMap<TypeId, Vec<(usize, Range<Anchor>, Hsla)>>,
426 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
427 scrollbar_marker_state: ScrollbarMarkerState,
428 nav_history: Option<ItemNavHistory>,
429 context_menu: RwLock<Option<ContextMenu>>,
430 mouse_context_menu: Option<MouseContextMenu>,
431 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
432 find_all_references_task_sources: Vec<Anchor>,
433 next_completion_id: CompletionId,
434 completion_documentation_pre_resolve_debounce: DebouncedDelay,
435 available_code_actions: Option<(Model<Buffer>, Arc<[CodeAction]>)>,
436 code_actions_task: Option<Task<()>>,
437 document_highlights_task: Option<Task<()>>,
438 pending_rename: Option<RenameState>,
439 searchable: bool,
440 cursor_shape: CursorShape,
441 collapse_matches: bool,
442 autoindent_mode: Option<AutoindentMode>,
443 workspace: Option<(WeakView<Workspace>, WorkspaceId)>,
444 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
445 input_enabled: bool,
446 use_modal_editing: bool,
447 read_only: bool,
448 leader_peer_id: Option<PeerId>,
449 remote_id: Option<ViewId>,
450 hover_state: HoverState,
451 gutter_hovered: bool,
452 hovered_link_state: Option<HoveredLinkState>,
453 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
454 active_inline_completion: Option<Inlay>,
455 show_inline_completions: bool,
456 inlay_hint_cache: InlayHintCache,
457 next_inlay_id: usize,
458 _subscriptions: Vec<Subscription>,
459 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
460 gutter_width: Pixels,
461 pub vim_replace_map: HashMap<Range<usize>, String>,
462 style: Option<EditorStyle>,
463 editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
464 use_autoclose: bool,
465 auto_replace_emoji_shortcode: bool,
466 show_git_blame: bool,
467 blame: Option<Model<GitBlame>>,
468 blame_subscription: Option<Subscription>,
469 custom_context_menu: Option<
470 Box<
471 dyn 'static
472 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
473 >,
474 >,
475 last_bounds: Option<Bounds<Pixels>>,
476 expect_bounds_change: Option<Bounds<Pixels>>,
477}
478
479#[derive(Clone)]
480pub struct EditorSnapshot {
481 pub mode: EditorMode,
482 show_gutter: bool,
483 show_git_blame: bool,
484 pub display_snapshot: DisplaySnapshot,
485 pub placeholder_text: Option<Arc<str>>,
486 is_focused: bool,
487 scroll_anchor: ScrollAnchor,
488 ongoing_scroll: OngoingScroll,
489}
490
491const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
492
493pub struct GutterDimensions {
494 pub left_padding: Pixels,
495 pub right_padding: Pixels,
496 pub width: Pixels,
497 pub margin: Pixels,
498 pub git_blame_entries_width: Option<Pixels>,
499}
500
501impl Default for GutterDimensions {
502 fn default() -> Self {
503 Self {
504 left_padding: Pixels::ZERO,
505 right_padding: Pixels::ZERO,
506 width: Pixels::ZERO,
507 margin: Pixels::ZERO,
508 git_blame_entries_width: None,
509 }
510 }
511}
512
513#[derive(Debug)]
514pub struct RemoteSelection {
515 pub replica_id: ReplicaId,
516 pub selection: Selection<Anchor>,
517 pub cursor_shape: CursorShape,
518 pub peer_id: PeerId,
519 pub line_mode: bool,
520 pub participant_index: Option<ParticipantIndex>,
521 pub user_name: Option<SharedString>,
522}
523
524#[derive(Clone, Debug)]
525struct SelectionHistoryEntry {
526 selections: Arc<[Selection<Anchor>]>,
527 select_next_state: Option<SelectNextState>,
528 select_prev_state: Option<SelectNextState>,
529 add_selections_state: Option<AddSelectionsState>,
530}
531
532enum SelectionHistoryMode {
533 Normal,
534 Undoing,
535 Redoing,
536}
537
538#[derive(Clone, PartialEq, Eq, Hash)]
539struct HoveredCursor {
540 replica_id: u16,
541 selection_id: usize,
542}
543
544impl Default for SelectionHistoryMode {
545 fn default() -> Self {
546 Self::Normal
547 }
548}
549
550#[derive(Default)]
551struct SelectionHistory {
552 #[allow(clippy::type_complexity)]
553 selections_by_transaction:
554 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
555 mode: SelectionHistoryMode,
556 undo_stack: VecDeque<SelectionHistoryEntry>,
557 redo_stack: VecDeque<SelectionHistoryEntry>,
558}
559
560impl SelectionHistory {
561 fn insert_transaction(
562 &mut self,
563 transaction_id: TransactionId,
564 selections: Arc<[Selection<Anchor>]>,
565 ) {
566 self.selections_by_transaction
567 .insert(transaction_id, (selections, None));
568 }
569
570 #[allow(clippy::type_complexity)]
571 fn transaction(
572 &self,
573 transaction_id: TransactionId,
574 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
575 self.selections_by_transaction.get(&transaction_id)
576 }
577
578 #[allow(clippy::type_complexity)]
579 fn transaction_mut(
580 &mut self,
581 transaction_id: TransactionId,
582 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
583 self.selections_by_transaction.get_mut(&transaction_id)
584 }
585
586 fn push(&mut self, entry: SelectionHistoryEntry) {
587 if !entry.selections.is_empty() {
588 match self.mode {
589 SelectionHistoryMode::Normal => {
590 self.push_undo(entry);
591 self.redo_stack.clear();
592 }
593 SelectionHistoryMode::Undoing => self.push_redo(entry),
594 SelectionHistoryMode::Redoing => self.push_undo(entry),
595 }
596 }
597 }
598
599 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
600 if self
601 .undo_stack
602 .back()
603 .map_or(true, |e| e.selections != entry.selections)
604 {
605 self.undo_stack.push_back(entry);
606 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
607 self.undo_stack.pop_front();
608 }
609 }
610 }
611
612 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
613 if self
614 .redo_stack
615 .back()
616 .map_or(true, |e| e.selections != entry.selections)
617 {
618 self.redo_stack.push_back(entry);
619 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
620 self.redo_stack.pop_front();
621 }
622 }
623 }
624}
625
626#[derive(Clone, Debug)]
627struct AddSelectionsState {
628 above: bool,
629 stack: Vec<usize>,
630}
631
632#[derive(Clone)]
633struct SelectNextState {
634 query: AhoCorasick,
635 wordwise: bool,
636 done: bool,
637}
638
639impl std::fmt::Debug for SelectNextState {
640 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
641 f.debug_struct(std::any::type_name::<Self>())
642 .field("wordwise", &self.wordwise)
643 .field("done", &self.done)
644 .finish()
645 }
646}
647
648#[derive(Debug)]
649struct AutocloseRegion {
650 selection_id: usize,
651 range: Range<Anchor>,
652 pair: BracketPair,
653}
654
655#[derive(Debug)]
656struct SnippetState {
657 ranges: Vec<Vec<Range<Anchor>>>,
658 active_index: usize,
659}
660
661#[doc(hidden)]
662pub struct RenameState {
663 pub range: Range<Anchor>,
664 pub old_name: Arc<str>,
665 pub editor: View<Editor>,
666 block_id: BlockId,
667}
668
669struct InvalidationStack<T>(Vec<T>);
670
671struct RegisteredInlineCompletionProvider {
672 provider: Arc<dyn InlineCompletionProviderHandle>,
673 _subscription: Subscription,
674}
675
676enum ContextMenu {
677 Completions(CompletionsMenu),
678 CodeActions(CodeActionsMenu),
679}
680
681impl ContextMenu {
682 fn select_first(
683 &mut self,
684 project: Option<&Model<Project>>,
685 cx: &mut ViewContext<Editor>,
686 ) -> bool {
687 if self.visible() {
688 match self {
689 ContextMenu::Completions(menu) => menu.select_first(project, cx),
690 ContextMenu::CodeActions(menu) => menu.select_first(cx),
691 }
692 true
693 } else {
694 false
695 }
696 }
697
698 fn select_prev(
699 &mut self,
700 project: Option<&Model<Project>>,
701 cx: &mut ViewContext<Editor>,
702 ) -> bool {
703 if self.visible() {
704 match self {
705 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
706 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
707 }
708 true
709 } else {
710 false
711 }
712 }
713
714 fn select_next(
715 &mut self,
716 project: Option<&Model<Project>>,
717 cx: &mut ViewContext<Editor>,
718 ) -> bool {
719 if self.visible() {
720 match self {
721 ContextMenu::Completions(menu) => menu.select_next(project, cx),
722 ContextMenu::CodeActions(menu) => menu.select_next(cx),
723 }
724 true
725 } else {
726 false
727 }
728 }
729
730 fn select_last(
731 &mut self,
732 project: Option<&Model<Project>>,
733 cx: &mut ViewContext<Editor>,
734 ) -> bool {
735 if self.visible() {
736 match self {
737 ContextMenu::Completions(menu) => menu.select_last(project, cx),
738 ContextMenu::CodeActions(menu) => menu.select_last(cx),
739 }
740 true
741 } else {
742 false
743 }
744 }
745
746 fn visible(&self) -> bool {
747 match self {
748 ContextMenu::Completions(menu) => menu.visible(),
749 ContextMenu::CodeActions(menu) => menu.visible(),
750 }
751 }
752
753 fn render(
754 &self,
755 cursor_position: DisplayPoint,
756 style: &EditorStyle,
757 max_height: Pixels,
758 workspace: Option<WeakView<Workspace>>,
759 cx: &mut ViewContext<Editor>,
760 ) -> (DisplayPoint, AnyElement) {
761 match self {
762 ContextMenu::Completions(menu) => (
763 cursor_position,
764 menu.render(style, max_height, workspace, cx),
765 ),
766 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
767 }
768 }
769}
770
771#[derive(Clone)]
772struct CompletionsMenu {
773 id: CompletionId,
774 initial_position: Anchor,
775 buffer: Model<Buffer>,
776 completions: Arc<RwLock<Box<[Completion]>>>,
777 match_candidates: Arc<[StringMatchCandidate]>,
778 matches: Arc<[StringMatch]>,
779 selected_item: usize,
780 scroll_handle: UniformListScrollHandle,
781 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
782}
783
784impl CompletionsMenu {
785 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
786 self.selected_item = 0;
787 self.scroll_handle.scroll_to_item(self.selected_item);
788 self.attempt_resolve_selected_completion_documentation(project, cx);
789 cx.notify();
790 }
791
792 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
793 if self.selected_item > 0 {
794 self.selected_item -= 1;
795 } else {
796 self.selected_item = self.matches.len() - 1;
797 }
798 self.scroll_handle.scroll_to_item(self.selected_item);
799 self.attempt_resolve_selected_completion_documentation(project, cx);
800 cx.notify();
801 }
802
803 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
804 if self.selected_item + 1 < self.matches.len() {
805 self.selected_item += 1;
806 } else {
807 self.selected_item = 0;
808 }
809 self.scroll_handle.scroll_to_item(self.selected_item);
810 self.attempt_resolve_selected_completion_documentation(project, cx);
811 cx.notify();
812 }
813
814 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
815 self.selected_item = self.matches.len() - 1;
816 self.scroll_handle.scroll_to_item(self.selected_item);
817 self.attempt_resolve_selected_completion_documentation(project, cx);
818 cx.notify();
819 }
820
821 fn pre_resolve_completion_documentation(
822 completions: Arc<RwLock<Box<[Completion]>>>,
823 matches: Arc<[StringMatch]>,
824 editor: &Editor,
825 cx: &mut ViewContext<Editor>,
826 ) -> Task<()> {
827 let settings = EditorSettings::get_global(cx);
828 if !settings.show_completion_documentation {
829 return Task::ready(());
830 }
831
832 let Some(provider) = editor.completion_provider.as_ref() else {
833 return Task::ready(());
834 };
835
836 let resolve_task = provider.resolve_completions(
837 matches.iter().map(|m| m.candidate_id).collect(),
838 completions.clone(),
839 cx,
840 );
841
842 return cx.spawn(move |this, mut cx| async move {
843 if let Some(true) = resolve_task.await.log_err() {
844 this.update(&mut cx, |_, cx| cx.notify()).ok();
845 }
846 });
847 }
848
849 fn attempt_resolve_selected_completion_documentation(
850 &mut self,
851 project: Option<&Model<Project>>,
852 cx: &mut ViewContext<Editor>,
853 ) {
854 let settings = EditorSettings::get_global(cx);
855 if !settings.show_completion_documentation {
856 return;
857 }
858
859 let completion_index = self.matches[self.selected_item].candidate_id;
860 let Some(project) = project else {
861 return;
862 };
863
864 let resolve_task = project.update(cx, |project, cx| {
865 project.resolve_completions(vec![completion_index], self.completions.clone(), cx)
866 });
867
868 let delay_ms =
869 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
870 let delay = Duration::from_millis(delay_ms);
871
872 self.selected_completion_documentation_resolve_debounce
873 .lock()
874 .fire_new(delay, cx, |_, cx| {
875 cx.spawn(move |this, mut cx| async move {
876 if let Some(true) = resolve_task.await.log_err() {
877 this.update(&mut cx, |_, cx| cx.notify()).ok();
878 }
879 })
880 });
881 }
882
883 fn visible(&self) -> bool {
884 !self.matches.is_empty()
885 }
886
887 fn render(
888 &self,
889 style: &EditorStyle,
890 max_height: Pixels,
891 workspace: Option<WeakView<Workspace>>,
892 cx: &mut ViewContext<Editor>,
893 ) -> AnyElement {
894 let settings = EditorSettings::get_global(cx);
895 let show_completion_documentation = settings.show_completion_documentation;
896
897 let widest_completion_ix = self
898 .matches
899 .iter()
900 .enumerate()
901 .max_by_key(|(_, mat)| {
902 let completions = self.completions.read();
903 let completion = &completions[mat.candidate_id];
904 let documentation = &completion.documentation;
905
906 let mut len = completion.label.text.chars().count();
907 if let Some(Documentation::SingleLine(text)) = documentation {
908 if show_completion_documentation {
909 len += text.chars().count();
910 }
911 }
912
913 len
914 })
915 .map(|(ix, _)| ix);
916
917 let completions = self.completions.clone();
918 let matches = self.matches.clone();
919 let selected_item = self.selected_item;
920 let style = style.clone();
921
922 let multiline_docs = if show_completion_documentation {
923 let mat = &self.matches[selected_item];
924 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
925 Some(Documentation::MultiLinePlainText(text)) => {
926 Some(div().child(SharedString::from(text.clone())))
927 }
928 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
929 Some(div().child(render_parsed_markdown(
930 "completions_markdown",
931 parsed,
932 &style,
933 workspace,
934 cx,
935 )))
936 }
937 _ => None,
938 };
939 multiline_docs.map(|div| {
940 div.id("multiline_docs")
941 .max_h(max_height)
942 .flex_1()
943 .px_1p5()
944 .py_1()
945 .min_w(px(260.))
946 .max_w(px(640.))
947 .w(px(500.))
948 .overflow_y_scroll()
949 .occlude()
950 })
951 } else {
952 None
953 };
954
955 let list = uniform_list(
956 cx.view().clone(),
957 "completions",
958 matches.len(),
959 move |_editor, range, cx| {
960 let start_ix = range.start;
961 let completions_guard = completions.read();
962
963 matches[range]
964 .iter()
965 .enumerate()
966 .map(|(ix, mat)| {
967 let item_ix = start_ix + ix;
968 let candidate_id = mat.candidate_id;
969 let completion = &completions_guard[candidate_id];
970
971 let documentation = if show_completion_documentation {
972 &completion.documentation
973 } else {
974 &None
975 };
976
977 let highlights = gpui::combine_highlights(
978 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
979 styled_runs_for_code_label(&completion.label, &style.syntax).map(
980 |(range, mut highlight)| {
981 // Ignore font weight for syntax highlighting, as we'll use it
982 // for fuzzy matches.
983 highlight.font_weight = None;
984
985 if completion.lsp_completion.deprecated.unwrap_or(false) {
986 highlight.strikethrough = Some(StrikethroughStyle {
987 thickness: 1.0.into(),
988 ..Default::default()
989 });
990 highlight.color = Some(cx.theme().colors().text_muted);
991 }
992
993 (range, highlight)
994 },
995 ),
996 );
997 let completion_label = StyledText::new(completion.label.text.clone())
998 .with_highlights(&style.text, highlights);
999 let documentation_label =
1000 if let Some(Documentation::SingleLine(text)) = documentation {
1001 if text.trim().is_empty() {
1002 None
1003 } else {
1004 Some(
1005 h_flex().ml_4().child(
1006 Label::new(text.clone())
1007 .size(LabelSize::Small)
1008 .color(Color::Muted),
1009 ),
1010 )
1011 }
1012 } else {
1013 None
1014 };
1015
1016 div().min_w(px(220.)).max_w(px(540.)).child(
1017 ListItem::new(mat.candidate_id)
1018 .inset(true)
1019 .selected(item_ix == selected_item)
1020 .on_click(cx.listener(move |editor, _event, cx| {
1021 cx.stop_propagation();
1022 if let Some(task) = editor.confirm_completion(
1023 &ConfirmCompletion {
1024 item_ix: Some(item_ix),
1025 },
1026 cx,
1027 ) {
1028 task.detach_and_log_err(cx)
1029 }
1030 }))
1031 .child(h_flex().overflow_hidden().child(completion_label))
1032 .end_slot::<Div>(documentation_label),
1033 )
1034 })
1035 .collect()
1036 },
1037 )
1038 .occlude()
1039 .max_h(max_height)
1040 .track_scroll(self.scroll_handle.clone())
1041 .with_width_from_item(widest_completion_ix);
1042
1043 Popover::new()
1044 .child(list)
1045 .when_some(multiline_docs, |popover, multiline_docs| {
1046 popover.aside(multiline_docs)
1047 })
1048 .into_any_element()
1049 }
1050
1051 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1052 let mut matches = if let Some(query) = query {
1053 fuzzy::match_strings(
1054 &self.match_candidates,
1055 query,
1056 query.chars().any(|c| c.is_uppercase()),
1057 100,
1058 &Default::default(),
1059 executor,
1060 )
1061 .await
1062 } else {
1063 self.match_candidates
1064 .iter()
1065 .enumerate()
1066 .map(|(candidate_id, candidate)| StringMatch {
1067 candidate_id,
1068 score: Default::default(),
1069 positions: Default::default(),
1070 string: candidate.string.clone(),
1071 })
1072 .collect()
1073 };
1074
1075 // Remove all candidates where the query's start does not match the start of any word in the candidate
1076 if let Some(query) = query {
1077 if let Some(query_start) = query.chars().next() {
1078 matches.retain(|string_match| {
1079 split_words(&string_match.string).any(|word| {
1080 // Check that the first codepoint of the word as lowercase matches the first
1081 // codepoint of the query as lowercase
1082 word.chars()
1083 .flat_map(|codepoint| codepoint.to_lowercase())
1084 .zip(query_start.to_lowercase())
1085 .all(|(word_cp, query_cp)| word_cp == query_cp)
1086 })
1087 });
1088 }
1089 }
1090
1091 let completions = self.completions.read();
1092 matches.sort_unstable_by_key(|mat| {
1093 // We do want to strike a balance here between what the language server tells us
1094 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1095 // `Creat` and there is a local variable called `CreateComponent`).
1096 // So what we do is: we bucket all matches into two buckets
1097 // - Strong matches
1098 // - Weak matches
1099 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1100 // and the Weak matches are the rest.
1101 //
1102 // For the strong matches, we sort by the language-servers score first and for the weak
1103 // matches, we prefer our fuzzy finder first.
1104 //
1105 // The thinking behind that: it's useless to take the sort_text the language-server gives
1106 // us into account when it's obviously a bad match.
1107
1108 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1109 enum MatchScore<'a> {
1110 Strong {
1111 sort_text: Option<&'a str>,
1112 score: Reverse<OrderedFloat<f64>>,
1113 sort_key: (usize, &'a str),
1114 },
1115 Weak {
1116 score: Reverse<OrderedFloat<f64>>,
1117 sort_text: Option<&'a str>,
1118 sort_key: (usize, &'a str),
1119 },
1120 }
1121
1122 let completion = &completions[mat.candidate_id];
1123 let sort_key = completion.sort_key();
1124 let sort_text = completion.lsp_completion.sort_text.as_deref();
1125 let score = Reverse(OrderedFloat(mat.score));
1126
1127 if mat.score >= 0.2 {
1128 MatchScore::Strong {
1129 sort_text,
1130 score,
1131 sort_key,
1132 }
1133 } else {
1134 MatchScore::Weak {
1135 score,
1136 sort_text,
1137 sort_key,
1138 }
1139 }
1140 });
1141
1142 for mat in &mut matches {
1143 let completion = &completions[mat.candidate_id];
1144 mat.string = completion.label.text.clone();
1145 for position in &mut mat.positions {
1146 *position += completion.label.filter_range.start;
1147 }
1148 }
1149 drop(completions);
1150
1151 self.matches = matches.into();
1152 self.selected_item = 0;
1153 }
1154}
1155
1156#[derive(Clone)]
1157struct CodeActionsMenu {
1158 actions: Arc<[CodeAction]>,
1159 buffer: Model<Buffer>,
1160 selected_item: usize,
1161 scroll_handle: UniformListScrollHandle,
1162 deployed_from_indicator: bool,
1163}
1164
1165impl CodeActionsMenu {
1166 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1167 self.selected_item = 0;
1168 self.scroll_handle.scroll_to_item(self.selected_item);
1169 cx.notify()
1170 }
1171
1172 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1173 if self.selected_item > 0 {
1174 self.selected_item -= 1;
1175 } else {
1176 self.selected_item = self.actions.len() - 1;
1177 }
1178 self.scroll_handle.scroll_to_item(self.selected_item);
1179 cx.notify();
1180 }
1181
1182 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1183 if self.selected_item + 1 < self.actions.len() {
1184 self.selected_item += 1;
1185 } else {
1186 self.selected_item = 0;
1187 }
1188 self.scroll_handle.scroll_to_item(self.selected_item);
1189 cx.notify();
1190 }
1191
1192 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1193 self.selected_item = self.actions.len() - 1;
1194 self.scroll_handle.scroll_to_item(self.selected_item);
1195 cx.notify()
1196 }
1197
1198 fn visible(&self) -> bool {
1199 !self.actions.is_empty()
1200 }
1201
1202 fn render(
1203 &self,
1204 mut cursor_position: DisplayPoint,
1205 _style: &EditorStyle,
1206 max_height: Pixels,
1207 cx: &mut ViewContext<Editor>,
1208 ) -> (DisplayPoint, AnyElement) {
1209 let actions = self.actions.clone();
1210 let selected_item = self.selected_item;
1211
1212 let element = uniform_list(
1213 cx.view().clone(),
1214 "code_actions_menu",
1215 self.actions.len(),
1216 move |_this, range, cx| {
1217 actions[range.clone()]
1218 .iter()
1219 .enumerate()
1220 .map(|(ix, action)| {
1221 let item_ix = range.start + ix;
1222 let selected = selected_item == item_ix;
1223 let colors = cx.theme().colors();
1224 div()
1225 .px_2()
1226 .text_color(colors.text)
1227 .when(selected, |style| {
1228 style
1229 .bg(colors.element_active)
1230 .text_color(colors.text_accent)
1231 })
1232 .hover(|style| {
1233 style
1234 .bg(colors.element_hover)
1235 .text_color(colors.text_accent)
1236 })
1237 .on_mouse_down(
1238 MouseButton::Left,
1239 cx.listener(move |editor, _, cx| {
1240 cx.stop_propagation();
1241 if let Some(task) = editor.confirm_code_action(
1242 &ConfirmCodeAction {
1243 item_ix: Some(item_ix),
1244 },
1245 cx,
1246 ) {
1247 task.detach_and_log_err(cx)
1248 }
1249 }),
1250 )
1251 .whitespace_nowrap()
1252 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1253 .child(SharedString::from(action.lsp_action.title.clone()))
1254 })
1255 .collect()
1256 },
1257 )
1258 .elevation_1(cx)
1259 .px_2()
1260 .py_1()
1261 .max_h(max_height)
1262 .occlude()
1263 .track_scroll(self.scroll_handle.clone())
1264 .with_width_from_item(
1265 self.actions
1266 .iter()
1267 .enumerate()
1268 .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
1269 .map(|(ix, _)| ix),
1270 )
1271 .into_any_element();
1272
1273 if self.deployed_from_indicator {
1274 *cursor_position.column_mut() = 0;
1275 }
1276
1277 (cursor_position, element)
1278 }
1279}
1280
1281#[derive(Debug)]
1282struct ActiveDiagnosticGroup {
1283 primary_range: Range<Anchor>,
1284 primary_message: String,
1285 blocks: HashMap<BlockId, Diagnostic>,
1286 is_valid: bool,
1287}
1288
1289#[derive(Serialize, Deserialize)]
1290pub struct ClipboardSelection {
1291 pub len: usize,
1292 pub is_entire_line: bool,
1293 pub first_line_indent: u32,
1294}
1295
1296#[derive(Debug)]
1297pub(crate) struct NavigationData {
1298 cursor_anchor: Anchor,
1299 cursor_position: Point,
1300 scroll_anchor: ScrollAnchor,
1301 scroll_top_row: u32,
1302}
1303
1304enum GotoDefinitionKind {
1305 Symbol,
1306 Type,
1307 Implementation,
1308}
1309
1310#[derive(Debug, Clone)]
1311enum InlayHintRefreshReason {
1312 Toggle(bool),
1313 SettingsChange(InlayHintSettings),
1314 NewLinesShown,
1315 BufferEdited(HashSet<Arc<Language>>),
1316 RefreshRequested,
1317 ExcerptsRemoved(Vec<ExcerptId>),
1318}
1319
1320impl InlayHintRefreshReason {
1321 fn description(&self) -> &'static str {
1322 match self {
1323 Self::Toggle(_) => "toggle",
1324 Self::SettingsChange(_) => "settings change",
1325 Self::NewLinesShown => "new lines shown",
1326 Self::BufferEdited(_) => "buffer edited",
1327 Self::RefreshRequested => "refresh requested",
1328 Self::ExcerptsRemoved(_) => "excerpts removed",
1329 }
1330 }
1331}
1332
1333impl Editor {
1334 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1335 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1336 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1337 Self::new(EditorMode::SingleLine, buffer, None, cx)
1338 }
1339
1340 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1341 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1342 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1343 Self::new(EditorMode::Full, buffer, None, cx)
1344 }
1345
1346 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1347 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1348 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1349 Self::new(EditorMode::AutoHeight { max_lines }, buffer, None, cx)
1350 }
1351
1352 pub fn for_buffer(
1353 buffer: Model<Buffer>,
1354 project: Option<Model<Project>>,
1355 cx: &mut ViewContext<Self>,
1356 ) -> Self {
1357 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1358 Self::new(EditorMode::Full, buffer, project, cx)
1359 }
1360
1361 pub fn for_multibuffer(
1362 buffer: Model<MultiBuffer>,
1363 project: Option<Model<Project>>,
1364 cx: &mut ViewContext<Self>,
1365 ) -> Self {
1366 Self::new(EditorMode::Full, buffer, project, cx)
1367 }
1368
1369 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1370 let mut clone = Self::new(self.mode, self.buffer.clone(), self.project.clone(), cx);
1371 self.display_map.update(cx, |display_map, cx| {
1372 let snapshot = display_map.snapshot(cx);
1373 clone.display_map.update(cx, |display_map, cx| {
1374 display_map.set_state(&snapshot, cx);
1375 });
1376 });
1377 clone.selections.clone_state(&self.selections);
1378 clone.scroll_manager.clone_state(&self.scroll_manager);
1379 clone.searchable = self.searchable;
1380 clone
1381 }
1382
1383 fn new(
1384 mode: EditorMode,
1385 buffer: Model<MultiBuffer>,
1386 project: Option<Model<Project>>,
1387 cx: &mut ViewContext<Self>,
1388 ) -> Self {
1389 let style = cx.text_style();
1390 let font_size = style.font_size.to_pixels(cx.rem_size());
1391 let display_map = cx.new_model(|cx| {
1392 DisplayMap::new(buffer.clone(), style.font(), font_size, None, 2, 1, cx)
1393 });
1394
1395 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1396
1397 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1398
1399 let soft_wrap_mode_override =
1400 (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::None);
1401
1402 let mut project_subscriptions = Vec::new();
1403 if mode == EditorMode::Full {
1404 if let Some(project) = project.as_ref() {
1405 if buffer.read(cx).is_singleton() {
1406 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1407 cx.emit(EditorEvent::TitleChanged);
1408 }));
1409 }
1410 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1411 if let project::Event::RefreshInlayHints = event {
1412 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1413 };
1414 }));
1415 }
1416 }
1417
1418 let inlay_hint_settings = inlay_hint_settings(
1419 selections.newest_anchor().head(),
1420 &buffer.read(cx).snapshot(cx),
1421 cx,
1422 );
1423
1424 let focus_handle = cx.focus_handle();
1425 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1426 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1427
1428 let mut this = Self {
1429 focus_handle,
1430 buffer: buffer.clone(),
1431 display_map: display_map.clone(),
1432 selections,
1433 scroll_manager: ScrollManager::new(cx),
1434 columnar_selection_tail: None,
1435 add_selections_state: None,
1436 select_next_state: None,
1437 select_prev_state: None,
1438 selection_history: Default::default(),
1439 autoclose_regions: Default::default(),
1440 snippet_stack: Default::default(),
1441 select_larger_syntax_node_stack: Vec::new(),
1442 ime_transaction: Default::default(),
1443 active_diagnostics: None,
1444 soft_wrap_mode_override,
1445 completion_provider: project.clone().map(|project| Box::new(project) as _),
1446 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1447 project,
1448 blink_manager: blink_manager.clone(),
1449 show_local_selections: true,
1450 mode,
1451 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1452 show_gutter: mode == EditorMode::Full,
1453 show_wrap_guides: None,
1454 placeholder_text: None,
1455 highlight_order: 0,
1456 highlighted_rows: HashMap::default(),
1457 background_highlights: Default::default(),
1458 scrollbar_marker_state: ScrollbarMarkerState::default(),
1459 nav_history: None,
1460 context_menu: RwLock::new(None),
1461 mouse_context_menu: None,
1462 completion_tasks: Default::default(),
1463 find_all_references_task_sources: Vec::new(),
1464 next_completion_id: 0,
1465 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1466 next_inlay_id: 0,
1467 available_code_actions: Default::default(),
1468 code_actions_task: Default::default(),
1469 document_highlights_task: Default::default(),
1470 pending_rename: Default::default(),
1471 searchable: true,
1472 cursor_shape: Default::default(),
1473 autoindent_mode: Some(AutoindentMode::EachLine),
1474 collapse_matches: false,
1475 workspace: None,
1476 keymap_context_layers: Default::default(),
1477 input_enabled: true,
1478 use_modal_editing: mode == EditorMode::Full,
1479 read_only: false,
1480 use_autoclose: true,
1481 auto_replace_emoji_shortcode: false,
1482 leader_peer_id: None,
1483 remote_id: None,
1484 hover_state: Default::default(),
1485 hovered_link_state: Default::default(),
1486 inline_completion_provider: None,
1487 active_inline_completion: None,
1488 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1489 gutter_hovered: false,
1490 pixel_position_of_newest_cursor: None,
1491 last_bounds: None,
1492 expect_bounds_change: None,
1493 gutter_width: Default::default(),
1494 style: None,
1495 show_cursor_names: false,
1496 hovered_cursors: Default::default(),
1497 editor_actions: Default::default(),
1498 vim_replace_map: Default::default(),
1499 show_inline_completions: mode == EditorMode::Full,
1500 custom_context_menu: None,
1501 show_git_blame: false,
1502 blame: None,
1503 blame_subscription: None,
1504 _subscriptions: vec![
1505 cx.observe(&buffer, Self::on_buffer_changed),
1506 cx.subscribe(&buffer, Self::on_buffer_event),
1507 cx.observe(&display_map, Self::on_display_map_changed),
1508 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1509 cx.observe_global::<SettingsStore>(Self::settings_changed),
1510 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1511 cx.observe_window_activation(|editor, cx| {
1512 let active = cx.is_window_active();
1513 editor.blink_manager.update(cx, |blink_manager, cx| {
1514 if active {
1515 blink_manager.enable(cx);
1516 } else {
1517 blink_manager.show_cursor(cx);
1518 blink_manager.disable(cx);
1519 }
1520 });
1521 }),
1522 ],
1523 };
1524
1525 this._subscriptions.extend(project_subscriptions);
1526
1527 this.end_selection(cx);
1528 this.scroll_manager.show_scrollbar(cx);
1529
1530 if mode == EditorMode::Full {
1531 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1532 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1533 }
1534
1535 this.report_editor_event("open", None, cx);
1536 this
1537 }
1538
1539 fn key_context(&self, cx: &AppContext) -> KeyContext {
1540 let mut key_context = KeyContext::default();
1541 key_context.add("Editor");
1542 let mode = match self.mode {
1543 EditorMode::SingleLine => "single_line",
1544 EditorMode::AutoHeight { .. } => "auto_height",
1545 EditorMode::Full => "full",
1546 };
1547 key_context.set("mode", mode);
1548 if self.pending_rename.is_some() {
1549 key_context.add("renaming");
1550 }
1551 if self.context_menu_visible() {
1552 match self.context_menu.read().as_ref() {
1553 Some(ContextMenu::Completions(_)) => {
1554 key_context.add("menu");
1555 key_context.add("showing_completions")
1556 }
1557 Some(ContextMenu::CodeActions(_)) => {
1558 key_context.add("menu");
1559 key_context.add("showing_code_actions")
1560 }
1561 None => {}
1562 }
1563 }
1564
1565 for layer in self.keymap_context_layers.values() {
1566 key_context.extend(layer);
1567 }
1568
1569 if let Some(extension) = self
1570 .buffer
1571 .read(cx)
1572 .as_singleton()
1573 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1574 {
1575 key_context.set("extension", extension.to_string());
1576 }
1577
1578 if self.has_active_inline_completion(cx) {
1579 key_context.add("copilot_suggestion");
1580 key_context.add("inline_completion");
1581 }
1582
1583 key_context
1584 }
1585
1586 pub fn new_file(
1587 workspace: &mut Workspace,
1588 _: &workspace::NewFile,
1589 cx: &mut ViewContext<Workspace>,
1590 ) {
1591 let project = workspace.project().clone();
1592 if project.read(cx).is_remote() {
1593 cx.propagate();
1594 } else if let Some(buffer) = project
1595 .update(cx, |project, cx| project.create_buffer("", None, cx))
1596 .log_err()
1597 {
1598 workspace.add_item_to_active_pane(
1599 Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1600 cx,
1601 );
1602 }
1603 }
1604
1605 pub fn new_file_in_direction(
1606 workspace: &mut Workspace,
1607 action: &workspace::NewFileInDirection,
1608 cx: &mut ViewContext<Workspace>,
1609 ) {
1610 let project = workspace.project().clone();
1611 if project.read(cx).is_remote() {
1612 cx.propagate();
1613 } else if let Some(buffer) = project
1614 .update(cx, |project, cx| project.create_buffer("", None, cx))
1615 .log_err()
1616 {
1617 workspace.split_item(
1618 action.0,
1619 Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1620 cx,
1621 );
1622 }
1623 }
1624
1625 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
1626 self.buffer.read(cx).replica_id()
1627 }
1628
1629 pub fn leader_peer_id(&self) -> Option<PeerId> {
1630 self.leader_peer_id
1631 }
1632
1633 pub fn buffer(&self) -> &Model<MultiBuffer> {
1634 &self.buffer
1635 }
1636
1637 pub fn workspace(&self) -> Option<View<Workspace>> {
1638 self.workspace.as_ref()?.0.upgrade()
1639 }
1640
1641 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1642 self.buffer().read(cx).title(cx)
1643 }
1644
1645 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1646 EditorSnapshot {
1647 mode: self.mode,
1648 show_gutter: self.show_gutter,
1649 show_git_blame: self
1650 .blame
1651 .as_ref()
1652 .map_or(false, |blame| blame.read(cx).has_generated_entries()),
1653 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1654 scroll_anchor: self.scroll_manager.anchor(),
1655 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1656 placeholder_text: self.placeholder_text.clone(),
1657 is_focused: self.focus_handle.is_focused(cx),
1658 }
1659 }
1660
1661 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1662 self.buffer.read(cx).language_at(point, cx)
1663 }
1664
1665 pub fn file_at<T: ToOffset>(
1666 &self,
1667 point: T,
1668 cx: &AppContext,
1669 ) -> Option<Arc<dyn language::File>> {
1670 self.buffer.read(cx).read(cx).file_at(point).cloned()
1671 }
1672
1673 pub fn active_excerpt(
1674 &self,
1675 cx: &AppContext,
1676 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1677 self.buffer
1678 .read(cx)
1679 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1680 }
1681
1682 pub fn mode(&self) -> EditorMode {
1683 self.mode
1684 }
1685
1686 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1687 self.collaboration_hub.as_deref()
1688 }
1689
1690 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1691 self.collaboration_hub = Some(hub);
1692 }
1693
1694 pub fn set_custom_context_menu(
1695 &mut self,
1696 f: impl 'static
1697 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1698 ) {
1699 self.custom_context_menu = Some(Box::new(f))
1700 }
1701
1702 pub fn set_completion_provider(&mut self, hub: Box<dyn CompletionProvider>) {
1703 self.completion_provider = Some(hub);
1704 }
1705
1706 pub fn set_inline_completion_provider(
1707 &mut self,
1708 provider: Model<impl InlineCompletionProvider>,
1709 cx: &mut ViewContext<Self>,
1710 ) {
1711 self.inline_completion_provider = Some(RegisteredInlineCompletionProvider {
1712 _subscription: cx.observe(&provider, |this, _, cx| {
1713 if this.focus_handle.is_focused(cx) {
1714 this.update_visible_inline_completion(cx);
1715 }
1716 }),
1717 provider: Arc::new(provider),
1718 });
1719 self.refresh_inline_completion(false, cx);
1720 }
1721
1722 pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
1723 self.placeholder_text.as_deref()
1724 }
1725
1726 pub fn set_placeholder_text(
1727 &mut self,
1728 placeholder_text: impl Into<Arc<str>>,
1729 cx: &mut ViewContext<Self>,
1730 ) {
1731 let placeholder_text = Some(placeholder_text.into());
1732 if self.placeholder_text != placeholder_text {
1733 self.placeholder_text = placeholder_text;
1734 cx.notify();
1735 }
1736 }
1737
1738 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1739 self.cursor_shape = cursor_shape;
1740 cx.notify();
1741 }
1742
1743 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1744 self.collapse_matches = collapse_matches;
1745 }
1746
1747 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1748 if self.collapse_matches {
1749 return range.start..range.start;
1750 }
1751 range.clone()
1752 }
1753
1754 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1755 if self.display_map.read(cx).clip_at_line_ends != clip {
1756 self.display_map
1757 .update(cx, |map, _| map.clip_at_line_ends = clip);
1758 }
1759 }
1760
1761 pub fn set_keymap_context_layer<Tag: 'static>(
1762 &mut self,
1763 context: KeyContext,
1764 cx: &mut ViewContext<Self>,
1765 ) {
1766 self.keymap_context_layers
1767 .insert(TypeId::of::<Tag>(), context);
1768 cx.notify();
1769 }
1770
1771 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
1772 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
1773 cx.notify();
1774 }
1775
1776 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1777 self.input_enabled = input_enabled;
1778 }
1779
1780 pub fn set_autoindent(&mut self, autoindent: bool) {
1781 if autoindent {
1782 self.autoindent_mode = Some(AutoindentMode::EachLine);
1783 } else {
1784 self.autoindent_mode = None;
1785 }
1786 }
1787
1788 pub fn read_only(&self, cx: &AppContext) -> bool {
1789 self.read_only || self.buffer.read(cx).read_only()
1790 }
1791
1792 pub fn set_read_only(&mut self, read_only: bool) {
1793 self.read_only = read_only;
1794 }
1795
1796 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1797 self.use_autoclose = autoclose;
1798 }
1799
1800 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1801 self.auto_replace_emoji_shortcode = auto_replace;
1802 }
1803
1804 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
1805 self.show_inline_completions = show_inline_completions;
1806 }
1807
1808 pub fn set_use_modal_editing(&mut self, to: bool) {
1809 self.use_modal_editing = to;
1810 }
1811
1812 pub fn use_modal_editing(&self) -> bool {
1813 self.use_modal_editing
1814 }
1815
1816 fn selections_did_change(
1817 &mut self,
1818 local: bool,
1819 old_cursor_position: &Anchor,
1820 cx: &mut ViewContext<Self>,
1821 ) {
1822 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1823 self.buffer.update(cx, |buffer, cx| {
1824 buffer.set_active_selections(
1825 &self.selections.disjoint_anchors(),
1826 self.selections.line_mode,
1827 self.cursor_shape,
1828 cx,
1829 )
1830 });
1831 }
1832
1833 let display_map = self
1834 .display_map
1835 .update(cx, |display_map, cx| display_map.snapshot(cx));
1836 let buffer = &display_map.buffer_snapshot;
1837 self.add_selections_state = None;
1838 self.select_next_state = None;
1839 self.select_prev_state = None;
1840 self.select_larger_syntax_node_stack.clear();
1841 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1842 self.snippet_stack
1843 .invalidate(&self.selections.disjoint_anchors(), buffer);
1844 self.take_rename(false, cx);
1845
1846 let new_cursor_position = self.selections.newest_anchor().head();
1847
1848 self.push_to_nav_history(
1849 *old_cursor_position,
1850 Some(new_cursor_position.to_point(buffer)),
1851 cx,
1852 );
1853
1854 if local {
1855 let new_cursor_position = self.selections.newest_anchor().head();
1856 let mut context_menu = self.context_menu.write();
1857 let completion_menu = match context_menu.as_ref() {
1858 Some(ContextMenu::Completions(menu)) => Some(menu),
1859
1860 _ => {
1861 *context_menu = None;
1862 None
1863 }
1864 };
1865
1866 if let Some(completion_menu) = completion_menu {
1867 let cursor_position = new_cursor_position.to_offset(buffer);
1868 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
1869 if kind == Some(CharKind::Word)
1870 && word_range.to_inclusive().contains(&cursor_position)
1871 {
1872 let mut completion_menu = completion_menu.clone();
1873 drop(context_menu);
1874
1875 let query = Self::completion_query(buffer, cursor_position);
1876 cx.spawn(move |this, mut cx| async move {
1877 completion_menu
1878 .filter(query.as_deref(), cx.background_executor().clone())
1879 .await;
1880
1881 this.update(&mut cx, |this, cx| {
1882 let mut context_menu = this.context_menu.write();
1883 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
1884 return;
1885 };
1886
1887 if menu.id > completion_menu.id {
1888 return;
1889 }
1890
1891 *context_menu = Some(ContextMenu::Completions(completion_menu));
1892 drop(context_menu);
1893 cx.notify();
1894 })
1895 })
1896 .detach();
1897
1898 self.show_completions(&ShowCompletions, cx);
1899 } else {
1900 drop(context_menu);
1901 self.hide_context_menu(cx);
1902 }
1903 } else {
1904 drop(context_menu);
1905 }
1906
1907 hide_hover(self, cx);
1908
1909 if old_cursor_position.to_display_point(&display_map).row()
1910 != new_cursor_position.to_display_point(&display_map).row()
1911 {
1912 self.available_code_actions.take();
1913 }
1914 self.refresh_code_actions(cx);
1915 self.refresh_document_highlights(cx);
1916 refresh_matching_bracket_highlights(self, cx);
1917 self.discard_inline_completion(cx);
1918 }
1919
1920 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1921 cx.emit(EditorEvent::SelectionsChanged { local });
1922
1923 if self.selections.disjoint_anchors().len() == 1 {
1924 cx.emit(SearchEvent::ActiveMatchChanged)
1925 }
1926
1927 cx.notify();
1928 }
1929
1930 pub fn change_selections<R>(
1931 &mut self,
1932 autoscroll: Option<Autoscroll>,
1933 cx: &mut ViewContext<Self>,
1934 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1935 ) -> R {
1936 let old_cursor_position = self.selections.newest_anchor().head();
1937 self.push_to_selection_history();
1938
1939 let (changed, result) = self.selections.change_with(cx, change);
1940
1941 if changed {
1942 if let Some(autoscroll) = autoscroll {
1943 self.request_autoscroll(autoscroll, cx);
1944 }
1945 self.selections_did_change(true, &old_cursor_position, cx);
1946 }
1947
1948 result
1949 }
1950
1951 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
1952 where
1953 I: IntoIterator<Item = (Range<S>, T)>,
1954 S: ToOffset,
1955 T: Into<Arc<str>>,
1956 {
1957 if self.read_only(cx) {
1958 return;
1959 }
1960
1961 self.buffer
1962 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
1963 }
1964
1965 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
1966 where
1967 I: IntoIterator<Item = (Range<S>, T)>,
1968 S: ToOffset,
1969 T: Into<Arc<str>>,
1970 {
1971 if self.read_only(cx) {
1972 return;
1973 }
1974
1975 self.buffer.update(cx, |buffer, cx| {
1976 buffer.edit(edits, self.autoindent_mode.clone(), cx)
1977 });
1978 }
1979
1980 pub fn edit_with_block_indent<I, S, T>(
1981 &mut self,
1982 edits: I,
1983 original_indent_columns: Vec<u32>,
1984 cx: &mut ViewContext<Self>,
1985 ) where
1986 I: IntoIterator<Item = (Range<S>, T)>,
1987 S: ToOffset,
1988 T: Into<Arc<str>>,
1989 {
1990 if self.read_only(cx) {
1991 return;
1992 }
1993
1994 self.buffer.update(cx, |buffer, cx| {
1995 buffer.edit(
1996 edits,
1997 Some(AutoindentMode::Block {
1998 original_indent_columns,
1999 }),
2000 cx,
2001 )
2002 });
2003 }
2004
2005 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2006 self.hide_context_menu(cx);
2007
2008 match phase {
2009 SelectPhase::Begin {
2010 position,
2011 add,
2012 click_count,
2013 } => self.begin_selection(position, add, click_count, cx),
2014 SelectPhase::BeginColumnar {
2015 position,
2016 goal_column,
2017 } => self.begin_columnar_selection(position, goal_column, cx),
2018 SelectPhase::Extend {
2019 position,
2020 click_count,
2021 } => self.extend_selection(position, click_count, cx),
2022 SelectPhase::Update {
2023 position,
2024 goal_column,
2025 scroll_delta,
2026 } => self.update_selection(position, goal_column, scroll_delta, cx),
2027 SelectPhase::End => self.end_selection(cx),
2028 }
2029 }
2030
2031 fn extend_selection(
2032 &mut self,
2033 position: DisplayPoint,
2034 click_count: usize,
2035 cx: &mut ViewContext<Self>,
2036 ) {
2037 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2038 let tail = self.selections.newest::<usize>(cx).tail();
2039 self.begin_selection(position, false, click_count, cx);
2040
2041 let position = position.to_offset(&display_map, Bias::Left);
2042 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2043
2044 let mut pending_selection = self
2045 .selections
2046 .pending_anchor()
2047 .expect("extend_selection not called with pending selection");
2048 if position >= tail {
2049 pending_selection.start = tail_anchor;
2050 } else {
2051 pending_selection.end = tail_anchor;
2052 pending_selection.reversed = true;
2053 }
2054
2055 let mut pending_mode = self.selections.pending_mode().unwrap();
2056 match &mut pending_mode {
2057 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2058 _ => {}
2059 }
2060
2061 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2062 s.set_pending(pending_selection, pending_mode)
2063 });
2064 }
2065
2066 fn begin_selection(
2067 &mut self,
2068 position: DisplayPoint,
2069 add: bool,
2070 click_count: usize,
2071 cx: &mut ViewContext<Self>,
2072 ) {
2073 if !self.focus_handle.is_focused(cx) {
2074 cx.focus(&self.focus_handle);
2075 }
2076
2077 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2078 let buffer = &display_map.buffer_snapshot;
2079 let newest_selection = self.selections.newest_anchor().clone();
2080 let position = display_map.clip_point(position, Bias::Left);
2081
2082 let start;
2083 let end;
2084 let mode;
2085 let auto_scroll;
2086 match click_count {
2087 1 => {
2088 start = buffer.anchor_before(position.to_point(&display_map));
2089 end = start;
2090 mode = SelectMode::Character;
2091 auto_scroll = true;
2092 }
2093 2 => {
2094 let range = movement::surrounding_word(&display_map, position);
2095 start = buffer.anchor_before(range.start.to_point(&display_map));
2096 end = buffer.anchor_before(range.end.to_point(&display_map));
2097 mode = SelectMode::Word(start..end);
2098 auto_scroll = true;
2099 }
2100 3 => {
2101 let position = display_map
2102 .clip_point(position, Bias::Left)
2103 .to_point(&display_map);
2104 let line_start = display_map.prev_line_boundary(position).0;
2105 let next_line_start = buffer.clip_point(
2106 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2107 Bias::Left,
2108 );
2109 start = buffer.anchor_before(line_start);
2110 end = buffer.anchor_before(next_line_start);
2111 mode = SelectMode::Line(start..end);
2112 auto_scroll = true;
2113 }
2114 _ => {
2115 start = buffer.anchor_before(0);
2116 end = buffer.anchor_before(buffer.len());
2117 mode = SelectMode::All;
2118 auto_scroll = false;
2119 }
2120 }
2121
2122 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2123 if !add {
2124 s.clear_disjoint();
2125 } else if click_count > 1 {
2126 s.delete(newest_selection.id)
2127 }
2128
2129 s.set_pending_anchor_range(start..end, mode);
2130 });
2131 }
2132
2133 fn begin_columnar_selection(
2134 &mut self,
2135 position: DisplayPoint,
2136 goal_column: u32,
2137 cx: &mut ViewContext<Self>,
2138 ) {
2139 if !self.focus_handle.is_focused(cx) {
2140 cx.focus(&self.focus_handle);
2141 }
2142
2143 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2144 let tail = self.selections.newest::<Point>(cx).tail();
2145 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2146
2147 self.select_columns(
2148 tail.to_display_point(&display_map),
2149 position,
2150 goal_column,
2151 &display_map,
2152 cx,
2153 );
2154 }
2155
2156 fn update_selection(
2157 &mut self,
2158 position: DisplayPoint,
2159 goal_column: u32,
2160 scroll_delta: gpui::Point<f32>,
2161 cx: &mut ViewContext<Self>,
2162 ) {
2163 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2164
2165 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2166 let tail = tail.to_display_point(&display_map);
2167 self.select_columns(tail, position, goal_column, &display_map, cx);
2168 } else if let Some(mut pending) = self.selections.pending_anchor() {
2169 let buffer = self.buffer.read(cx).snapshot(cx);
2170 let head;
2171 let tail;
2172 let mode = self.selections.pending_mode().unwrap();
2173 match &mode {
2174 SelectMode::Character => {
2175 head = position.to_point(&display_map);
2176 tail = pending.tail().to_point(&buffer);
2177 }
2178 SelectMode::Word(original_range) => {
2179 let original_display_range = original_range.start.to_display_point(&display_map)
2180 ..original_range.end.to_display_point(&display_map);
2181 let original_buffer_range = original_display_range.start.to_point(&display_map)
2182 ..original_display_range.end.to_point(&display_map);
2183 if movement::is_inside_word(&display_map, position)
2184 || original_display_range.contains(&position)
2185 {
2186 let word_range = movement::surrounding_word(&display_map, position);
2187 if word_range.start < original_display_range.start {
2188 head = word_range.start.to_point(&display_map);
2189 } else {
2190 head = word_range.end.to_point(&display_map);
2191 }
2192 } else {
2193 head = position.to_point(&display_map);
2194 }
2195
2196 if head <= original_buffer_range.start {
2197 tail = original_buffer_range.end;
2198 } else {
2199 tail = original_buffer_range.start;
2200 }
2201 }
2202 SelectMode::Line(original_range) => {
2203 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2204
2205 let position = display_map
2206 .clip_point(position, Bias::Left)
2207 .to_point(&display_map);
2208 let line_start = display_map.prev_line_boundary(position).0;
2209 let next_line_start = buffer.clip_point(
2210 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2211 Bias::Left,
2212 );
2213
2214 if line_start < original_range.start {
2215 head = line_start
2216 } else {
2217 head = next_line_start
2218 }
2219
2220 if head <= original_range.start {
2221 tail = original_range.end;
2222 } else {
2223 tail = original_range.start;
2224 }
2225 }
2226 SelectMode::All => {
2227 return;
2228 }
2229 };
2230
2231 if head < tail {
2232 pending.start = buffer.anchor_before(head);
2233 pending.end = buffer.anchor_before(tail);
2234 pending.reversed = true;
2235 } else {
2236 pending.start = buffer.anchor_before(tail);
2237 pending.end = buffer.anchor_before(head);
2238 pending.reversed = false;
2239 }
2240
2241 self.change_selections(None, cx, |s| {
2242 s.set_pending(pending, mode);
2243 });
2244 } else {
2245 log::error!("update_selection dispatched with no pending selection");
2246 return;
2247 }
2248
2249 self.apply_scroll_delta(scroll_delta, cx);
2250 cx.notify();
2251 }
2252
2253 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2254 self.columnar_selection_tail.take();
2255 if self.selections.pending_anchor().is_some() {
2256 let selections = self.selections.all::<usize>(cx);
2257 self.change_selections(None, cx, |s| {
2258 s.select(selections);
2259 s.clear_pending();
2260 });
2261 }
2262 }
2263
2264 fn select_columns(
2265 &mut self,
2266 tail: DisplayPoint,
2267 head: DisplayPoint,
2268 goal_column: u32,
2269 display_map: &DisplaySnapshot,
2270 cx: &mut ViewContext<Self>,
2271 ) {
2272 let start_row = cmp::min(tail.row(), head.row());
2273 let end_row = cmp::max(tail.row(), head.row());
2274 let start_column = cmp::min(tail.column(), goal_column);
2275 let end_column = cmp::max(tail.column(), goal_column);
2276 let reversed = start_column < tail.column();
2277
2278 let selection_ranges = (start_row..=end_row)
2279 .filter_map(|row| {
2280 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2281 let start = display_map
2282 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2283 .to_point(display_map);
2284 let end = display_map
2285 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2286 .to_point(display_map);
2287 if reversed {
2288 Some(end..start)
2289 } else {
2290 Some(start..end)
2291 }
2292 } else {
2293 None
2294 }
2295 })
2296 .collect::<Vec<_>>();
2297
2298 self.change_selections(None, cx, |s| {
2299 s.select_ranges(selection_ranges);
2300 });
2301 cx.notify();
2302 }
2303
2304 pub fn has_pending_nonempty_selection(&self) -> bool {
2305 let pending_nonempty_selection = match self.selections.pending_anchor() {
2306 Some(Selection { start, end, .. }) => start != end,
2307 None => false,
2308 };
2309 pending_nonempty_selection || self.columnar_selection_tail.is_some()
2310 }
2311
2312 pub fn has_pending_selection(&self) -> bool {
2313 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2314 }
2315
2316 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2317 if self.dismiss_menus_and_popups(cx) {
2318 return;
2319 }
2320
2321 if self.mode == EditorMode::Full {
2322 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2323 return;
2324 }
2325 }
2326
2327 cx.propagate();
2328 }
2329
2330 pub fn dismiss_menus_and_popups(&mut self, cx: &mut ViewContext<Self>) -> bool {
2331 if self.take_rename(false, cx).is_some() {
2332 return true;
2333 }
2334
2335 if hide_hover(self, cx) {
2336 return true;
2337 }
2338
2339 if self.hide_context_menu(cx).is_some() {
2340 return true;
2341 }
2342
2343 if self.discard_inline_completion(cx) {
2344 return true;
2345 }
2346
2347 if self.snippet_stack.pop().is_some() {
2348 return true;
2349 }
2350
2351 if self.mode == EditorMode::Full {
2352 if self.active_diagnostics.is_some() {
2353 self.dismiss_diagnostics(cx);
2354 return true;
2355 }
2356 }
2357
2358 false
2359 }
2360
2361 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2362 let text: Arc<str> = text.into();
2363
2364 if self.read_only(cx) {
2365 return;
2366 }
2367
2368 let selections = self.selections.all_adjusted(cx);
2369 let mut brace_inserted = false;
2370 let mut edits = Vec::new();
2371 let mut new_selections = Vec::with_capacity(selections.len());
2372 let mut new_autoclose_regions = Vec::new();
2373 let snapshot = self.buffer.read(cx).read(cx);
2374
2375 for (selection, autoclose_region) in
2376 self.selections_with_autoclose_regions(selections, &snapshot)
2377 {
2378 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2379 // Determine if the inserted text matches the opening or closing
2380 // bracket of any of this language's bracket pairs.
2381 let mut bracket_pair = None;
2382 let mut is_bracket_pair_start = false;
2383 let mut is_bracket_pair_end = false;
2384 if !text.is_empty() {
2385 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2386 // and they are removing the character that triggered IME popup.
2387 for (pair, enabled) in scope.brackets() {
2388 if !pair.close {
2389 continue;
2390 }
2391
2392 if enabled && pair.start.ends_with(text.as_ref()) {
2393 bracket_pair = Some(pair.clone());
2394 is_bracket_pair_start = true;
2395 break;
2396 }
2397 if pair.end.as_str() == text.as_ref() {
2398 bracket_pair = Some(pair.clone());
2399 is_bracket_pair_end = true;
2400 break;
2401 }
2402 }
2403 }
2404
2405 if let Some(bracket_pair) = bracket_pair {
2406 if selection.is_empty() {
2407 if is_bracket_pair_start {
2408 let prefix_len = bracket_pair.start.len() - text.len();
2409
2410 // If the inserted text is a suffix of an opening bracket and the
2411 // selection is preceded by the rest of the opening bracket, then
2412 // insert the closing bracket.
2413 let following_text_allows_autoclose = snapshot
2414 .chars_at(selection.start)
2415 .next()
2416 .map_or(true, |c| scope.should_autoclose_before(c));
2417 let preceding_text_matches_prefix = prefix_len == 0
2418 || (selection.start.column >= (prefix_len as u32)
2419 && snapshot.contains_str_at(
2420 Point::new(
2421 selection.start.row,
2422 selection.start.column - (prefix_len as u32),
2423 ),
2424 &bracket_pair.start[..prefix_len],
2425 ));
2426 let autoclose = self.use_autoclose
2427 && snapshot.settings_at(selection.start, cx).use_autoclose;
2428 if autoclose
2429 && following_text_allows_autoclose
2430 && preceding_text_matches_prefix
2431 {
2432 let anchor = snapshot.anchor_before(selection.end);
2433 new_selections.push((selection.map(|_| anchor), text.len()));
2434 new_autoclose_regions.push((
2435 anchor,
2436 text.len(),
2437 selection.id,
2438 bracket_pair.clone(),
2439 ));
2440 edits.push((
2441 selection.range(),
2442 format!("{}{}", text, bracket_pair.end).into(),
2443 ));
2444 brace_inserted = true;
2445 continue;
2446 }
2447 }
2448
2449 if let Some(region) = autoclose_region {
2450 // If the selection is followed by an auto-inserted closing bracket,
2451 // then don't insert that closing bracket again; just move the selection
2452 // past the closing bracket.
2453 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2454 && text.as_ref() == region.pair.end.as_str();
2455 if should_skip {
2456 let anchor = snapshot.anchor_after(selection.end);
2457 new_selections
2458 .push((selection.map(|_| anchor), region.pair.end.len()));
2459 continue;
2460 }
2461 }
2462
2463 let always_treat_brackets_as_autoclosed = snapshot
2464 .settings_at(selection.start, cx)
2465 .always_treat_brackets_as_autoclosed;
2466 if always_treat_brackets_as_autoclosed
2467 && is_bracket_pair_end
2468 && snapshot.contains_str_at(selection.end, text.as_ref())
2469 {
2470 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2471 // and the inserted text is a closing bracket and the selection is followed
2472 // by the closing bracket then move the selection past the closing bracket.
2473 let anchor = snapshot.anchor_after(selection.end);
2474 new_selections.push((selection.map(|_| anchor), text.len()));
2475 continue;
2476 }
2477 }
2478 // If an opening bracket is 1 character long and is typed while
2479 // text is selected, then surround that text with the bracket pair.
2480 else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
2481 edits.push((selection.start..selection.start, text.clone()));
2482 edits.push((
2483 selection.end..selection.end,
2484 bracket_pair.end.as_str().into(),
2485 ));
2486 brace_inserted = true;
2487 new_selections.push((
2488 Selection {
2489 id: selection.id,
2490 start: snapshot.anchor_after(selection.start),
2491 end: snapshot.anchor_before(selection.end),
2492 reversed: selection.reversed,
2493 goal: selection.goal,
2494 },
2495 0,
2496 ));
2497 continue;
2498 }
2499 }
2500 }
2501
2502 if self.auto_replace_emoji_shortcode
2503 && selection.is_empty()
2504 && text.as_ref().ends_with(':')
2505 {
2506 if let Some(possible_emoji_short_code) =
2507 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2508 {
2509 if !possible_emoji_short_code.is_empty() {
2510 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2511 let emoji_shortcode_start = Point::new(
2512 selection.start.row,
2513 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2514 );
2515
2516 // Remove shortcode from buffer
2517 edits.push((
2518 emoji_shortcode_start..selection.start,
2519 "".to_string().into(),
2520 ));
2521 new_selections.push((
2522 Selection {
2523 id: selection.id,
2524 start: snapshot.anchor_after(emoji_shortcode_start),
2525 end: snapshot.anchor_before(selection.start),
2526 reversed: selection.reversed,
2527 goal: selection.goal,
2528 },
2529 0,
2530 ));
2531
2532 // Insert emoji
2533 let selection_start_anchor = snapshot.anchor_after(selection.start);
2534 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2535 edits.push((selection.start..selection.end, emoji.to_string().into()));
2536
2537 continue;
2538 }
2539 }
2540 }
2541 }
2542
2543 // If not handling any auto-close operation, then just replace the selected
2544 // text with the given input and move the selection to the end of the
2545 // newly inserted text.
2546 let anchor = snapshot.anchor_after(selection.end);
2547 new_selections.push((selection.map(|_| anchor), 0));
2548 edits.push((selection.start..selection.end, text.clone()));
2549 }
2550
2551 drop(snapshot);
2552 self.transact(cx, |this, cx| {
2553 this.buffer.update(cx, |buffer, cx| {
2554 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2555 });
2556
2557 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2558 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2559 let snapshot = this.buffer.read(cx).read(cx);
2560 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
2561 .zip(new_selection_deltas)
2562 .map(|(selection, delta)| Selection {
2563 id: selection.id,
2564 start: selection.start + delta,
2565 end: selection.end + delta,
2566 reversed: selection.reversed,
2567 goal: SelectionGoal::None,
2568 })
2569 .collect::<Vec<_>>();
2570
2571 let mut i = 0;
2572 for (position, delta, selection_id, pair) in new_autoclose_regions {
2573 let position = position.to_offset(&snapshot) + delta;
2574 let start = snapshot.anchor_before(position);
2575 let end = snapshot.anchor_after(position);
2576 while let Some(existing_state) = this.autoclose_regions.get(i) {
2577 match existing_state.range.start.cmp(&start, &snapshot) {
2578 Ordering::Less => i += 1,
2579 Ordering::Greater => break,
2580 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
2581 Ordering::Less => i += 1,
2582 Ordering::Equal => break,
2583 Ordering::Greater => break,
2584 },
2585 }
2586 }
2587 this.autoclose_regions.insert(
2588 i,
2589 AutocloseRegion {
2590 selection_id,
2591 range: start..end,
2592 pair,
2593 },
2594 );
2595 }
2596
2597 drop(snapshot);
2598 let had_active_copilot_completion = this.has_active_inline_completion(cx);
2599 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2600
2601 if brace_inserted {
2602 // If we inserted a brace while composing text (i.e. typing `"` on a
2603 // Brazilian keyboard), exit the composing state because most likely
2604 // the user wanted to surround the selection.
2605 this.unmark_text(cx);
2606 } else if EditorSettings::get_global(cx).use_on_type_format {
2607 if let Some(on_type_format_task) =
2608 this.trigger_on_type_formatting(text.to_string(), cx)
2609 {
2610 on_type_format_task.detach_and_log_err(cx);
2611 }
2612 }
2613
2614 if had_active_copilot_completion {
2615 this.refresh_inline_completion(true, cx);
2616 if !this.has_active_inline_completion(cx) {
2617 this.trigger_completion_on_input(&text, cx);
2618 }
2619 } else {
2620 this.trigger_completion_on_input(&text, cx);
2621 this.refresh_inline_completion(true, cx);
2622 }
2623 });
2624 }
2625
2626 fn find_possible_emoji_shortcode_at_position(
2627 snapshot: &MultiBufferSnapshot,
2628 position: Point,
2629 ) -> Option<String> {
2630 let mut chars = Vec::new();
2631 let mut found_colon = false;
2632 for char in snapshot.reversed_chars_at(position).take(100) {
2633 // Found a possible emoji shortcode in the middle of the buffer
2634 if found_colon {
2635 if char.is_whitespace() {
2636 chars.reverse();
2637 return Some(chars.iter().collect());
2638 }
2639 // If the previous character is not a whitespace, we are in the middle of a word
2640 // and we only want to complete the shortcode if the word is made up of other emojis
2641 let mut containing_word = String::new();
2642 for ch in snapshot
2643 .reversed_chars_at(position)
2644 .skip(chars.len() + 1)
2645 .take(100)
2646 {
2647 if ch.is_whitespace() {
2648 break;
2649 }
2650 containing_word.push(ch);
2651 }
2652 let containing_word = containing_word.chars().rev().collect::<String>();
2653 if util::word_consists_of_emojis(containing_word.as_str()) {
2654 chars.reverse();
2655 return Some(chars.iter().collect());
2656 }
2657 }
2658
2659 if char.is_whitespace() || !char.is_ascii() {
2660 return None;
2661 }
2662 if char == ':' {
2663 found_colon = true;
2664 } else {
2665 chars.push(char);
2666 }
2667 }
2668 // Found a possible emoji shortcode at the beginning of the buffer
2669 chars.reverse();
2670 Some(chars.iter().collect())
2671 }
2672
2673 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2674 self.transact(cx, |this, cx| {
2675 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2676 let selections = this.selections.all::<usize>(cx);
2677 let multi_buffer = this.buffer.read(cx);
2678 let buffer = multi_buffer.snapshot(cx);
2679 selections
2680 .iter()
2681 .map(|selection| {
2682 let start_point = selection.start.to_point(&buffer);
2683 let mut indent = buffer.indent_size_for_line(start_point.row);
2684 indent.len = cmp::min(indent.len, start_point.column);
2685 let start = selection.start;
2686 let end = selection.end;
2687 let is_cursor = start == end;
2688 let language_scope = buffer.language_scope_at(start);
2689 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2690 &language_scope
2691 {
2692 let leading_whitespace_len = buffer
2693 .reversed_chars_at(start)
2694 .take_while(|c| c.is_whitespace() && *c != '\n')
2695 .map(|c| c.len_utf8())
2696 .sum::<usize>();
2697
2698 let trailing_whitespace_len = buffer
2699 .chars_at(end)
2700 .take_while(|c| c.is_whitespace() && *c != '\n')
2701 .map(|c| c.len_utf8())
2702 .sum::<usize>();
2703
2704 let insert_extra_newline =
2705 language.brackets().any(|(pair, enabled)| {
2706 let pair_start = pair.start.trim_end();
2707 let pair_end = pair.end.trim_start();
2708
2709 enabled
2710 && pair.newline
2711 && buffer.contains_str_at(
2712 end + trailing_whitespace_len,
2713 pair_end,
2714 )
2715 && buffer.contains_str_at(
2716 (start - leading_whitespace_len)
2717 .saturating_sub(pair_start.len()),
2718 pair_start,
2719 )
2720 });
2721 // Comment extension on newline is allowed only for cursor selections
2722 let comment_delimiter = language.line_comment_prefixes().filter(|_| {
2723 let is_comment_extension_enabled =
2724 multi_buffer.settings_at(0, cx).extend_comment_on_newline;
2725 is_cursor && is_comment_extension_enabled
2726 });
2727 let get_comment_delimiter = |delimiters: &[Arc<str>]| {
2728 let max_len_of_delimiter =
2729 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2730 let (snapshot, range) =
2731 buffer.buffer_line_for_row(start_point.row)?;
2732
2733 let mut index_of_first_non_whitespace = 0;
2734 let comment_candidate = snapshot
2735 .chars_for_range(range)
2736 .skip_while(|c| {
2737 let should_skip = c.is_whitespace();
2738 if should_skip {
2739 index_of_first_non_whitespace += 1;
2740 }
2741 should_skip
2742 })
2743 .take(max_len_of_delimiter)
2744 .collect::<String>();
2745 let comment_prefix = delimiters.iter().find(|comment_prefix| {
2746 comment_candidate.starts_with(comment_prefix.as_ref())
2747 })?;
2748 let cursor_is_placed_after_comment_marker =
2749 index_of_first_non_whitespace + comment_prefix.len()
2750 <= start_point.column as usize;
2751 if cursor_is_placed_after_comment_marker {
2752 Some(comment_prefix.clone())
2753 } else {
2754 None
2755 }
2756 };
2757 let comment_delimiter = if let Some(delimiters) = comment_delimiter {
2758 get_comment_delimiter(delimiters)
2759 } else {
2760 None
2761 };
2762 (comment_delimiter, insert_extra_newline)
2763 } else {
2764 (None, false)
2765 };
2766
2767 let capacity_for_delimiter = comment_delimiter
2768 .as_deref()
2769 .map(str::len)
2770 .unwrap_or_default();
2771 let mut new_text =
2772 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
2773 new_text.push_str("\n");
2774 new_text.extend(indent.chars());
2775 if let Some(delimiter) = &comment_delimiter {
2776 new_text.push_str(&delimiter);
2777 }
2778 if insert_extra_newline {
2779 new_text = new_text.repeat(2);
2780 }
2781
2782 let anchor = buffer.anchor_after(end);
2783 let new_selection = selection.map(|_| anchor);
2784 (
2785 (start..end, new_text),
2786 (insert_extra_newline, new_selection),
2787 )
2788 })
2789 .unzip()
2790 };
2791
2792 this.edit_with_autoindent(edits, cx);
2793 let buffer = this.buffer.read(cx).snapshot(cx);
2794 let new_selections = selection_fixup_info
2795 .into_iter()
2796 .map(|(extra_newline_inserted, new_selection)| {
2797 let mut cursor = new_selection.end.to_point(&buffer);
2798 if extra_newline_inserted {
2799 cursor.row -= 1;
2800 cursor.column = buffer.line_len(cursor.row);
2801 }
2802 new_selection.map(|_| cursor)
2803 })
2804 .collect();
2805
2806 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2807 this.refresh_inline_completion(true, cx);
2808 });
2809 }
2810
2811 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
2812 let buffer = self.buffer.read(cx);
2813 let snapshot = buffer.snapshot(cx);
2814
2815 let mut edits = Vec::new();
2816 let mut rows = Vec::new();
2817
2818 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
2819 let cursor = selection.head();
2820 let row = cursor.row;
2821
2822 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
2823
2824 let newline = "\n".to_string();
2825 edits.push((start_of_line..start_of_line, newline));
2826
2827 rows.push(row + rows_inserted as u32);
2828 }
2829
2830 self.transact(cx, |editor, cx| {
2831 editor.edit(edits, cx);
2832
2833 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
2834 let mut index = 0;
2835 s.move_cursors_with(|map, _, _| {
2836 let row = rows[index];
2837 index += 1;
2838
2839 let point = Point::new(row, 0);
2840 let boundary = map.next_line_boundary(point).1;
2841 let clipped = map.clip_point(boundary, Bias::Left);
2842
2843 (clipped, SelectionGoal::None)
2844 });
2845 });
2846
2847 let mut indent_edits = Vec::new();
2848 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
2849 for row in rows {
2850 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
2851 for (row, indent) in indents {
2852 if indent.len == 0 {
2853 continue;
2854 }
2855
2856 let text = match indent.kind {
2857 IndentKind::Space => " ".repeat(indent.len as usize),
2858 IndentKind::Tab => "\t".repeat(indent.len as usize),
2859 };
2860 let point = Point::new(row, 0);
2861 indent_edits.push((point..point, text));
2862 }
2863 }
2864 editor.edit(indent_edits, cx);
2865 });
2866 }
2867
2868 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
2869 let buffer = self.buffer.read(cx);
2870 let snapshot = buffer.snapshot(cx);
2871
2872 let mut edits = Vec::new();
2873 let mut rows = Vec::new();
2874 let mut rows_inserted = 0;
2875
2876 for selection in self.selections.all_adjusted(cx) {
2877 let cursor = selection.head();
2878 let row = cursor.row;
2879
2880 let point = Point::new(row + 1, 0);
2881 let start_of_line = snapshot.clip_point(point, Bias::Left);
2882
2883 let newline = "\n".to_string();
2884 edits.push((start_of_line..start_of_line, newline));
2885
2886 rows_inserted += 1;
2887 rows.push(row + rows_inserted);
2888 }
2889
2890 self.transact(cx, |editor, cx| {
2891 editor.edit(edits, cx);
2892
2893 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
2894 let mut index = 0;
2895 s.move_cursors_with(|map, _, _| {
2896 let row = rows[index];
2897 index += 1;
2898
2899 let point = Point::new(row, 0);
2900 let boundary = map.next_line_boundary(point).1;
2901 let clipped = map.clip_point(boundary, Bias::Left);
2902
2903 (clipped, SelectionGoal::None)
2904 });
2905 });
2906
2907 let mut indent_edits = Vec::new();
2908 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
2909 for row in rows {
2910 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
2911 for (row, indent) in indents {
2912 if indent.len == 0 {
2913 continue;
2914 }
2915
2916 let text = match indent.kind {
2917 IndentKind::Space => " ".repeat(indent.len as usize),
2918 IndentKind::Tab => "\t".repeat(indent.len as usize),
2919 };
2920 let point = Point::new(row, 0);
2921 indent_edits.push((point..point, text));
2922 }
2923 }
2924 editor.edit(indent_edits, cx);
2925 });
2926 }
2927
2928 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2929 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
2930 original_indent_columns: Vec::new(),
2931 });
2932 self.insert_with_autoindent_mode(text, autoindent, cx);
2933 }
2934
2935 fn insert_with_autoindent_mode(
2936 &mut self,
2937 text: &str,
2938 autoindent_mode: Option<AutoindentMode>,
2939 cx: &mut ViewContext<Self>,
2940 ) {
2941 if self.read_only(cx) {
2942 return;
2943 }
2944
2945 let text: Arc<str> = text.into();
2946 self.transact(cx, |this, cx| {
2947 let old_selections = this.selections.all_adjusted(cx);
2948 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
2949 let anchors = {
2950 let snapshot = buffer.read(cx);
2951 old_selections
2952 .iter()
2953 .map(|s| {
2954 let anchor = snapshot.anchor_after(s.head());
2955 s.map(|_| anchor)
2956 })
2957 .collect::<Vec<_>>()
2958 };
2959 buffer.edit(
2960 old_selections
2961 .iter()
2962 .map(|s| (s.start..s.end, text.clone())),
2963 autoindent_mode,
2964 cx,
2965 );
2966 anchors
2967 });
2968
2969 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
2970 s.select_anchors(selection_anchors);
2971 })
2972 });
2973 }
2974
2975 fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2976 if !EditorSettings::get_global(cx).show_completions_on_input {
2977 return;
2978 }
2979
2980 let selection = self.selections.newest_anchor();
2981 if self
2982 .buffer
2983 .read(cx)
2984 .is_completion_trigger(selection.head(), text, cx)
2985 {
2986 self.show_completions(&ShowCompletions, cx);
2987 } else {
2988 self.hide_context_menu(cx);
2989 }
2990 }
2991
2992 /// If any empty selections is touching the start of its innermost containing autoclose
2993 /// region, expand it to select the brackets.
2994 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
2995 let selections = self.selections.all::<usize>(cx);
2996 let buffer = self.buffer.read(cx).read(cx);
2997 let new_selections = self
2998 .selections_with_autoclose_regions(selections, &buffer)
2999 .map(|(mut selection, region)| {
3000 if !selection.is_empty() {
3001 return selection;
3002 }
3003
3004 if let Some(region) = region {
3005 let mut range = region.range.to_offset(&buffer);
3006 if selection.start == range.start && range.start >= region.pair.start.len() {
3007 range.start -= region.pair.start.len();
3008 if buffer.contains_str_at(range.start, ®ion.pair.start)
3009 && buffer.contains_str_at(range.end, ®ion.pair.end)
3010 {
3011 range.end += region.pair.end.len();
3012 selection.start = range.start;
3013 selection.end = range.end;
3014
3015 return selection;
3016 }
3017 }
3018 }
3019
3020 let always_treat_brackets_as_autoclosed = buffer
3021 .settings_at(selection.start, cx)
3022 .always_treat_brackets_as_autoclosed;
3023
3024 if !always_treat_brackets_as_autoclosed {
3025 return selection;
3026 }
3027
3028 if let Some(scope) = buffer.language_scope_at(selection.start) {
3029 for (pair, enabled) in scope.brackets() {
3030 if !enabled || !pair.close {
3031 continue;
3032 }
3033
3034 if buffer.contains_str_at(selection.start, &pair.end) {
3035 let pair_start_len = pair.start.len();
3036 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3037 {
3038 selection.start -= pair_start_len;
3039 selection.end += pair.end.len();
3040
3041 return selection;
3042 }
3043 }
3044 }
3045 }
3046
3047 selection
3048 })
3049 .collect();
3050
3051 drop(buffer);
3052 self.change_selections(None, cx, |selections| selections.select(new_selections));
3053 }
3054
3055 /// Iterate the given selections, and for each one, find the smallest surrounding
3056 /// autoclose region. This uses the ordering of the selections and the autoclose
3057 /// regions to avoid repeated comparisons.
3058 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3059 &'a self,
3060 selections: impl IntoIterator<Item = Selection<D>>,
3061 buffer: &'a MultiBufferSnapshot,
3062 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3063 let mut i = 0;
3064 let mut regions = self.autoclose_regions.as_slice();
3065 selections.into_iter().map(move |selection| {
3066 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3067
3068 let mut enclosing = None;
3069 while let Some(pair_state) = regions.get(i) {
3070 if pair_state.range.end.to_offset(buffer) < range.start {
3071 regions = ®ions[i + 1..];
3072 i = 0;
3073 } else if pair_state.range.start.to_offset(buffer) > range.end {
3074 break;
3075 } else {
3076 if pair_state.selection_id == selection.id {
3077 enclosing = Some(pair_state);
3078 }
3079 i += 1;
3080 }
3081 }
3082
3083 (selection.clone(), enclosing)
3084 })
3085 }
3086
3087 /// Remove any autoclose regions that no longer contain their selection.
3088 fn invalidate_autoclose_regions(
3089 &mut self,
3090 mut selections: &[Selection<Anchor>],
3091 buffer: &MultiBufferSnapshot,
3092 ) {
3093 self.autoclose_regions.retain(|state| {
3094 let mut i = 0;
3095 while let Some(selection) = selections.get(i) {
3096 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3097 selections = &selections[1..];
3098 continue;
3099 }
3100 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3101 break;
3102 }
3103 if selection.id == state.selection_id {
3104 return true;
3105 } else {
3106 i += 1;
3107 }
3108 }
3109 false
3110 });
3111 }
3112
3113 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3114 let offset = position.to_offset(buffer);
3115 let (word_range, kind) = buffer.surrounding_word(offset);
3116 if offset > word_range.start && kind == Some(CharKind::Word) {
3117 Some(
3118 buffer
3119 .text_for_range(word_range.start..offset)
3120 .collect::<String>(),
3121 )
3122 } else {
3123 None
3124 }
3125 }
3126
3127 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3128 self.refresh_inlay_hints(
3129 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3130 cx,
3131 );
3132 }
3133
3134 pub fn inlay_hints_enabled(&self) -> bool {
3135 self.inlay_hint_cache.enabled
3136 }
3137
3138 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3139 if self.project.is_none() || self.mode != EditorMode::Full {
3140 return;
3141 }
3142
3143 let reason_description = reason.description();
3144 let ignore_debounce = matches!(
3145 reason,
3146 InlayHintRefreshReason::SettingsChange(_)
3147 | InlayHintRefreshReason::Toggle(_)
3148 | InlayHintRefreshReason::ExcerptsRemoved(_)
3149 );
3150 let (invalidate_cache, required_languages) = match reason {
3151 InlayHintRefreshReason::Toggle(enabled) => {
3152 self.inlay_hint_cache.enabled = enabled;
3153 if enabled {
3154 (InvalidationStrategy::RefreshRequested, None)
3155 } else {
3156 self.inlay_hint_cache.clear();
3157 self.splice_inlays(
3158 self.visible_inlay_hints(cx)
3159 .iter()
3160 .map(|inlay| inlay.id)
3161 .collect(),
3162 Vec::new(),
3163 cx,
3164 );
3165 return;
3166 }
3167 }
3168 InlayHintRefreshReason::SettingsChange(new_settings) => {
3169 match self.inlay_hint_cache.update_settings(
3170 &self.buffer,
3171 new_settings,
3172 self.visible_inlay_hints(cx),
3173 cx,
3174 ) {
3175 ControlFlow::Break(Some(InlaySplice {
3176 to_remove,
3177 to_insert,
3178 })) => {
3179 self.splice_inlays(to_remove, to_insert, cx);
3180 return;
3181 }
3182 ControlFlow::Break(None) => return,
3183 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3184 }
3185 }
3186 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3187 if let Some(InlaySplice {
3188 to_remove,
3189 to_insert,
3190 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3191 {
3192 self.splice_inlays(to_remove, to_insert, cx);
3193 }
3194 return;
3195 }
3196 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3197 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3198 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3199 }
3200 InlayHintRefreshReason::RefreshRequested => {
3201 (InvalidationStrategy::RefreshRequested, None)
3202 }
3203 };
3204
3205 if let Some(InlaySplice {
3206 to_remove,
3207 to_insert,
3208 }) = self.inlay_hint_cache.spawn_hint_refresh(
3209 reason_description,
3210 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3211 invalidate_cache,
3212 ignore_debounce,
3213 cx,
3214 ) {
3215 self.splice_inlays(to_remove, to_insert, cx);
3216 }
3217 }
3218
3219 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3220 self.display_map
3221 .read(cx)
3222 .current_inlays()
3223 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3224 .cloned()
3225 .collect()
3226 }
3227
3228 pub fn excerpts_for_inlay_hints_query(
3229 &self,
3230 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3231 cx: &mut ViewContext<Editor>,
3232 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3233 let Some(project) = self.project.as_ref() else {
3234 return HashMap::default();
3235 };
3236 let project = project.read(cx);
3237 let multi_buffer = self.buffer().read(cx);
3238 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3239 let multi_buffer_visible_start = self
3240 .scroll_manager
3241 .anchor()
3242 .anchor
3243 .to_point(&multi_buffer_snapshot);
3244 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3245 multi_buffer_visible_start
3246 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3247 Bias::Left,
3248 );
3249 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3250 multi_buffer
3251 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3252 .into_iter()
3253 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3254 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3255 let buffer = buffer_handle.read(cx);
3256 let buffer_file = project::File::from_dyn(buffer.file())?;
3257 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3258 let worktree_entry = buffer_worktree
3259 .read(cx)
3260 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3261 if worktree_entry.is_ignored {
3262 return None;
3263 }
3264
3265 let language = buffer.language()?;
3266 if let Some(restrict_to_languages) = restrict_to_languages {
3267 if !restrict_to_languages.contains(language) {
3268 return None;
3269 }
3270 }
3271 Some((
3272 excerpt_id,
3273 (
3274 buffer_handle,
3275 buffer.version().clone(),
3276 excerpt_visible_range,
3277 ),
3278 ))
3279 })
3280 .collect()
3281 }
3282
3283 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3284 TextLayoutDetails {
3285 text_system: cx.text_system().clone(),
3286 editor_style: self.style.clone().unwrap(),
3287 rem_size: cx.rem_size(),
3288 scroll_anchor: self.scroll_manager.anchor(),
3289 visible_rows: self.visible_line_count(),
3290 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3291 }
3292 }
3293
3294 fn splice_inlays(
3295 &self,
3296 to_remove: Vec<InlayId>,
3297 to_insert: Vec<Inlay>,
3298 cx: &mut ViewContext<Self>,
3299 ) {
3300 self.display_map.update(cx, |display_map, cx| {
3301 display_map.splice_inlays(to_remove, to_insert, cx);
3302 });
3303 cx.notify();
3304 }
3305
3306 fn trigger_on_type_formatting(
3307 &self,
3308 input: String,
3309 cx: &mut ViewContext<Self>,
3310 ) -> Option<Task<Result<()>>> {
3311 if input.len() != 1 {
3312 return None;
3313 }
3314
3315 let project = self.project.as_ref()?;
3316 let position = self.selections.newest_anchor().head();
3317 let (buffer, buffer_position) = self
3318 .buffer
3319 .read(cx)
3320 .text_anchor_for_position(position, cx)?;
3321
3322 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3323 // hence we do LSP request & edit on host side only — add formats to host's history.
3324 let push_to_lsp_host_history = true;
3325 // If this is not the host, append its history with new edits.
3326 let push_to_client_history = project.read(cx).is_remote();
3327
3328 let on_type_formatting = project.update(cx, |project, cx| {
3329 project.on_type_format(
3330 buffer.clone(),
3331 buffer_position,
3332 input,
3333 push_to_lsp_host_history,
3334 cx,
3335 )
3336 });
3337 Some(cx.spawn(|editor, mut cx| async move {
3338 if let Some(transaction) = on_type_formatting.await? {
3339 if push_to_client_history {
3340 buffer
3341 .update(&mut cx, |buffer, _| {
3342 buffer.push_transaction(transaction, Instant::now());
3343 })
3344 .ok();
3345 }
3346 editor.update(&mut cx, |editor, cx| {
3347 editor.refresh_document_highlights(cx);
3348 })?;
3349 }
3350 Ok(())
3351 }))
3352 }
3353
3354 fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
3355 if self.pending_rename.is_some() {
3356 return;
3357 }
3358
3359 let Some(provider) = self.completion_provider.as_ref() else {
3360 return;
3361 };
3362
3363 let position = self.selections.newest_anchor().head();
3364 let (buffer, buffer_position) =
3365 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3366 output
3367 } else {
3368 return;
3369 };
3370
3371 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3372 let completions = provider.completions(&buffer, buffer_position, cx);
3373
3374 let id = post_inc(&mut self.next_completion_id);
3375 let task = cx.spawn(|this, mut cx| {
3376 async move {
3377 let completions = completions.await.log_err();
3378 let menu = if let Some(completions) = completions {
3379 let mut menu = CompletionsMenu {
3380 id,
3381 initial_position: position,
3382 match_candidates: completions
3383 .iter()
3384 .enumerate()
3385 .map(|(id, completion)| {
3386 StringMatchCandidate::new(
3387 id,
3388 completion.label.text[completion.label.filter_range.clone()]
3389 .into(),
3390 )
3391 })
3392 .collect(),
3393 buffer,
3394 completions: Arc::new(RwLock::new(completions.into())),
3395 matches: Vec::new().into(),
3396 selected_item: 0,
3397 scroll_handle: UniformListScrollHandle::new(),
3398 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
3399 DebouncedDelay::new(),
3400 )),
3401 };
3402 menu.filter(query.as_deref(), cx.background_executor().clone())
3403 .await;
3404
3405 if menu.matches.is_empty() {
3406 None
3407 } else {
3408 this.update(&mut cx, |editor, cx| {
3409 let completions = menu.completions.clone();
3410 let matches = menu.matches.clone();
3411
3412 let delay_ms = EditorSettings::get_global(cx)
3413 .completion_documentation_secondary_query_debounce;
3414 let delay = Duration::from_millis(delay_ms);
3415
3416 editor
3417 .completion_documentation_pre_resolve_debounce
3418 .fire_new(delay, cx, |editor, cx| {
3419 CompletionsMenu::pre_resolve_completion_documentation(
3420 completions,
3421 matches,
3422 editor,
3423 cx,
3424 )
3425 });
3426 })
3427 .ok();
3428 Some(menu)
3429 }
3430 } else {
3431 None
3432 };
3433
3434 this.update(&mut cx, |this, cx| {
3435 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3436
3437 let mut context_menu = this.context_menu.write();
3438 match context_menu.as_ref() {
3439 None => {}
3440
3441 Some(ContextMenu::Completions(prev_menu)) => {
3442 if prev_menu.id > id {
3443 return;
3444 }
3445 }
3446
3447 _ => return,
3448 }
3449
3450 if this.focus_handle.is_focused(cx) && menu.is_some() {
3451 let menu = menu.unwrap();
3452 *context_menu = Some(ContextMenu::Completions(menu));
3453 drop(context_menu);
3454 this.discard_inline_completion(cx);
3455 cx.notify();
3456 } else if this.completion_tasks.len() <= 1 {
3457 // If there are no more completion tasks and the last menu was
3458 // empty, we should hide it. If it was already hidden, we should
3459 // also show the copilot completion when available.
3460 drop(context_menu);
3461 if this.hide_context_menu(cx).is_none() {
3462 this.update_visible_inline_completion(cx);
3463 }
3464 }
3465 })?;
3466
3467 Ok::<_, anyhow::Error>(())
3468 }
3469 .log_err()
3470 });
3471
3472 self.completion_tasks.push((id, task));
3473 }
3474
3475 pub fn confirm_completion(
3476 &mut self,
3477 action: &ConfirmCompletion,
3478 cx: &mut ViewContext<Self>,
3479 ) -> Option<Task<Result<()>>> {
3480 use language::ToOffset as _;
3481
3482 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3483 menu
3484 } else {
3485 return None;
3486 };
3487
3488 let mat = completions_menu
3489 .matches
3490 .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
3491 let buffer_handle = completions_menu.buffer;
3492 let completions = completions_menu.completions.read();
3493 let completion = completions.get(mat.candidate_id)?;
3494 cx.stop_propagation();
3495
3496 let snippet;
3497 let text;
3498 if completion.is_snippet() {
3499 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3500 text = snippet.as_ref().unwrap().text.clone();
3501 } else {
3502 snippet = None;
3503 text = completion.new_text.clone();
3504 };
3505 let selections = self.selections.all::<usize>(cx);
3506 let buffer = buffer_handle.read(cx);
3507 let old_range = completion.old_range.to_offset(buffer);
3508 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3509
3510 let newest_selection = self.selections.newest_anchor();
3511 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3512 return None;
3513 }
3514
3515 let lookbehind = newest_selection
3516 .start
3517 .text_anchor
3518 .to_offset(buffer)
3519 .saturating_sub(old_range.start);
3520 let lookahead = old_range
3521 .end
3522 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3523 let mut common_prefix_len = old_text
3524 .bytes()
3525 .zip(text.bytes())
3526 .take_while(|(a, b)| a == b)
3527 .count();
3528
3529 let snapshot = self.buffer.read(cx).snapshot(cx);
3530 let mut range_to_replace: Option<Range<isize>> = None;
3531 let mut ranges = Vec::new();
3532 for selection in &selections {
3533 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3534 let start = selection.start.saturating_sub(lookbehind);
3535 let end = selection.end + lookahead;
3536 if selection.id == newest_selection.id {
3537 range_to_replace = Some(
3538 ((start + common_prefix_len) as isize - selection.start as isize)
3539 ..(end as isize - selection.start as isize),
3540 );
3541 }
3542 ranges.push(start + common_prefix_len..end);
3543 } else {
3544 common_prefix_len = 0;
3545 ranges.clear();
3546 ranges.extend(selections.iter().map(|s| {
3547 if s.id == newest_selection.id {
3548 range_to_replace = Some(
3549 old_range.start.to_offset_utf16(&snapshot).0 as isize
3550 - selection.start as isize
3551 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3552 - selection.start as isize,
3553 );
3554 old_range.clone()
3555 } else {
3556 s.start..s.end
3557 }
3558 }));
3559 break;
3560 }
3561 }
3562 let text = &text[common_prefix_len..];
3563
3564 cx.emit(EditorEvent::InputHandled {
3565 utf16_range_to_replace: range_to_replace,
3566 text: text.into(),
3567 });
3568
3569 self.transact(cx, |this, cx| {
3570 if let Some(mut snippet) = snippet {
3571 snippet.text = text.to_string();
3572 for tabstop in snippet.tabstops.iter_mut().flatten() {
3573 tabstop.start -= common_prefix_len as isize;
3574 tabstop.end -= common_prefix_len as isize;
3575 }
3576
3577 this.insert_snippet(&ranges, snippet, cx).log_err();
3578 } else {
3579 this.buffer.update(cx, |buffer, cx| {
3580 buffer.edit(
3581 ranges.iter().map(|range| (range.clone(), text)),
3582 this.autoindent_mode.clone(),
3583 cx,
3584 );
3585 });
3586 }
3587
3588 this.refresh_inline_completion(true, cx);
3589 });
3590
3591 let provider = self.completion_provider.as_ref()?;
3592 let apply_edits = provider.apply_additional_edits_for_completion(
3593 buffer_handle,
3594 completion.clone(),
3595 true,
3596 cx,
3597 );
3598 Some(cx.foreground_executor().spawn(async move {
3599 apply_edits.await?;
3600 Ok(())
3601 }))
3602 }
3603
3604 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3605 let mut context_menu = self.context_menu.write();
3606 if matches!(context_menu.as_ref(), Some(ContextMenu::CodeActions(_))) {
3607 *context_menu = None;
3608 cx.notify();
3609 return;
3610 }
3611 drop(context_menu);
3612
3613 let deployed_from_indicator = action.deployed_from_indicator;
3614 let mut task = self.code_actions_task.take();
3615 cx.spawn(|this, mut cx| async move {
3616 while let Some(prev_task) = task {
3617 prev_task.await;
3618 task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
3619 }
3620
3621 this.update(&mut cx, |this, cx| {
3622 if this.focus_handle.is_focused(cx) {
3623 if let Some((buffer, actions)) = this.available_code_actions.clone() {
3624 this.completion_tasks.clear();
3625 this.discard_inline_completion(cx);
3626 *this.context_menu.write() =
3627 Some(ContextMenu::CodeActions(CodeActionsMenu {
3628 buffer,
3629 actions,
3630 selected_item: Default::default(),
3631 scroll_handle: UniformListScrollHandle::default(),
3632 deployed_from_indicator,
3633 }));
3634 cx.notify();
3635 }
3636 }
3637 })?;
3638
3639 Ok::<_, anyhow::Error>(())
3640 })
3641 .detach_and_log_err(cx);
3642 }
3643
3644 pub fn confirm_code_action(
3645 &mut self,
3646 action: &ConfirmCodeAction,
3647 cx: &mut ViewContext<Self>,
3648 ) -> Option<Task<Result<()>>> {
3649 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
3650 menu
3651 } else {
3652 return None;
3653 };
3654 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
3655 let action = actions_menu.actions.get(action_ix)?.clone();
3656 let title = action.lsp_action.title.clone();
3657 let buffer = actions_menu.buffer;
3658 let workspace = self.workspace()?;
3659
3660 let apply_code_actions = workspace
3661 .read(cx)
3662 .project()
3663 .clone()
3664 .update(cx, |project, cx| {
3665 project.apply_code_action(buffer, action, true, cx)
3666 });
3667 let workspace = workspace.downgrade();
3668 Some(cx.spawn(|editor, cx| async move {
3669 let project_transaction = apply_code_actions.await?;
3670 Self::open_project_transaction(&editor, workspace, project_transaction, title, cx).await
3671 }))
3672 }
3673
3674 async fn open_project_transaction(
3675 this: &WeakView<Editor>,
3676 workspace: WeakView<Workspace>,
3677 transaction: ProjectTransaction,
3678 title: String,
3679 mut cx: AsyncWindowContext,
3680 ) -> Result<()> {
3681 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
3682
3683 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
3684 cx.update(|cx| {
3685 entries.sort_unstable_by_key(|(buffer, _)| {
3686 buffer.read(cx).file().map(|f| f.path().clone())
3687 });
3688 })?;
3689
3690 // If the project transaction's edits are all contained within this editor, then
3691 // avoid opening a new editor to display them.
3692
3693 if let Some((buffer, transaction)) = entries.first() {
3694 if entries.len() == 1 {
3695 let excerpt = this.update(&mut cx, |editor, cx| {
3696 editor
3697 .buffer()
3698 .read(cx)
3699 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
3700 })?;
3701 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
3702 if excerpted_buffer == *buffer {
3703 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
3704 let excerpt_range = excerpt_range.to_offset(buffer);
3705 buffer
3706 .edited_ranges_for_transaction::<usize>(transaction)
3707 .all(|range| {
3708 excerpt_range.start <= range.start
3709 && excerpt_range.end >= range.end
3710 })
3711 })?;
3712
3713 if all_edits_within_excerpt {
3714 return Ok(());
3715 }
3716 }
3717 }
3718 }
3719 } else {
3720 return Ok(());
3721 }
3722
3723 let mut ranges_to_highlight = Vec::new();
3724 let excerpt_buffer = cx.new_model(|cx| {
3725 let mut multibuffer =
3726 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
3727 for (buffer_handle, transaction) in &entries {
3728 let buffer = buffer_handle.read(cx);
3729 ranges_to_highlight.extend(
3730 multibuffer.push_excerpts_with_context_lines(
3731 buffer_handle.clone(),
3732 buffer
3733 .edited_ranges_for_transaction::<usize>(transaction)
3734 .collect(),
3735 1,
3736 cx,
3737 ),
3738 );
3739 }
3740 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
3741 multibuffer
3742 })?;
3743
3744 workspace.update(&mut cx, |workspace, cx| {
3745 let project = workspace.project().clone();
3746 let editor =
3747 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
3748 workspace.add_item_to_active_pane(Box::new(editor.clone()), cx);
3749 editor.update(cx, |editor, cx| {
3750 editor.highlight_background::<Self>(
3751 &ranges_to_highlight,
3752 |theme| theme.editor_highlighted_line_background,
3753 cx,
3754 );
3755 });
3756 })?;
3757
3758 Ok(())
3759 }
3760
3761 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3762 let project = self.project.clone()?;
3763 let buffer = self.buffer.read(cx);
3764 let newest_selection = self.selections.newest_anchor().clone();
3765 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
3766 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
3767 if start_buffer != end_buffer {
3768 return None;
3769 }
3770
3771 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
3772 cx.background_executor()
3773 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
3774 .await;
3775
3776 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
3777 project.code_actions(&start_buffer, start..end, cx)
3778 }) {
3779 code_actions.await
3780 } else {
3781 Vec::new()
3782 };
3783
3784 this.update(&mut cx, |this, cx| {
3785 this.available_code_actions = if actions.is_empty() {
3786 None
3787 } else {
3788 Some((start_buffer, actions.into()))
3789 };
3790 cx.notify();
3791 })
3792 .log_err();
3793 }));
3794 None
3795 }
3796
3797 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3798 if self.pending_rename.is_some() {
3799 return None;
3800 }
3801
3802 let project = self.project.clone()?;
3803 let buffer = self.buffer.read(cx);
3804 let newest_selection = self.selections.newest_anchor().clone();
3805 let cursor_position = newest_selection.head();
3806 let (cursor_buffer, cursor_buffer_position) =
3807 buffer.text_anchor_for_position(cursor_position, cx)?;
3808 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
3809 if cursor_buffer != tail_buffer {
3810 return None;
3811 }
3812
3813 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
3814 cx.background_executor()
3815 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
3816 .await;
3817
3818 let highlights = if let Some(highlights) = project
3819 .update(&mut cx, |project, cx| {
3820 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
3821 })
3822 .log_err()
3823 {
3824 highlights.await.log_err()
3825 } else {
3826 None
3827 };
3828
3829 if let Some(highlights) = highlights {
3830 this.update(&mut cx, |this, cx| {
3831 if this.pending_rename.is_some() {
3832 return;
3833 }
3834
3835 let buffer_id = cursor_position.buffer_id;
3836 let buffer = this.buffer.read(cx);
3837 if !buffer
3838 .text_anchor_for_position(cursor_position, cx)
3839 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
3840 {
3841 return;
3842 }
3843
3844 let cursor_buffer_snapshot = cursor_buffer.read(cx);
3845 let mut write_ranges = Vec::new();
3846 let mut read_ranges = Vec::new();
3847 for highlight in highlights {
3848 for (excerpt_id, excerpt_range) in
3849 buffer.excerpts_for_buffer(&cursor_buffer, cx)
3850 {
3851 let start = highlight
3852 .range
3853 .start
3854 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
3855 let end = highlight
3856 .range
3857 .end
3858 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
3859 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
3860 continue;
3861 }
3862
3863 let range = Anchor {
3864 buffer_id,
3865 excerpt_id: excerpt_id,
3866 text_anchor: start,
3867 }..Anchor {
3868 buffer_id,
3869 excerpt_id,
3870 text_anchor: end,
3871 };
3872 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
3873 write_ranges.push(range);
3874 } else {
3875 read_ranges.push(range);
3876 }
3877 }
3878 }
3879
3880 this.highlight_background::<DocumentHighlightRead>(
3881 &read_ranges,
3882 |theme| theme.editor_document_highlight_read_background,
3883 cx,
3884 );
3885 this.highlight_background::<DocumentHighlightWrite>(
3886 &write_ranges,
3887 |theme| theme.editor_document_highlight_write_background,
3888 cx,
3889 );
3890 cx.notify();
3891 })
3892 .log_err();
3893 }
3894 }));
3895 None
3896 }
3897
3898 fn refresh_inline_completion(
3899 &mut self,
3900 debounce: bool,
3901 cx: &mut ViewContext<Self>,
3902 ) -> Option<()> {
3903 let provider = self.inline_completion_provider()?;
3904 let cursor = self.selections.newest_anchor().head();
3905 let (buffer, cursor_buffer_position) =
3906 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
3907 if !self.show_inline_completions
3908 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
3909 {
3910 self.clear_inline_completion(cx);
3911 return None;
3912 }
3913
3914 self.update_visible_inline_completion(cx);
3915 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
3916 Some(())
3917 }
3918
3919 fn cycle_inline_completion(
3920 &mut self,
3921 direction: Direction,
3922 cx: &mut ViewContext<Self>,
3923 ) -> Option<()> {
3924 let provider = self.inline_completion_provider()?;
3925 let cursor = self.selections.newest_anchor().head();
3926 let (buffer, cursor_buffer_position) =
3927 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
3928 if !self.show_inline_completions
3929 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
3930 {
3931 return None;
3932 }
3933
3934 provider.cycle(buffer, cursor_buffer_position, direction, cx);
3935 self.update_visible_inline_completion(cx);
3936
3937 Some(())
3938 }
3939
3940 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
3941 if !self.has_active_inline_completion(cx) {
3942 self.refresh_inline_completion(false, cx);
3943 return;
3944 }
3945
3946 self.update_visible_inline_completion(cx);
3947 }
3948
3949 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
3950 self.show_cursor_names(cx);
3951 }
3952
3953 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
3954 self.show_cursor_names = true;
3955 cx.notify();
3956 cx.spawn(|this, mut cx| async move {
3957 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
3958 this.update(&mut cx, |this, cx| {
3959 this.show_cursor_names = false;
3960 cx.notify()
3961 })
3962 .ok()
3963 })
3964 .detach();
3965 }
3966
3967 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
3968 if self.has_active_inline_completion(cx) {
3969 self.cycle_inline_completion(Direction::Next, cx);
3970 } else {
3971 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
3972 if is_copilot_disabled {
3973 cx.propagate();
3974 }
3975 }
3976 }
3977
3978 pub fn previous_inline_completion(
3979 &mut self,
3980 _: &PreviousInlineCompletion,
3981 cx: &mut ViewContext<Self>,
3982 ) {
3983 if self.has_active_inline_completion(cx) {
3984 self.cycle_inline_completion(Direction::Prev, cx);
3985 } else {
3986 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
3987 if is_copilot_disabled {
3988 cx.propagate();
3989 }
3990 }
3991 }
3992
3993 fn accept_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> bool {
3994 if let Some(completion) = self.take_active_inline_completion(cx) {
3995 if let Some(provider) = self.inline_completion_provider() {
3996 provider.accept(cx);
3997 }
3998
3999 cx.emit(EditorEvent::InputHandled {
4000 utf16_range_to_replace: None,
4001 text: completion.text.to_string().into(),
4002 });
4003 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
4004 cx.notify();
4005 true
4006 } else {
4007 false
4008 }
4009 }
4010
4011 pub fn accept_partial_inline_completion(
4012 &mut self,
4013 _: &AcceptPartialInlineCompletion,
4014 cx: &mut ViewContext<Self>,
4015 ) {
4016 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
4017 if let Some(completion) = self.take_active_inline_completion(cx) {
4018 let mut partial_completion = completion
4019 .text
4020 .chars()
4021 .by_ref()
4022 .take_while(|c| c.is_alphabetic())
4023 .collect::<String>();
4024 if partial_completion.is_empty() {
4025 partial_completion = completion
4026 .text
4027 .chars()
4028 .by_ref()
4029 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4030 .collect::<String>();
4031 }
4032
4033 cx.emit(EditorEvent::InputHandled {
4034 utf16_range_to_replace: None,
4035 text: partial_completion.clone().into(),
4036 });
4037 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4038 self.refresh_inline_completion(true, cx);
4039 cx.notify();
4040 }
4041 }
4042 }
4043
4044 fn discard_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> bool {
4045 if let Some(provider) = self.inline_completion_provider() {
4046 provider.discard(cx);
4047 }
4048
4049 self.take_active_inline_completion(cx).is_some()
4050 }
4051
4052 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
4053 if let Some(completion) = self.active_inline_completion.as_ref() {
4054 let buffer = self.buffer.read(cx).read(cx);
4055 completion.position.is_valid(&buffer)
4056 } else {
4057 false
4058 }
4059 }
4060
4061 fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
4062 let completion = self.active_inline_completion.take()?;
4063 self.display_map.update(cx, |map, cx| {
4064 map.splice_inlays(vec![completion.id], Default::default(), cx);
4065 });
4066 let buffer = self.buffer.read(cx).read(cx);
4067
4068 if completion.position.is_valid(&buffer) {
4069 Some(completion)
4070 } else {
4071 None
4072 }
4073 }
4074
4075 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
4076 let selection = self.selections.newest_anchor();
4077 let cursor = selection.head();
4078
4079 if self.context_menu.read().is_none()
4080 && self.completion_tasks.is_empty()
4081 && selection.start == selection.end
4082 {
4083 if let Some(provider) = self.inline_completion_provider() {
4084 if let Some((buffer, cursor_buffer_position)) =
4085 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4086 {
4087 if let Some(text) =
4088 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
4089 {
4090 let text = Rope::from(text);
4091 let mut to_remove = Vec::new();
4092 if let Some(completion) = self.active_inline_completion.take() {
4093 to_remove.push(completion.id);
4094 }
4095
4096 let completion_inlay =
4097 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
4098 self.active_inline_completion = Some(completion_inlay.clone());
4099 self.display_map.update(cx, move |map, cx| {
4100 map.splice_inlays(to_remove, vec![completion_inlay], cx)
4101 });
4102 cx.notify();
4103 return;
4104 }
4105 }
4106 }
4107 }
4108
4109 self.discard_inline_completion(cx);
4110 }
4111
4112 fn clear_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
4113 if let Some(old_completion) = self.active_inline_completion.take() {
4114 self.splice_inlays(vec![old_completion.id], Vec::new(), cx);
4115 }
4116 self.discard_inline_completion(cx);
4117 }
4118
4119 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4120 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4121 }
4122
4123 pub fn render_code_actions_indicator(
4124 &self,
4125 _style: &EditorStyle,
4126 is_active: bool,
4127 cx: &mut ViewContext<Self>,
4128 ) -> Option<IconButton> {
4129 if self.available_code_actions.is_some() {
4130 Some(
4131 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4132 .icon_size(IconSize::XSmall)
4133 .size(ui::ButtonSize::None)
4134 .icon_color(Color::Muted)
4135 .selected(is_active)
4136 .on_click(cx.listener(|editor, _e, cx| {
4137 editor.toggle_code_actions(
4138 &ToggleCodeActions {
4139 deployed_from_indicator: true,
4140 },
4141 cx,
4142 );
4143 })),
4144 )
4145 } else {
4146 None
4147 }
4148 }
4149
4150 pub fn render_fold_indicators(
4151 &mut self,
4152 fold_data: Vec<Option<(FoldStatus, u32, bool)>>,
4153 _style: &EditorStyle,
4154 gutter_hovered: bool,
4155 _line_height: Pixels,
4156 _gutter_margin: Pixels,
4157 cx: &mut ViewContext<Self>,
4158 ) -> Vec<Option<AnyElement>> {
4159 fold_data
4160 .iter()
4161 .enumerate()
4162 .map(|(ix, fold_data)| {
4163 fold_data
4164 .map(|(fold_status, buffer_row, active)| {
4165 (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
4166 IconButton::new(ix, ui::IconName::ChevronDown)
4167 .on_click(cx.listener(move |this, _e, cx| match fold_status {
4168 FoldStatus::Folded => {
4169 this.unfold_at(&UnfoldAt { buffer_row }, cx);
4170 }
4171 FoldStatus::Foldable => {
4172 this.fold_at(&FoldAt { buffer_row }, cx);
4173 }
4174 }))
4175 .icon_color(ui::Color::Muted)
4176 .icon_size(ui::IconSize::Small)
4177 .selected(fold_status == FoldStatus::Folded)
4178 .selected_icon(ui::IconName::ChevronRight)
4179 .size(ui::ButtonSize::None)
4180 .into_any_element()
4181 })
4182 })
4183 .flatten()
4184 })
4185 .collect()
4186 }
4187
4188 pub fn context_menu_visible(&self) -> bool {
4189 self.context_menu
4190 .read()
4191 .as_ref()
4192 .map_or(false, |menu| menu.visible())
4193 }
4194
4195 pub fn render_context_menu(
4196 &self,
4197 cursor_position: DisplayPoint,
4198 style: &EditorStyle,
4199 max_height: Pixels,
4200 cx: &mut ViewContext<Editor>,
4201 ) -> Option<(DisplayPoint, AnyElement)> {
4202 self.context_menu.read().as_ref().map(|menu| {
4203 menu.render(
4204 cursor_position,
4205 style,
4206 max_height,
4207 self.workspace.as_ref().map(|(w, _)| w.clone()),
4208 cx,
4209 )
4210 })
4211 }
4212
4213 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
4214 cx.notify();
4215 self.completion_tasks.clear();
4216 let context_menu = self.context_menu.write().take();
4217 if context_menu.is_some() {
4218 self.update_visible_inline_completion(cx);
4219 }
4220 context_menu
4221 }
4222
4223 pub fn insert_snippet(
4224 &mut self,
4225 insertion_ranges: &[Range<usize>],
4226 snippet: Snippet,
4227 cx: &mut ViewContext<Self>,
4228 ) -> Result<()> {
4229 let tabstops = self.buffer.update(cx, |buffer, cx| {
4230 let snippet_text: Arc<str> = snippet.text.clone().into();
4231 buffer.edit(
4232 insertion_ranges
4233 .iter()
4234 .cloned()
4235 .map(|range| (range, snippet_text.clone())),
4236 Some(AutoindentMode::EachLine),
4237 cx,
4238 );
4239
4240 let snapshot = &*buffer.read(cx);
4241 let snippet = &snippet;
4242 snippet
4243 .tabstops
4244 .iter()
4245 .map(|tabstop| {
4246 let mut tabstop_ranges = tabstop
4247 .iter()
4248 .flat_map(|tabstop_range| {
4249 let mut delta = 0_isize;
4250 insertion_ranges.iter().map(move |insertion_range| {
4251 let insertion_start = insertion_range.start as isize + delta;
4252 delta +=
4253 snippet.text.len() as isize - insertion_range.len() as isize;
4254
4255 let start = snapshot.anchor_before(
4256 (insertion_start + tabstop_range.start) as usize,
4257 );
4258 let end = snapshot
4259 .anchor_after((insertion_start + tabstop_range.end) as usize);
4260 start..end
4261 })
4262 })
4263 .collect::<Vec<_>>();
4264 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
4265 tabstop_ranges
4266 })
4267 .collect::<Vec<_>>()
4268 });
4269
4270 if let Some(tabstop) = tabstops.first() {
4271 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4272 s.select_ranges(tabstop.iter().cloned());
4273 });
4274 self.snippet_stack.push(SnippetState {
4275 active_index: 0,
4276 ranges: tabstops,
4277 });
4278
4279 // Check whether the just-entered snippet ends with an auto-closable bracket.
4280 if self.autoclose_regions.is_empty() {
4281 let snapshot = self.buffer.read(cx).snapshot(cx);
4282 for selection in &mut self.selections.all::<Point>(cx) {
4283 let selection_head = selection.head();
4284 let Some(scope) = snapshot.language_scope_at(selection_head) else {
4285 continue;
4286 };
4287
4288 let mut bracket_pair = None;
4289 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
4290 let prev_chars = snapshot
4291 .reversed_chars_at(selection_head)
4292 .collect::<String>();
4293 for (pair, enabled) in scope.brackets() {
4294 if enabled
4295 && pair.close
4296 && prev_chars.starts_with(pair.start.as_str())
4297 && next_chars.starts_with(pair.end.as_str())
4298 {
4299 bracket_pair = Some(pair.clone());
4300 break;
4301 }
4302 }
4303 if let Some(pair) = bracket_pair {
4304 let start = snapshot.anchor_after(selection_head);
4305 let end = snapshot.anchor_after(selection_head);
4306 self.autoclose_regions.push(AutocloseRegion {
4307 selection_id: selection.id,
4308 range: start..end,
4309 pair,
4310 });
4311 }
4312 }
4313 }
4314 }
4315 Ok(())
4316 }
4317
4318 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4319 self.move_to_snippet_tabstop(Bias::Right, cx)
4320 }
4321
4322 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4323 self.move_to_snippet_tabstop(Bias::Left, cx)
4324 }
4325
4326 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
4327 if let Some(mut snippet) = self.snippet_stack.pop() {
4328 match bias {
4329 Bias::Left => {
4330 if snippet.active_index > 0 {
4331 snippet.active_index -= 1;
4332 } else {
4333 self.snippet_stack.push(snippet);
4334 return false;
4335 }
4336 }
4337 Bias::Right => {
4338 if snippet.active_index + 1 < snippet.ranges.len() {
4339 snippet.active_index += 1;
4340 } else {
4341 self.snippet_stack.push(snippet);
4342 return false;
4343 }
4344 }
4345 }
4346 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
4347 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4348 s.select_anchor_ranges(current_ranges.iter().cloned())
4349 });
4350 // If snippet state is not at the last tabstop, push it back on the stack
4351 if snippet.active_index + 1 < snippet.ranges.len() {
4352 self.snippet_stack.push(snippet);
4353 }
4354 return true;
4355 }
4356 }
4357
4358 false
4359 }
4360
4361 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
4362 self.transact(cx, |this, cx| {
4363 this.select_all(&SelectAll, cx);
4364 this.insert("", cx);
4365 });
4366 }
4367
4368 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
4369 self.transact(cx, |this, cx| {
4370 this.select_autoclose_pair(cx);
4371 let mut selections = this.selections.all::<Point>(cx);
4372 if !this.selections.line_mode {
4373 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
4374 for selection in &mut selections {
4375 if selection.is_empty() {
4376 let old_head = selection.head();
4377 let mut new_head =
4378 movement::left(&display_map, old_head.to_display_point(&display_map))
4379 .to_point(&display_map);
4380 if let Some((buffer, line_buffer_range)) = display_map
4381 .buffer_snapshot
4382 .buffer_line_for_row(old_head.row)
4383 {
4384 let indent_size =
4385 buffer.indent_size_for_line(line_buffer_range.start.row);
4386 let indent_len = match indent_size.kind {
4387 IndentKind::Space => {
4388 buffer.settings_at(line_buffer_range.start, cx).tab_size
4389 }
4390 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
4391 };
4392 if old_head.column <= indent_size.len && old_head.column > 0 {
4393 let indent_len = indent_len.get();
4394 new_head = cmp::min(
4395 new_head,
4396 Point::new(
4397 old_head.row,
4398 ((old_head.column - 1) / indent_len) * indent_len,
4399 ),
4400 );
4401 }
4402 }
4403
4404 selection.set_head(new_head, SelectionGoal::None);
4405 }
4406 }
4407 }
4408
4409 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4410 this.insert("", cx);
4411 this.refresh_inline_completion(true, cx);
4412 });
4413 }
4414
4415 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
4416 self.transact(cx, |this, cx| {
4417 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4418 let line_mode = s.line_mode;
4419 s.move_with(|map, selection| {
4420 if selection.is_empty() && !line_mode {
4421 let cursor = movement::right(map, selection.head());
4422 selection.end = cursor;
4423 selection.reversed = true;
4424 selection.goal = SelectionGoal::None;
4425 }
4426 })
4427 });
4428 this.insert("", cx);
4429 this.refresh_inline_completion(true, cx);
4430 });
4431 }
4432
4433 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
4434 if self.move_to_prev_snippet_tabstop(cx) {
4435 return;
4436 }
4437
4438 self.outdent(&Outdent, cx);
4439 }
4440
4441 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
4442 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
4443 return;
4444 }
4445
4446 let mut selections = self.selections.all_adjusted(cx);
4447 let buffer = self.buffer.read(cx);
4448 let snapshot = buffer.snapshot(cx);
4449 let rows_iter = selections.iter().map(|s| s.head().row);
4450 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
4451
4452 let mut edits = Vec::new();
4453 let mut prev_edited_row = 0;
4454 let mut row_delta = 0;
4455 for selection in &mut selections {
4456 if selection.start.row != prev_edited_row {
4457 row_delta = 0;
4458 }
4459 prev_edited_row = selection.end.row;
4460
4461 // If the selection is non-empty, then increase the indentation of the selected lines.
4462 if !selection.is_empty() {
4463 row_delta =
4464 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4465 continue;
4466 }
4467
4468 // If the selection is empty and the cursor is in the leading whitespace before the
4469 // suggested indentation, then auto-indent the line.
4470 let cursor = selection.head();
4471 let current_indent = snapshot.indent_size_for_line(cursor.row);
4472 if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
4473 if cursor.column < suggested_indent.len
4474 && cursor.column <= current_indent.len
4475 && current_indent.len <= suggested_indent.len
4476 {
4477 selection.start = Point::new(cursor.row, suggested_indent.len);
4478 selection.end = selection.start;
4479 if row_delta == 0 {
4480 edits.extend(Buffer::edit_for_indent_size_adjustment(
4481 cursor.row,
4482 current_indent,
4483 suggested_indent,
4484 ));
4485 row_delta = suggested_indent.len - current_indent.len;
4486 }
4487 continue;
4488 }
4489 }
4490
4491 // Accept copilot completion if there is only one selection and the cursor is not
4492 // in the leading whitespace.
4493 if self.selections.count() == 1
4494 && cursor.column >= current_indent.len
4495 && self.has_active_inline_completion(cx)
4496 {
4497 self.accept_inline_completion(cx);
4498 return;
4499 }
4500
4501 // Otherwise, insert a hard or soft tab.
4502 let settings = buffer.settings_at(cursor, cx);
4503 let tab_size = if settings.hard_tabs {
4504 IndentSize::tab()
4505 } else {
4506 let tab_size = settings.tab_size.get();
4507 let char_column = snapshot
4508 .text_for_range(Point::new(cursor.row, 0)..cursor)
4509 .flat_map(str::chars)
4510 .count()
4511 + row_delta as usize;
4512 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
4513 IndentSize::spaces(chars_to_next_tab_stop)
4514 };
4515 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
4516 selection.end = selection.start;
4517 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
4518 row_delta += tab_size.len;
4519 }
4520
4521 self.transact(cx, |this, cx| {
4522 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4523 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4524 this.refresh_inline_completion(true, cx);
4525 });
4526 }
4527
4528 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
4529 if self.read_only(cx) {
4530 return;
4531 }
4532 let mut selections = self.selections.all::<Point>(cx);
4533 let mut prev_edited_row = 0;
4534 let mut row_delta = 0;
4535 let mut edits = Vec::new();
4536 let buffer = self.buffer.read(cx);
4537 let snapshot = buffer.snapshot(cx);
4538 for selection in &mut selections {
4539 if selection.start.row != prev_edited_row {
4540 row_delta = 0;
4541 }
4542 prev_edited_row = selection.end.row;
4543
4544 row_delta =
4545 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4546 }
4547
4548 self.transact(cx, |this, cx| {
4549 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4550 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4551 });
4552 }
4553
4554 fn indent_selection(
4555 buffer: &MultiBuffer,
4556 snapshot: &MultiBufferSnapshot,
4557 selection: &mut Selection<Point>,
4558 edits: &mut Vec<(Range<Point>, String)>,
4559 delta_for_start_row: u32,
4560 cx: &AppContext,
4561 ) -> u32 {
4562 let settings = buffer.settings_at(selection.start, cx);
4563 let tab_size = settings.tab_size.get();
4564 let indent_kind = if settings.hard_tabs {
4565 IndentKind::Tab
4566 } else {
4567 IndentKind::Space
4568 };
4569 let mut start_row = selection.start.row;
4570 let mut end_row = selection.end.row + 1;
4571
4572 // If a selection ends at the beginning of a line, don't indent
4573 // that last line.
4574 if selection.end.column == 0 && selection.end.row > selection.start.row {
4575 end_row -= 1;
4576 }
4577
4578 // Avoid re-indenting a row that has already been indented by a
4579 // previous selection, but still update this selection's column
4580 // to reflect that indentation.
4581 if delta_for_start_row > 0 {
4582 start_row += 1;
4583 selection.start.column += delta_for_start_row;
4584 if selection.end.row == selection.start.row {
4585 selection.end.column += delta_for_start_row;
4586 }
4587 }
4588
4589 let mut delta_for_end_row = 0;
4590 let has_multiple_rows = start_row + 1 != end_row;
4591 for row in start_row..end_row {
4592 let current_indent = snapshot.indent_size_for_line(row);
4593 let indent_delta = match (current_indent.kind, indent_kind) {
4594 (IndentKind::Space, IndentKind::Space) => {
4595 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
4596 IndentSize::spaces(columns_to_next_tab_stop)
4597 }
4598 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
4599 (_, IndentKind::Tab) => IndentSize::tab(),
4600 };
4601
4602 let start = if has_multiple_rows || current_indent.len < selection.start.column {
4603 0
4604 } else {
4605 selection.start.column
4606 };
4607 let row_start = Point::new(row, start);
4608 edits.push((
4609 row_start..row_start,
4610 indent_delta.chars().collect::<String>(),
4611 ));
4612
4613 // Update this selection's endpoints to reflect the indentation.
4614 if row == selection.start.row {
4615 selection.start.column += indent_delta.len;
4616 }
4617 if row == selection.end.row {
4618 selection.end.column += indent_delta.len;
4619 delta_for_end_row = indent_delta.len;
4620 }
4621 }
4622
4623 if selection.start.row == selection.end.row {
4624 delta_for_start_row + delta_for_end_row
4625 } else {
4626 delta_for_end_row
4627 }
4628 }
4629
4630 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
4631 if self.read_only(cx) {
4632 return;
4633 }
4634 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4635 let selections = self.selections.all::<Point>(cx);
4636 let mut deletion_ranges = Vec::new();
4637 let mut last_outdent = None;
4638 {
4639 let buffer = self.buffer.read(cx);
4640 let snapshot = buffer.snapshot(cx);
4641 for selection in &selections {
4642 let settings = buffer.settings_at(selection.start, cx);
4643 let tab_size = settings.tab_size.get();
4644 let mut rows = selection.spanned_rows(false, &display_map);
4645
4646 // Avoid re-outdenting a row that has already been outdented by a
4647 // previous selection.
4648 if let Some(last_row) = last_outdent {
4649 if last_row == rows.start {
4650 rows.start += 1;
4651 }
4652 }
4653 let has_multiple_rows = rows.len() > 1;
4654 for row in rows {
4655 let indent_size = snapshot.indent_size_for_line(row);
4656 if indent_size.len > 0 {
4657 let deletion_len = match indent_size.kind {
4658 IndentKind::Space => {
4659 let columns_to_prev_tab_stop = indent_size.len % tab_size;
4660 if columns_to_prev_tab_stop == 0 {
4661 tab_size
4662 } else {
4663 columns_to_prev_tab_stop
4664 }
4665 }
4666 IndentKind::Tab => 1,
4667 };
4668 let start = if has_multiple_rows
4669 || deletion_len > selection.start.column
4670 || indent_size.len < selection.start.column
4671 {
4672 0
4673 } else {
4674 selection.start.column - deletion_len
4675 };
4676 deletion_ranges
4677 .push(Point::new(row, start)..Point::new(row, start + deletion_len));
4678 last_outdent = Some(row);
4679 }
4680 }
4681 }
4682 }
4683
4684 self.transact(cx, |this, cx| {
4685 this.buffer.update(cx, |buffer, cx| {
4686 let empty_str: Arc<str> = "".into();
4687 buffer.edit(
4688 deletion_ranges
4689 .into_iter()
4690 .map(|range| (range, empty_str.clone())),
4691 None,
4692 cx,
4693 );
4694 });
4695 let selections = this.selections.all::<usize>(cx);
4696 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4697 });
4698 }
4699
4700 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
4701 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4702 let selections = self.selections.all::<Point>(cx);
4703
4704 let mut new_cursors = Vec::new();
4705 let mut edit_ranges = Vec::new();
4706 let mut selections = selections.iter().peekable();
4707 while let Some(selection) = selections.next() {
4708 let mut rows = selection.spanned_rows(false, &display_map);
4709 let goal_display_column = selection.head().to_display_point(&display_map).column();
4710
4711 // Accumulate contiguous regions of rows that we want to delete.
4712 while let Some(next_selection) = selections.peek() {
4713 let next_rows = next_selection.spanned_rows(false, &display_map);
4714 if next_rows.start <= rows.end {
4715 rows.end = next_rows.end;
4716 selections.next().unwrap();
4717 } else {
4718 break;
4719 }
4720 }
4721
4722 let buffer = &display_map.buffer_snapshot;
4723 let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
4724 let edit_end;
4725 let cursor_buffer_row;
4726 if buffer.max_point().row >= rows.end {
4727 // If there's a line after the range, delete the \n from the end of the row range
4728 // and position the cursor on the next line.
4729 edit_end = Point::new(rows.end, 0).to_offset(buffer);
4730 cursor_buffer_row = rows.end;
4731 } else {
4732 // If there isn't a line after the range, delete the \n from the line before the
4733 // start of the row range and position the cursor there.
4734 edit_start = edit_start.saturating_sub(1);
4735 edit_end = buffer.len();
4736 cursor_buffer_row = rows.start.saturating_sub(1);
4737 }
4738
4739 let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
4740 *cursor.column_mut() =
4741 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
4742
4743 new_cursors.push((
4744 selection.id,
4745 buffer.anchor_after(cursor.to_point(&display_map)),
4746 ));
4747 edit_ranges.push(edit_start..edit_end);
4748 }
4749
4750 self.transact(cx, |this, cx| {
4751 let buffer = this.buffer.update(cx, |buffer, cx| {
4752 let empty_str: Arc<str> = "".into();
4753 buffer.edit(
4754 edit_ranges
4755 .into_iter()
4756 .map(|range| (range, empty_str.clone())),
4757 None,
4758 cx,
4759 );
4760 buffer.snapshot(cx)
4761 });
4762 let new_selections = new_cursors
4763 .into_iter()
4764 .map(|(id, cursor)| {
4765 let cursor = cursor.to_point(&buffer);
4766 Selection {
4767 id,
4768 start: cursor,
4769 end: cursor,
4770 reversed: false,
4771 goal: SelectionGoal::None,
4772 }
4773 })
4774 .collect();
4775
4776 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4777 s.select(new_selections);
4778 });
4779 });
4780 }
4781
4782 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
4783 if self.read_only(cx) {
4784 return;
4785 }
4786 let mut row_ranges = Vec::<Range<u32>>::new();
4787 for selection in self.selections.all::<Point>(cx) {
4788 let start = selection.start.row;
4789 let end = if selection.start.row == selection.end.row {
4790 selection.start.row + 1
4791 } else {
4792 selection.end.row
4793 };
4794
4795 if let Some(last_row_range) = row_ranges.last_mut() {
4796 if start <= last_row_range.end {
4797 last_row_range.end = end;
4798 continue;
4799 }
4800 }
4801 row_ranges.push(start..end);
4802 }
4803
4804 let snapshot = self.buffer.read(cx).snapshot(cx);
4805 let mut cursor_positions = Vec::new();
4806 for row_range in &row_ranges {
4807 let anchor = snapshot.anchor_before(Point::new(
4808 row_range.end - 1,
4809 snapshot.line_len(row_range.end - 1),
4810 ));
4811 cursor_positions.push(anchor..anchor);
4812 }
4813
4814 self.transact(cx, |this, cx| {
4815 for row_range in row_ranges.into_iter().rev() {
4816 for row in row_range.rev() {
4817 let end_of_line = Point::new(row, snapshot.line_len(row));
4818 let indent = snapshot.indent_size_for_line(row + 1);
4819 let start_of_next_line = Point::new(row + 1, indent.len);
4820
4821 let replace = if snapshot.line_len(row + 1) > indent.len {
4822 " "
4823 } else {
4824 ""
4825 };
4826
4827 this.buffer.update(cx, |buffer, cx| {
4828 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
4829 });
4830 }
4831 }
4832
4833 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4834 s.select_anchor_ranges(cursor_positions)
4835 });
4836 });
4837 }
4838
4839 pub fn sort_lines_case_sensitive(
4840 &mut self,
4841 _: &SortLinesCaseSensitive,
4842 cx: &mut ViewContext<Self>,
4843 ) {
4844 self.manipulate_lines(cx, |lines| lines.sort())
4845 }
4846
4847 pub fn sort_lines_case_insensitive(
4848 &mut self,
4849 _: &SortLinesCaseInsensitive,
4850 cx: &mut ViewContext<Self>,
4851 ) {
4852 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
4853 }
4854
4855 pub fn unique_lines_case_insensitive(
4856 &mut self,
4857 _: &UniqueLinesCaseInsensitive,
4858 cx: &mut ViewContext<Self>,
4859 ) {
4860 self.manipulate_lines(cx, |lines| {
4861 let mut seen = HashSet::default();
4862 lines.retain(|line| seen.insert(line.to_lowercase()));
4863 })
4864 }
4865
4866 pub fn unique_lines_case_sensitive(
4867 &mut self,
4868 _: &UniqueLinesCaseSensitive,
4869 cx: &mut ViewContext<Self>,
4870 ) {
4871 self.manipulate_lines(cx, |lines| {
4872 let mut seen = HashSet::default();
4873 lines.retain(|line| seen.insert(*line));
4874 })
4875 }
4876
4877 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
4878 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
4879 if !revert_changes.is_empty() {
4880 self.transact(cx, |editor, cx| {
4881 editor.buffer().update(cx, |multi_buffer, cx| {
4882 for (buffer_id, buffer_revert_ranges) in revert_changes {
4883 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
4884 buffer.update(cx, |buffer, cx| {
4885 buffer.edit(buffer_revert_ranges, None, cx);
4886 });
4887 }
4888 }
4889 });
4890 editor.change_selections(None, cx, |selections| selections.refresh());
4891 });
4892 }
4893 }
4894
4895 fn gather_revert_changes(
4896 &mut self,
4897 selections: &[Selection<Anchor>],
4898 cx: &mut ViewContext<'_, Editor>,
4899 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Arc<str>)>> {
4900 let mut revert_changes = HashMap::default();
4901 self.buffer.update(cx, |multi_buffer, cx| {
4902 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4903 let selected_multi_buffer_rows = selections.iter().map(|selection| {
4904 let head = selection.head();
4905 let tail = selection.tail();
4906 let start = tail.to_point(&multi_buffer_snapshot).row;
4907 let end = head.to_point(&multi_buffer_snapshot).row;
4908 if start > end {
4909 end..start
4910 } else {
4911 start..end
4912 }
4913 });
4914
4915 let mut processed_buffer_rows =
4916 HashMap::<BufferId, HashSet<Range<text::Anchor>>>::default();
4917 for selected_multi_buffer_rows in selected_multi_buffer_rows {
4918 let query_rows =
4919 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end + 1;
4920 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
4921 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
4922 // when the caret is just above or just below the deleted hunk.
4923 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
4924 let related_to_selection = if allow_adjacent {
4925 hunk.associated_range.overlaps(&query_rows)
4926 || hunk.associated_range.start == query_rows.end
4927 || hunk.associated_range.end == query_rows.start
4928 } else {
4929 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
4930 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
4931 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
4932 || selected_multi_buffer_rows.end == hunk.associated_range.start
4933 };
4934 if related_to_selection {
4935 if !processed_buffer_rows
4936 .entry(hunk.buffer_id)
4937 .or_default()
4938 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
4939 {
4940 continue;
4941 }
4942 Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
4943 }
4944 }
4945 }
4946 });
4947 revert_changes
4948 }
4949
4950 fn prepare_revert_change(
4951 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Arc<str>)>>,
4952 multi_buffer: &MultiBuffer,
4953 hunk: &DiffHunk<u32>,
4954 cx: &mut AppContext,
4955 ) -> Option<()> {
4956 let buffer = multi_buffer.buffer(hunk.buffer_id)?;
4957 let buffer = buffer.read(cx);
4958 let original_text = buffer.diff_base()?.get(hunk.diff_base_byte_range.clone())?;
4959 let buffer_snapshot = buffer.snapshot();
4960 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
4961 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
4962 probe
4963 .0
4964 .start
4965 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
4966 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
4967 .then(probe.1.as_ref().cmp(original_text))
4968 }) {
4969 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), Arc::from(original_text)));
4970 Some(())
4971 } else {
4972 None
4973 }
4974 }
4975
4976 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
4977 self.manipulate_lines(cx, |lines| lines.reverse())
4978 }
4979
4980 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
4981 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
4982 }
4983
4984 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
4985 where
4986 Fn: FnMut(&mut Vec<&str>),
4987 {
4988 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4989 let buffer = self.buffer.read(cx).snapshot(cx);
4990
4991 let mut edits = Vec::new();
4992
4993 let selections = self.selections.all::<Point>(cx);
4994 let mut selections = selections.iter().peekable();
4995 let mut contiguous_row_selections = Vec::new();
4996 let mut new_selections = Vec::new();
4997 let mut added_lines = 0;
4998 let mut removed_lines = 0;
4999
5000 while let Some(selection) = selections.next() {
5001 let (start_row, end_row) = consume_contiguous_rows(
5002 &mut contiguous_row_selections,
5003 selection,
5004 &display_map,
5005 &mut selections,
5006 );
5007
5008 let start_point = Point::new(start_row, 0);
5009 let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
5010 let text = buffer
5011 .text_for_range(start_point..end_point)
5012 .collect::<String>();
5013
5014 let mut lines = text.split('\n').collect_vec();
5015
5016 let lines_before = lines.len();
5017 callback(&mut lines);
5018 let lines_after = lines.len();
5019
5020 edits.push((start_point..end_point, lines.join("\n")));
5021
5022 // Selections must change based on added and removed line count
5023 let start_row = start_point.row + added_lines as u32 - removed_lines as u32;
5024 let end_row = start_row + lines_after.saturating_sub(1) as u32;
5025 new_selections.push(Selection {
5026 id: selection.id,
5027 start: start_row,
5028 end: end_row,
5029 goal: SelectionGoal::None,
5030 reversed: selection.reversed,
5031 });
5032
5033 if lines_after > lines_before {
5034 added_lines += lines_after - lines_before;
5035 } else if lines_before > lines_after {
5036 removed_lines += lines_before - lines_after;
5037 }
5038 }
5039
5040 self.transact(cx, |this, cx| {
5041 let buffer = this.buffer.update(cx, |buffer, cx| {
5042 buffer.edit(edits, None, cx);
5043 buffer.snapshot(cx)
5044 });
5045
5046 // Recalculate offsets on newly edited buffer
5047 let new_selections = new_selections
5048 .iter()
5049 .map(|s| {
5050 let start_point = Point::new(s.start, 0);
5051 let end_point = Point::new(s.end, buffer.line_len(s.end));
5052 Selection {
5053 id: s.id,
5054 start: buffer.point_to_offset(start_point),
5055 end: buffer.point_to_offset(end_point),
5056 goal: s.goal,
5057 reversed: s.reversed,
5058 }
5059 })
5060 .collect();
5061
5062 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5063 s.select(new_selections);
5064 });
5065
5066 this.request_autoscroll(Autoscroll::fit(), cx);
5067 });
5068 }
5069
5070 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
5071 self.manipulate_text(cx, |text| text.to_uppercase())
5072 }
5073
5074 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
5075 self.manipulate_text(cx, |text| text.to_lowercase())
5076 }
5077
5078 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
5079 self.manipulate_text(cx, |text| {
5080 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5081 // https://github.com/rutrum/convert-case/issues/16
5082 text.split('\n')
5083 .map(|line| line.to_case(Case::Title))
5084 .join("\n")
5085 })
5086 }
5087
5088 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
5089 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
5090 }
5091
5092 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
5093 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
5094 }
5095
5096 pub fn convert_to_upper_camel_case(
5097 &mut self,
5098 _: &ConvertToUpperCamelCase,
5099 cx: &mut ViewContext<Self>,
5100 ) {
5101 self.manipulate_text(cx, |text| {
5102 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5103 // https://github.com/rutrum/convert-case/issues/16
5104 text.split('\n')
5105 .map(|line| line.to_case(Case::UpperCamel))
5106 .join("\n")
5107 })
5108 }
5109
5110 pub fn convert_to_lower_camel_case(
5111 &mut self,
5112 _: &ConvertToLowerCamelCase,
5113 cx: &mut ViewContext<Self>,
5114 ) {
5115 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
5116 }
5117
5118 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5119 where
5120 Fn: FnMut(&str) -> String,
5121 {
5122 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5123 let buffer = self.buffer.read(cx).snapshot(cx);
5124
5125 let mut new_selections = Vec::new();
5126 let mut edits = Vec::new();
5127 let mut selection_adjustment = 0i32;
5128
5129 for selection in self.selections.all::<usize>(cx) {
5130 let selection_is_empty = selection.is_empty();
5131
5132 let (start, end) = if selection_is_empty {
5133 let word_range = movement::surrounding_word(
5134 &display_map,
5135 selection.start.to_display_point(&display_map),
5136 );
5137 let start = word_range.start.to_offset(&display_map, Bias::Left);
5138 let end = word_range.end.to_offset(&display_map, Bias::Left);
5139 (start, end)
5140 } else {
5141 (selection.start, selection.end)
5142 };
5143
5144 let text = buffer.text_for_range(start..end).collect::<String>();
5145 let old_length = text.len() as i32;
5146 let text = callback(&text);
5147
5148 new_selections.push(Selection {
5149 start: (start as i32 - selection_adjustment) as usize,
5150 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
5151 goal: SelectionGoal::None,
5152 ..selection
5153 });
5154
5155 selection_adjustment += old_length - text.len() as i32;
5156
5157 edits.push((start..end, text));
5158 }
5159
5160 self.transact(cx, |this, cx| {
5161 this.buffer.update(cx, |buffer, cx| {
5162 buffer.edit(edits, None, cx);
5163 });
5164
5165 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5166 s.select(new_selections);
5167 });
5168
5169 this.request_autoscroll(Autoscroll::fit(), cx);
5170 });
5171 }
5172
5173 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
5174 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5175 let buffer = &display_map.buffer_snapshot;
5176 let selections = self.selections.all::<Point>(cx);
5177
5178 let mut edits = Vec::new();
5179 let mut selections_iter = selections.iter().peekable();
5180 while let Some(selection) = selections_iter.next() {
5181 // Avoid duplicating the same lines twice.
5182 let mut rows = selection.spanned_rows(false, &display_map);
5183
5184 while let Some(next_selection) = selections_iter.peek() {
5185 let next_rows = next_selection.spanned_rows(false, &display_map);
5186 if next_rows.start < rows.end {
5187 rows.end = next_rows.end;
5188 selections_iter.next().unwrap();
5189 } else {
5190 break;
5191 }
5192 }
5193
5194 // Copy the text from the selected row region and splice it either at the start
5195 // or end of the region.
5196 let start = Point::new(rows.start, 0);
5197 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
5198 let text = buffer
5199 .text_for_range(start..end)
5200 .chain(Some("\n"))
5201 .collect::<String>();
5202 let insert_location = if upwards {
5203 Point::new(rows.end, 0)
5204 } else {
5205 start
5206 };
5207 edits.push((insert_location..insert_location, text));
5208 }
5209
5210 self.transact(cx, |this, cx| {
5211 this.buffer.update(cx, |buffer, cx| {
5212 buffer.edit(edits, None, cx);
5213 });
5214
5215 this.request_autoscroll(Autoscroll::fit(), cx);
5216 });
5217 }
5218
5219 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
5220 self.duplicate_line(true, cx);
5221 }
5222
5223 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
5224 self.duplicate_line(false, cx);
5225 }
5226
5227 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
5228 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5229 let buffer = self.buffer.read(cx).snapshot(cx);
5230
5231 let mut edits = Vec::new();
5232 let mut unfold_ranges = Vec::new();
5233 let mut refold_ranges = Vec::new();
5234
5235 let selections = self.selections.all::<Point>(cx);
5236 let mut selections = selections.iter().peekable();
5237 let mut contiguous_row_selections = Vec::new();
5238 let mut new_selections = Vec::new();
5239
5240 while let Some(selection) = selections.next() {
5241 // Find all the selections that span a contiguous row range
5242 let (start_row, end_row) = consume_contiguous_rows(
5243 &mut contiguous_row_selections,
5244 selection,
5245 &display_map,
5246 &mut selections,
5247 );
5248
5249 // Move the text spanned by the row range to be before the line preceding the row range
5250 if start_row > 0 {
5251 let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
5252 ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
5253 let insertion_point = display_map
5254 .prev_line_boundary(Point::new(start_row - 1, 0))
5255 .0;
5256
5257 // Don't move lines across excerpts
5258 if buffer
5259 .excerpt_boundaries_in_range((
5260 Bound::Excluded(insertion_point),
5261 Bound::Included(range_to_move.end),
5262 ))
5263 .next()
5264 .is_none()
5265 {
5266 let text = buffer
5267 .text_for_range(range_to_move.clone())
5268 .flat_map(|s| s.chars())
5269 .skip(1)
5270 .chain(['\n'])
5271 .collect::<String>();
5272
5273 edits.push((
5274 buffer.anchor_after(range_to_move.start)
5275 ..buffer.anchor_before(range_to_move.end),
5276 String::new(),
5277 ));
5278 let insertion_anchor = buffer.anchor_after(insertion_point);
5279 edits.push((insertion_anchor..insertion_anchor, text));
5280
5281 let row_delta = range_to_move.start.row - insertion_point.row + 1;
5282
5283 // Move selections up
5284 new_selections.extend(contiguous_row_selections.drain(..).map(
5285 |mut selection| {
5286 selection.start.row -= row_delta;
5287 selection.end.row -= row_delta;
5288 selection
5289 },
5290 ));
5291
5292 // Move folds up
5293 unfold_ranges.push(range_to_move.clone());
5294 for fold in display_map.folds_in_range(
5295 buffer.anchor_before(range_to_move.start)
5296 ..buffer.anchor_after(range_to_move.end),
5297 ) {
5298 let mut start = fold.range.start.to_point(&buffer);
5299 let mut end = fold.range.end.to_point(&buffer);
5300 start.row -= row_delta;
5301 end.row -= row_delta;
5302 refold_ranges.push(start..end);
5303 }
5304 }
5305 }
5306
5307 // If we didn't move line(s), preserve the existing selections
5308 new_selections.append(&mut contiguous_row_selections);
5309 }
5310
5311 self.transact(cx, |this, cx| {
5312 this.unfold_ranges(unfold_ranges, true, true, cx);
5313 this.buffer.update(cx, |buffer, cx| {
5314 for (range, text) in edits {
5315 buffer.edit([(range, text)], None, cx);
5316 }
5317 });
5318 this.fold_ranges(refold_ranges, true, cx);
5319 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5320 s.select(new_selections);
5321 })
5322 });
5323 }
5324
5325 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5326 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5327 let buffer = self.buffer.read(cx).snapshot(cx);
5328
5329 let mut edits = Vec::new();
5330 let mut unfold_ranges = Vec::new();
5331 let mut refold_ranges = Vec::new();
5332
5333 let selections = self.selections.all::<Point>(cx);
5334 let mut selections = selections.iter().peekable();
5335 let mut contiguous_row_selections = Vec::new();
5336 let mut new_selections = Vec::new();
5337
5338 while let Some(selection) = selections.next() {
5339 // Find all the selections that span a contiguous row range
5340 let (start_row, end_row) = consume_contiguous_rows(
5341 &mut contiguous_row_selections,
5342 selection,
5343 &display_map,
5344 &mut selections,
5345 );
5346
5347 // Move the text spanned by the row range to be after the last line of the row range
5348 if end_row <= buffer.max_point().row {
5349 let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
5350 let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
5351
5352 // Don't move lines across excerpt boundaries
5353 if buffer
5354 .excerpt_boundaries_in_range((
5355 Bound::Excluded(range_to_move.start),
5356 Bound::Included(insertion_point),
5357 ))
5358 .next()
5359 .is_none()
5360 {
5361 let mut text = String::from("\n");
5362 text.extend(buffer.text_for_range(range_to_move.clone()));
5363 text.pop(); // Drop trailing newline
5364 edits.push((
5365 buffer.anchor_after(range_to_move.start)
5366 ..buffer.anchor_before(range_to_move.end),
5367 String::new(),
5368 ));
5369 let insertion_anchor = buffer.anchor_after(insertion_point);
5370 edits.push((insertion_anchor..insertion_anchor, text));
5371
5372 let row_delta = insertion_point.row - range_to_move.end.row + 1;
5373
5374 // Move selections down
5375 new_selections.extend(contiguous_row_selections.drain(..).map(
5376 |mut selection| {
5377 selection.start.row += row_delta;
5378 selection.end.row += row_delta;
5379 selection
5380 },
5381 ));
5382
5383 // Move folds down
5384 unfold_ranges.push(range_to_move.clone());
5385 for fold in display_map.folds_in_range(
5386 buffer.anchor_before(range_to_move.start)
5387 ..buffer.anchor_after(range_to_move.end),
5388 ) {
5389 let mut start = fold.range.start.to_point(&buffer);
5390 let mut end = fold.range.end.to_point(&buffer);
5391 start.row += row_delta;
5392 end.row += row_delta;
5393 refold_ranges.push(start..end);
5394 }
5395 }
5396 }
5397
5398 // If we didn't move line(s), preserve the existing selections
5399 new_selections.append(&mut contiguous_row_selections);
5400 }
5401
5402 self.transact(cx, |this, cx| {
5403 this.unfold_ranges(unfold_ranges, true, true, cx);
5404 this.buffer.update(cx, |buffer, cx| {
5405 for (range, text) in edits {
5406 buffer.edit([(range, text)], None, cx);
5407 }
5408 });
5409 this.fold_ranges(refold_ranges, true, cx);
5410 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
5411 });
5412 }
5413
5414 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
5415 let text_layout_details = &self.text_layout_details(cx);
5416 self.transact(cx, |this, cx| {
5417 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5418 let mut edits: Vec<(Range<usize>, String)> = Default::default();
5419 let line_mode = s.line_mode;
5420 s.move_with(|display_map, selection| {
5421 if !selection.is_empty() || line_mode {
5422 return;
5423 }
5424
5425 let mut head = selection.head();
5426 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
5427 if head.column() == display_map.line_len(head.row()) {
5428 transpose_offset = display_map
5429 .buffer_snapshot
5430 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5431 }
5432
5433 if transpose_offset == 0 {
5434 return;
5435 }
5436
5437 *head.column_mut() += 1;
5438 head = display_map.clip_point(head, Bias::Right);
5439 let goal = SelectionGoal::HorizontalPosition(
5440 display_map
5441 .x_for_display_point(head, &text_layout_details)
5442 .into(),
5443 );
5444 selection.collapse_to(head, goal);
5445
5446 let transpose_start = display_map
5447 .buffer_snapshot
5448 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5449 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
5450 let transpose_end = display_map
5451 .buffer_snapshot
5452 .clip_offset(transpose_offset + 1, Bias::Right);
5453 if let Some(ch) =
5454 display_map.buffer_snapshot.chars_at(transpose_start).next()
5455 {
5456 edits.push((transpose_start..transpose_offset, String::new()));
5457 edits.push((transpose_end..transpose_end, ch.to_string()));
5458 }
5459 }
5460 });
5461 edits
5462 });
5463 this.buffer
5464 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
5465 let selections = this.selections.all::<usize>(cx);
5466 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5467 s.select(selections);
5468 });
5469 });
5470 }
5471
5472 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
5473 let mut text = String::new();
5474 let buffer = self.buffer.read(cx).snapshot(cx);
5475 let mut selections = self.selections.all::<Point>(cx);
5476 let mut clipboard_selections = Vec::with_capacity(selections.len());
5477 {
5478 let max_point = buffer.max_point();
5479 let mut is_first = true;
5480 for selection in &mut selections {
5481 let is_entire_line = selection.is_empty() || self.selections.line_mode;
5482 if is_entire_line {
5483 selection.start = Point::new(selection.start.row, 0);
5484 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
5485 selection.goal = SelectionGoal::None;
5486 }
5487 if is_first {
5488 is_first = false;
5489 } else {
5490 text += "\n";
5491 }
5492 let mut len = 0;
5493 for chunk in buffer.text_for_range(selection.start..selection.end) {
5494 text.push_str(chunk);
5495 len += chunk.len();
5496 }
5497 clipboard_selections.push(ClipboardSelection {
5498 len,
5499 is_entire_line,
5500 first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
5501 });
5502 }
5503 }
5504
5505 self.transact(cx, |this, cx| {
5506 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5507 s.select(selections);
5508 });
5509 this.insert("", cx);
5510 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5511 });
5512 }
5513
5514 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
5515 let selections = self.selections.all::<Point>(cx);
5516 let buffer = self.buffer.read(cx).read(cx);
5517 let mut text = String::new();
5518
5519 let mut clipboard_selections = Vec::with_capacity(selections.len());
5520 {
5521 let max_point = buffer.max_point();
5522 let mut is_first = true;
5523 for selection in selections.iter() {
5524 let mut start = selection.start;
5525 let mut end = selection.end;
5526 let is_entire_line = selection.is_empty() || self.selections.line_mode;
5527 if is_entire_line {
5528 start = Point::new(start.row, 0);
5529 end = cmp::min(max_point, Point::new(end.row + 1, 0));
5530 }
5531 if is_first {
5532 is_first = false;
5533 } else {
5534 text += "\n";
5535 }
5536 let mut len = 0;
5537 for chunk in buffer.text_for_range(start..end) {
5538 text.push_str(chunk);
5539 len += chunk.len();
5540 }
5541 clipboard_selections.push(ClipboardSelection {
5542 len,
5543 is_entire_line,
5544 first_line_indent: buffer.indent_size_for_line(start.row).len,
5545 });
5546 }
5547 }
5548
5549 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5550 }
5551
5552 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
5553 if self.read_only(cx) {
5554 return;
5555 }
5556
5557 self.transact(cx, |this, cx| {
5558 if let Some(item) = cx.read_from_clipboard() {
5559 let clipboard_text = Cow::Borrowed(item.text());
5560 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
5561 let old_selections = this.selections.all::<usize>(cx);
5562 let all_selections_were_entire_line =
5563 clipboard_selections.iter().all(|s| s.is_entire_line);
5564 let first_selection_indent_column =
5565 clipboard_selections.first().map(|s| s.first_line_indent);
5566 if clipboard_selections.len() != old_selections.len() {
5567 clipboard_selections.drain(..);
5568 }
5569
5570 this.buffer.update(cx, |buffer, cx| {
5571 let snapshot = buffer.read(cx);
5572 let mut start_offset = 0;
5573 let mut edits = Vec::new();
5574 let mut original_indent_columns = Vec::new();
5575 let line_mode = this.selections.line_mode;
5576 for (ix, selection) in old_selections.iter().enumerate() {
5577 let to_insert;
5578 let entire_line;
5579 let original_indent_column;
5580 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
5581 let end_offset = start_offset + clipboard_selection.len;
5582 to_insert = &clipboard_text[start_offset..end_offset];
5583 entire_line = clipboard_selection.is_entire_line;
5584 start_offset = end_offset + 1;
5585 original_indent_column =
5586 Some(clipboard_selection.first_line_indent);
5587 } else {
5588 to_insert = clipboard_text.as_str();
5589 entire_line = all_selections_were_entire_line;
5590 original_indent_column = first_selection_indent_column
5591 }
5592
5593 // If the corresponding selection was empty when this slice of the
5594 // clipboard text was written, then the entire line containing the
5595 // selection was copied. If this selection is also currently empty,
5596 // then paste the line before the current line of the buffer.
5597 let range = if selection.is_empty() && !line_mode && entire_line {
5598 let column = selection.start.to_point(&snapshot).column as usize;
5599 let line_start = selection.start - column;
5600 line_start..line_start
5601 } else {
5602 selection.range()
5603 };
5604
5605 edits.push((range, to_insert));
5606 original_indent_columns.extend(original_indent_column);
5607 }
5608 drop(snapshot);
5609
5610 buffer.edit(
5611 edits,
5612 Some(AutoindentMode::Block {
5613 original_indent_columns,
5614 }),
5615 cx,
5616 );
5617 });
5618
5619 let selections = this.selections.all::<usize>(cx);
5620 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5621 } else {
5622 this.insert(&clipboard_text, cx);
5623 }
5624 }
5625 });
5626 }
5627
5628 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
5629 if self.read_only(cx) {
5630 return;
5631 }
5632
5633 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
5634 if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
5635 self.change_selections(None, cx, |s| {
5636 s.select_anchors(selections.to_vec());
5637 });
5638 }
5639 self.request_autoscroll(Autoscroll::fit(), cx);
5640 self.unmark_text(cx);
5641 self.refresh_inline_completion(true, cx);
5642 cx.emit(EditorEvent::Edited);
5643 cx.emit(EditorEvent::TransactionUndone {
5644 transaction_id: tx_id,
5645 });
5646 }
5647 }
5648
5649 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
5650 if self.read_only(cx) {
5651 return;
5652 }
5653
5654 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
5655 if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
5656 {
5657 self.change_selections(None, cx, |s| {
5658 s.select_anchors(selections.to_vec());
5659 });
5660 }
5661 self.request_autoscroll(Autoscroll::fit(), cx);
5662 self.unmark_text(cx);
5663 self.refresh_inline_completion(true, cx);
5664 cx.emit(EditorEvent::Edited);
5665 }
5666 }
5667
5668 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
5669 self.buffer
5670 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
5671 }
5672
5673 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
5674 self.buffer
5675 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
5676 }
5677
5678 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
5679 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5680 let line_mode = s.line_mode;
5681 s.move_with(|map, selection| {
5682 let cursor = if selection.is_empty() && !line_mode {
5683 movement::left(map, selection.start)
5684 } else {
5685 selection.start
5686 };
5687 selection.collapse_to(cursor, SelectionGoal::None);
5688 });
5689 })
5690 }
5691
5692 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
5693 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5694 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
5695 })
5696 }
5697
5698 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
5699 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5700 let line_mode = s.line_mode;
5701 s.move_with(|map, selection| {
5702 let cursor = if selection.is_empty() && !line_mode {
5703 movement::right(map, selection.end)
5704 } else {
5705 selection.end
5706 };
5707 selection.collapse_to(cursor, SelectionGoal::None)
5708 });
5709 })
5710 }
5711
5712 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
5713 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5714 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
5715 })
5716 }
5717
5718 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
5719 if self.take_rename(true, cx).is_some() {
5720 return;
5721 }
5722
5723 if matches!(self.mode, EditorMode::SingleLine) {
5724 cx.propagate();
5725 return;
5726 }
5727
5728 let text_layout_details = &self.text_layout_details(cx);
5729
5730 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5731 let line_mode = s.line_mode;
5732 s.move_with(|map, selection| {
5733 if !selection.is_empty() && !line_mode {
5734 selection.goal = SelectionGoal::None;
5735 }
5736 let (cursor, goal) = movement::up(
5737 map,
5738 selection.start,
5739 selection.goal,
5740 false,
5741 &text_layout_details,
5742 );
5743 selection.collapse_to(cursor, goal);
5744 });
5745 })
5746 }
5747
5748 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
5749 if self.take_rename(true, cx).is_some() {
5750 return;
5751 }
5752
5753 if matches!(self.mode, EditorMode::SingleLine) {
5754 cx.propagate();
5755 return;
5756 }
5757
5758 let text_layout_details = &self.text_layout_details(cx);
5759
5760 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5761 let line_mode = s.line_mode;
5762 s.move_with(|map, selection| {
5763 if !selection.is_empty() && !line_mode {
5764 selection.goal = SelectionGoal::None;
5765 }
5766 let (cursor, goal) = movement::up_by_rows(
5767 map,
5768 selection.start,
5769 action.lines,
5770 selection.goal,
5771 false,
5772 &text_layout_details,
5773 );
5774 selection.collapse_to(cursor, goal);
5775 });
5776 })
5777 }
5778
5779 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
5780 if self.take_rename(true, cx).is_some() {
5781 return;
5782 }
5783
5784 if matches!(self.mode, EditorMode::SingleLine) {
5785 cx.propagate();
5786 return;
5787 }
5788
5789 let text_layout_details = &self.text_layout_details(cx);
5790
5791 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5792 let line_mode = s.line_mode;
5793 s.move_with(|map, selection| {
5794 if !selection.is_empty() && !line_mode {
5795 selection.goal = SelectionGoal::None;
5796 }
5797 let (cursor, goal) = movement::down_by_rows(
5798 map,
5799 selection.start,
5800 action.lines,
5801 selection.goal,
5802 false,
5803 &text_layout_details,
5804 );
5805 selection.collapse_to(cursor, goal);
5806 });
5807 })
5808 }
5809
5810 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
5811 let text_layout_details = &self.text_layout_details(cx);
5812 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5813 s.move_heads_with(|map, head, goal| {
5814 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
5815 })
5816 })
5817 }
5818
5819 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
5820 let text_layout_details = &self.text_layout_details(cx);
5821 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5822 s.move_heads_with(|map, head, goal| {
5823 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
5824 })
5825 })
5826 }
5827
5828 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
5829 if self.take_rename(true, cx).is_some() {
5830 return;
5831 }
5832
5833 if matches!(self.mode, EditorMode::SingleLine) {
5834 cx.propagate();
5835 return;
5836 }
5837
5838 let row_count = if let Some(row_count) = self.visible_line_count() {
5839 row_count as u32 - 1
5840 } else {
5841 return;
5842 };
5843
5844 let autoscroll = if action.center_cursor {
5845 Autoscroll::center()
5846 } else {
5847 Autoscroll::fit()
5848 };
5849
5850 let text_layout_details = &self.text_layout_details(cx);
5851
5852 self.change_selections(Some(autoscroll), cx, |s| {
5853 let line_mode = s.line_mode;
5854 s.move_with(|map, selection| {
5855 if !selection.is_empty() && !line_mode {
5856 selection.goal = SelectionGoal::None;
5857 }
5858 let (cursor, goal) = movement::up_by_rows(
5859 map,
5860 selection.end,
5861 row_count,
5862 selection.goal,
5863 false,
5864 &text_layout_details,
5865 );
5866 selection.collapse_to(cursor, goal);
5867 });
5868 });
5869 }
5870
5871 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
5872 let text_layout_details = &self.text_layout_details(cx);
5873 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5874 s.move_heads_with(|map, head, goal| {
5875 movement::up(map, head, goal, false, &text_layout_details)
5876 })
5877 })
5878 }
5879
5880 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
5881 self.take_rename(true, cx);
5882
5883 if self.mode == EditorMode::SingleLine {
5884 cx.propagate();
5885 return;
5886 }
5887
5888 let text_layout_details = &self.text_layout_details(cx);
5889 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5890 let line_mode = s.line_mode;
5891 s.move_with(|map, selection| {
5892 if !selection.is_empty() && !line_mode {
5893 selection.goal = SelectionGoal::None;
5894 }
5895 let (cursor, goal) = movement::down(
5896 map,
5897 selection.end,
5898 selection.goal,
5899 false,
5900 &text_layout_details,
5901 );
5902 selection.collapse_to(cursor, goal);
5903 });
5904 });
5905 }
5906
5907 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
5908 if self.take_rename(true, cx).is_some() {
5909 return;
5910 }
5911
5912 if self
5913 .context_menu
5914 .write()
5915 .as_mut()
5916 .map(|menu| menu.select_last(self.project.as_ref(), cx))
5917 .unwrap_or(false)
5918 {
5919 return;
5920 }
5921
5922 if matches!(self.mode, EditorMode::SingleLine) {
5923 cx.propagate();
5924 return;
5925 }
5926
5927 let row_count = if let Some(row_count) = self.visible_line_count() {
5928 row_count as u32 - 1
5929 } else {
5930 return;
5931 };
5932
5933 let autoscroll = if action.center_cursor {
5934 Autoscroll::center()
5935 } else {
5936 Autoscroll::fit()
5937 };
5938
5939 let text_layout_details = &self.text_layout_details(cx);
5940 self.change_selections(Some(autoscroll), cx, |s| {
5941 let line_mode = s.line_mode;
5942 s.move_with(|map, selection| {
5943 if !selection.is_empty() && !line_mode {
5944 selection.goal = SelectionGoal::None;
5945 }
5946 let (cursor, goal) = movement::down_by_rows(
5947 map,
5948 selection.end,
5949 row_count,
5950 selection.goal,
5951 false,
5952 &text_layout_details,
5953 );
5954 selection.collapse_to(cursor, goal);
5955 });
5956 });
5957 }
5958
5959 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
5960 let text_layout_details = &self.text_layout_details(cx);
5961 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5962 s.move_heads_with(|map, head, goal| {
5963 movement::down(map, head, goal, false, &text_layout_details)
5964 })
5965 });
5966 }
5967
5968 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
5969 if let Some(context_menu) = self.context_menu.write().as_mut() {
5970 context_menu.select_first(self.project.as_ref(), cx);
5971 }
5972 }
5973
5974 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
5975 if let Some(context_menu) = self.context_menu.write().as_mut() {
5976 context_menu.select_prev(self.project.as_ref(), cx);
5977 }
5978 }
5979
5980 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
5981 if let Some(context_menu) = self.context_menu.write().as_mut() {
5982 context_menu.select_next(self.project.as_ref(), cx);
5983 }
5984 }
5985
5986 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
5987 if let Some(context_menu) = self.context_menu.write().as_mut() {
5988 context_menu.select_last(self.project.as_ref(), cx);
5989 }
5990 }
5991
5992 pub fn move_to_previous_word_start(
5993 &mut self,
5994 _: &MoveToPreviousWordStart,
5995 cx: &mut ViewContext<Self>,
5996 ) {
5997 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5998 s.move_cursors_with(|map, head, _| {
5999 (
6000 movement::previous_word_start(map, head),
6001 SelectionGoal::None,
6002 )
6003 });
6004 })
6005 }
6006
6007 pub fn move_to_previous_subword_start(
6008 &mut self,
6009 _: &MoveToPreviousSubwordStart,
6010 cx: &mut ViewContext<Self>,
6011 ) {
6012 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6013 s.move_cursors_with(|map, head, _| {
6014 (
6015 movement::previous_subword_start(map, head),
6016 SelectionGoal::None,
6017 )
6018 });
6019 })
6020 }
6021
6022 pub fn select_to_previous_word_start(
6023 &mut self,
6024 _: &SelectToPreviousWordStart,
6025 cx: &mut ViewContext<Self>,
6026 ) {
6027 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6028 s.move_heads_with(|map, head, _| {
6029 (
6030 movement::previous_word_start(map, head),
6031 SelectionGoal::None,
6032 )
6033 });
6034 })
6035 }
6036
6037 pub fn select_to_previous_subword_start(
6038 &mut self,
6039 _: &SelectToPreviousSubwordStart,
6040 cx: &mut ViewContext<Self>,
6041 ) {
6042 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6043 s.move_heads_with(|map, head, _| {
6044 (
6045 movement::previous_subword_start(map, head),
6046 SelectionGoal::None,
6047 )
6048 });
6049 })
6050 }
6051
6052 pub fn delete_to_previous_word_start(
6053 &mut self,
6054 _: &DeleteToPreviousWordStart,
6055 cx: &mut ViewContext<Self>,
6056 ) {
6057 self.transact(cx, |this, cx| {
6058 this.select_autoclose_pair(cx);
6059 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6060 let line_mode = s.line_mode;
6061 s.move_with(|map, selection| {
6062 if selection.is_empty() && !line_mode {
6063 let cursor = movement::previous_word_start(map, selection.head());
6064 selection.set_head(cursor, SelectionGoal::None);
6065 }
6066 });
6067 });
6068 this.insert("", cx);
6069 });
6070 }
6071
6072 pub fn delete_to_previous_subword_start(
6073 &mut self,
6074 _: &DeleteToPreviousSubwordStart,
6075 cx: &mut ViewContext<Self>,
6076 ) {
6077 self.transact(cx, |this, cx| {
6078 this.select_autoclose_pair(cx);
6079 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6080 let line_mode = s.line_mode;
6081 s.move_with(|map, selection| {
6082 if selection.is_empty() && !line_mode {
6083 let cursor = movement::previous_subword_start(map, selection.head());
6084 selection.set_head(cursor, SelectionGoal::None);
6085 }
6086 });
6087 });
6088 this.insert("", cx);
6089 });
6090 }
6091
6092 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
6093 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6094 s.move_cursors_with(|map, head, _| {
6095 (movement::next_word_end(map, head), SelectionGoal::None)
6096 });
6097 })
6098 }
6099
6100 pub fn move_to_next_subword_end(
6101 &mut self,
6102 _: &MoveToNextSubwordEnd,
6103 cx: &mut ViewContext<Self>,
6104 ) {
6105 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6106 s.move_cursors_with(|map, head, _| {
6107 (movement::next_subword_end(map, head), SelectionGoal::None)
6108 });
6109 })
6110 }
6111
6112 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
6113 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6114 s.move_heads_with(|map, head, _| {
6115 (movement::next_word_end(map, head), SelectionGoal::None)
6116 });
6117 })
6118 }
6119
6120 pub fn select_to_next_subword_end(
6121 &mut self,
6122 _: &SelectToNextSubwordEnd,
6123 cx: &mut ViewContext<Self>,
6124 ) {
6125 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6126 s.move_heads_with(|map, head, _| {
6127 (movement::next_subword_end(map, head), SelectionGoal::None)
6128 });
6129 })
6130 }
6131
6132 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
6133 self.transact(cx, |this, cx| {
6134 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6135 let line_mode = s.line_mode;
6136 s.move_with(|map, selection| {
6137 if selection.is_empty() && !line_mode {
6138 let cursor = movement::next_word_end(map, selection.head());
6139 selection.set_head(cursor, SelectionGoal::None);
6140 }
6141 });
6142 });
6143 this.insert("", cx);
6144 });
6145 }
6146
6147 pub fn delete_to_next_subword_end(
6148 &mut self,
6149 _: &DeleteToNextSubwordEnd,
6150 cx: &mut ViewContext<Self>,
6151 ) {
6152 self.transact(cx, |this, cx| {
6153 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6154 s.move_with(|map, selection| {
6155 if selection.is_empty() {
6156 let cursor = movement::next_subword_end(map, selection.head());
6157 selection.set_head(cursor, SelectionGoal::None);
6158 }
6159 });
6160 });
6161 this.insert("", cx);
6162 });
6163 }
6164
6165 pub fn move_to_beginning_of_line(
6166 &mut self,
6167 _: &MoveToBeginningOfLine,
6168 cx: &mut ViewContext<Self>,
6169 ) {
6170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6171 s.move_cursors_with(|map, head, _| {
6172 (
6173 movement::indented_line_beginning(map, head, true),
6174 SelectionGoal::None,
6175 )
6176 });
6177 })
6178 }
6179
6180 pub fn select_to_beginning_of_line(
6181 &mut self,
6182 action: &SelectToBeginningOfLine,
6183 cx: &mut ViewContext<Self>,
6184 ) {
6185 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6186 s.move_heads_with(|map, head, _| {
6187 (
6188 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6189 SelectionGoal::None,
6190 )
6191 });
6192 });
6193 }
6194
6195 pub fn delete_to_beginning_of_line(
6196 &mut self,
6197 _: &DeleteToBeginningOfLine,
6198 cx: &mut ViewContext<Self>,
6199 ) {
6200 self.transact(cx, |this, cx| {
6201 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6202 s.move_with(|_, selection| {
6203 selection.reversed = true;
6204 });
6205 });
6206
6207 this.select_to_beginning_of_line(
6208 &SelectToBeginningOfLine {
6209 stop_at_soft_wraps: false,
6210 },
6211 cx,
6212 );
6213 this.backspace(&Backspace, cx);
6214 });
6215 }
6216
6217 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
6218 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6219 s.move_cursors_with(|map, head, _| {
6220 (movement::line_end(map, head, true), SelectionGoal::None)
6221 });
6222 })
6223 }
6224
6225 pub fn select_to_end_of_line(
6226 &mut self,
6227 action: &SelectToEndOfLine,
6228 cx: &mut ViewContext<Self>,
6229 ) {
6230 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6231 s.move_heads_with(|map, head, _| {
6232 (
6233 movement::line_end(map, head, action.stop_at_soft_wraps),
6234 SelectionGoal::None,
6235 )
6236 });
6237 })
6238 }
6239
6240 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
6241 self.transact(cx, |this, cx| {
6242 this.select_to_end_of_line(
6243 &SelectToEndOfLine {
6244 stop_at_soft_wraps: false,
6245 },
6246 cx,
6247 );
6248 this.delete(&Delete, cx);
6249 });
6250 }
6251
6252 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
6253 self.transact(cx, |this, cx| {
6254 this.select_to_end_of_line(
6255 &SelectToEndOfLine {
6256 stop_at_soft_wraps: false,
6257 },
6258 cx,
6259 );
6260 this.cut(&Cut, cx);
6261 });
6262 }
6263
6264 pub fn move_to_start_of_paragraph(
6265 &mut self,
6266 _: &MoveToStartOfParagraph,
6267 cx: &mut ViewContext<Self>,
6268 ) {
6269 if matches!(self.mode, EditorMode::SingleLine) {
6270 cx.propagate();
6271 return;
6272 }
6273
6274 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6275 s.move_with(|map, selection| {
6276 selection.collapse_to(
6277 movement::start_of_paragraph(map, selection.head(), 1),
6278 SelectionGoal::None,
6279 )
6280 });
6281 })
6282 }
6283
6284 pub fn move_to_end_of_paragraph(
6285 &mut self,
6286 _: &MoveToEndOfParagraph,
6287 cx: &mut ViewContext<Self>,
6288 ) {
6289 if matches!(self.mode, EditorMode::SingleLine) {
6290 cx.propagate();
6291 return;
6292 }
6293
6294 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6295 s.move_with(|map, selection| {
6296 selection.collapse_to(
6297 movement::end_of_paragraph(map, selection.head(), 1),
6298 SelectionGoal::None,
6299 )
6300 });
6301 })
6302 }
6303
6304 pub fn select_to_start_of_paragraph(
6305 &mut self,
6306 _: &SelectToStartOfParagraph,
6307 cx: &mut ViewContext<Self>,
6308 ) {
6309 if matches!(self.mode, EditorMode::SingleLine) {
6310 cx.propagate();
6311 return;
6312 }
6313
6314 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6315 s.move_heads_with(|map, head, _| {
6316 (
6317 movement::start_of_paragraph(map, head, 1),
6318 SelectionGoal::None,
6319 )
6320 });
6321 })
6322 }
6323
6324 pub fn select_to_end_of_paragraph(
6325 &mut self,
6326 _: &SelectToEndOfParagraph,
6327 cx: &mut ViewContext<Self>,
6328 ) {
6329 if matches!(self.mode, EditorMode::SingleLine) {
6330 cx.propagate();
6331 return;
6332 }
6333
6334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6335 s.move_heads_with(|map, head, _| {
6336 (
6337 movement::end_of_paragraph(map, head, 1),
6338 SelectionGoal::None,
6339 )
6340 });
6341 })
6342 }
6343
6344 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
6345 if matches!(self.mode, EditorMode::SingleLine) {
6346 cx.propagate();
6347 return;
6348 }
6349
6350 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6351 s.select_ranges(vec![0..0]);
6352 });
6353 }
6354
6355 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
6356 let mut selection = self.selections.last::<Point>(cx);
6357 selection.set_head(Point::zero(), SelectionGoal::None);
6358
6359 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6360 s.select(vec![selection]);
6361 });
6362 }
6363
6364 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
6365 if matches!(self.mode, EditorMode::SingleLine) {
6366 cx.propagate();
6367 return;
6368 }
6369
6370 let cursor = self.buffer.read(cx).read(cx).len();
6371 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6372 s.select_ranges(vec![cursor..cursor])
6373 });
6374 }
6375
6376 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
6377 self.nav_history = nav_history;
6378 }
6379
6380 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
6381 self.nav_history.as_ref()
6382 }
6383
6384 fn push_to_nav_history(
6385 &mut self,
6386 cursor_anchor: Anchor,
6387 new_position: Option<Point>,
6388 cx: &mut ViewContext<Self>,
6389 ) {
6390 if let Some(nav_history) = self.nav_history.as_mut() {
6391 let buffer = self.buffer.read(cx).read(cx);
6392 let cursor_position = cursor_anchor.to_point(&buffer);
6393 let scroll_state = self.scroll_manager.anchor();
6394 let scroll_top_row = scroll_state.top_row(&buffer);
6395 drop(buffer);
6396
6397 if let Some(new_position) = new_position {
6398 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
6399 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
6400 return;
6401 }
6402 }
6403
6404 nav_history.push(
6405 Some(NavigationData {
6406 cursor_anchor,
6407 cursor_position,
6408 scroll_anchor: scroll_state,
6409 scroll_top_row,
6410 }),
6411 cx,
6412 );
6413 }
6414 }
6415
6416 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
6417 let buffer = self.buffer.read(cx).snapshot(cx);
6418 let mut selection = self.selections.first::<usize>(cx);
6419 selection.set_head(buffer.len(), SelectionGoal::None);
6420 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6421 s.select(vec![selection]);
6422 });
6423 }
6424
6425 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
6426 let end = self.buffer.read(cx).read(cx).len();
6427 self.change_selections(None, cx, |s| {
6428 s.select_ranges(vec![0..end]);
6429 });
6430 }
6431
6432 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
6433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6434 let mut selections = self.selections.all::<Point>(cx);
6435 let max_point = display_map.buffer_snapshot.max_point();
6436 for selection in &mut selections {
6437 let rows = selection.spanned_rows(true, &display_map);
6438 selection.start = Point::new(rows.start, 0);
6439 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
6440 selection.reversed = false;
6441 }
6442 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6443 s.select(selections);
6444 });
6445 }
6446
6447 pub fn split_selection_into_lines(
6448 &mut self,
6449 _: &SplitSelectionIntoLines,
6450 cx: &mut ViewContext<Self>,
6451 ) {
6452 let mut to_unfold = Vec::new();
6453 let mut new_selection_ranges = Vec::new();
6454 {
6455 let selections = self.selections.all::<Point>(cx);
6456 let buffer = self.buffer.read(cx).read(cx);
6457 for selection in selections {
6458 for row in selection.start.row..selection.end.row {
6459 let cursor = Point::new(row, buffer.line_len(row));
6460 new_selection_ranges.push(cursor..cursor);
6461 }
6462 new_selection_ranges.push(selection.end..selection.end);
6463 to_unfold.push(selection.start..selection.end);
6464 }
6465 }
6466 self.unfold_ranges(to_unfold, true, true, cx);
6467 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6468 s.select_ranges(new_selection_ranges);
6469 });
6470 }
6471
6472 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
6473 self.add_selection(true, cx);
6474 }
6475
6476 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
6477 self.add_selection(false, cx);
6478 }
6479
6480 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
6481 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6482 let mut selections = self.selections.all::<Point>(cx);
6483 let text_layout_details = self.text_layout_details(cx);
6484 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
6485 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
6486 let range = oldest_selection.display_range(&display_map).sorted();
6487
6488 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
6489 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
6490 let positions = start_x.min(end_x)..start_x.max(end_x);
6491
6492 selections.clear();
6493 let mut stack = Vec::new();
6494 for row in range.start.row()..=range.end.row() {
6495 if let Some(selection) = self.selections.build_columnar_selection(
6496 &display_map,
6497 row,
6498 &positions,
6499 oldest_selection.reversed,
6500 &text_layout_details,
6501 ) {
6502 stack.push(selection.id);
6503 selections.push(selection);
6504 }
6505 }
6506
6507 if above {
6508 stack.reverse();
6509 }
6510
6511 AddSelectionsState { above, stack }
6512 });
6513
6514 let last_added_selection = *state.stack.last().unwrap();
6515 let mut new_selections = Vec::new();
6516 if above == state.above {
6517 let end_row = if above {
6518 0
6519 } else {
6520 display_map.max_point().row()
6521 };
6522
6523 'outer: for selection in selections {
6524 if selection.id == last_added_selection {
6525 let range = selection.display_range(&display_map).sorted();
6526 debug_assert_eq!(range.start.row(), range.end.row());
6527 let mut row = range.start.row();
6528 let positions =
6529 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
6530 px(start)..px(end)
6531 } else {
6532 let start_x =
6533 display_map.x_for_display_point(range.start, &text_layout_details);
6534 let end_x =
6535 display_map.x_for_display_point(range.end, &text_layout_details);
6536 start_x.min(end_x)..start_x.max(end_x)
6537 };
6538
6539 while row != end_row {
6540 if above {
6541 row -= 1;
6542 } else {
6543 row += 1;
6544 }
6545
6546 if let Some(new_selection) = self.selections.build_columnar_selection(
6547 &display_map,
6548 row,
6549 &positions,
6550 selection.reversed,
6551 &text_layout_details,
6552 ) {
6553 state.stack.push(new_selection.id);
6554 if above {
6555 new_selections.push(new_selection);
6556 new_selections.push(selection);
6557 } else {
6558 new_selections.push(selection);
6559 new_selections.push(new_selection);
6560 }
6561
6562 continue 'outer;
6563 }
6564 }
6565 }
6566
6567 new_selections.push(selection);
6568 }
6569 } else {
6570 new_selections = selections;
6571 new_selections.retain(|s| s.id != last_added_selection);
6572 state.stack.pop();
6573 }
6574
6575 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6576 s.select(new_selections);
6577 });
6578 if state.stack.len() > 1 {
6579 self.add_selections_state = Some(state);
6580 }
6581 }
6582
6583 pub fn select_next_match_internal(
6584 &mut self,
6585 display_map: &DisplaySnapshot,
6586 replace_newest: bool,
6587 autoscroll: Option<Autoscroll>,
6588 cx: &mut ViewContext<Self>,
6589 ) -> Result<()> {
6590 fn select_next_match_ranges(
6591 this: &mut Editor,
6592 range: Range<usize>,
6593 replace_newest: bool,
6594 auto_scroll: Option<Autoscroll>,
6595 cx: &mut ViewContext<Editor>,
6596 ) {
6597 this.unfold_ranges([range.clone()], false, true, cx);
6598 this.change_selections(auto_scroll, cx, |s| {
6599 if replace_newest {
6600 s.delete(s.newest_anchor().id);
6601 }
6602 s.insert_range(range.clone());
6603 });
6604 }
6605
6606 let buffer = &display_map.buffer_snapshot;
6607 let mut selections = self.selections.all::<usize>(cx);
6608 if let Some(mut select_next_state) = self.select_next_state.take() {
6609 let query = &select_next_state.query;
6610 if !select_next_state.done {
6611 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6612 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6613 let mut next_selected_range = None;
6614
6615 let bytes_after_last_selection =
6616 buffer.bytes_in_range(last_selection.end..buffer.len());
6617 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
6618 let query_matches = query
6619 .stream_find_iter(bytes_after_last_selection)
6620 .map(|result| (last_selection.end, result))
6621 .chain(
6622 query
6623 .stream_find_iter(bytes_before_first_selection)
6624 .map(|result| (0, result)),
6625 );
6626
6627 for (start_offset, query_match) in query_matches {
6628 let query_match = query_match.unwrap(); // can only fail due to I/O
6629 let offset_range =
6630 start_offset + query_match.start()..start_offset + query_match.end();
6631 let display_range = offset_range.start.to_display_point(&display_map)
6632 ..offset_range.end.to_display_point(&display_map);
6633
6634 if !select_next_state.wordwise
6635 || (!movement::is_inside_word(&display_map, display_range.start)
6636 && !movement::is_inside_word(&display_map, display_range.end))
6637 {
6638 // TODO: This is n^2, because we might check all the selections
6639 if !selections
6640 .iter()
6641 .any(|selection| selection.range().overlaps(&offset_range))
6642 {
6643 next_selected_range = Some(offset_range);
6644 break;
6645 }
6646 }
6647 }
6648
6649 if let Some(next_selected_range) = next_selected_range {
6650 select_next_match_ranges(
6651 self,
6652 next_selected_range,
6653 replace_newest,
6654 autoscroll,
6655 cx,
6656 );
6657 } else {
6658 select_next_state.done = true;
6659 }
6660 }
6661
6662 self.select_next_state = Some(select_next_state);
6663 } else {
6664 let mut only_carets = true;
6665 let mut same_text_selected = true;
6666 let mut selected_text = None;
6667
6668 let mut selections_iter = selections.iter().peekable();
6669 while let Some(selection) = selections_iter.next() {
6670 if selection.start != selection.end {
6671 only_carets = false;
6672 }
6673
6674 if same_text_selected {
6675 if selected_text.is_none() {
6676 selected_text =
6677 Some(buffer.text_for_range(selection.range()).collect::<String>());
6678 }
6679
6680 if let Some(next_selection) = selections_iter.peek() {
6681 if next_selection.range().len() == selection.range().len() {
6682 let next_selected_text = buffer
6683 .text_for_range(next_selection.range())
6684 .collect::<String>();
6685 if Some(next_selected_text) != selected_text {
6686 same_text_selected = false;
6687 selected_text = None;
6688 }
6689 } else {
6690 same_text_selected = false;
6691 selected_text = None;
6692 }
6693 }
6694 }
6695 }
6696
6697 if only_carets {
6698 for selection in &mut selections {
6699 let word_range = movement::surrounding_word(
6700 &display_map,
6701 selection.start.to_display_point(&display_map),
6702 );
6703 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6704 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6705 selection.goal = SelectionGoal::None;
6706 selection.reversed = false;
6707 select_next_match_ranges(
6708 self,
6709 selection.start..selection.end,
6710 replace_newest,
6711 autoscroll,
6712 cx,
6713 );
6714 }
6715
6716 if selections.len() == 1 {
6717 let selection = selections
6718 .last()
6719 .expect("ensured that there's only one selection");
6720 let query = buffer
6721 .text_for_range(selection.start..selection.end)
6722 .collect::<String>();
6723 let is_empty = query.is_empty();
6724 let select_state = SelectNextState {
6725 query: AhoCorasick::new(&[query])?,
6726 wordwise: true,
6727 done: is_empty,
6728 };
6729 self.select_next_state = Some(select_state);
6730 } else {
6731 self.select_next_state = None;
6732 }
6733 } else if let Some(selected_text) = selected_text {
6734 self.select_next_state = Some(SelectNextState {
6735 query: AhoCorasick::new(&[selected_text])?,
6736 wordwise: false,
6737 done: false,
6738 });
6739 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
6740 }
6741 }
6742 Ok(())
6743 }
6744
6745 pub fn select_all_matches(
6746 &mut self,
6747 _action: &SelectAllMatches,
6748 cx: &mut ViewContext<Self>,
6749 ) -> Result<()> {
6750 self.push_to_selection_history();
6751 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6752
6753 self.select_next_match_internal(&display_map, false, None, cx)?;
6754 let Some(select_next_state) = self.select_next_state.as_mut() else {
6755 return Ok(());
6756 };
6757 if select_next_state.done {
6758 return Ok(());
6759 }
6760
6761 let mut new_selections = self.selections.all::<usize>(cx);
6762
6763 let buffer = &display_map.buffer_snapshot;
6764 let query_matches = select_next_state
6765 .query
6766 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
6767
6768 for query_match in query_matches {
6769 let query_match = query_match.unwrap(); // can only fail due to I/O
6770 let offset_range = query_match.start()..query_match.end();
6771 let display_range = offset_range.start.to_display_point(&display_map)
6772 ..offset_range.end.to_display_point(&display_map);
6773
6774 if !select_next_state.wordwise
6775 || (!movement::is_inside_word(&display_map, display_range.start)
6776 && !movement::is_inside_word(&display_map, display_range.end))
6777 {
6778 self.selections.change_with(cx, |selections| {
6779 new_selections.push(Selection {
6780 id: selections.new_selection_id(),
6781 start: offset_range.start,
6782 end: offset_range.end,
6783 reversed: false,
6784 goal: SelectionGoal::None,
6785 });
6786 });
6787 }
6788 }
6789
6790 new_selections.sort_by_key(|selection| selection.start);
6791 let mut ix = 0;
6792 while ix + 1 < new_selections.len() {
6793 let current_selection = &new_selections[ix];
6794 let next_selection = &new_selections[ix + 1];
6795 if current_selection.range().overlaps(&next_selection.range()) {
6796 if current_selection.id < next_selection.id {
6797 new_selections.remove(ix + 1);
6798 } else {
6799 new_selections.remove(ix);
6800 }
6801 } else {
6802 ix += 1;
6803 }
6804 }
6805
6806 select_next_state.done = true;
6807 self.unfold_ranges(
6808 new_selections.iter().map(|selection| selection.range()),
6809 false,
6810 false,
6811 cx,
6812 );
6813 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
6814 selections.select(new_selections)
6815 });
6816
6817 Ok(())
6818 }
6819
6820 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
6821 self.push_to_selection_history();
6822 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6823 self.select_next_match_internal(
6824 &display_map,
6825 action.replace_newest,
6826 Some(Autoscroll::newest()),
6827 cx,
6828 )?;
6829 Ok(())
6830 }
6831
6832 pub fn select_previous(
6833 &mut self,
6834 action: &SelectPrevious,
6835 cx: &mut ViewContext<Self>,
6836 ) -> Result<()> {
6837 self.push_to_selection_history();
6838 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6839 let buffer = &display_map.buffer_snapshot;
6840 let mut selections = self.selections.all::<usize>(cx);
6841 if let Some(mut select_prev_state) = self.select_prev_state.take() {
6842 let query = &select_prev_state.query;
6843 if !select_prev_state.done {
6844 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6845 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6846 let mut next_selected_range = None;
6847 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
6848 let bytes_before_last_selection =
6849 buffer.reversed_bytes_in_range(0..last_selection.start);
6850 let bytes_after_first_selection =
6851 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
6852 let query_matches = query
6853 .stream_find_iter(bytes_before_last_selection)
6854 .map(|result| (last_selection.start, result))
6855 .chain(
6856 query
6857 .stream_find_iter(bytes_after_first_selection)
6858 .map(|result| (buffer.len(), result)),
6859 );
6860 for (end_offset, query_match) in query_matches {
6861 let query_match = query_match.unwrap(); // can only fail due to I/O
6862 let offset_range =
6863 end_offset - query_match.end()..end_offset - query_match.start();
6864 let display_range = offset_range.start.to_display_point(&display_map)
6865 ..offset_range.end.to_display_point(&display_map);
6866
6867 if !select_prev_state.wordwise
6868 || (!movement::is_inside_word(&display_map, display_range.start)
6869 && !movement::is_inside_word(&display_map, display_range.end))
6870 {
6871 next_selected_range = Some(offset_range);
6872 break;
6873 }
6874 }
6875
6876 if let Some(next_selected_range) = next_selected_range {
6877 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
6878 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6879 if action.replace_newest {
6880 s.delete(s.newest_anchor().id);
6881 }
6882 s.insert_range(next_selected_range);
6883 });
6884 } else {
6885 select_prev_state.done = true;
6886 }
6887 }
6888
6889 self.select_prev_state = Some(select_prev_state);
6890 } else {
6891 let mut only_carets = true;
6892 let mut same_text_selected = true;
6893 let mut selected_text = None;
6894
6895 let mut selections_iter = selections.iter().peekable();
6896 while let Some(selection) = selections_iter.next() {
6897 if selection.start != selection.end {
6898 only_carets = false;
6899 }
6900
6901 if same_text_selected {
6902 if selected_text.is_none() {
6903 selected_text =
6904 Some(buffer.text_for_range(selection.range()).collect::<String>());
6905 }
6906
6907 if let Some(next_selection) = selections_iter.peek() {
6908 if next_selection.range().len() == selection.range().len() {
6909 let next_selected_text = buffer
6910 .text_for_range(next_selection.range())
6911 .collect::<String>();
6912 if Some(next_selected_text) != selected_text {
6913 same_text_selected = false;
6914 selected_text = None;
6915 }
6916 } else {
6917 same_text_selected = false;
6918 selected_text = None;
6919 }
6920 }
6921 }
6922 }
6923
6924 if only_carets {
6925 for selection in &mut selections {
6926 let word_range = movement::surrounding_word(
6927 &display_map,
6928 selection.start.to_display_point(&display_map),
6929 );
6930 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6931 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6932 selection.goal = SelectionGoal::None;
6933 selection.reversed = false;
6934 }
6935 if selections.len() == 1 {
6936 let selection = selections
6937 .last()
6938 .expect("ensured that there's only one selection");
6939 let query = buffer
6940 .text_for_range(selection.start..selection.end)
6941 .collect::<String>();
6942 let is_empty = query.is_empty();
6943 let select_state = SelectNextState {
6944 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
6945 wordwise: true,
6946 done: is_empty,
6947 };
6948 self.select_prev_state = Some(select_state);
6949 } else {
6950 self.select_prev_state = None;
6951 }
6952
6953 self.unfold_ranges(
6954 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
6955 false,
6956 true,
6957 cx,
6958 );
6959 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6960 s.select(selections);
6961 });
6962 } else if let Some(selected_text) = selected_text {
6963 self.select_prev_state = Some(SelectNextState {
6964 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
6965 wordwise: false,
6966 done: false,
6967 });
6968 self.select_previous(action, cx)?;
6969 }
6970 }
6971 Ok(())
6972 }
6973
6974 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
6975 let text_layout_details = &self.text_layout_details(cx);
6976 self.transact(cx, |this, cx| {
6977 let mut selections = this.selections.all::<Point>(cx);
6978 let mut edits = Vec::new();
6979 let mut selection_edit_ranges = Vec::new();
6980 let mut last_toggled_row = None;
6981 let snapshot = this.buffer.read(cx).read(cx);
6982 let empty_str: Arc<str> = "".into();
6983 let mut suffixes_inserted = Vec::new();
6984
6985 fn comment_prefix_range(
6986 snapshot: &MultiBufferSnapshot,
6987 row: u32,
6988 comment_prefix: &str,
6989 comment_prefix_whitespace: &str,
6990 ) -> Range<Point> {
6991 let start = Point::new(row, snapshot.indent_size_for_line(row).len);
6992
6993 let mut line_bytes = snapshot
6994 .bytes_in_range(start..snapshot.max_point())
6995 .flatten()
6996 .copied();
6997
6998 // If this line currently begins with the line comment prefix, then record
6999 // the range containing the prefix.
7000 if line_bytes
7001 .by_ref()
7002 .take(comment_prefix.len())
7003 .eq(comment_prefix.bytes())
7004 {
7005 // Include any whitespace that matches the comment prefix.
7006 let matching_whitespace_len = line_bytes
7007 .zip(comment_prefix_whitespace.bytes())
7008 .take_while(|(a, b)| a == b)
7009 .count() as u32;
7010 let end = Point::new(
7011 start.row,
7012 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
7013 );
7014 start..end
7015 } else {
7016 start..start
7017 }
7018 }
7019
7020 fn comment_suffix_range(
7021 snapshot: &MultiBufferSnapshot,
7022 row: u32,
7023 comment_suffix: &str,
7024 comment_suffix_has_leading_space: bool,
7025 ) -> Range<Point> {
7026 let end = Point::new(row, snapshot.line_len(row));
7027 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
7028
7029 let mut line_end_bytes = snapshot
7030 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
7031 .flatten()
7032 .copied();
7033
7034 let leading_space_len = if suffix_start_column > 0
7035 && line_end_bytes.next() == Some(b' ')
7036 && comment_suffix_has_leading_space
7037 {
7038 1
7039 } else {
7040 0
7041 };
7042
7043 // If this line currently begins with the line comment prefix, then record
7044 // the range containing the prefix.
7045 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
7046 let start = Point::new(end.row, suffix_start_column - leading_space_len);
7047 start..end
7048 } else {
7049 end..end
7050 }
7051 }
7052
7053 // TODO: Handle selections that cross excerpts
7054 for selection in &mut selections {
7055 let start_column = snapshot.indent_size_for_line(selection.start.row).len;
7056 let language = if let Some(language) =
7057 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
7058 {
7059 language
7060 } else {
7061 continue;
7062 };
7063
7064 selection_edit_ranges.clear();
7065
7066 // If multiple selections contain a given row, avoid processing that
7067 // row more than once.
7068 let mut start_row = selection.start.row;
7069 if last_toggled_row == Some(start_row) {
7070 start_row += 1;
7071 }
7072 let end_row =
7073 if selection.end.row > selection.start.row && selection.end.column == 0 {
7074 selection.end.row - 1
7075 } else {
7076 selection.end.row
7077 };
7078 last_toggled_row = Some(end_row);
7079
7080 if start_row > end_row {
7081 continue;
7082 }
7083
7084 // If the language has line comments, toggle those.
7085 if let Some(full_comment_prefixes) = language
7086 .line_comment_prefixes()
7087 .filter(|prefixes| !prefixes.is_empty())
7088 {
7089 let first_prefix = full_comment_prefixes
7090 .first()
7091 .expect("prefixes is non-empty");
7092 let prefix_trimmed_lengths = full_comment_prefixes
7093 .iter()
7094 .map(|p| p.trim_end_matches(' ').len())
7095 .collect::<SmallVec<[usize; 4]>>();
7096
7097 let mut all_selection_lines_are_comments = true;
7098
7099 for row in start_row..=end_row {
7100 if start_row < end_row && snapshot.is_line_blank(row) {
7101 continue;
7102 }
7103
7104 let prefix_range = full_comment_prefixes
7105 .iter()
7106 .zip(prefix_trimmed_lengths.iter().copied())
7107 .map(|(prefix, trimmed_prefix_len)| {
7108 comment_prefix_range(
7109 snapshot.deref(),
7110 row,
7111 &prefix[..trimmed_prefix_len],
7112 &prefix[trimmed_prefix_len..],
7113 )
7114 })
7115 .max_by_key(|range| range.end.column - range.start.column)
7116 .expect("prefixes is non-empty");
7117
7118 if prefix_range.is_empty() {
7119 all_selection_lines_are_comments = false;
7120 }
7121
7122 selection_edit_ranges.push(prefix_range);
7123 }
7124
7125 if all_selection_lines_are_comments {
7126 edits.extend(
7127 selection_edit_ranges
7128 .iter()
7129 .cloned()
7130 .map(|range| (range, empty_str.clone())),
7131 );
7132 } else {
7133 let min_column = selection_edit_ranges
7134 .iter()
7135 .map(|range| range.start.column)
7136 .min()
7137 .unwrap_or(0);
7138 edits.extend(selection_edit_ranges.iter().map(|range| {
7139 let position = Point::new(range.start.row, min_column);
7140 (position..position, first_prefix.clone())
7141 }));
7142 }
7143 } else if let Some((full_comment_prefix, comment_suffix)) =
7144 language.block_comment_delimiters()
7145 {
7146 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
7147 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
7148 let prefix_range = comment_prefix_range(
7149 snapshot.deref(),
7150 start_row,
7151 comment_prefix,
7152 comment_prefix_whitespace,
7153 );
7154 let suffix_range = comment_suffix_range(
7155 snapshot.deref(),
7156 end_row,
7157 comment_suffix.trim_start_matches(' '),
7158 comment_suffix.starts_with(' '),
7159 );
7160
7161 if prefix_range.is_empty() || suffix_range.is_empty() {
7162 edits.push((
7163 prefix_range.start..prefix_range.start,
7164 full_comment_prefix.clone(),
7165 ));
7166 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
7167 suffixes_inserted.push((end_row, comment_suffix.len()));
7168 } else {
7169 edits.push((prefix_range, empty_str.clone()));
7170 edits.push((suffix_range, empty_str.clone()));
7171 }
7172 } else {
7173 continue;
7174 }
7175 }
7176
7177 drop(snapshot);
7178 this.buffer.update(cx, |buffer, cx| {
7179 buffer.edit(edits, None, cx);
7180 });
7181
7182 // Adjust selections so that they end before any comment suffixes that
7183 // were inserted.
7184 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
7185 let mut selections = this.selections.all::<Point>(cx);
7186 let snapshot = this.buffer.read(cx).read(cx);
7187 for selection in &mut selections {
7188 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
7189 match row.cmp(&selection.end.row) {
7190 Ordering::Less => {
7191 suffixes_inserted.next();
7192 continue;
7193 }
7194 Ordering::Greater => break,
7195 Ordering::Equal => {
7196 if selection.end.column == snapshot.line_len(row) {
7197 if selection.is_empty() {
7198 selection.start.column -= suffix_len as u32;
7199 }
7200 selection.end.column -= suffix_len as u32;
7201 }
7202 break;
7203 }
7204 }
7205 }
7206 }
7207
7208 drop(snapshot);
7209 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7210
7211 let selections = this.selections.all::<Point>(cx);
7212 let selections_on_single_row = selections.windows(2).all(|selections| {
7213 selections[0].start.row == selections[1].start.row
7214 && selections[0].end.row == selections[1].end.row
7215 && selections[0].start.row == selections[0].end.row
7216 });
7217 let selections_selecting = selections
7218 .iter()
7219 .any(|selection| selection.start != selection.end);
7220 let advance_downwards = action.advance_downwards
7221 && selections_on_single_row
7222 && !selections_selecting
7223 && this.mode != EditorMode::SingleLine;
7224
7225 if advance_downwards {
7226 let snapshot = this.buffer.read(cx).snapshot(cx);
7227
7228 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7229 s.move_cursors_with(|display_snapshot, display_point, _| {
7230 let mut point = display_point.to_point(display_snapshot);
7231 point.row += 1;
7232 point = snapshot.clip_point(point, Bias::Left);
7233 let display_point = point.to_display_point(display_snapshot);
7234 let goal = SelectionGoal::HorizontalPosition(
7235 display_snapshot
7236 .x_for_display_point(display_point, &text_layout_details)
7237 .into(),
7238 );
7239 (display_point, goal)
7240 })
7241 });
7242 }
7243 });
7244 }
7245
7246 pub fn select_larger_syntax_node(
7247 &mut self,
7248 _: &SelectLargerSyntaxNode,
7249 cx: &mut ViewContext<Self>,
7250 ) {
7251 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7252 let buffer = self.buffer.read(cx).snapshot(cx);
7253 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
7254
7255 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7256 let mut selected_larger_node = false;
7257 let new_selections = old_selections
7258 .iter()
7259 .map(|selection| {
7260 let old_range = selection.start..selection.end;
7261 let mut new_range = old_range.clone();
7262 while let Some(containing_range) =
7263 buffer.range_for_syntax_ancestor(new_range.clone())
7264 {
7265 new_range = containing_range;
7266 if !display_map.intersects_fold(new_range.start)
7267 && !display_map.intersects_fold(new_range.end)
7268 {
7269 break;
7270 }
7271 }
7272
7273 selected_larger_node |= new_range != old_range;
7274 Selection {
7275 id: selection.id,
7276 start: new_range.start,
7277 end: new_range.end,
7278 goal: SelectionGoal::None,
7279 reversed: selection.reversed,
7280 }
7281 })
7282 .collect::<Vec<_>>();
7283
7284 if selected_larger_node {
7285 stack.push(old_selections);
7286 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7287 s.select(new_selections);
7288 });
7289 }
7290 self.select_larger_syntax_node_stack = stack;
7291 }
7292
7293 pub fn select_smaller_syntax_node(
7294 &mut self,
7295 _: &SelectSmallerSyntaxNode,
7296 cx: &mut ViewContext<Self>,
7297 ) {
7298 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7299 if let Some(selections) = stack.pop() {
7300 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7301 s.select(selections.to_vec());
7302 });
7303 }
7304 self.select_larger_syntax_node_stack = stack;
7305 }
7306
7307 pub fn move_to_enclosing_bracket(
7308 &mut self,
7309 _: &MoveToEnclosingBracket,
7310 cx: &mut ViewContext<Self>,
7311 ) {
7312 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7313 s.move_offsets_with(|snapshot, selection| {
7314 let Some(enclosing_bracket_ranges) =
7315 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
7316 else {
7317 return;
7318 };
7319
7320 let mut best_length = usize::MAX;
7321 let mut best_inside = false;
7322 let mut best_in_bracket_range = false;
7323 let mut best_destination = None;
7324 for (open, close) in enclosing_bracket_ranges {
7325 let close = close.to_inclusive();
7326 let length = close.end() - open.start;
7327 let inside = selection.start >= open.end && selection.end <= *close.start();
7328 let in_bracket_range = open.to_inclusive().contains(&selection.head())
7329 || close.contains(&selection.head());
7330
7331 // If best is next to a bracket and current isn't, skip
7332 if !in_bracket_range && best_in_bracket_range {
7333 continue;
7334 }
7335
7336 // Prefer smaller lengths unless best is inside and current isn't
7337 if length > best_length && (best_inside || !inside) {
7338 continue;
7339 }
7340
7341 best_length = length;
7342 best_inside = inside;
7343 best_in_bracket_range = in_bracket_range;
7344 best_destination = Some(
7345 if close.contains(&selection.start) && close.contains(&selection.end) {
7346 if inside {
7347 open.end
7348 } else {
7349 open.start
7350 }
7351 } else {
7352 if inside {
7353 *close.start()
7354 } else {
7355 *close.end()
7356 }
7357 },
7358 );
7359 }
7360
7361 if let Some(destination) = best_destination {
7362 selection.collapse_to(destination, SelectionGoal::None);
7363 }
7364 })
7365 });
7366 }
7367
7368 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
7369 self.end_selection(cx);
7370 self.selection_history.mode = SelectionHistoryMode::Undoing;
7371 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
7372 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7373 self.select_next_state = entry.select_next_state;
7374 self.select_prev_state = entry.select_prev_state;
7375 self.add_selections_state = entry.add_selections_state;
7376 self.request_autoscroll(Autoscroll::newest(), cx);
7377 }
7378 self.selection_history.mode = SelectionHistoryMode::Normal;
7379 }
7380
7381 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
7382 self.end_selection(cx);
7383 self.selection_history.mode = SelectionHistoryMode::Redoing;
7384 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
7385 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7386 self.select_next_state = entry.select_next_state;
7387 self.select_prev_state = entry.select_prev_state;
7388 self.add_selections_state = entry.add_selections_state;
7389 self.request_autoscroll(Autoscroll::newest(), cx);
7390 }
7391 self.selection_history.mode = SelectionHistoryMode::Normal;
7392 }
7393
7394 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
7395 self.go_to_diagnostic_impl(Direction::Next, cx)
7396 }
7397
7398 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
7399 self.go_to_diagnostic_impl(Direction::Prev, cx)
7400 }
7401
7402 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
7403 let buffer = self.buffer.read(cx).snapshot(cx);
7404 let selection = self.selections.newest::<usize>(cx);
7405
7406 // If there is an active Diagnostic Popover jump to its diagnostic instead.
7407 if direction == Direction::Next {
7408 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
7409 let (group_id, jump_to) = popover.activation_info();
7410 if self.activate_diagnostics(group_id, cx) {
7411 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7412 let mut new_selection = s.newest_anchor().clone();
7413 new_selection.collapse_to(jump_to, SelectionGoal::None);
7414 s.select_anchors(vec![new_selection.clone()]);
7415 });
7416 }
7417 return;
7418 }
7419 }
7420
7421 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
7422 active_diagnostics
7423 .primary_range
7424 .to_offset(&buffer)
7425 .to_inclusive()
7426 });
7427 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
7428 if active_primary_range.contains(&selection.head()) {
7429 *active_primary_range.end()
7430 } else {
7431 selection.head()
7432 }
7433 } else {
7434 selection.head()
7435 };
7436
7437 loop {
7438 let mut diagnostics = if direction == Direction::Prev {
7439 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
7440 } else {
7441 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
7442 };
7443 let group = diagnostics.find_map(|entry| {
7444 if entry.diagnostic.is_primary
7445 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
7446 && !entry.range.is_empty()
7447 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
7448 && !entry.range.contains(&search_start)
7449 {
7450 Some((entry.range, entry.diagnostic.group_id))
7451 } else {
7452 None
7453 }
7454 });
7455
7456 if let Some((primary_range, group_id)) = group {
7457 if self.activate_diagnostics(group_id, cx) {
7458 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7459 s.select(vec![Selection {
7460 id: selection.id,
7461 start: primary_range.start,
7462 end: primary_range.start,
7463 reversed: false,
7464 goal: SelectionGoal::None,
7465 }]);
7466 });
7467 }
7468 break;
7469 } else {
7470 // Cycle around to the start of the buffer, potentially moving back to the start of
7471 // the currently active diagnostic.
7472 active_primary_range.take();
7473 if direction == Direction::Prev {
7474 if search_start == buffer.len() {
7475 break;
7476 } else {
7477 search_start = buffer.len();
7478 }
7479 } else if search_start == 0 {
7480 break;
7481 } else {
7482 search_start = 0;
7483 }
7484 }
7485 }
7486 }
7487
7488 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
7489 let snapshot = self
7490 .display_map
7491 .update(cx, |display_map, cx| display_map.snapshot(cx));
7492 let selection = self.selections.newest::<Point>(cx);
7493
7494 if !self.seek_in_direction(
7495 &snapshot,
7496 selection.head(),
7497 false,
7498 snapshot
7499 .buffer_snapshot
7500 .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
7501 cx,
7502 ) {
7503 let wrapped_point = Point::zero();
7504 self.seek_in_direction(
7505 &snapshot,
7506 wrapped_point,
7507 true,
7508 snapshot
7509 .buffer_snapshot
7510 .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
7511 cx,
7512 );
7513 }
7514 }
7515
7516 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
7517 let snapshot = self
7518 .display_map
7519 .update(cx, |display_map, cx| display_map.snapshot(cx));
7520 let selection = self.selections.newest::<Point>(cx);
7521
7522 if !self.seek_in_direction(
7523 &snapshot,
7524 selection.head(),
7525 false,
7526 snapshot
7527 .buffer_snapshot
7528 .git_diff_hunks_in_range_rev(0..selection.head().row),
7529 cx,
7530 ) {
7531 let wrapped_point = snapshot.buffer_snapshot.max_point();
7532 self.seek_in_direction(
7533 &snapshot,
7534 wrapped_point,
7535 true,
7536 snapshot
7537 .buffer_snapshot
7538 .git_diff_hunks_in_range_rev(0..wrapped_point.row),
7539 cx,
7540 );
7541 }
7542 }
7543
7544 fn seek_in_direction(
7545 &mut self,
7546 snapshot: &DisplaySnapshot,
7547 initial_point: Point,
7548 is_wrapped: bool,
7549 hunks: impl Iterator<Item = DiffHunk<u32>>,
7550 cx: &mut ViewContext<Editor>,
7551 ) -> bool {
7552 let display_point = initial_point.to_display_point(snapshot);
7553 let mut hunks = hunks
7554 .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
7555 .filter(|hunk| {
7556 if is_wrapped {
7557 true
7558 } else {
7559 !hunk.contains_display_row(display_point.row())
7560 }
7561 })
7562 .dedup();
7563
7564 if let Some(hunk) = hunks.next() {
7565 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7566 let row = hunk.start_display_row();
7567 let point = DisplayPoint::new(row, 0);
7568 s.select_display_ranges([point..point]);
7569 });
7570
7571 true
7572 } else {
7573 false
7574 }
7575 }
7576
7577 pub fn go_to_definition(
7578 &mut self,
7579 _: &GoToDefinition,
7580 cx: &mut ViewContext<Self>,
7581 ) -> Task<Result<bool>> {
7582 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
7583 }
7584
7585 pub fn go_to_implementation(
7586 &mut self,
7587 _: &GoToImplementation,
7588 cx: &mut ViewContext<Self>,
7589 ) -> Task<Result<bool>> {
7590 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
7591 }
7592
7593 pub fn go_to_implementation_split(
7594 &mut self,
7595 _: &GoToImplementationSplit,
7596 cx: &mut ViewContext<Self>,
7597 ) -> Task<Result<bool>> {
7598 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
7599 }
7600
7601 pub fn go_to_type_definition(
7602 &mut self,
7603 _: &GoToTypeDefinition,
7604 cx: &mut ViewContext<Self>,
7605 ) -> Task<Result<bool>> {
7606 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
7607 }
7608
7609 pub fn go_to_definition_split(
7610 &mut self,
7611 _: &GoToDefinitionSplit,
7612 cx: &mut ViewContext<Self>,
7613 ) -> Task<Result<bool>> {
7614 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
7615 }
7616
7617 pub fn go_to_type_definition_split(
7618 &mut self,
7619 _: &GoToTypeDefinitionSplit,
7620 cx: &mut ViewContext<Self>,
7621 ) -> Task<Result<bool>> {
7622 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
7623 }
7624
7625 fn go_to_definition_of_kind(
7626 &mut self,
7627 kind: GotoDefinitionKind,
7628 split: bool,
7629 cx: &mut ViewContext<Self>,
7630 ) -> Task<Result<bool>> {
7631 let Some(workspace) = self.workspace() else {
7632 return Task::ready(Ok(false));
7633 };
7634 let buffer = self.buffer.read(cx);
7635 let head = self.selections.newest::<usize>(cx).head();
7636 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
7637 text_anchor
7638 } else {
7639 return Task::ready(Ok(false));
7640 };
7641
7642 let project = workspace.read(cx).project().clone();
7643 let definitions = project.update(cx, |project, cx| match kind {
7644 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
7645 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
7646 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
7647 });
7648
7649 cx.spawn(|editor, mut cx| async move {
7650 let definitions = definitions.await?;
7651 let navigated = editor
7652 .update(&mut cx, |editor, cx| {
7653 editor.navigate_to_hover_links(
7654 Some(kind),
7655 definitions.into_iter().map(HoverLink::Text).collect(),
7656 split,
7657 cx,
7658 )
7659 })?
7660 .await?;
7661 anyhow::Ok(navigated)
7662 })
7663 }
7664
7665 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
7666 let position = self.selections.newest_anchor().head();
7667 let Some((buffer, buffer_position)) =
7668 self.buffer.read(cx).text_anchor_for_position(position, cx)
7669 else {
7670 return;
7671 };
7672
7673 cx.spawn(|editor, mut cx| async move {
7674 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
7675 editor.update(&mut cx, |_, cx| {
7676 cx.open_url(&url);
7677 })
7678 } else {
7679 Ok(())
7680 }
7681 })
7682 .detach();
7683 }
7684
7685 pub(crate) fn navigate_to_hover_links(
7686 &mut self,
7687 kind: Option<GotoDefinitionKind>,
7688 mut definitions: Vec<HoverLink>,
7689 split: bool,
7690 cx: &mut ViewContext<Editor>,
7691 ) -> Task<Result<bool>> {
7692 // If there is one definition, just open it directly
7693 if definitions.len() == 1 {
7694 let definition = definitions.pop().unwrap();
7695 let target_task = match definition {
7696 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7697 HoverLink::InlayHint(lsp_location, server_id) => {
7698 self.compute_target_location(lsp_location, server_id, cx)
7699 }
7700 HoverLink::Url(url) => {
7701 cx.open_url(&url);
7702 Task::ready(Ok(None))
7703 }
7704 };
7705 cx.spawn(|editor, mut cx| async move {
7706 let target = target_task.await.context("target resolution task")?;
7707 if let Some(target) = target {
7708 editor.update(&mut cx, |editor, cx| {
7709 let Some(workspace) = editor.workspace() else {
7710 return false;
7711 };
7712 let pane = workspace.read(cx).active_pane().clone();
7713
7714 let range = target.range.to_offset(target.buffer.read(cx));
7715 let range = editor.range_for_match(&range);
7716 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
7717 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
7718 s.select_ranges([range]);
7719 });
7720 } else {
7721 cx.window_context().defer(move |cx| {
7722 let target_editor: View<Self> =
7723 workspace.update(cx, |workspace, cx| {
7724 let pane = if split {
7725 workspace.adjacent_pane(cx)
7726 } else {
7727 workspace.active_pane().clone()
7728 };
7729
7730 workspace.open_project_item(pane, target.buffer.clone(), cx)
7731 });
7732 target_editor.update(cx, |target_editor, cx| {
7733 // When selecting a definition in a different buffer, disable the nav history
7734 // to avoid creating a history entry at the previous cursor location.
7735 pane.update(cx, |pane, _| pane.disable_history());
7736 target_editor.change_selections(
7737 Some(Autoscroll::focused()),
7738 cx,
7739 |s| {
7740 s.select_ranges([range]);
7741 },
7742 );
7743 pane.update(cx, |pane, _| pane.enable_history());
7744 });
7745 });
7746 }
7747 true
7748 })
7749 } else {
7750 Ok(false)
7751 }
7752 })
7753 } else if !definitions.is_empty() {
7754 let replica_id = self.replica_id(cx);
7755 cx.spawn(|editor, mut cx| async move {
7756 let (title, location_tasks, workspace) = editor
7757 .update(&mut cx, |editor, cx| {
7758 let tab_kind = match kind {
7759 Some(GotoDefinitionKind::Implementation) => "Implementations",
7760 _ => "Definitions",
7761 };
7762 let title = definitions
7763 .iter()
7764 .find_map(|definition| match definition {
7765 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
7766 let buffer = origin.buffer.read(cx);
7767 format!(
7768 "{} for {}",
7769 tab_kind,
7770 buffer
7771 .text_for_range(origin.range.clone())
7772 .collect::<String>()
7773 )
7774 }),
7775 HoverLink::InlayHint(_, _) => None,
7776 HoverLink::Url(_) => None,
7777 })
7778 .unwrap_or(tab_kind.to_string());
7779 let location_tasks = definitions
7780 .into_iter()
7781 .map(|definition| match definition {
7782 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7783 HoverLink::InlayHint(lsp_location, server_id) => {
7784 editor.compute_target_location(lsp_location, server_id, cx)
7785 }
7786 HoverLink::Url(_) => Task::ready(Ok(None)),
7787 })
7788 .collect::<Vec<_>>();
7789 (title, location_tasks, editor.workspace().clone())
7790 })
7791 .context("location tasks preparation")?;
7792
7793 let locations = futures::future::join_all(location_tasks)
7794 .await
7795 .into_iter()
7796 .filter_map(|location| location.transpose())
7797 .collect::<Result<_>>()
7798 .context("location tasks")?;
7799
7800 let Some(workspace) = workspace else {
7801 return Ok(false);
7802 };
7803 let opened = workspace
7804 .update(&mut cx, |workspace, cx| {
7805 Self::open_locations_in_multibuffer(
7806 workspace, locations, replica_id, title, split, cx,
7807 )
7808 })
7809 .ok();
7810
7811 anyhow::Ok(opened.is_some())
7812 })
7813 } else {
7814 Task::ready(Ok(false))
7815 }
7816 }
7817
7818 fn compute_target_location(
7819 &self,
7820 lsp_location: lsp::Location,
7821 server_id: LanguageServerId,
7822 cx: &mut ViewContext<Editor>,
7823 ) -> Task<anyhow::Result<Option<Location>>> {
7824 let Some(project) = self.project.clone() else {
7825 return Task::Ready(Some(Ok(None)));
7826 };
7827
7828 cx.spawn(move |editor, mut cx| async move {
7829 let location_task = editor.update(&mut cx, |editor, cx| {
7830 project.update(cx, |project, cx| {
7831 let language_server_name =
7832 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
7833 project
7834 .language_server_for_buffer(buffer.read(cx), server_id, cx)
7835 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
7836 });
7837 language_server_name.map(|language_server_name| {
7838 project.open_local_buffer_via_lsp(
7839 lsp_location.uri.clone(),
7840 server_id,
7841 language_server_name,
7842 cx,
7843 )
7844 })
7845 })
7846 })?;
7847 let location = match location_task {
7848 Some(task) => Some({
7849 let target_buffer_handle = task.await.context("open local buffer")?;
7850 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
7851 let target_start = target_buffer
7852 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
7853 let target_end = target_buffer
7854 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
7855 target_buffer.anchor_after(target_start)
7856 ..target_buffer.anchor_before(target_end)
7857 })?;
7858 Location {
7859 buffer: target_buffer_handle,
7860 range,
7861 }
7862 }),
7863 None => None,
7864 };
7865 Ok(location)
7866 })
7867 }
7868
7869 pub fn find_all_references(
7870 &mut self,
7871 _: &FindAllReferences,
7872 cx: &mut ViewContext<Self>,
7873 ) -> Option<Task<Result<()>>> {
7874 let multi_buffer = self.buffer.read(cx);
7875 let selection = self.selections.newest::<usize>(cx);
7876 let head = selection.head();
7877
7878 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
7879 let head_anchor = multi_buffer_snapshot.anchor_at(
7880 head,
7881 if head < selection.tail() {
7882 Bias::Right
7883 } else {
7884 Bias::Left
7885 },
7886 );
7887
7888 match self
7889 .find_all_references_task_sources
7890 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
7891 {
7892 Ok(_) => {
7893 log::info!(
7894 "Ignoring repeated FindAllReferences invocation with the position of already running task"
7895 );
7896 return None;
7897 }
7898 Err(i) => {
7899 self.find_all_references_task_sources.insert(i, head_anchor);
7900 }
7901 }
7902
7903 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
7904 let replica_id = self.replica_id(cx);
7905 let workspace = self.workspace()?;
7906 let project = workspace.read(cx).project().clone();
7907 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
7908 Some(cx.spawn(|editor, mut cx| async move {
7909 let _cleanup = defer({
7910 let mut cx = cx.clone();
7911 move || {
7912 let _ = editor.update(&mut cx, |editor, _| {
7913 if let Ok(i) =
7914 editor
7915 .find_all_references_task_sources
7916 .binary_search_by(|anchor| {
7917 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
7918 })
7919 {
7920 editor.find_all_references_task_sources.remove(i);
7921 }
7922 });
7923 }
7924 });
7925
7926 let locations = references.await?;
7927 if locations.is_empty() {
7928 return anyhow::Ok(());
7929 }
7930
7931 workspace.update(&mut cx, |workspace, cx| {
7932 let title = locations
7933 .first()
7934 .as_ref()
7935 .map(|location| {
7936 let buffer = location.buffer.read(cx);
7937 format!(
7938 "References to `{}`",
7939 buffer
7940 .text_for_range(location.range.clone())
7941 .collect::<String>()
7942 )
7943 })
7944 .unwrap();
7945 Self::open_locations_in_multibuffer(
7946 workspace, locations, replica_id, title, false, cx,
7947 );
7948 })
7949 }))
7950 }
7951
7952 /// Opens a multibuffer with the given project locations in it
7953 pub fn open_locations_in_multibuffer(
7954 workspace: &mut Workspace,
7955 mut locations: Vec<Location>,
7956 replica_id: ReplicaId,
7957 title: String,
7958 split: bool,
7959 cx: &mut ViewContext<Workspace>,
7960 ) {
7961 // If there are multiple definitions, open them in a multibuffer
7962 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
7963 let mut locations = locations.into_iter().peekable();
7964 let mut ranges_to_highlight = Vec::new();
7965 let capability = workspace.project().read(cx).capability();
7966
7967 let excerpt_buffer = cx.new_model(|cx| {
7968 let mut multibuffer = MultiBuffer::new(replica_id, capability);
7969 while let Some(location) = locations.next() {
7970 let buffer = location.buffer.read(cx);
7971 let mut ranges_for_buffer = Vec::new();
7972 let range = location.range.to_offset(buffer);
7973 ranges_for_buffer.push(range.clone());
7974
7975 while let Some(next_location) = locations.peek() {
7976 if next_location.buffer == location.buffer {
7977 ranges_for_buffer.push(next_location.range.to_offset(buffer));
7978 locations.next();
7979 } else {
7980 break;
7981 }
7982 }
7983
7984 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
7985 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
7986 location.buffer.clone(),
7987 ranges_for_buffer,
7988 1,
7989 cx,
7990 ))
7991 }
7992
7993 multibuffer.with_title(title)
7994 });
7995
7996 let editor = cx.new_view(|cx| {
7997 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
7998 });
7999 editor.update(cx, |editor, cx| {
8000 editor.highlight_background::<Self>(
8001 &ranges_to_highlight,
8002 |theme| theme.editor_highlighted_line_background,
8003 cx,
8004 );
8005 });
8006 let item = Box::new(editor);
8007 if split {
8008 workspace.split_item(SplitDirection::Right, item.clone(), cx);
8009 } else {
8010 workspace.add_item_to_active_pane(item.clone(), cx);
8011 }
8012 workspace.active_pane().clone().update(cx, |pane, cx| {
8013 let item_id = item.item_id();
8014 pane.set_preview_item_id(Some(item_id), cx);
8015 });
8016 }
8017
8018 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8019 use language::ToOffset as _;
8020
8021 let project = self.project.clone()?;
8022 let selection = self.selections.newest_anchor().clone();
8023 let (cursor_buffer, cursor_buffer_position) = self
8024 .buffer
8025 .read(cx)
8026 .text_anchor_for_position(selection.head(), cx)?;
8027 let (tail_buffer, _) = self
8028 .buffer
8029 .read(cx)
8030 .text_anchor_for_position(selection.tail(), cx)?;
8031 if tail_buffer != cursor_buffer {
8032 return None;
8033 }
8034
8035 let snapshot = cursor_buffer.read(cx).snapshot();
8036 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
8037 let prepare_rename = project.update(cx, |project, cx| {
8038 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
8039 });
8040 drop(snapshot);
8041
8042 Some(cx.spawn(|this, mut cx| async move {
8043 let rename_range = if let Some(range) = prepare_rename.await? {
8044 Some(range)
8045 } else {
8046 this.update(&mut cx, |this, cx| {
8047 let buffer = this.buffer.read(cx).snapshot(cx);
8048 let mut buffer_highlights = this
8049 .document_highlights_for_position(selection.head(), &buffer)
8050 .filter(|highlight| {
8051 highlight.start.excerpt_id == selection.head().excerpt_id
8052 && highlight.end.excerpt_id == selection.head().excerpt_id
8053 });
8054 buffer_highlights
8055 .next()
8056 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
8057 })?
8058 };
8059 if let Some(rename_range) = rename_range {
8060 this.update(&mut cx, |this, cx| {
8061 let snapshot = cursor_buffer.read(cx).snapshot();
8062 let rename_buffer_range = rename_range.to_offset(&snapshot);
8063 let cursor_offset_in_rename_range =
8064 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
8065
8066 this.take_rename(false, cx);
8067 let buffer = this.buffer.read(cx).read(cx);
8068 let cursor_offset = selection.head().to_offset(&buffer);
8069 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
8070 let rename_end = rename_start + rename_buffer_range.len();
8071 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
8072 let mut old_highlight_id = None;
8073 let old_name: Arc<str> = buffer
8074 .chunks(rename_start..rename_end, true)
8075 .map(|chunk| {
8076 if old_highlight_id.is_none() {
8077 old_highlight_id = chunk.syntax_highlight_id;
8078 }
8079 chunk.text
8080 })
8081 .collect::<String>()
8082 .into();
8083
8084 drop(buffer);
8085
8086 // Position the selection in the rename editor so that it matches the current selection.
8087 this.show_local_selections = false;
8088 let rename_editor = cx.new_view(|cx| {
8089 let mut editor = Editor::single_line(cx);
8090 editor.buffer.update(cx, |buffer, cx| {
8091 buffer.edit([(0..0, old_name.clone())], None, cx)
8092 });
8093 editor.select_all(&SelectAll, cx);
8094 editor
8095 });
8096
8097 let write_highlights =
8098 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
8099 let read_highlights =
8100 this.clear_background_highlights::<DocumentHighlightRead>(cx);
8101 let ranges = write_highlights
8102 .iter()
8103 .flat_map(|(_, ranges)| ranges.iter())
8104 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
8105 .cloned()
8106 .collect();
8107
8108 this.highlight_text::<Rename>(
8109 ranges,
8110 HighlightStyle {
8111 fade_out: Some(0.6),
8112 ..Default::default()
8113 },
8114 cx,
8115 );
8116 let rename_focus_handle = rename_editor.focus_handle(cx);
8117 cx.focus(&rename_focus_handle);
8118 let block_id = this.insert_blocks(
8119 [BlockProperties {
8120 style: BlockStyle::Flex,
8121 position: range.start,
8122 height: 1,
8123 render: Box::new({
8124 let rename_editor = rename_editor.clone();
8125 move |cx: &mut BlockContext| {
8126 let mut text_style = cx.editor_style.text.clone();
8127 if let Some(highlight_style) = old_highlight_id
8128 .and_then(|h| h.style(&cx.editor_style.syntax))
8129 {
8130 text_style = text_style.highlight(highlight_style);
8131 }
8132 div()
8133 .pl(cx.anchor_x)
8134 .child(EditorElement::new(
8135 &rename_editor,
8136 EditorStyle {
8137 background: cx.theme().system().transparent,
8138 local_player: cx.editor_style.local_player,
8139 text: text_style,
8140 scrollbar_width: cx.editor_style.scrollbar_width,
8141 syntax: cx.editor_style.syntax.clone(),
8142 status: cx.editor_style.status.clone(),
8143 inlay_hints_style: HighlightStyle {
8144 color: Some(cx.theme().status().hint),
8145 font_weight: Some(FontWeight::BOLD),
8146 ..HighlightStyle::default()
8147 },
8148 suggestions_style: HighlightStyle {
8149 color: Some(cx.theme().status().predictive),
8150 ..HighlightStyle::default()
8151 },
8152 },
8153 ))
8154 .into_any_element()
8155 }
8156 }),
8157 disposition: BlockDisposition::Below,
8158 }],
8159 Some(Autoscroll::fit()),
8160 cx,
8161 )[0];
8162 this.pending_rename = Some(RenameState {
8163 range,
8164 old_name,
8165 editor: rename_editor,
8166 block_id,
8167 });
8168 })?;
8169 }
8170
8171 Ok(())
8172 }))
8173 }
8174
8175 pub fn confirm_rename(
8176 &mut self,
8177 _: &ConfirmRename,
8178 cx: &mut ViewContext<Self>,
8179 ) -> Option<Task<Result<()>>> {
8180 let rename = self.take_rename(false, cx)?;
8181 let workspace = self.workspace()?;
8182 let (start_buffer, start) = self
8183 .buffer
8184 .read(cx)
8185 .text_anchor_for_position(rename.range.start, cx)?;
8186 let (end_buffer, end) = self
8187 .buffer
8188 .read(cx)
8189 .text_anchor_for_position(rename.range.end, cx)?;
8190 if start_buffer != end_buffer {
8191 return None;
8192 }
8193
8194 let buffer = start_buffer;
8195 let range = start..end;
8196 let old_name = rename.old_name;
8197 let new_name = rename.editor.read(cx).text(cx);
8198
8199 let rename = workspace
8200 .read(cx)
8201 .project()
8202 .clone()
8203 .update(cx, |project, cx| {
8204 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
8205 });
8206 let workspace = workspace.downgrade();
8207
8208 Some(cx.spawn(|editor, mut cx| async move {
8209 let project_transaction = rename.await?;
8210 Self::open_project_transaction(
8211 &editor,
8212 workspace,
8213 project_transaction,
8214 format!("Rename: {} → {}", old_name, new_name),
8215 cx.clone(),
8216 )
8217 .await?;
8218
8219 editor.update(&mut cx, |editor, cx| {
8220 editor.refresh_document_highlights(cx);
8221 })?;
8222 Ok(())
8223 }))
8224 }
8225
8226 fn take_rename(
8227 &mut self,
8228 moving_cursor: bool,
8229 cx: &mut ViewContext<Self>,
8230 ) -> Option<RenameState> {
8231 let rename = self.pending_rename.take()?;
8232 if rename.editor.focus_handle(cx).is_focused(cx) {
8233 cx.focus(&self.focus_handle);
8234 }
8235
8236 self.remove_blocks(
8237 [rename.block_id].into_iter().collect(),
8238 Some(Autoscroll::fit()),
8239 cx,
8240 );
8241 self.clear_highlights::<Rename>(cx);
8242 self.show_local_selections = true;
8243
8244 if moving_cursor {
8245 let rename_editor = rename.editor.read(cx);
8246 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
8247
8248 // Update the selection to match the position of the selection inside
8249 // the rename editor.
8250 let snapshot = self.buffer.read(cx).read(cx);
8251 let rename_range = rename.range.to_offset(&snapshot);
8252 let cursor_in_editor = snapshot
8253 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
8254 .min(rename_range.end);
8255 drop(snapshot);
8256
8257 self.change_selections(None, cx, |s| {
8258 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
8259 });
8260 } else {
8261 self.refresh_document_highlights(cx);
8262 }
8263
8264 Some(rename)
8265 }
8266
8267 pub fn pending_rename(&self) -> Option<&RenameState> {
8268 self.pending_rename.as_ref()
8269 }
8270
8271 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8272 let project = match &self.project {
8273 Some(project) => project.clone(),
8274 None => return None,
8275 };
8276
8277 Some(self.perform_format(project, FormatTrigger::Manual, cx))
8278 }
8279
8280 fn perform_format(
8281 &mut self,
8282 project: Model<Project>,
8283 trigger: FormatTrigger,
8284 cx: &mut ViewContext<Self>,
8285 ) -> Task<Result<()>> {
8286 let buffer = self.buffer().clone();
8287 let mut buffers = buffer.read(cx).all_buffers();
8288 if trigger == FormatTrigger::Save {
8289 buffers.retain(|buffer| buffer.read(cx).is_dirty());
8290 }
8291
8292 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
8293 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
8294
8295 cx.spawn(|_, mut cx| async move {
8296 let transaction = futures::select_biased! {
8297 () = timeout => {
8298 log::warn!("timed out waiting for formatting");
8299 None
8300 }
8301 transaction = format.log_err().fuse() => transaction,
8302 };
8303
8304 buffer
8305 .update(&mut cx, |buffer, cx| {
8306 if let Some(transaction) = transaction {
8307 if !buffer.is_singleton() {
8308 buffer.push_transaction(&transaction.0, cx);
8309 }
8310 }
8311
8312 cx.notify();
8313 })
8314 .ok();
8315
8316 Ok(())
8317 })
8318 }
8319
8320 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
8321 if let Some(project) = self.project.clone() {
8322 self.buffer.update(cx, |multi_buffer, cx| {
8323 project.update(cx, |project, cx| {
8324 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
8325 });
8326 })
8327 }
8328 }
8329
8330 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
8331 cx.show_character_palette();
8332 }
8333
8334 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
8335 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
8336 let buffer = self.buffer.read(cx).snapshot(cx);
8337 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
8338 let is_valid = buffer
8339 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
8340 .any(|entry| {
8341 entry.diagnostic.is_primary
8342 && !entry.range.is_empty()
8343 && entry.range.start == primary_range_start
8344 && entry.diagnostic.message == active_diagnostics.primary_message
8345 });
8346
8347 if is_valid != active_diagnostics.is_valid {
8348 active_diagnostics.is_valid = is_valid;
8349 let mut new_styles = HashMap::default();
8350 for (block_id, diagnostic) in &active_diagnostics.blocks {
8351 new_styles.insert(
8352 *block_id,
8353 diagnostic_block_renderer(diagnostic.clone(), is_valid),
8354 );
8355 }
8356 self.display_map
8357 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
8358 }
8359 }
8360 }
8361
8362 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
8363 self.dismiss_diagnostics(cx);
8364 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
8365 let buffer = self.buffer.read(cx).snapshot(cx);
8366
8367 let mut primary_range = None;
8368 let mut primary_message = None;
8369 let mut group_end = Point::zero();
8370 let diagnostic_group = buffer
8371 .diagnostic_group::<Point>(group_id)
8372 .map(|entry| {
8373 if entry.range.end > group_end {
8374 group_end = entry.range.end;
8375 }
8376 if entry.diagnostic.is_primary {
8377 primary_range = Some(entry.range.clone());
8378 primary_message = Some(entry.diagnostic.message.clone());
8379 }
8380 entry
8381 })
8382 .collect::<Vec<_>>();
8383 let primary_range = primary_range?;
8384 let primary_message = primary_message?;
8385 let primary_range =
8386 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
8387
8388 let blocks = display_map
8389 .insert_blocks(
8390 diagnostic_group.iter().map(|entry| {
8391 let diagnostic = entry.diagnostic.clone();
8392 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
8393 BlockProperties {
8394 style: BlockStyle::Fixed,
8395 position: buffer.anchor_after(entry.range.start),
8396 height: message_height,
8397 render: diagnostic_block_renderer(diagnostic, true),
8398 disposition: BlockDisposition::Below,
8399 }
8400 }),
8401 cx,
8402 )
8403 .into_iter()
8404 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
8405 .collect();
8406
8407 Some(ActiveDiagnosticGroup {
8408 primary_range,
8409 primary_message,
8410 blocks,
8411 is_valid: true,
8412 })
8413 });
8414 self.active_diagnostics.is_some()
8415 }
8416
8417 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
8418 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
8419 self.display_map.update(cx, |display_map, cx| {
8420 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
8421 });
8422 cx.notify();
8423 }
8424 }
8425
8426 pub fn set_selections_from_remote(
8427 &mut self,
8428 selections: Vec<Selection<Anchor>>,
8429 pending_selection: Option<Selection<Anchor>>,
8430 cx: &mut ViewContext<Self>,
8431 ) {
8432 let old_cursor_position = self.selections.newest_anchor().head();
8433 self.selections.change_with(cx, |s| {
8434 s.select_anchors(selections);
8435 if let Some(pending_selection) = pending_selection {
8436 s.set_pending(pending_selection, SelectMode::Character);
8437 } else {
8438 s.clear_pending();
8439 }
8440 });
8441 self.selections_did_change(false, &old_cursor_position, cx);
8442 }
8443
8444 fn push_to_selection_history(&mut self) {
8445 self.selection_history.push(SelectionHistoryEntry {
8446 selections: self.selections.disjoint_anchors(),
8447 select_next_state: self.select_next_state.clone(),
8448 select_prev_state: self.select_prev_state.clone(),
8449 add_selections_state: self.add_selections_state.clone(),
8450 });
8451 }
8452
8453 pub fn transact(
8454 &mut self,
8455 cx: &mut ViewContext<Self>,
8456 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
8457 ) -> Option<TransactionId> {
8458 self.start_transaction_at(Instant::now(), cx);
8459 update(self, cx);
8460 self.end_transaction_at(Instant::now(), cx)
8461 }
8462
8463 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
8464 self.end_selection(cx);
8465 if let Some(tx_id) = self
8466 .buffer
8467 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
8468 {
8469 self.selection_history
8470 .insert_transaction(tx_id, self.selections.disjoint_anchors());
8471 cx.emit(EditorEvent::TransactionBegun {
8472 transaction_id: tx_id,
8473 })
8474 }
8475 }
8476
8477 fn end_transaction_at(
8478 &mut self,
8479 now: Instant,
8480 cx: &mut ViewContext<Self>,
8481 ) -> Option<TransactionId> {
8482 if let Some(tx_id) = self
8483 .buffer
8484 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
8485 {
8486 if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
8487 *end_selections = Some(self.selections.disjoint_anchors());
8488 } else {
8489 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
8490 }
8491
8492 cx.emit(EditorEvent::Edited);
8493 Some(tx_id)
8494 } else {
8495 None
8496 }
8497 }
8498
8499 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
8500 let mut fold_ranges = Vec::new();
8501
8502 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8503
8504 let selections = self.selections.all_adjusted(cx);
8505 for selection in selections {
8506 let range = selection.range().sorted();
8507 let buffer_start_row = range.start.row;
8508
8509 for row in (0..=range.end.row).rev() {
8510 let fold_range = display_map.foldable_range(row);
8511
8512 if let Some(fold_range) = fold_range {
8513 if fold_range.end.row >= buffer_start_row {
8514 fold_ranges.push(fold_range);
8515 if row <= range.start.row {
8516 break;
8517 }
8518 }
8519 }
8520 }
8521 }
8522
8523 self.fold_ranges(fold_ranges, true, cx);
8524 }
8525
8526 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
8527 let buffer_row = fold_at.buffer_row;
8528 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8529
8530 if let Some(fold_range) = display_map.foldable_range(buffer_row) {
8531 let autoscroll = self
8532 .selections
8533 .all::<Point>(cx)
8534 .iter()
8535 .any(|selection| fold_range.overlaps(&selection.range()));
8536
8537 self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
8538 }
8539 }
8540
8541 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
8542 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8543 let buffer = &display_map.buffer_snapshot;
8544 let selections = self.selections.all::<Point>(cx);
8545 let ranges = selections
8546 .iter()
8547 .map(|s| {
8548 let range = s.display_range(&display_map).sorted();
8549 let mut start = range.start.to_point(&display_map);
8550 let mut end = range.end.to_point(&display_map);
8551 start.column = 0;
8552 end.column = buffer.line_len(end.row);
8553 start..end
8554 })
8555 .collect::<Vec<_>>();
8556
8557 self.unfold_ranges(ranges, true, true, cx);
8558 }
8559
8560 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
8561 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8562
8563 let intersection_range = Point::new(unfold_at.buffer_row, 0)
8564 ..Point::new(
8565 unfold_at.buffer_row,
8566 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
8567 );
8568
8569 let autoscroll = self
8570 .selections
8571 .all::<Point>(cx)
8572 .iter()
8573 .any(|selection| selection.range().overlaps(&intersection_range));
8574
8575 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
8576 }
8577
8578 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
8579 let selections = self.selections.all::<Point>(cx);
8580 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8581 let line_mode = self.selections.line_mode;
8582 let ranges = selections.into_iter().map(|s| {
8583 if line_mode {
8584 let start = Point::new(s.start.row, 0);
8585 let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
8586 start..end
8587 } else {
8588 s.start..s.end
8589 }
8590 });
8591 self.fold_ranges(ranges, true, cx);
8592 }
8593
8594 pub fn fold_ranges<T: ToOffset + Clone>(
8595 &mut self,
8596 ranges: impl IntoIterator<Item = Range<T>>,
8597 auto_scroll: bool,
8598 cx: &mut ViewContext<Self>,
8599 ) {
8600 let mut ranges = ranges.into_iter().peekable();
8601 if ranges.peek().is_some() {
8602 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
8603
8604 if auto_scroll {
8605 self.request_autoscroll(Autoscroll::fit(), cx);
8606 }
8607
8608 cx.notify();
8609 }
8610 }
8611
8612 pub fn unfold_ranges<T: ToOffset + Clone>(
8613 &mut self,
8614 ranges: impl IntoIterator<Item = Range<T>>,
8615 inclusive: bool,
8616 auto_scroll: bool,
8617 cx: &mut ViewContext<Self>,
8618 ) {
8619 let mut ranges = ranges.into_iter().peekable();
8620 if ranges.peek().is_some() {
8621 self.display_map
8622 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
8623 if auto_scroll {
8624 self.request_autoscroll(Autoscroll::fit(), cx);
8625 }
8626
8627 cx.notify();
8628 }
8629 }
8630
8631 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
8632 if hovered != self.gutter_hovered {
8633 self.gutter_hovered = hovered;
8634 cx.notify();
8635 }
8636 }
8637
8638 pub fn insert_blocks(
8639 &mut self,
8640 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
8641 autoscroll: Option<Autoscroll>,
8642 cx: &mut ViewContext<Self>,
8643 ) -> Vec<BlockId> {
8644 let blocks = self
8645 .display_map
8646 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
8647 if let Some(autoscroll) = autoscroll {
8648 self.request_autoscroll(autoscroll, cx);
8649 }
8650 blocks
8651 }
8652
8653 pub fn replace_blocks(
8654 &mut self,
8655 blocks: HashMap<BlockId, RenderBlock>,
8656 autoscroll: Option<Autoscroll>,
8657 cx: &mut ViewContext<Self>,
8658 ) {
8659 self.display_map
8660 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
8661 if let Some(autoscroll) = autoscroll {
8662 self.request_autoscroll(autoscroll, cx);
8663 }
8664 }
8665
8666 pub fn remove_blocks(
8667 &mut self,
8668 block_ids: HashSet<BlockId>,
8669 autoscroll: Option<Autoscroll>,
8670 cx: &mut ViewContext<Self>,
8671 ) {
8672 self.display_map.update(cx, |display_map, cx| {
8673 display_map.remove_blocks(block_ids, cx)
8674 });
8675 if let Some(autoscroll) = autoscroll {
8676 self.request_autoscroll(autoscroll, cx);
8677 }
8678 }
8679
8680 pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
8681 self.display_map
8682 .update(cx, |map, cx| map.snapshot(cx))
8683 .longest_row()
8684 }
8685
8686 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
8687 self.display_map
8688 .update(cx, |map, cx| map.snapshot(cx))
8689 .max_point()
8690 }
8691
8692 pub fn text(&self, cx: &AppContext) -> String {
8693 self.buffer.read(cx).read(cx).text()
8694 }
8695
8696 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
8697 let text = self.text(cx);
8698 let text = text.trim();
8699
8700 if text.is_empty() {
8701 return None;
8702 }
8703
8704 Some(text.to_string())
8705 }
8706
8707 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
8708 self.transact(cx, |this, cx| {
8709 this.buffer
8710 .read(cx)
8711 .as_singleton()
8712 .expect("you can only call set_text on editors for singleton buffers")
8713 .update(cx, |buffer, cx| buffer.set_text(text, cx));
8714 });
8715 }
8716
8717 pub fn display_text(&self, cx: &mut AppContext) -> String {
8718 self.display_map
8719 .update(cx, |map, cx| map.snapshot(cx))
8720 .text()
8721 }
8722
8723 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
8724 let mut wrap_guides = smallvec::smallvec![];
8725
8726 if self.show_wrap_guides == Some(false) {
8727 return wrap_guides;
8728 }
8729
8730 let settings = self.buffer.read(cx).settings_at(0, cx);
8731 if settings.show_wrap_guides {
8732 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
8733 wrap_guides.push((soft_wrap as usize, true));
8734 }
8735 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
8736 }
8737
8738 wrap_guides
8739 }
8740
8741 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
8742 let settings = self.buffer.read(cx).settings_at(0, cx);
8743 let mode = self
8744 .soft_wrap_mode_override
8745 .unwrap_or_else(|| settings.soft_wrap);
8746 match mode {
8747 language_settings::SoftWrap::None => SoftWrap::None,
8748 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
8749 language_settings::SoftWrap::PreferredLineLength => {
8750 SoftWrap::Column(settings.preferred_line_length)
8751 }
8752 }
8753 }
8754
8755 pub fn set_soft_wrap_mode(
8756 &mut self,
8757 mode: language_settings::SoftWrap,
8758 cx: &mut ViewContext<Self>,
8759 ) {
8760 self.soft_wrap_mode_override = Some(mode);
8761 cx.notify();
8762 }
8763
8764 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
8765 let rem_size = cx.rem_size();
8766 self.display_map.update(cx, |map, cx| {
8767 map.set_font(
8768 style.text.font(),
8769 style.text.font_size.to_pixels(rem_size),
8770 cx,
8771 )
8772 });
8773 self.style = Some(style);
8774 }
8775
8776 #[cfg(any(test, feature = "test-support"))]
8777 pub fn style(&self) -> Option<&EditorStyle> {
8778 self.style.as_ref()
8779 }
8780
8781 // Called by the element. This method is not designed to be called outside of the editor
8782 // element's layout code because it does not notify when rewrapping is computed synchronously.
8783 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
8784 self.display_map
8785 .update(cx, |map, cx| map.set_wrap_width(width, cx))
8786 }
8787
8788 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
8789 if self.soft_wrap_mode_override.is_some() {
8790 self.soft_wrap_mode_override.take();
8791 } else {
8792 let soft_wrap = match self.soft_wrap_mode(cx) {
8793 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
8794 SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
8795 };
8796 self.soft_wrap_mode_override = Some(soft_wrap);
8797 }
8798 cx.notify();
8799 }
8800
8801 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
8802 let mut editor_settings = EditorSettings::get_global(cx).clone();
8803 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
8804 EditorSettings::override_global(editor_settings, cx);
8805 }
8806
8807 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8808 self.show_gutter = show_gutter;
8809 cx.notify();
8810 }
8811
8812 pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8813 self.show_wrap_guides = Some(show_gutter);
8814 cx.notify();
8815 }
8816
8817 pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
8818 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8819 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8820 cx.reveal_path(&file.abs_path(cx));
8821 }
8822 }
8823 }
8824
8825 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
8826 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8827 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8828 if let Some(path) = file.abs_path(cx).to_str() {
8829 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8830 }
8831 }
8832 }
8833 }
8834
8835 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
8836 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8837 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8838 if let Some(path) = file.path().to_str() {
8839 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8840 }
8841 }
8842 }
8843 }
8844
8845 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
8846 if self.show_git_blame {
8847 self.blame_subscription.take();
8848 self.blame.take();
8849 self.show_git_blame = false
8850 } else {
8851 if let Err(error) = self.show_git_blame_internal(cx) {
8852 log::error!("failed to toggle on 'git blame': {}", error);
8853 return;
8854 }
8855 self.show_git_blame = true
8856 }
8857
8858 cx.notify();
8859 }
8860
8861 fn show_git_blame_internal(&mut self, cx: &mut ViewContext<Self>) -> Result<()> {
8862 if let Some(project) = self.project.as_ref() {
8863 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
8864 anyhow::bail!("git blame not available in multi buffers")
8865 };
8866
8867 let project = project.clone();
8868 let blame = cx.new_model(|cx| GitBlame::new(buffer, project, cx));
8869 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
8870 self.blame = Some(blame);
8871 }
8872
8873 Ok(())
8874 }
8875
8876 pub fn blame(&self) -> Option<&Model<GitBlame>> {
8877 self.blame.as_ref()
8878 }
8879
8880 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
8881 let (path, repo) = maybe!({
8882 let project_handle = self.project.as_ref()?.clone();
8883 let project = project_handle.read(cx);
8884 let buffer = self.buffer().read(cx).as_singleton()?;
8885 let path = buffer
8886 .read(cx)
8887 .file()?
8888 .as_local()?
8889 .path()
8890 .to_str()?
8891 .to_string();
8892 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
8893 Some((path, repo))
8894 })
8895 .ok_or_else(|| anyhow!("unable to open git repository"))?;
8896
8897 const REMOTE_NAME: &str = "origin";
8898 let origin_url = repo
8899 .lock()
8900 .remote_url(REMOTE_NAME)
8901 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
8902 let sha = repo
8903 .lock()
8904 .head_sha()
8905 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
8906 let selections = self.selections.all::<Point>(cx);
8907 let selection = selections.iter().peekable().next();
8908
8909 build_permalink(BuildPermalinkParams {
8910 remote_url: &origin_url,
8911 sha: &sha,
8912 path: &path,
8913 selection: selection.map(|selection| {
8914 let range = selection.range();
8915 let start = range.start.row;
8916 let end = range.end.row;
8917 start..end
8918 }),
8919 })
8920 }
8921
8922 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
8923 let permalink = self.get_permalink_to_line(cx);
8924
8925 match permalink {
8926 Ok(permalink) => {
8927 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
8928 }
8929 Err(err) => {
8930 let message = format!("Failed to copy permalink: {err}");
8931
8932 Err::<(), anyhow::Error>(err).log_err();
8933
8934 if let Some(workspace) = self.workspace() {
8935 workspace.update(cx, |workspace, cx| {
8936 struct CopyPermalinkToLine;
8937
8938 workspace.show_toast(
8939 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
8940 cx,
8941 )
8942 })
8943 }
8944 }
8945 }
8946 }
8947
8948 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
8949 let permalink = self.get_permalink_to_line(cx);
8950
8951 match permalink {
8952 Ok(permalink) => {
8953 cx.open_url(permalink.as_ref());
8954 }
8955 Err(err) => {
8956 let message = format!("Failed to open permalink: {err}");
8957
8958 Err::<(), anyhow::Error>(err).log_err();
8959
8960 if let Some(workspace) = self.workspace() {
8961 workspace.update(cx, |workspace, cx| {
8962 struct OpenPermalinkToLine;
8963
8964 workspace.show_toast(
8965 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
8966 cx,
8967 )
8968 })
8969 }
8970 }
8971 }
8972 }
8973
8974 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
8975 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
8976 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
8977 pub fn highlight_rows<T: 'static>(
8978 &mut self,
8979 rows: Range<Anchor>,
8980 color: Option<Hsla>,
8981 cx: &mut ViewContext<Self>,
8982 ) {
8983 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
8984 match self.highlighted_rows.entry(TypeId::of::<T>()) {
8985 hash_map::Entry::Occupied(o) => {
8986 let row_highlights = o.into_mut();
8987 let existing_highlight_index =
8988 row_highlights.binary_search_by(|(_, highlight_range, _)| {
8989 highlight_range
8990 .start
8991 .cmp(&rows.start, &multi_buffer_snapshot)
8992 .then(highlight_range.end.cmp(&rows.end, &multi_buffer_snapshot))
8993 });
8994 match color {
8995 Some(color) => {
8996 let insert_index = match existing_highlight_index {
8997 Ok(i) => i,
8998 Err(i) => i,
8999 };
9000 row_highlights.insert(
9001 insert_index,
9002 (post_inc(&mut self.highlight_order), rows, color),
9003 );
9004 }
9005 None => {
9006 if let Ok(i) = existing_highlight_index {
9007 row_highlights.remove(i);
9008 }
9009 }
9010 }
9011 }
9012 hash_map::Entry::Vacant(v) => {
9013 if let Some(color) = color {
9014 v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
9015 }
9016 }
9017 }
9018 }
9019
9020 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
9021 pub fn clear_row_highlights<T: 'static>(&mut self) {
9022 self.highlighted_rows.remove(&TypeId::of::<T>());
9023 }
9024
9025 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
9026 pub fn highlighted_rows<T: 'static>(
9027 &self,
9028 ) -> Option<impl Iterator<Item = (&Range<Anchor>, &Hsla)>> {
9029 Some(
9030 self.highlighted_rows
9031 .get(&TypeId::of::<T>())?
9032 .iter()
9033 .map(|(_, range, color)| (range, color)),
9034 )
9035 }
9036
9037 // Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
9038 // Rerturns a map of display rows that are highlighted and their corresponding highlight color.
9039 pub fn highlighted_display_rows(&mut self, cx: &mut WindowContext) -> BTreeMap<u32, Hsla> {
9040 let snapshot = self.snapshot(cx);
9041 let mut used_highlight_orders = HashMap::default();
9042 self.highlighted_rows
9043 .iter()
9044 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
9045 .fold(
9046 BTreeMap::<u32, Hsla>::new(),
9047 |mut unique_rows, (highlight_order, anchor_range, hsla)| {
9048 let start_row = anchor_range.start.to_display_point(&snapshot).row();
9049 let end_row = anchor_range.end.to_display_point(&snapshot).row();
9050 for row in start_row..=end_row {
9051 let used_index =
9052 used_highlight_orders.entry(row).or_insert(*highlight_order);
9053 if highlight_order >= used_index {
9054 *used_index = *highlight_order;
9055 unique_rows.insert(row, *hsla);
9056 }
9057 }
9058 unique_rows
9059 },
9060 )
9061 }
9062
9063 pub fn highlight_background<T: 'static>(
9064 &mut self,
9065 ranges: &[Range<Anchor>],
9066 color_fetcher: fn(&ThemeColors) -> Hsla,
9067 cx: &mut ViewContext<Self>,
9068 ) {
9069 let snapshot = self.snapshot(cx);
9070 // this is to try and catch a panic sooner
9071 for range in ranges {
9072 snapshot
9073 .buffer_snapshot
9074 .summary_for_anchor::<usize>(&range.start);
9075 snapshot
9076 .buffer_snapshot
9077 .summary_for_anchor::<usize>(&range.end);
9078 }
9079
9080 self.background_highlights
9081 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
9082 self.scrollbar_marker_state.dirty = true;
9083 cx.notify();
9084 }
9085
9086 pub fn clear_background_highlights<T: 'static>(
9087 &mut self,
9088 cx: &mut ViewContext<Self>,
9089 ) -> Option<BackgroundHighlight> {
9090 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
9091 if !text_highlights.1.is_empty() {
9092 self.scrollbar_marker_state.dirty = true;
9093 cx.notify();
9094 }
9095 Some(text_highlights)
9096 }
9097
9098 #[cfg(feature = "test-support")]
9099 pub fn all_text_background_highlights(
9100 &mut self,
9101 cx: &mut ViewContext<Self>,
9102 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
9103 let snapshot = self.snapshot(cx);
9104 let buffer = &snapshot.buffer_snapshot;
9105 let start = buffer.anchor_before(0);
9106 let end = buffer.anchor_after(buffer.len());
9107 let theme = cx.theme().colors();
9108 self.background_highlights_in_range(start..end, &snapshot, theme)
9109 }
9110
9111 fn document_highlights_for_position<'a>(
9112 &'a self,
9113 position: Anchor,
9114 buffer: &'a MultiBufferSnapshot,
9115 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
9116 let read_highlights = self
9117 .background_highlights
9118 .get(&TypeId::of::<DocumentHighlightRead>())
9119 .map(|h| &h.1);
9120 let write_highlights = self
9121 .background_highlights
9122 .get(&TypeId::of::<DocumentHighlightWrite>())
9123 .map(|h| &h.1);
9124 let left_position = position.bias_left(buffer);
9125 let right_position = position.bias_right(buffer);
9126 read_highlights
9127 .into_iter()
9128 .chain(write_highlights)
9129 .flat_map(move |ranges| {
9130 let start_ix = match ranges.binary_search_by(|probe| {
9131 let cmp = probe.end.cmp(&left_position, buffer);
9132 if cmp.is_ge() {
9133 Ordering::Greater
9134 } else {
9135 Ordering::Less
9136 }
9137 }) {
9138 Ok(i) | Err(i) => i,
9139 };
9140
9141 ranges[start_ix..]
9142 .iter()
9143 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
9144 })
9145 }
9146
9147 pub fn has_background_highlights<T: 'static>(&self) -> bool {
9148 self.background_highlights
9149 .get(&TypeId::of::<T>())
9150 .map_or(false, |(_, highlights)| !highlights.is_empty())
9151 }
9152
9153 pub fn background_highlights_in_range(
9154 &self,
9155 search_range: Range<Anchor>,
9156 display_snapshot: &DisplaySnapshot,
9157 theme: &ThemeColors,
9158 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
9159 let mut results = Vec::new();
9160 for (color_fetcher, ranges) in self.background_highlights.values() {
9161 let color = color_fetcher(theme);
9162 let start_ix = match ranges.binary_search_by(|probe| {
9163 let cmp = probe
9164 .end
9165 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
9166 if cmp.is_gt() {
9167 Ordering::Greater
9168 } else {
9169 Ordering::Less
9170 }
9171 }) {
9172 Ok(i) | Err(i) => i,
9173 };
9174 for range in &ranges[start_ix..] {
9175 if range
9176 .start
9177 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
9178 .is_ge()
9179 {
9180 break;
9181 }
9182
9183 let start = range.start.to_display_point(&display_snapshot);
9184 let end = range.end.to_display_point(&display_snapshot);
9185 results.push((start..end, color))
9186 }
9187 }
9188 results
9189 }
9190
9191 pub fn background_highlight_row_ranges<T: 'static>(
9192 &self,
9193 search_range: Range<Anchor>,
9194 display_snapshot: &DisplaySnapshot,
9195 count: usize,
9196 ) -> Vec<RangeInclusive<DisplayPoint>> {
9197 let mut results = Vec::new();
9198 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
9199 return vec![];
9200 };
9201
9202 let start_ix = match ranges.binary_search_by(|probe| {
9203 let cmp = probe
9204 .end
9205 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
9206 if cmp.is_gt() {
9207 Ordering::Greater
9208 } else {
9209 Ordering::Less
9210 }
9211 }) {
9212 Ok(i) | Err(i) => i,
9213 };
9214 let mut push_region = |start: Option<Point>, end: Option<Point>| {
9215 if let (Some(start_display), Some(end_display)) = (start, end) {
9216 results.push(
9217 start_display.to_display_point(display_snapshot)
9218 ..=end_display.to_display_point(display_snapshot),
9219 );
9220 }
9221 };
9222 let mut start_row: Option<Point> = None;
9223 let mut end_row: Option<Point> = None;
9224 if ranges.len() > count {
9225 return Vec::new();
9226 }
9227 for range in &ranges[start_ix..] {
9228 if range
9229 .start
9230 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
9231 .is_ge()
9232 {
9233 break;
9234 }
9235 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
9236 if let Some(current_row) = &end_row {
9237 if end.row == current_row.row {
9238 continue;
9239 }
9240 }
9241 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
9242 if start_row.is_none() {
9243 assert_eq!(end_row, None);
9244 start_row = Some(start);
9245 end_row = Some(end);
9246 continue;
9247 }
9248 if let Some(current_end) = end_row.as_mut() {
9249 if start.row > current_end.row + 1 {
9250 push_region(start_row, end_row);
9251 start_row = Some(start);
9252 end_row = Some(end);
9253 } else {
9254 // Merge two hunks.
9255 *current_end = end;
9256 }
9257 } else {
9258 unreachable!();
9259 }
9260 }
9261 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
9262 push_region(start_row, end_row);
9263 results
9264 }
9265
9266 /// Get the text ranges corresponding to the redaction query
9267 pub fn redacted_ranges(
9268 &self,
9269 search_range: Range<Anchor>,
9270 display_snapshot: &DisplaySnapshot,
9271 cx: &WindowContext,
9272 ) -> Vec<Range<DisplayPoint>> {
9273 display_snapshot
9274 .buffer_snapshot
9275 .redacted_ranges(search_range, |file| {
9276 if let Some(file) = file {
9277 file.is_private()
9278 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
9279 } else {
9280 false
9281 }
9282 })
9283 .map(|range| {
9284 range.start.to_display_point(display_snapshot)
9285 ..range.end.to_display_point(display_snapshot)
9286 })
9287 .collect()
9288 }
9289
9290 pub fn highlight_text<T: 'static>(
9291 &mut self,
9292 ranges: Vec<Range<Anchor>>,
9293 style: HighlightStyle,
9294 cx: &mut ViewContext<Self>,
9295 ) {
9296 self.display_map.update(cx, |map, _| {
9297 map.highlight_text(TypeId::of::<T>(), ranges, style)
9298 });
9299 cx.notify();
9300 }
9301
9302 pub(crate) fn highlight_inlays<T: 'static>(
9303 &mut self,
9304 highlights: Vec<InlayHighlight>,
9305 style: HighlightStyle,
9306 cx: &mut ViewContext<Self>,
9307 ) {
9308 self.display_map.update(cx, |map, _| {
9309 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
9310 });
9311 cx.notify();
9312 }
9313
9314 pub fn text_highlights<'a, T: 'static>(
9315 &'a self,
9316 cx: &'a AppContext,
9317 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
9318 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
9319 }
9320
9321 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
9322 let cleared = self
9323 .display_map
9324 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
9325 if cleared {
9326 cx.notify();
9327 }
9328 }
9329
9330 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
9331 (self.read_only(cx) || self.blink_manager.read(cx).visible())
9332 && self.focus_handle.is_focused(cx)
9333 }
9334
9335 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
9336 cx.notify();
9337 }
9338
9339 fn on_buffer_event(
9340 &mut self,
9341 multibuffer: Model<MultiBuffer>,
9342 event: &multi_buffer::Event,
9343 cx: &mut ViewContext<Self>,
9344 ) {
9345 match event {
9346 multi_buffer::Event::Edited {
9347 singleton_buffer_edited,
9348 } => {
9349 self.scrollbar_marker_state.dirty = true;
9350 self.refresh_active_diagnostics(cx);
9351 self.refresh_code_actions(cx);
9352 if self.has_active_inline_completion(cx) {
9353 self.update_visible_inline_completion(cx);
9354 }
9355 cx.emit(EditorEvent::BufferEdited);
9356 cx.emit(SearchEvent::MatchesInvalidated);
9357
9358 if *singleton_buffer_edited {
9359 if let Some(project) = &self.project {
9360 let project = project.read(cx);
9361 let languages_affected = multibuffer
9362 .read(cx)
9363 .all_buffers()
9364 .into_iter()
9365 .filter_map(|buffer| {
9366 let buffer = buffer.read(cx);
9367 let language = buffer.language()?;
9368 if project.is_local()
9369 && project.language_servers_for_buffer(buffer, cx).count() == 0
9370 {
9371 None
9372 } else {
9373 Some(language)
9374 }
9375 })
9376 .cloned()
9377 .collect::<HashSet<_>>();
9378 if !languages_affected.is_empty() {
9379 self.refresh_inlay_hints(
9380 InlayHintRefreshReason::BufferEdited(languages_affected),
9381 cx,
9382 );
9383 }
9384 }
9385 }
9386
9387 let Some(project) = &self.project else { return };
9388 let telemetry = project.read(cx).client().telemetry().clone();
9389 telemetry.log_edit_event("editor");
9390 }
9391 multi_buffer::Event::ExcerptsAdded {
9392 buffer,
9393 predecessor,
9394 excerpts,
9395 } => {
9396 cx.emit(EditorEvent::ExcerptsAdded {
9397 buffer: buffer.clone(),
9398 predecessor: *predecessor,
9399 excerpts: excerpts.clone(),
9400 });
9401 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
9402 }
9403 multi_buffer::Event::ExcerptsRemoved { ids } => {
9404 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
9405 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
9406 }
9407 multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
9408 multi_buffer::Event::LanguageChanged => {
9409 cx.emit(EditorEvent::Reparsed);
9410 cx.notify();
9411 }
9412 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
9413 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
9414 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
9415 cx.emit(EditorEvent::TitleChanged)
9416 }
9417 multi_buffer::Event::DiffBaseChanged => {
9418 self.scrollbar_marker_state.dirty = true;
9419 cx.emit(EditorEvent::DiffBaseChanged);
9420 cx.notify();
9421 }
9422 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
9423 multi_buffer::Event::DiagnosticsUpdated => {
9424 self.refresh_active_diagnostics(cx);
9425 self.scrollbar_marker_state.dirty = true;
9426 cx.notify();
9427 }
9428 _ => {}
9429 };
9430 }
9431
9432 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
9433 cx.notify();
9434 }
9435
9436 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
9437 self.refresh_inline_completion(true, cx);
9438 self.refresh_inlay_hints(
9439 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
9440 self.selections.newest_anchor().head(),
9441 &self.buffer.read(cx).snapshot(cx),
9442 cx,
9443 )),
9444 cx,
9445 );
9446 let editor_settings = EditorSettings::get_global(cx);
9447 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
9448 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
9449 cx.notify();
9450 }
9451
9452 pub fn set_searchable(&mut self, searchable: bool) {
9453 self.searchable = searchable;
9454 }
9455
9456 pub fn searchable(&self) -> bool {
9457 self.searchable
9458 }
9459
9460 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
9461 self.open_excerpts_common(true, cx)
9462 }
9463
9464 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
9465 self.open_excerpts_common(false, cx)
9466 }
9467
9468 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
9469 let buffer = self.buffer.read(cx);
9470 if buffer.is_singleton() {
9471 cx.propagate();
9472 return;
9473 }
9474
9475 let Some(workspace) = self.workspace() else {
9476 cx.propagate();
9477 return;
9478 };
9479
9480 let mut new_selections_by_buffer = HashMap::default();
9481 for selection in self.selections.all::<usize>(cx) {
9482 for (buffer, mut range, _) in
9483 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
9484 {
9485 if selection.reversed {
9486 mem::swap(&mut range.start, &mut range.end);
9487 }
9488 new_selections_by_buffer
9489 .entry(buffer)
9490 .or_insert(Vec::new())
9491 .push(range)
9492 }
9493 }
9494
9495 // We defer the pane interaction because we ourselves are a workspace item
9496 // and activating a new item causes the pane to call a method on us reentrantly,
9497 // which panics if we're on the stack.
9498 cx.window_context().defer(move |cx| {
9499 workspace.update(cx, |workspace, cx| {
9500 let pane = if split {
9501 workspace.adjacent_pane(cx)
9502 } else {
9503 workspace.active_pane().clone()
9504 };
9505
9506 for (buffer, ranges) in new_selections_by_buffer {
9507 let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
9508 editor.update(cx, |editor, cx| {
9509 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
9510 s.select_ranges(ranges);
9511 });
9512 });
9513 }
9514 })
9515 });
9516 }
9517
9518 fn jump(
9519 &mut self,
9520 path: ProjectPath,
9521 position: Point,
9522 anchor: language::Anchor,
9523 offset_from_top: u32,
9524 cx: &mut ViewContext<Self>,
9525 ) {
9526 let workspace = self.workspace();
9527 cx.spawn(|_, mut cx| async move {
9528 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
9529 let editor = workspace.update(&mut cx, |workspace, cx| {
9530 // Reset the preview item id before opening the new item
9531 workspace.active_pane().update(cx, |pane, cx| {
9532 pane.set_preview_item_id(None, cx);
9533 });
9534 workspace.open_path_preview(path, None, true, true, cx)
9535 })?;
9536 let editor = editor
9537 .await?
9538 .downcast::<Editor>()
9539 .ok_or_else(|| anyhow!("opened item was not an editor"))?
9540 .downgrade();
9541 editor.update(&mut cx, |editor, cx| {
9542 let buffer = editor
9543 .buffer()
9544 .read(cx)
9545 .as_singleton()
9546 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
9547 let buffer = buffer.read(cx);
9548 let cursor = if buffer.can_resolve(&anchor) {
9549 language::ToPoint::to_point(&anchor, buffer)
9550 } else {
9551 buffer.clip_point(position, Bias::Left)
9552 };
9553
9554 let nav_history = editor.nav_history.take();
9555 editor.change_selections(
9556 Some(Autoscroll::top_relative(offset_from_top as usize)),
9557 cx,
9558 |s| {
9559 s.select_ranges([cursor..cursor]);
9560 },
9561 );
9562 editor.nav_history = nav_history;
9563
9564 anyhow::Ok(())
9565 })??;
9566
9567 anyhow::Ok(())
9568 })
9569 .detach_and_log_err(cx);
9570 }
9571
9572 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
9573 let snapshot = self.buffer.read(cx).read(cx);
9574 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
9575 Some(
9576 ranges
9577 .iter()
9578 .map(move |range| {
9579 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
9580 })
9581 .collect(),
9582 )
9583 }
9584
9585 fn selection_replacement_ranges(
9586 &self,
9587 range: Range<OffsetUtf16>,
9588 cx: &AppContext,
9589 ) -> Vec<Range<OffsetUtf16>> {
9590 let selections = self.selections.all::<OffsetUtf16>(cx);
9591 let newest_selection = selections
9592 .iter()
9593 .max_by_key(|selection| selection.id)
9594 .unwrap();
9595 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
9596 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
9597 let snapshot = self.buffer.read(cx).read(cx);
9598 selections
9599 .into_iter()
9600 .map(|mut selection| {
9601 selection.start.0 =
9602 (selection.start.0 as isize).saturating_add(start_delta) as usize;
9603 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
9604 snapshot.clip_offset_utf16(selection.start, Bias::Left)
9605 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
9606 })
9607 .collect()
9608 }
9609
9610 fn report_editor_event(
9611 &self,
9612 operation: &'static str,
9613 file_extension: Option<String>,
9614 cx: &AppContext,
9615 ) {
9616 if cfg!(any(test, feature = "test-support")) {
9617 return;
9618 }
9619
9620 let Some(project) = &self.project else { return };
9621
9622 // If None, we are in a file without an extension
9623 let file = self
9624 .buffer
9625 .read(cx)
9626 .as_singleton()
9627 .and_then(|b| b.read(cx).file());
9628 let file_extension = file_extension.or(file
9629 .as_ref()
9630 .and_then(|file| Path::new(file.file_name(cx)).extension())
9631 .and_then(|e| e.to_str())
9632 .map(|a| a.to_string()));
9633
9634 let vim_mode = cx
9635 .global::<SettingsStore>()
9636 .raw_user_settings()
9637 .get("vim_mode")
9638 == Some(&serde_json::Value::Bool(true));
9639 let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
9640 let copilot_enabled_for_language = self
9641 .buffer
9642 .read(cx)
9643 .settings_at(0, cx)
9644 .show_copilot_suggestions;
9645
9646 let telemetry = project.read(cx).client().telemetry().clone();
9647 telemetry.report_editor_event(
9648 file_extension,
9649 vim_mode,
9650 operation,
9651 copilot_enabled,
9652 copilot_enabled_for_language,
9653 )
9654 }
9655
9656 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
9657 /// with each line being an array of {text, highlight} objects.
9658 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
9659 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
9660 return;
9661 };
9662
9663 #[derive(Serialize)]
9664 struct Chunk<'a> {
9665 text: String,
9666 highlight: Option<&'a str>,
9667 }
9668
9669 let snapshot = buffer.read(cx).snapshot();
9670 let range = self
9671 .selected_text_range(cx)
9672 .and_then(|selected_range| {
9673 if selected_range.is_empty() {
9674 None
9675 } else {
9676 Some(selected_range)
9677 }
9678 })
9679 .unwrap_or_else(|| 0..snapshot.len());
9680
9681 let chunks = snapshot.chunks(range, true);
9682 let mut lines = Vec::new();
9683 let mut line: VecDeque<Chunk> = VecDeque::new();
9684
9685 let Some(style) = self.style.as_ref() else {
9686 return;
9687 };
9688
9689 for chunk in chunks {
9690 let highlight = chunk
9691 .syntax_highlight_id
9692 .and_then(|id| id.name(&style.syntax));
9693 let mut chunk_lines = chunk.text.split('\n').peekable();
9694 while let Some(text) = chunk_lines.next() {
9695 let mut merged_with_last_token = false;
9696 if let Some(last_token) = line.back_mut() {
9697 if last_token.highlight == highlight {
9698 last_token.text.push_str(text);
9699 merged_with_last_token = true;
9700 }
9701 }
9702
9703 if !merged_with_last_token {
9704 line.push_back(Chunk {
9705 text: text.into(),
9706 highlight,
9707 });
9708 }
9709
9710 if chunk_lines.peek().is_some() {
9711 if line.len() > 1 && line.front().unwrap().text.is_empty() {
9712 line.pop_front();
9713 }
9714 if line.len() > 1 && line.back().unwrap().text.is_empty() {
9715 line.pop_back();
9716 }
9717
9718 lines.push(mem::take(&mut line));
9719 }
9720 }
9721 }
9722
9723 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
9724 return;
9725 };
9726 cx.write_to_clipboard(ClipboardItem::new(lines));
9727 }
9728
9729 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
9730 &self.inlay_hint_cache
9731 }
9732
9733 pub fn replay_insert_event(
9734 &mut self,
9735 text: &str,
9736 relative_utf16_range: Option<Range<isize>>,
9737 cx: &mut ViewContext<Self>,
9738 ) {
9739 if !self.input_enabled {
9740 cx.emit(EditorEvent::InputIgnored { text: text.into() });
9741 return;
9742 }
9743 if let Some(relative_utf16_range) = relative_utf16_range {
9744 let selections = self.selections.all::<OffsetUtf16>(cx);
9745 self.change_selections(None, cx, |s| {
9746 let new_ranges = selections.into_iter().map(|range| {
9747 let start = OffsetUtf16(
9748 range
9749 .head()
9750 .0
9751 .saturating_add_signed(relative_utf16_range.start),
9752 );
9753 let end = OffsetUtf16(
9754 range
9755 .head()
9756 .0
9757 .saturating_add_signed(relative_utf16_range.end),
9758 );
9759 start..end
9760 });
9761 s.select_ranges(new_ranges);
9762 });
9763 }
9764
9765 self.handle_input(text, cx);
9766 }
9767
9768 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
9769 let Some(project) = self.project.as_ref() else {
9770 return false;
9771 };
9772 let project = project.read(cx);
9773
9774 let mut supports = false;
9775 self.buffer().read(cx).for_each_buffer(|buffer| {
9776 if !supports {
9777 supports = project
9778 .language_servers_for_buffer(buffer.read(cx), cx)
9779 .any(
9780 |(_, server)| match server.capabilities().inlay_hint_provider {
9781 Some(lsp::OneOf::Left(enabled)) => enabled,
9782 Some(lsp::OneOf::Right(_)) => true,
9783 None => false,
9784 },
9785 )
9786 }
9787 });
9788 supports
9789 }
9790
9791 pub fn focus(&self, cx: &mut WindowContext) {
9792 cx.focus(&self.focus_handle)
9793 }
9794
9795 pub fn is_focused(&self, cx: &WindowContext) -> bool {
9796 self.focus_handle.is_focused(cx)
9797 }
9798
9799 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
9800 cx.emit(EditorEvent::Focused);
9801
9802 if let Some(rename) = self.pending_rename.as_ref() {
9803 let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
9804 cx.focus(&rename_editor_focus_handle);
9805 } else {
9806 self.blink_manager.update(cx, BlinkManager::enable);
9807 self.show_cursor_names(cx);
9808 self.buffer.update(cx, |buffer, cx| {
9809 buffer.finalize_last_transaction(cx);
9810 if self.leader_peer_id.is_none() {
9811 buffer.set_active_selections(
9812 &self.selections.disjoint_anchors(),
9813 self.selections.line_mode,
9814 self.cursor_shape,
9815 cx,
9816 );
9817 }
9818 });
9819 }
9820 }
9821
9822 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
9823 self.blink_manager.update(cx, BlinkManager::disable);
9824 self.buffer
9825 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
9826 self.hide_context_menu(cx);
9827 hide_hover(self, cx);
9828 cx.emit(EditorEvent::Blurred);
9829 cx.notify();
9830 }
9831
9832 pub fn register_action<A: Action>(
9833 &mut self,
9834 listener: impl Fn(&A, &mut WindowContext) + 'static,
9835 ) -> &mut Self {
9836 let listener = Arc::new(listener);
9837
9838 self.editor_actions.push(Box::new(move |cx| {
9839 let _view = cx.view().clone();
9840 let cx = cx.window_context();
9841 let listener = listener.clone();
9842 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
9843 let action = action.downcast_ref().unwrap();
9844 if phase == DispatchPhase::Bubble {
9845 listener(action, cx)
9846 }
9847 })
9848 }));
9849 self
9850 }
9851}
9852
9853pub trait CollaborationHub {
9854 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
9855 fn user_participant_indices<'a>(
9856 &self,
9857 cx: &'a AppContext,
9858 ) -> &'a HashMap<u64, ParticipantIndex>;
9859 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
9860}
9861
9862impl CollaborationHub for Model<Project> {
9863 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
9864 self.read(cx).collaborators()
9865 }
9866
9867 fn user_participant_indices<'a>(
9868 &self,
9869 cx: &'a AppContext,
9870 ) -> &'a HashMap<u64, ParticipantIndex> {
9871 self.read(cx).user_store().read(cx).participant_indices()
9872 }
9873
9874 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
9875 let this = self.read(cx);
9876 let user_ids = this.collaborators().values().map(|c| c.user_id);
9877 this.user_store().read_with(cx, |user_store, cx| {
9878 user_store.participant_names(user_ids, cx)
9879 })
9880 }
9881}
9882
9883pub trait CompletionProvider {
9884 fn completions(
9885 &self,
9886 buffer: &Model<Buffer>,
9887 buffer_position: text::Anchor,
9888 cx: &mut ViewContext<Editor>,
9889 ) -> Task<Result<Vec<Completion>>>;
9890
9891 fn resolve_completions(
9892 &self,
9893 completion_indices: Vec<usize>,
9894 completions: Arc<RwLock<Box<[Completion]>>>,
9895 cx: &mut ViewContext<Editor>,
9896 ) -> Task<Result<bool>>;
9897
9898 fn apply_additional_edits_for_completion(
9899 &self,
9900 buffer: Model<Buffer>,
9901 completion: Completion,
9902 push_to_history: bool,
9903 cx: &mut ViewContext<Editor>,
9904 ) -> Task<Result<Option<language::Transaction>>>;
9905}
9906
9907impl CompletionProvider for Model<Project> {
9908 fn completions(
9909 &self,
9910 buffer: &Model<Buffer>,
9911 buffer_position: text::Anchor,
9912 cx: &mut ViewContext<Editor>,
9913 ) -> Task<Result<Vec<Completion>>> {
9914 self.update(cx, |project, cx| {
9915 project.completions(&buffer, buffer_position, cx)
9916 })
9917 }
9918
9919 fn resolve_completions(
9920 &self,
9921 completion_indices: Vec<usize>,
9922 completions: Arc<RwLock<Box<[Completion]>>>,
9923 cx: &mut ViewContext<Editor>,
9924 ) -> Task<Result<bool>> {
9925 self.update(cx, |project, cx| {
9926 project.resolve_completions(completion_indices, completions, cx)
9927 })
9928 }
9929
9930 fn apply_additional_edits_for_completion(
9931 &self,
9932 buffer: Model<Buffer>,
9933 completion: Completion,
9934 push_to_history: bool,
9935 cx: &mut ViewContext<Editor>,
9936 ) -> Task<Result<Option<language::Transaction>>> {
9937 self.update(cx, |project, cx| {
9938 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
9939 })
9940 }
9941}
9942
9943fn inlay_hint_settings(
9944 location: Anchor,
9945 snapshot: &MultiBufferSnapshot,
9946 cx: &mut ViewContext<'_, Editor>,
9947) -> InlayHintSettings {
9948 let file = snapshot.file_at(location);
9949 let language = snapshot.language_at(location);
9950 let settings = all_language_settings(file, cx);
9951 settings
9952 .language(language.map(|l| l.name()).as_deref())
9953 .inlay_hints
9954}
9955
9956fn consume_contiguous_rows(
9957 contiguous_row_selections: &mut Vec<Selection<Point>>,
9958 selection: &Selection<Point>,
9959 display_map: &DisplaySnapshot,
9960 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
9961) -> (u32, u32) {
9962 contiguous_row_selections.push(selection.clone());
9963 let start_row = selection.start.row;
9964 let mut end_row = ending_row(selection, display_map);
9965
9966 while let Some(next_selection) = selections.peek() {
9967 if next_selection.start.row <= end_row {
9968 end_row = ending_row(next_selection, display_map);
9969 contiguous_row_selections.push(selections.next().unwrap().clone());
9970 } else {
9971 break;
9972 }
9973 }
9974 (start_row, end_row)
9975}
9976
9977fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
9978 if next_selection.end.column > 0 || next_selection.is_empty() {
9979 display_map.next_line_boundary(next_selection.end).0.row + 1
9980 } else {
9981 next_selection.end.row
9982 }
9983}
9984
9985impl EditorSnapshot {
9986 pub fn remote_selections_in_range<'a>(
9987 &'a self,
9988 range: &'a Range<Anchor>,
9989 collaboration_hub: &dyn CollaborationHub,
9990 cx: &'a AppContext,
9991 ) -> impl 'a + Iterator<Item = RemoteSelection> {
9992 let participant_names = collaboration_hub.user_names(cx);
9993 let participant_indices = collaboration_hub.user_participant_indices(cx);
9994 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
9995 let collaborators_by_replica_id = collaborators_by_peer_id
9996 .iter()
9997 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
9998 .collect::<HashMap<_, _>>();
9999 self.buffer_snapshot
10000 .remote_selections_in_range(range)
10001 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10002 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10003 let participant_index = participant_indices.get(&collaborator.user_id).copied();
10004 let user_name = participant_names.get(&collaborator.user_id).cloned();
10005 Some(RemoteSelection {
10006 replica_id,
10007 selection,
10008 cursor_shape,
10009 line_mode,
10010 participant_index,
10011 peer_id: collaborator.peer_id,
10012 user_name,
10013 })
10014 })
10015 }
10016
10017 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10018 self.display_snapshot.buffer_snapshot.language_at(position)
10019 }
10020
10021 pub fn is_focused(&self) -> bool {
10022 self.is_focused
10023 }
10024
10025 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10026 self.placeholder_text.as_ref()
10027 }
10028
10029 pub fn scroll_position(&self) -> gpui::Point<f32> {
10030 self.scroll_anchor.scroll_position(&self.display_snapshot)
10031 }
10032
10033 pub fn gutter_dimensions(
10034 &self,
10035 font_id: FontId,
10036 font_size: Pixels,
10037 em_width: Pixels,
10038 max_line_number_width: Pixels,
10039 cx: &AppContext,
10040 ) -> GutterDimensions {
10041 if !self.show_gutter {
10042 return GutterDimensions::default();
10043 }
10044 let descent = cx.text_system().descent(font_id, font_size);
10045
10046 let show_git_gutter = matches!(
10047 ProjectSettings::get_global(cx).git.git_gutter,
10048 Some(GitGutterSetting::TrackedFiles)
10049 );
10050 let gutter_settings = EditorSettings::get_global(cx).gutter;
10051
10052 let line_gutter_width = if gutter_settings.line_numbers {
10053 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10054 let min_width_for_number_on_gutter = em_width * 4.0;
10055 max_line_number_width.max(min_width_for_number_on_gutter)
10056 } else {
10057 0.0.into()
10058 };
10059
10060 let git_blame_entries_width = self
10061 .show_git_blame
10062 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
10063
10064 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
10065 left_padding += if gutter_settings.code_actions {
10066 em_width * 3.0
10067 } else if show_git_gutter && gutter_settings.line_numbers {
10068 em_width * 2.0
10069 } else if show_git_gutter || gutter_settings.line_numbers {
10070 em_width
10071 } else {
10072 px(0.)
10073 };
10074
10075 let right_padding = if gutter_settings.folds && gutter_settings.line_numbers {
10076 em_width * 4.0
10077 } else if gutter_settings.folds {
10078 em_width * 3.0
10079 } else if gutter_settings.line_numbers {
10080 em_width
10081 } else {
10082 px(0.)
10083 };
10084
10085 GutterDimensions {
10086 left_padding,
10087 right_padding,
10088 width: line_gutter_width + left_padding + right_padding,
10089 margin: -descent,
10090 git_blame_entries_width,
10091 }
10092 }
10093}
10094
10095impl Deref for EditorSnapshot {
10096 type Target = DisplaySnapshot;
10097
10098 fn deref(&self) -> &Self::Target {
10099 &self.display_snapshot
10100 }
10101}
10102
10103#[derive(Clone, Debug, PartialEq, Eq)]
10104pub enum EditorEvent {
10105 InputIgnored {
10106 text: Arc<str>,
10107 },
10108 InputHandled {
10109 utf16_range_to_replace: Option<Range<isize>>,
10110 text: Arc<str>,
10111 },
10112 ExcerptsAdded {
10113 buffer: Model<Buffer>,
10114 predecessor: ExcerptId,
10115 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
10116 },
10117 ExcerptsRemoved {
10118 ids: Vec<ExcerptId>,
10119 },
10120 BufferEdited,
10121 Edited,
10122 Reparsed,
10123 Focused,
10124 Blurred,
10125 DirtyChanged,
10126 Saved,
10127 TitleChanged,
10128 DiffBaseChanged,
10129 SelectionsChanged {
10130 local: bool,
10131 },
10132 ScrollPositionChanged {
10133 local: bool,
10134 autoscroll: bool,
10135 },
10136 Closed,
10137 TransactionUndone {
10138 transaction_id: clock::Lamport,
10139 },
10140 TransactionBegun {
10141 transaction_id: clock::Lamport,
10142 },
10143}
10144
10145impl EventEmitter<EditorEvent> for Editor {}
10146
10147impl FocusableView for Editor {
10148 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
10149 self.focus_handle.clone()
10150 }
10151}
10152
10153impl Render for Editor {
10154 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
10155 let settings = ThemeSettings::get_global(cx);
10156 let text_style = match self.mode {
10157 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
10158 color: cx.theme().colors().editor_foreground,
10159 font_family: settings.ui_font.family.clone(),
10160 font_features: settings.ui_font.features,
10161 font_size: rems(0.875).into(),
10162 font_weight: FontWeight::NORMAL,
10163 font_style: FontStyle::Normal,
10164 line_height: relative(settings.buffer_line_height.value()),
10165 background_color: None,
10166 underline: None,
10167 strikethrough: None,
10168 white_space: WhiteSpace::Normal,
10169 },
10170
10171 EditorMode::Full => TextStyle {
10172 color: cx.theme().colors().editor_foreground,
10173 font_family: settings.buffer_font.family.clone(),
10174 font_features: settings.buffer_font.features,
10175 font_size: settings.buffer_font_size(cx).into(),
10176 font_weight: FontWeight::NORMAL,
10177 font_style: FontStyle::Normal,
10178 line_height: relative(settings.buffer_line_height.value()),
10179 background_color: None,
10180 underline: None,
10181 strikethrough: None,
10182 white_space: WhiteSpace::Normal,
10183 },
10184 };
10185
10186 let background = match self.mode {
10187 EditorMode::SingleLine => cx.theme().system().transparent,
10188 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
10189 EditorMode::Full => cx.theme().colors().editor_background,
10190 };
10191
10192 EditorElement::new(
10193 cx.view(),
10194 EditorStyle {
10195 background,
10196 local_player: cx.theme().players().local(),
10197 text: text_style,
10198 scrollbar_width: px(13.),
10199 syntax: cx.theme().syntax().clone(),
10200 status: cx.theme().status().clone(),
10201 inlay_hints_style: HighlightStyle {
10202 color: Some(cx.theme().status().hint),
10203 ..HighlightStyle::default()
10204 },
10205 suggestions_style: HighlightStyle {
10206 color: Some(cx.theme().status().predictive),
10207 ..HighlightStyle::default()
10208 },
10209 },
10210 )
10211 }
10212}
10213
10214impl ViewInputHandler for Editor {
10215 fn text_for_range(
10216 &mut self,
10217 range_utf16: Range<usize>,
10218 cx: &mut ViewContext<Self>,
10219 ) -> Option<String> {
10220 Some(
10221 self.buffer
10222 .read(cx)
10223 .read(cx)
10224 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
10225 .collect(),
10226 )
10227 }
10228
10229 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10230 // Prevent the IME menu from appearing when holding down an alphabetic key
10231 // while input is disabled.
10232 if !self.input_enabled {
10233 return None;
10234 }
10235
10236 let range = self.selections.newest::<OffsetUtf16>(cx).range();
10237 Some(range.start.0..range.end.0)
10238 }
10239
10240 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10241 let snapshot = self.buffer.read(cx).read(cx);
10242 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
10243 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
10244 }
10245
10246 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
10247 self.clear_highlights::<InputComposition>(cx);
10248 self.ime_transaction.take();
10249 }
10250
10251 fn replace_text_in_range(
10252 &mut self,
10253 range_utf16: Option<Range<usize>>,
10254 text: &str,
10255 cx: &mut ViewContext<Self>,
10256 ) {
10257 if !self.input_enabled {
10258 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10259 return;
10260 }
10261
10262 self.transact(cx, |this, cx| {
10263 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
10264 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10265 Some(this.selection_replacement_ranges(range_utf16, cx))
10266 } else {
10267 this.marked_text_ranges(cx)
10268 };
10269
10270 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
10271 let newest_selection_id = this.selections.newest_anchor().id;
10272 this.selections
10273 .all::<OffsetUtf16>(cx)
10274 .iter()
10275 .zip(ranges_to_replace.iter())
10276 .find_map(|(selection, range)| {
10277 if selection.id == newest_selection_id {
10278 Some(
10279 (range.start.0 as isize - selection.head().0 as isize)
10280 ..(range.end.0 as isize - selection.head().0 as isize),
10281 )
10282 } else {
10283 None
10284 }
10285 })
10286 });
10287
10288 cx.emit(EditorEvent::InputHandled {
10289 utf16_range_to_replace: range_to_replace,
10290 text: text.into(),
10291 });
10292
10293 if let Some(new_selected_ranges) = new_selected_ranges {
10294 this.change_selections(None, cx, |selections| {
10295 selections.select_ranges(new_selected_ranges)
10296 });
10297 this.backspace(&Default::default(), cx);
10298 }
10299
10300 this.handle_input(text, cx);
10301 });
10302
10303 if let Some(transaction) = self.ime_transaction {
10304 self.buffer.update(cx, |buffer, cx| {
10305 buffer.group_until_transaction(transaction, cx);
10306 });
10307 }
10308
10309 self.unmark_text(cx);
10310 }
10311
10312 fn replace_and_mark_text_in_range(
10313 &mut self,
10314 range_utf16: Option<Range<usize>>,
10315 text: &str,
10316 new_selected_range_utf16: Option<Range<usize>>,
10317 cx: &mut ViewContext<Self>,
10318 ) {
10319 if !self.input_enabled {
10320 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10321 return;
10322 }
10323
10324 let transaction = self.transact(cx, |this, cx| {
10325 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
10326 let snapshot = this.buffer.read(cx).read(cx);
10327 if let Some(relative_range_utf16) = range_utf16.as_ref() {
10328 for marked_range in &mut marked_ranges {
10329 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
10330 marked_range.start.0 += relative_range_utf16.start;
10331 marked_range.start =
10332 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
10333 marked_range.end =
10334 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
10335 }
10336 }
10337 Some(marked_ranges)
10338 } else if let Some(range_utf16) = range_utf16 {
10339 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10340 Some(this.selection_replacement_ranges(range_utf16, cx))
10341 } else {
10342 None
10343 };
10344
10345 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
10346 let newest_selection_id = this.selections.newest_anchor().id;
10347 this.selections
10348 .all::<OffsetUtf16>(cx)
10349 .iter()
10350 .zip(ranges_to_replace.iter())
10351 .find_map(|(selection, range)| {
10352 if selection.id == newest_selection_id {
10353 Some(
10354 (range.start.0 as isize - selection.head().0 as isize)
10355 ..(range.end.0 as isize - selection.head().0 as isize),
10356 )
10357 } else {
10358 None
10359 }
10360 })
10361 });
10362
10363 cx.emit(EditorEvent::InputHandled {
10364 utf16_range_to_replace: range_to_replace,
10365 text: text.into(),
10366 });
10367
10368 if let Some(ranges) = ranges_to_replace {
10369 this.change_selections(None, cx, |s| s.select_ranges(ranges));
10370 }
10371
10372 let marked_ranges = {
10373 let snapshot = this.buffer.read(cx).read(cx);
10374 this.selections
10375 .disjoint_anchors()
10376 .iter()
10377 .map(|selection| {
10378 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
10379 })
10380 .collect::<Vec<_>>()
10381 };
10382
10383 if text.is_empty() {
10384 this.unmark_text(cx);
10385 } else {
10386 this.highlight_text::<InputComposition>(
10387 marked_ranges.clone(),
10388 HighlightStyle {
10389 underline: Some(UnderlineStyle {
10390 thickness: px(1.),
10391 color: None,
10392 wavy: false,
10393 }),
10394 ..Default::default()
10395 },
10396 cx,
10397 );
10398 }
10399
10400 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
10401 let use_autoclose = this.use_autoclose;
10402 this.set_use_autoclose(false);
10403 this.handle_input(text, cx);
10404 this.set_use_autoclose(use_autoclose);
10405
10406 if let Some(new_selected_range) = new_selected_range_utf16 {
10407 let snapshot = this.buffer.read(cx).read(cx);
10408 let new_selected_ranges = marked_ranges
10409 .into_iter()
10410 .map(|marked_range| {
10411 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
10412 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
10413 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
10414 snapshot.clip_offset_utf16(new_start, Bias::Left)
10415 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
10416 })
10417 .collect::<Vec<_>>();
10418
10419 drop(snapshot);
10420 this.change_selections(None, cx, |selections| {
10421 selections.select_ranges(new_selected_ranges)
10422 });
10423 }
10424 });
10425
10426 self.ime_transaction = self.ime_transaction.or(transaction);
10427 if let Some(transaction) = self.ime_transaction {
10428 self.buffer.update(cx, |buffer, cx| {
10429 buffer.group_until_transaction(transaction, cx);
10430 });
10431 }
10432
10433 if self.text_highlights::<InputComposition>(cx).is_none() {
10434 self.ime_transaction.take();
10435 }
10436 }
10437
10438 fn bounds_for_range(
10439 &mut self,
10440 range_utf16: Range<usize>,
10441 element_bounds: gpui::Bounds<Pixels>,
10442 cx: &mut ViewContext<Self>,
10443 ) -> Option<gpui::Bounds<Pixels>> {
10444 let text_layout_details = self.text_layout_details(cx);
10445 let style = &text_layout_details.editor_style;
10446 let font_id = cx.text_system().resolve_font(&style.text.font());
10447 let font_size = style.text.font_size.to_pixels(cx.rem_size());
10448 let line_height = style.text.line_height_in_pixels(cx.rem_size());
10449 let em_width = cx
10450 .text_system()
10451 .typographic_bounds(font_id, font_size, 'm')
10452 .unwrap()
10453 .size
10454 .width;
10455
10456 let snapshot = self.snapshot(cx);
10457 let scroll_position = snapshot.scroll_position();
10458 let scroll_left = scroll_position.x * em_width;
10459
10460 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
10461 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
10462 + self.gutter_width;
10463 let y = line_height * (start.row() as f32 - scroll_position.y);
10464
10465 Some(Bounds {
10466 origin: element_bounds.origin + point(x, y),
10467 size: size(em_width, line_height),
10468 })
10469 }
10470}
10471
10472trait SelectionExt {
10473 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
10474 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
10475 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
10476 fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
10477 -> Range<u32>;
10478}
10479
10480impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
10481 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
10482 let start = self.start.to_point(buffer);
10483 let end = self.end.to_point(buffer);
10484 if self.reversed {
10485 end..start
10486 } else {
10487 start..end
10488 }
10489 }
10490
10491 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
10492 let start = self.start.to_offset(buffer);
10493 let end = self.end.to_offset(buffer);
10494 if self.reversed {
10495 end..start
10496 } else {
10497 start..end
10498 }
10499 }
10500
10501 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
10502 let start = self
10503 .start
10504 .to_point(&map.buffer_snapshot)
10505 .to_display_point(map);
10506 let end = self
10507 .end
10508 .to_point(&map.buffer_snapshot)
10509 .to_display_point(map);
10510 if self.reversed {
10511 end..start
10512 } else {
10513 start..end
10514 }
10515 }
10516
10517 fn spanned_rows(
10518 &self,
10519 include_end_if_at_line_start: bool,
10520 map: &DisplaySnapshot,
10521 ) -> Range<u32> {
10522 let start = self.start.to_point(&map.buffer_snapshot);
10523 let mut end = self.end.to_point(&map.buffer_snapshot);
10524 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
10525 end.row -= 1;
10526 }
10527
10528 let buffer_start = map.prev_line_boundary(start).0;
10529 let buffer_end = map.next_line_boundary(end).0;
10530 buffer_start.row..buffer_end.row + 1
10531 }
10532}
10533
10534impl<T: InvalidationRegion> InvalidationStack<T> {
10535 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
10536 where
10537 S: Clone + ToOffset,
10538 {
10539 while let Some(region) = self.last() {
10540 let all_selections_inside_invalidation_ranges =
10541 if selections.len() == region.ranges().len() {
10542 selections
10543 .iter()
10544 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
10545 .all(|(selection, invalidation_range)| {
10546 let head = selection.head().to_offset(buffer);
10547 invalidation_range.start <= head && invalidation_range.end >= head
10548 })
10549 } else {
10550 false
10551 };
10552
10553 if all_selections_inside_invalidation_ranges {
10554 break;
10555 } else {
10556 self.pop();
10557 }
10558 }
10559 }
10560}
10561
10562impl<T> Default for InvalidationStack<T> {
10563 fn default() -> Self {
10564 Self(Default::default())
10565 }
10566}
10567
10568impl<T> Deref for InvalidationStack<T> {
10569 type Target = Vec<T>;
10570
10571 fn deref(&self) -> &Self::Target {
10572 &self.0
10573 }
10574}
10575
10576impl<T> DerefMut for InvalidationStack<T> {
10577 fn deref_mut(&mut self) -> &mut Self::Target {
10578 &mut self.0
10579 }
10580}
10581
10582impl InvalidationRegion for SnippetState {
10583 fn ranges(&self) -> &[Range<Anchor>] {
10584 &self.ranges[self.active_index]
10585 }
10586}
10587
10588pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
10589 let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
10590
10591 Box::new(move |cx: &mut BlockContext| {
10592 let group_id: SharedString = cx.block_id.to_string().into();
10593
10594 let mut text_style = cx.text_style().clone();
10595 text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
10596
10597 let multi_line_diagnostic = diagnostic.message.contains('\n');
10598
10599 let buttons = |diagnostic: &Diagnostic, block_id: usize| {
10600 if multi_line_diagnostic {
10601 v_flex()
10602 } else {
10603 h_flex()
10604 }
10605 .children(diagnostic.is_primary.then(|| {
10606 IconButton::new(("close-block", block_id), IconName::XCircle)
10607 .icon_color(Color::Muted)
10608 .size(ButtonSize::Compact)
10609 .style(ButtonStyle::Transparent)
10610 .visible_on_hover(group_id.clone())
10611 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
10612 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
10613 }))
10614 .child(
10615 IconButton::new(("copy-block", block_id), IconName::Copy)
10616 .icon_color(Color::Muted)
10617 .size(ButtonSize::Compact)
10618 .style(ButtonStyle::Transparent)
10619 .visible_on_hover(group_id.clone())
10620 .on_click({
10621 let message = diagnostic.message.clone();
10622 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
10623 })
10624 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
10625 )
10626 };
10627
10628 let icon_size = buttons(&diagnostic, cx.block_id)
10629 .into_any_element()
10630 .measure(AvailableSpace::min_size(), cx);
10631
10632 h_flex()
10633 .id(cx.block_id)
10634 .group(group_id.clone())
10635 .relative()
10636 .size_full()
10637 .pl(cx.gutter_dimensions.width)
10638 .w(cx.max_width + cx.gutter_dimensions.width)
10639 .child(
10640 div()
10641 .flex()
10642 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
10643 .flex_shrink(),
10644 )
10645 .child(buttons(&diagnostic, cx.block_id))
10646 .child(div().flex().flex_shrink_0().child(
10647 StyledText::new(text_without_backticks.clone()).with_highlights(
10648 &text_style,
10649 code_ranges.iter().map(|range| {
10650 (
10651 range.clone(),
10652 HighlightStyle {
10653 font_weight: Some(FontWeight::BOLD),
10654 ..Default::default()
10655 },
10656 )
10657 }),
10658 ),
10659 ))
10660 .into_any_element()
10661 })
10662}
10663
10664pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
10665 let mut text_without_backticks = String::new();
10666 let mut code_ranges = Vec::new();
10667
10668 if let Some(source) = &diagnostic.source {
10669 text_without_backticks.push_str(&source);
10670 code_ranges.push(0..source.len());
10671 text_without_backticks.push_str(": ");
10672 }
10673
10674 let mut prev_offset = 0;
10675 let mut in_code_block = false;
10676 for (ix, _) in diagnostic
10677 .message
10678 .match_indices('`')
10679 .chain([(diagnostic.message.len(), "")])
10680 {
10681 let prev_len = text_without_backticks.len();
10682 text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
10683 prev_offset = ix + 1;
10684 if in_code_block {
10685 code_ranges.push(prev_len..text_without_backticks.len());
10686 in_code_block = false;
10687 } else {
10688 in_code_block = true;
10689 }
10690 }
10691
10692 (text_without_backticks.into(), code_ranges)
10693}
10694
10695fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
10696 match (severity, valid) {
10697 (DiagnosticSeverity::ERROR, true) => colors.error,
10698 (DiagnosticSeverity::ERROR, false) => colors.error,
10699 (DiagnosticSeverity::WARNING, true) => colors.warning,
10700 (DiagnosticSeverity::WARNING, false) => colors.warning,
10701 (DiagnosticSeverity::INFORMATION, true) => colors.info,
10702 (DiagnosticSeverity::INFORMATION, false) => colors.info,
10703 (DiagnosticSeverity::HINT, true) => colors.info,
10704 (DiagnosticSeverity::HINT, false) => colors.info,
10705 _ => colors.ignored,
10706 }
10707}
10708
10709pub fn styled_runs_for_code_label<'a>(
10710 label: &'a CodeLabel,
10711 syntax_theme: &'a theme::SyntaxTheme,
10712) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
10713 let fade_out = HighlightStyle {
10714 fade_out: Some(0.35),
10715 ..Default::default()
10716 };
10717
10718 let mut prev_end = label.filter_range.end;
10719 label
10720 .runs
10721 .iter()
10722 .enumerate()
10723 .flat_map(move |(ix, (range, highlight_id))| {
10724 let style = if let Some(style) = highlight_id.style(syntax_theme) {
10725 style
10726 } else {
10727 return Default::default();
10728 };
10729 let mut muted_style = style;
10730 muted_style.highlight(fade_out);
10731
10732 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
10733 if range.start >= label.filter_range.end {
10734 if range.start > prev_end {
10735 runs.push((prev_end..range.start, fade_out));
10736 }
10737 runs.push((range.clone(), muted_style));
10738 } else if range.end <= label.filter_range.end {
10739 runs.push((range.clone(), style));
10740 } else {
10741 runs.push((range.start..label.filter_range.end, style));
10742 runs.push((label.filter_range.end..range.end, muted_style));
10743 }
10744 prev_end = cmp::max(prev_end, range.end);
10745
10746 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
10747 runs.push((prev_end..label.text.len(), fade_out));
10748 }
10749
10750 runs
10751 })
10752}
10753
10754pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
10755 let mut prev_index = 0;
10756 let mut prev_codepoint: Option<char> = None;
10757 text.char_indices()
10758 .chain([(text.len(), '\0')])
10759 .filter_map(move |(index, codepoint)| {
10760 let prev_codepoint = prev_codepoint.replace(codepoint)?;
10761 let is_boundary = index == text.len()
10762 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
10763 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
10764 if is_boundary {
10765 let chunk = &text[prev_index..index];
10766 prev_index = index;
10767 Some(chunk)
10768 } else {
10769 None
10770 }
10771 })
10772}
10773
10774trait RangeToAnchorExt {
10775 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
10776}
10777
10778impl<T: ToOffset> RangeToAnchorExt for Range<T> {
10779 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
10780 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
10781 }
10782}