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