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