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