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