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