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