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