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: Vec<(TaskSourceKind, TaskTemplate)>,
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 ) -> (Vec<(TaskSourceKind, TaskTemplate)>, Option<WorktreeId>) {
7729 let Some(project) = self.project.as_ref() else {
7730 return Default::default();
7731 };
7732 let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
7733 let worktree_id = project
7734 .buffer_for_id(runnable.buffer)
7735 .and_then(|buffer| buffer.read(cx).file())
7736 .map(|file| WorktreeId::from_usize(file.worktree_id()));
7737
7738 (project.task_inventory().clone(), worktree_id)
7739 });
7740
7741 let inventory = inventory.read(cx);
7742 let tags = mem::take(&mut runnable.tags);
7743 let mut tags: Vec<_> = tags
7744 .into_iter()
7745 .flat_map(|tag| {
7746 let tag = tag.0.clone();
7747 inventory
7748 .list_tasks(Some(runnable.language.clone()), worktree_id)
7749 .into_iter()
7750 .filter(move |(_, template)| {
7751 template.tags.iter().any(|source_tag| source_tag == &tag)
7752 })
7753 })
7754 .sorted_by_key(|(kind, _)| kind.to_owned())
7755 .collect();
7756 if let Some((leading_tag_source, _)) = tags.first() {
7757 // Strongest source wins; if we have worktree tag binding, prefer that to
7758 // global and language bindings;
7759 // if we have a global binding, prefer that to language binding.
7760 let first_mismatch = tags
7761 .iter()
7762 .position(|(tag_source, _)| tag_source != leading_tag_source);
7763 if let Some(index) = first_mismatch {
7764 tags.truncate(index);
7765 }
7766 }
7767
7768 (tags, worktree_id)
7769 }
7770
7771 pub fn move_to_enclosing_bracket(
7772 &mut self,
7773 _: &MoveToEnclosingBracket,
7774 cx: &mut ViewContext<Self>,
7775 ) {
7776 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7777 s.move_offsets_with(|snapshot, selection| {
7778 let Some(enclosing_bracket_ranges) =
7779 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
7780 else {
7781 return;
7782 };
7783
7784 let mut best_length = usize::MAX;
7785 let mut best_inside = false;
7786 let mut best_in_bracket_range = false;
7787 let mut best_destination = None;
7788 for (open, close) in enclosing_bracket_ranges {
7789 let close = close.to_inclusive();
7790 let length = close.end() - open.start;
7791 let inside = selection.start >= open.end && selection.end <= *close.start();
7792 let in_bracket_range = open.to_inclusive().contains(&selection.head())
7793 || close.contains(&selection.head());
7794
7795 // If best is next to a bracket and current isn't, skip
7796 if !in_bracket_range && best_in_bracket_range {
7797 continue;
7798 }
7799
7800 // Prefer smaller lengths unless best is inside and current isn't
7801 if length > best_length && (best_inside || !inside) {
7802 continue;
7803 }
7804
7805 best_length = length;
7806 best_inside = inside;
7807 best_in_bracket_range = in_bracket_range;
7808 best_destination = Some(
7809 if close.contains(&selection.start) && close.contains(&selection.end) {
7810 if inside {
7811 open.end
7812 } else {
7813 open.start
7814 }
7815 } else {
7816 if inside {
7817 *close.start()
7818 } else {
7819 *close.end()
7820 }
7821 },
7822 );
7823 }
7824
7825 if let Some(destination) = best_destination {
7826 selection.collapse_to(destination, SelectionGoal::None);
7827 }
7828 })
7829 });
7830 }
7831
7832 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
7833 self.end_selection(cx);
7834 self.selection_history.mode = SelectionHistoryMode::Undoing;
7835 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
7836 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7837 self.select_next_state = entry.select_next_state;
7838 self.select_prev_state = entry.select_prev_state;
7839 self.add_selections_state = entry.add_selections_state;
7840 self.request_autoscroll(Autoscroll::newest(), cx);
7841 }
7842 self.selection_history.mode = SelectionHistoryMode::Normal;
7843 }
7844
7845 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
7846 self.end_selection(cx);
7847 self.selection_history.mode = SelectionHistoryMode::Redoing;
7848 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
7849 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7850 self.select_next_state = entry.select_next_state;
7851 self.select_prev_state = entry.select_prev_state;
7852 self.add_selections_state = entry.add_selections_state;
7853 self.request_autoscroll(Autoscroll::newest(), cx);
7854 }
7855 self.selection_history.mode = SelectionHistoryMode::Normal;
7856 }
7857
7858 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
7859 let selections = self.selections.disjoint_anchors();
7860
7861 let lines = if action.lines == 0 { 3 } else { action.lines };
7862
7863 self.buffer.update(cx, |buffer, cx| {
7864 buffer.expand_excerpts(
7865 selections
7866 .into_iter()
7867 .map(|selection| selection.head().excerpt_id)
7868 .dedup(),
7869 lines,
7870 cx,
7871 )
7872 })
7873 }
7874
7875 pub fn expand_excerpt(&mut self, excerpt: ExcerptId, cx: &mut ViewContext<Self>) {
7876 self.buffer
7877 .update(cx, |buffer, cx| buffer.expand_excerpts([excerpt], 3, cx))
7878 }
7879
7880 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
7881 self.go_to_diagnostic_impl(Direction::Next, cx)
7882 }
7883
7884 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
7885 self.go_to_diagnostic_impl(Direction::Prev, cx)
7886 }
7887
7888 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
7889 let buffer = self.buffer.read(cx).snapshot(cx);
7890 let selection = self.selections.newest::<usize>(cx);
7891
7892 // If there is an active Diagnostic Popover jump to its diagnostic instead.
7893 if direction == Direction::Next {
7894 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
7895 let (group_id, jump_to) = popover.activation_info();
7896 if self.activate_diagnostics(group_id, cx) {
7897 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7898 let mut new_selection = s.newest_anchor().clone();
7899 new_selection.collapse_to(jump_to, SelectionGoal::None);
7900 s.select_anchors(vec![new_selection.clone()]);
7901 });
7902 }
7903 return;
7904 }
7905 }
7906
7907 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
7908 active_diagnostics
7909 .primary_range
7910 .to_offset(&buffer)
7911 .to_inclusive()
7912 });
7913 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
7914 if active_primary_range.contains(&selection.head()) {
7915 *active_primary_range.end()
7916 } else {
7917 selection.head()
7918 }
7919 } else {
7920 selection.head()
7921 };
7922 let snapshot = self.snapshot(cx);
7923 loop {
7924 let mut diagnostics = if direction == Direction::Prev {
7925 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
7926 } else {
7927 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
7928 }
7929 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
7930 let group = diagnostics.find_map(|entry| {
7931 if entry.diagnostic.is_primary
7932 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
7933 && !entry.range.is_empty()
7934 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
7935 && !entry.range.contains(&search_start)
7936 {
7937 Some((entry.range, entry.diagnostic.group_id))
7938 } else {
7939 None
7940 }
7941 });
7942
7943 if let Some((primary_range, group_id)) = group {
7944 if self.activate_diagnostics(group_id, cx) {
7945 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7946 s.select(vec![Selection {
7947 id: selection.id,
7948 start: primary_range.start,
7949 end: primary_range.start,
7950 reversed: false,
7951 goal: SelectionGoal::None,
7952 }]);
7953 });
7954 }
7955 break;
7956 } else {
7957 // Cycle around to the start of the buffer, potentially moving back to the start of
7958 // the currently active diagnostic.
7959 active_primary_range.take();
7960 if direction == Direction::Prev {
7961 if search_start == buffer.len() {
7962 break;
7963 } else {
7964 search_start = buffer.len();
7965 }
7966 } else if search_start == 0 {
7967 break;
7968 } else {
7969 search_start = 0;
7970 }
7971 }
7972 }
7973 }
7974
7975 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
7976 let snapshot = self
7977 .display_map
7978 .update(cx, |display_map, cx| display_map.snapshot(cx));
7979 let selection = self.selections.newest::<Point>(cx);
7980
7981 if !self.seek_in_direction(
7982 &snapshot,
7983 selection.head(),
7984 false,
7985 snapshot
7986 .buffer_snapshot
7987 .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
7988 cx,
7989 ) {
7990 let wrapped_point = Point::zero();
7991 self.seek_in_direction(
7992 &snapshot,
7993 wrapped_point,
7994 true,
7995 snapshot
7996 .buffer_snapshot
7997 .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
7998 cx,
7999 );
8000 }
8001 }
8002
8003 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8004 let snapshot = self
8005 .display_map
8006 .update(cx, |display_map, cx| display_map.snapshot(cx));
8007 let selection = self.selections.newest::<Point>(cx);
8008
8009 if !self.seek_in_direction(
8010 &snapshot,
8011 selection.head(),
8012 false,
8013 snapshot
8014 .buffer_snapshot
8015 .git_diff_hunks_in_range_rev(0..selection.head().row),
8016 cx,
8017 ) {
8018 let wrapped_point = snapshot.buffer_snapshot.max_point();
8019 self.seek_in_direction(
8020 &snapshot,
8021 wrapped_point,
8022 true,
8023 snapshot
8024 .buffer_snapshot
8025 .git_diff_hunks_in_range_rev(0..wrapped_point.row),
8026 cx,
8027 );
8028 }
8029 }
8030
8031 fn seek_in_direction(
8032 &mut self,
8033 snapshot: &DisplaySnapshot,
8034 initial_point: Point,
8035 is_wrapped: bool,
8036 hunks: impl Iterator<Item = DiffHunk<u32>>,
8037 cx: &mut ViewContext<Editor>,
8038 ) -> bool {
8039 let display_point = initial_point.to_display_point(snapshot);
8040 let mut hunks = hunks
8041 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8042 .filter(|hunk| {
8043 if is_wrapped {
8044 true
8045 } else {
8046 !hunk.contains_display_row(display_point.row())
8047 }
8048 })
8049 .dedup();
8050
8051 if let Some(hunk) = hunks.next() {
8052 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8053 let row = hunk.start_display_row();
8054 let point = DisplayPoint::new(row, 0);
8055 s.select_display_ranges([point..point]);
8056 });
8057
8058 true
8059 } else {
8060 false
8061 }
8062 }
8063
8064 pub fn go_to_definition(
8065 &mut self,
8066 _: &GoToDefinition,
8067 cx: &mut ViewContext<Self>,
8068 ) -> Task<Result<bool>> {
8069 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8070 }
8071
8072 pub fn go_to_implementation(
8073 &mut self,
8074 _: &GoToImplementation,
8075 cx: &mut ViewContext<Self>,
8076 ) -> Task<Result<bool>> {
8077 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8078 }
8079
8080 pub fn go_to_implementation_split(
8081 &mut self,
8082 _: &GoToImplementationSplit,
8083 cx: &mut ViewContext<Self>,
8084 ) -> Task<Result<bool>> {
8085 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8086 }
8087
8088 pub fn go_to_type_definition(
8089 &mut self,
8090 _: &GoToTypeDefinition,
8091 cx: &mut ViewContext<Self>,
8092 ) -> Task<Result<bool>> {
8093 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8094 }
8095
8096 pub fn go_to_definition_split(
8097 &mut self,
8098 _: &GoToDefinitionSplit,
8099 cx: &mut ViewContext<Self>,
8100 ) -> Task<Result<bool>> {
8101 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
8102 }
8103
8104 pub fn go_to_type_definition_split(
8105 &mut self,
8106 _: &GoToTypeDefinitionSplit,
8107 cx: &mut ViewContext<Self>,
8108 ) -> Task<Result<bool>> {
8109 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
8110 }
8111
8112 fn go_to_definition_of_kind(
8113 &mut self,
8114 kind: GotoDefinitionKind,
8115 split: bool,
8116 cx: &mut ViewContext<Self>,
8117 ) -> Task<Result<bool>> {
8118 let Some(workspace) = self.workspace() else {
8119 return Task::ready(Ok(false));
8120 };
8121 let buffer = self.buffer.read(cx);
8122 let head = self.selections.newest::<usize>(cx).head();
8123 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
8124 text_anchor
8125 } else {
8126 return Task::ready(Ok(false));
8127 };
8128
8129 let project = workspace.read(cx).project().clone();
8130 let definitions = project.update(cx, |project, cx| match kind {
8131 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
8132 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
8133 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
8134 });
8135
8136 cx.spawn(|editor, mut cx| async move {
8137 let definitions = definitions.await?;
8138 let navigated = editor
8139 .update(&mut cx, |editor, cx| {
8140 editor.navigate_to_hover_links(
8141 Some(kind),
8142 definitions
8143 .into_iter()
8144 .filter(|location| {
8145 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
8146 })
8147 .map(HoverLink::Text)
8148 .collect::<Vec<_>>(),
8149 split,
8150 cx,
8151 )
8152 })?
8153 .await?;
8154 anyhow::Ok(navigated)
8155 })
8156 }
8157
8158 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
8159 let position = self.selections.newest_anchor().head();
8160 let Some((buffer, buffer_position)) =
8161 self.buffer.read(cx).text_anchor_for_position(position, cx)
8162 else {
8163 return;
8164 };
8165
8166 cx.spawn(|editor, mut cx| async move {
8167 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
8168 editor.update(&mut cx, |_, cx| {
8169 cx.open_url(&url);
8170 })
8171 } else {
8172 Ok(())
8173 }
8174 })
8175 .detach();
8176 }
8177
8178 pub(crate) fn navigate_to_hover_links(
8179 &mut self,
8180 kind: Option<GotoDefinitionKind>,
8181 mut definitions: Vec<HoverLink>,
8182 split: bool,
8183 cx: &mut ViewContext<Editor>,
8184 ) -> Task<Result<bool>> {
8185 // If there is one definition, just open it directly
8186 if definitions.len() == 1 {
8187 let definition = definitions.pop().unwrap();
8188 let target_task = match definition {
8189 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8190 HoverLink::InlayHint(lsp_location, server_id) => {
8191 self.compute_target_location(lsp_location, server_id, cx)
8192 }
8193 HoverLink::Url(url) => {
8194 cx.open_url(&url);
8195 Task::ready(Ok(None))
8196 }
8197 };
8198 cx.spawn(|editor, mut cx| async move {
8199 let target = target_task.await.context("target resolution task")?;
8200 if let Some(target) = target {
8201 editor.update(&mut cx, |editor, cx| {
8202 let Some(workspace) = editor.workspace() else {
8203 return false;
8204 };
8205 let pane = workspace.read(cx).active_pane().clone();
8206
8207 let range = target.range.to_offset(target.buffer.read(cx));
8208 let range = editor.range_for_match(&range);
8209 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
8210 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
8211 s.select_ranges([range]);
8212 });
8213 } else {
8214 cx.window_context().defer(move |cx| {
8215 let target_editor: View<Self> =
8216 workspace.update(cx, |workspace, cx| {
8217 let pane = if split {
8218 workspace.adjacent_pane(cx)
8219 } else {
8220 workspace.active_pane().clone()
8221 };
8222
8223 workspace.open_project_item(pane, target.buffer.clone(), cx)
8224 });
8225 target_editor.update(cx, |target_editor, cx| {
8226 // When selecting a definition in a different buffer, disable the nav history
8227 // to avoid creating a history entry at the previous cursor location.
8228 pane.update(cx, |pane, _| pane.disable_history());
8229 target_editor.change_selections(
8230 Some(Autoscroll::focused()),
8231 cx,
8232 |s| {
8233 s.select_ranges([range]);
8234 },
8235 );
8236 pane.update(cx, |pane, _| pane.enable_history());
8237 });
8238 });
8239 }
8240 true
8241 })
8242 } else {
8243 Ok(false)
8244 }
8245 })
8246 } else if !definitions.is_empty() {
8247 let replica_id = self.replica_id(cx);
8248 cx.spawn(|editor, mut cx| async move {
8249 let (title, location_tasks, workspace) = editor
8250 .update(&mut cx, |editor, cx| {
8251 let tab_kind = match kind {
8252 Some(GotoDefinitionKind::Implementation) => "Implementations",
8253 _ => "Definitions",
8254 };
8255 let title = definitions
8256 .iter()
8257 .find_map(|definition| match definition {
8258 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
8259 let buffer = origin.buffer.read(cx);
8260 format!(
8261 "{} for {}",
8262 tab_kind,
8263 buffer
8264 .text_for_range(origin.range.clone())
8265 .collect::<String>()
8266 )
8267 }),
8268 HoverLink::InlayHint(_, _) => None,
8269 HoverLink::Url(_) => None,
8270 })
8271 .unwrap_or(tab_kind.to_string());
8272 let location_tasks = definitions
8273 .into_iter()
8274 .map(|definition| match definition {
8275 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8276 HoverLink::InlayHint(lsp_location, server_id) => {
8277 editor.compute_target_location(lsp_location, server_id, cx)
8278 }
8279 HoverLink::Url(_) => Task::ready(Ok(None)),
8280 })
8281 .collect::<Vec<_>>();
8282 (title, location_tasks, editor.workspace().clone())
8283 })
8284 .context("location tasks preparation")?;
8285
8286 let locations = futures::future::join_all(location_tasks)
8287 .await
8288 .into_iter()
8289 .filter_map(|location| location.transpose())
8290 .collect::<Result<_>>()
8291 .context("location tasks")?;
8292
8293 let Some(workspace) = workspace else {
8294 return Ok(false);
8295 };
8296 let opened = workspace
8297 .update(&mut cx, |workspace, cx| {
8298 Self::open_locations_in_multibuffer(
8299 workspace, locations, replica_id, title, split, cx,
8300 )
8301 })
8302 .ok();
8303
8304 anyhow::Ok(opened.is_some())
8305 })
8306 } else {
8307 Task::ready(Ok(false))
8308 }
8309 }
8310
8311 fn compute_target_location(
8312 &self,
8313 lsp_location: lsp::Location,
8314 server_id: LanguageServerId,
8315 cx: &mut ViewContext<Editor>,
8316 ) -> Task<anyhow::Result<Option<Location>>> {
8317 let Some(project) = self.project.clone() else {
8318 return Task::Ready(Some(Ok(None)));
8319 };
8320
8321 cx.spawn(move |editor, mut cx| async move {
8322 let location_task = editor.update(&mut cx, |editor, cx| {
8323 project.update(cx, |project, cx| {
8324 let language_server_name =
8325 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
8326 project
8327 .language_server_for_buffer(buffer.read(cx), server_id, cx)
8328 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
8329 });
8330 language_server_name.map(|language_server_name| {
8331 project.open_local_buffer_via_lsp(
8332 lsp_location.uri.clone(),
8333 server_id,
8334 language_server_name,
8335 cx,
8336 )
8337 })
8338 })
8339 })?;
8340 let location = match location_task {
8341 Some(task) => Some({
8342 let target_buffer_handle = task.await.context("open local buffer")?;
8343 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
8344 let target_start = target_buffer
8345 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
8346 let target_end = target_buffer
8347 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
8348 target_buffer.anchor_after(target_start)
8349 ..target_buffer.anchor_before(target_end)
8350 })?;
8351 Location {
8352 buffer: target_buffer_handle,
8353 range,
8354 }
8355 }),
8356 None => None,
8357 };
8358 Ok(location)
8359 })
8360 }
8361
8362 pub fn find_all_references(
8363 &mut self,
8364 _: &FindAllReferences,
8365 cx: &mut ViewContext<Self>,
8366 ) -> Option<Task<Result<()>>> {
8367 let multi_buffer = self.buffer.read(cx);
8368 let selection = self.selections.newest::<usize>(cx);
8369 let head = selection.head();
8370
8371 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
8372 let head_anchor = multi_buffer_snapshot.anchor_at(
8373 head,
8374 if head < selection.tail() {
8375 Bias::Right
8376 } else {
8377 Bias::Left
8378 },
8379 );
8380
8381 match self
8382 .find_all_references_task_sources
8383 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
8384 {
8385 Ok(_) => {
8386 log::info!(
8387 "Ignoring repeated FindAllReferences invocation with the position of already running task"
8388 );
8389 return None;
8390 }
8391 Err(i) => {
8392 self.find_all_references_task_sources.insert(i, head_anchor);
8393 }
8394 }
8395
8396 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
8397 let replica_id = self.replica_id(cx);
8398 let workspace = self.workspace()?;
8399 let project = workspace.read(cx).project().clone();
8400 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
8401 Some(cx.spawn(|editor, mut cx| async move {
8402 let _cleanup = defer({
8403 let mut cx = cx.clone();
8404 move || {
8405 let _ = editor.update(&mut cx, |editor, _| {
8406 if let Ok(i) =
8407 editor
8408 .find_all_references_task_sources
8409 .binary_search_by(|anchor| {
8410 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
8411 })
8412 {
8413 editor.find_all_references_task_sources.remove(i);
8414 }
8415 });
8416 }
8417 });
8418
8419 let locations = references.await?;
8420 if locations.is_empty() {
8421 return anyhow::Ok(());
8422 }
8423
8424 workspace.update(&mut cx, |workspace, cx| {
8425 let title = locations
8426 .first()
8427 .as_ref()
8428 .map(|location| {
8429 let buffer = location.buffer.read(cx);
8430 format!(
8431 "References to `{}`",
8432 buffer
8433 .text_for_range(location.range.clone())
8434 .collect::<String>()
8435 )
8436 })
8437 .unwrap();
8438 Self::open_locations_in_multibuffer(
8439 workspace, locations, replica_id, title, false, cx,
8440 );
8441 })
8442 }))
8443 }
8444
8445 /// Opens a multibuffer with the given project locations in it
8446 pub fn open_locations_in_multibuffer(
8447 workspace: &mut Workspace,
8448 mut locations: Vec<Location>,
8449 replica_id: ReplicaId,
8450 title: String,
8451 split: bool,
8452 cx: &mut ViewContext<Workspace>,
8453 ) {
8454 // If there are multiple definitions, open them in a multibuffer
8455 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
8456 let mut locations = locations.into_iter().peekable();
8457 let mut ranges_to_highlight = Vec::new();
8458 let capability = workspace.project().read(cx).capability();
8459
8460 let excerpt_buffer = cx.new_model(|cx| {
8461 let mut multibuffer = MultiBuffer::new(replica_id, capability);
8462 while let Some(location) = locations.next() {
8463 let buffer = location.buffer.read(cx);
8464 let mut ranges_for_buffer = Vec::new();
8465 let range = location.range.to_offset(buffer);
8466 ranges_for_buffer.push(range.clone());
8467
8468 while let Some(next_location) = locations.peek() {
8469 if next_location.buffer == location.buffer {
8470 ranges_for_buffer.push(next_location.range.to_offset(buffer));
8471 locations.next();
8472 } else {
8473 break;
8474 }
8475 }
8476
8477 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
8478 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
8479 location.buffer.clone(),
8480 ranges_for_buffer,
8481 DEFAULT_MULTIBUFFER_CONTEXT,
8482 cx,
8483 ))
8484 }
8485
8486 multibuffer.with_title(title)
8487 });
8488
8489 let editor = cx.new_view(|cx| {
8490 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
8491 });
8492 editor.update(cx, |editor, cx| {
8493 editor.highlight_background::<Self>(
8494 &ranges_to_highlight,
8495 |theme| theme.editor_highlighted_line_background,
8496 cx,
8497 );
8498 });
8499
8500 let item = Box::new(editor);
8501 let item_id = item.item_id();
8502
8503 if split {
8504 workspace.split_item(SplitDirection::Right, item.clone(), cx);
8505 } else {
8506 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
8507 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
8508 pane.close_current_preview_item(cx)
8509 } else {
8510 None
8511 }
8512 });
8513 workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
8514 }
8515 workspace.active_pane().update(cx, |pane, cx| {
8516 pane.set_preview_item_id(Some(item_id), cx);
8517 });
8518 }
8519
8520 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8521 use language::ToOffset as _;
8522
8523 let project = self.project.clone()?;
8524 let selection = self.selections.newest_anchor().clone();
8525 let (cursor_buffer, cursor_buffer_position) = self
8526 .buffer
8527 .read(cx)
8528 .text_anchor_for_position(selection.head(), cx)?;
8529 let (tail_buffer, cursor_buffer_position_end) = self
8530 .buffer
8531 .read(cx)
8532 .text_anchor_for_position(selection.tail(), cx)?;
8533 if tail_buffer != cursor_buffer {
8534 return None;
8535 }
8536
8537 let snapshot = cursor_buffer.read(cx).snapshot();
8538 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
8539 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
8540 let prepare_rename = project.update(cx, |project, cx| {
8541 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
8542 });
8543 drop(snapshot);
8544
8545 Some(cx.spawn(|this, mut cx| async move {
8546 let rename_range = if let Some(range) = prepare_rename.await? {
8547 Some(range)
8548 } else {
8549 this.update(&mut cx, |this, cx| {
8550 let buffer = this.buffer.read(cx).snapshot(cx);
8551 let mut buffer_highlights = this
8552 .document_highlights_for_position(selection.head(), &buffer)
8553 .filter(|highlight| {
8554 highlight.start.excerpt_id == selection.head().excerpt_id
8555 && highlight.end.excerpt_id == selection.head().excerpt_id
8556 });
8557 buffer_highlights
8558 .next()
8559 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
8560 })?
8561 };
8562 if let Some(rename_range) = rename_range {
8563 this.update(&mut cx, |this, cx| {
8564 let snapshot = cursor_buffer.read(cx).snapshot();
8565 let rename_buffer_range = rename_range.to_offset(&snapshot);
8566 let cursor_offset_in_rename_range =
8567 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
8568 let cursor_offset_in_rename_range_end =
8569 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
8570
8571 this.take_rename(false, cx);
8572 let buffer = this.buffer.read(cx).read(cx);
8573 let cursor_offset = selection.head().to_offset(&buffer);
8574 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
8575 let rename_end = rename_start + rename_buffer_range.len();
8576 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
8577 let mut old_highlight_id = None;
8578 let old_name: Arc<str> = buffer
8579 .chunks(rename_start..rename_end, true)
8580 .map(|chunk| {
8581 if old_highlight_id.is_none() {
8582 old_highlight_id = chunk.syntax_highlight_id;
8583 }
8584 chunk.text
8585 })
8586 .collect::<String>()
8587 .into();
8588
8589 drop(buffer);
8590
8591 // Position the selection in the rename editor so that it matches the current selection.
8592 this.show_local_selections = false;
8593 let rename_editor = cx.new_view(|cx| {
8594 let mut editor = Editor::single_line(cx);
8595 editor.buffer.update(cx, |buffer, cx| {
8596 buffer.edit([(0..0, old_name.clone())], None, cx)
8597 });
8598 let rename_selection_range = match cursor_offset_in_rename_range
8599 .cmp(&cursor_offset_in_rename_range_end)
8600 {
8601 Ordering::Equal => {
8602 editor.select_all(&SelectAll, cx);
8603 return editor;
8604 }
8605 Ordering::Less => {
8606 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
8607 }
8608 Ordering::Greater => {
8609 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
8610 }
8611 };
8612 if rename_selection_range.end > old_name.len() {
8613 editor.select_all(&SelectAll, cx);
8614 } else {
8615 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
8616 s.select_ranges([rename_selection_range]);
8617 });
8618 }
8619 editor
8620 });
8621
8622 let write_highlights =
8623 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
8624 let read_highlights =
8625 this.clear_background_highlights::<DocumentHighlightRead>(cx);
8626 let ranges = write_highlights
8627 .iter()
8628 .flat_map(|(_, ranges)| ranges.iter())
8629 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
8630 .cloned()
8631 .collect();
8632
8633 this.highlight_text::<Rename>(
8634 ranges,
8635 HighlightStyle {
8636 fade_out: Some(0.6),
8637 ..Default::default()
8638 },
8639 cx,
8640 );
8641 let rename_focus_handle = rename_editor.focus_handle(cx);
8642 cx.focus(&rename_focus_handle);
8643 let block_id = this.insert_blocks(
8644 [BlockProperties {
8645 style: BlockStyle::Flex,
8646 position: range.start,
8647 height: 1,
8648 render: Box::new({
8649 let rename_editor = rename_editor.clone();
8650 move |cx: &mut BlockContext| {
8651 let mut text_style = cx.editor_style.text.clone();
8652 if let Some(highlight_style) = old_highlight_id
8653 .and_then(|h| h.style(&cx.editor_style.syntax))
8654 {
8655 text_style = text_style.highlight(highlight_style);
8656 }
8657 div()
8658 .pl(cx.anchor_x)
8659 .child(EditorElement::new(
8660 &rename_editor,
8661 EditorStyle {
8662 background: cx.theme().system().transparent,
8663 local_player: cx.editor_style.local_player,
8664 text: text_style,
8665 scrollbar_width: cx.editor_style.scrollbar_width,
8666 syntax: cx.editor_style.syntax.clone(),
8667 status: cx.editor_style.status.clone(),
8668 inlay_hints_style: HighlightStyle {
8669 color: Some(cx.theme().status().hint),
8670 font_weight: Some(FontWeight::BOLD),
8671 ..HighlightStyle::default()
8672 },
8673 suggestions_style: HighlightStyle {
8674 color: Some(cx.theme().status().predictive),
8675 ..HighlightStyle::default()
8676 },
8677 },
8678 ))
8679 .into_any_element()
8680 }
8681 }),
8682 disposition: BlockDisposition::Below,
8683 }],
8684 Some(Autoscroll::fit()),
8685 cx,
8686 )[0];
8687 this.pending_rename = Some(RenameState {
8688 range,
8689 old_name,
8690 editor: rename_editor,
8691 block_id,
8692 });
8693 })?;
8694 }
8695
8696 Ok(())
8697 }))
8698 }
8699
8700 pub fn confirm_rename(
8701 &mut self,
8702 _: &ConfirmRename,
8703 cx: &mut ViewContext<Self>,
8704 ) -> Option<Task<Result<()>>> {
8705 let rename = self.take_rename(false, cx)?;
8706 let workspace = self.workspace()?;
8707 let (start_buffer, start) = self
8708 .buffer
8709 .read(cx)
8710 .text_anchor_for_position(rename.range.start, cx)?;
8711 let (end_buffer, end) = self
8712 .buffer
8713 .read(cx)
8714 .text_anchor_for_position(rename.range.end, cx)?;
8715 if start_buffer != end_buffer {
8716 return None;
8717 }
8718
8719 let buffer = start_buffer;
8720 let range = start..end;
8721 let old_name = rename.old_name;
8722 let new_name = rename.editor.read(cx).text(cx);
8723
8724 let rename = workspace
8725 .read(cx)
8726 .project()
8727 .clone()
8728 .update(cx, |project, cx| {
8729 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
8730 });
8731 let workspace = workspace.downgrade();
8732
8733 Some(cx.spawn(|editor, mut cx| async move {
8734 let project_transaction = rename.await?;
8735 Self::open_project_transaction(
8736 &editor,
8737 workspace,
8738 project_transaction,
8739 format!("Rename: {} → {}", old_name, new_name),
8740 cx.clone(),
8741 )
8742 .await?;
8743
8744 editor.update(&mut cx, |editor, cx| {
8745 editor.refresh_document_highlights(cx);
8746 })?;
8747 Ok(())
8748 }))
8749 }
8750
8751 fn take_rename(
8752 &mut self,
8753 moving_cursor: bool,
8754 cx: &mut ViewContext<Self>,
8755 ) -> Option<RenameState> {
8756 let rename = self.pending_rename.take()?;
8757 if rename.editor.focus_handle(cx).is_focused(cx) {
8758 cx.focus(&self.focus_handle);
8759 }
8760
8761 self.remove_blocks(
8762 [rename.block_id].into_iter().collect(),
8763 Some(Autoscroll::fit()),
8764 cx,
8765 );
8766 self.clear_highlights::<Rename>(cx);
8767 self.show_local_selections = true;
8768
8769 if moving_cursor {
8770 let rename_editor = rename.editor.read(cx);
8771 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
8772
8773 // Update the selection to match the position of the selection inside
8774 // the rename editor.
8775 let snapshot = self.buffer.read(cx).read(cx);
8776 let rename_range = rename.range.to_offset(&snapshot);
8777 let cursor_in_editor = snapshot
8778 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
8779 .min(rename_range.end);
8780 drop(snapshot);
8781
8782 self.change_selections(None, cx, |s| {
8783 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
8784 });
8785 } else {
8786 self.refresh_document_highlights(cx);
8787 }
8788
8789 Some(rename)
8790 }
8791
8792 pub fn pending_rename(&self) -> Option<&RenameState> {
8793 self.pending_rename.as_ref()
8794 }
8795
8796 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8797 let project = match &self.project {
8798 Some(project) => project.clone(),
8799 None => return None,
8800 };
8801
8802 Some(self.perform_format(project, FormatTrigger::Manual, cx))
8803 }
8804
8805 fn perform_format(
8806 &mut self,
8807 project: Model<Project>,
8808 trigger: FormatTrigger,
8809 cx: &mut ViewContext<Self>,
8810 ) -> Task<Result<()>> {
8811 let buffer = self.buffer().clone();
8812 let mut buffers = buffer.read(cx).all_buffers();
8813 if trigger == FormatTrigger::Save {
8814 buffers.retain(|buffer| buffer.read(cx).is_dirty());
8815 }
8816
8817 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
8818 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
8819
8820 cx.spawn(|_, mut cx| async move {
8821 let transaction = futures::select_biased! {
8822 () = timeout => {
8823 log::warn!("timed out waiting for formatting");
8824 None
8825 }
8826 transaction = format.log_err().fuse() => transaction,
8827 };
8828
8829 buffer
8830 .update(&mut cx, |buffer, cx| {
8831 if let Some(transaction) = transaction {
8832 if !buffer.is_singleton() {
8833 buffer.push_transaction(&transaction.0, cx);
8834 }
8835 }
8836
8837 cx.notify();
8838 })
8839 .ok();
8840
8841 Ok(())
8842 })
8843 }
8844
8845 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
8846 if let Some(project) = self.project.clone() {
8847 self.buffer.update(cx, |multi_buffer, cx| {
8848 project.update(cx, |project, cx| {
8849 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
8850 });
8851 })
8852 }
8853 }
8854
8855 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
8856 cx.show_character_palette();
8857 }
8858
8859 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
8860 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
8861 let buffer = self.buffer.read(cx).snapshot(cx);
8862 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
8863 let is_valid = buffer
8864 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
8865 .any(|entry| {
8866 entry.diagnostic.is_primary
8867 && !entry.range.is_empty()
8868 && entry.range.start == primary_range_start
8869 && entry.diagnostic.message == active_diagnostics.primary_message
8870 });
8871
8872 if is_valid != active_diagnostics.is_valid {
8873 active_diagnostics.is_valid = is_valid;
8874 let mut new_styles = HashMap::default();
8875 for (block_id, diagnostic) in &active_diagnostics.blocks {
8876 new_styles.insert(
8877 *block_id,
8878 diagnostic_block_renderer(diagnostic.clone(), is_valid),
8879 );
8880 }
8881 self.display_map
8882 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
8883 }
8884 }
8885 }
8886
8887 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
8888 self.dismiss_diagnostics(cx);
8889 let snapshot = self.snapshot(cx);
8890 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
8891 let buffer = self.buffer.read(cx).snapshot(cx);
8892
8893 let mut primary_range = None;
8894 let mut primary_message = None;
8895 let mut group_end = Point::zero();
8896 let diagnostic_group = buffer
8897 .diagnostic_group::<Point>(group_id)
8898 .filter_map(|entry| {
8899 if snapshot.is_line_folded(entry.range.start.row)
8900 && (entry.range.start.row == entry.range.end.row
8901 || snapshot.is_line_folded(entry.range.end.row))
8902 {
8903 return None;
8904 }
8905 if entry.range.end > group_end {
8906 group_end = entry.range.end;
8907 }
8908 if entry.diagnostic.is_primary {
8909 primary_range = Some(entry.range.clone());
8910 primary_message = Some(entry.diagnostic.message.clone());
8911 }
8912 Some(entry)
8913 })
8914 .collect::<Vec<_>>();
8915 let primary_range = primary_range?;
8916 let primary_message = primary_message?;
8917 let primary_range =
8918 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
8919
8920 let blocks = display_map
8921 .insert_blocks(
8922 diagnostic_group.iter().map(|entry| {
8923 let diagnostic = entry.diagnostic.clone();
8924 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
8925 BlockProperties {
8926 style: BlockStyle::Fixed,
8927 position: buffer.anchor_after(entry.range.start),
8928 height: message_height,
8929 render: diagnostic_block_renderer(diagnostic, true),
8930 disposition: BlockDisposition::Below,
8931 }
8932 }),
8933 cx,
8934 )
8935 .into_iter()
8936 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
8937 .collect();
8938
8939 Some(ActiveDiagnosticGroup {
8940 primary_range,
8941 primary_message,
8942 blocks,
8943 is_valid: true,
8944 })
8945 });
8946 self.active_diagnostics.is_some()
8947 }
8948
8949 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
8950 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
8951 self.display_map.update(cx, |display_map, cx| {
8952 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
8953 });
8954 cx.notify();
8955 }
8956 }
8957
8958 pub fn set_selections_from_remote(
8959 &mut self,
8960 selections: Vec<Selection<Anchor>>,
8961 pending_selection: Option<Selection<Anchor>>,
8962 cx: &mut ViewContext<Self>,
8963 ) {
8964 let old_cursor_position = self.selections.newest_anchor().head();
8965 self.selections.change_with(cx, |s| {
8966 s.select_anchors(selections);
8967 if let Some(pending_selection) = pending_selection {
8968 s.set_pending(pending_selection, SelectMode::Character);
8969 } else {
8970 s.clear_pending();
8971 }
8972 });
8973 self.selections_did_change(false, &old_cursor_position, cx);
8974 }
8975
8976 fn push_to_selection_history(&mut self) {
8977 self.selection_history.push(SelectionHistoryEntry {
8978 selections: self.selections.disjoint_anchors(),
8979 select_next_state: self.select_next_state.clone(),
8980 select_prev_state: self.select_prev_state.clone(),
8981 add_selections_state: self.add_selections_state.clone(),
8982 });
8983 }
8984
8985 pub fn transact(
8986 &mut self,
8987 cx: &mut ViewContext<Self>,
8988 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
8989 ) -> Option<TransactionId> {
8990 self.start_transaction_at(Instant::now(), cx);
8991 update(self, cx);
8992 self.end_transaction_at(Instant::now(), cx)
8993 }
8994
8995 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
8996 self.end_selection(cx);
8997 if let Some(tx_id) = self
8998 .buffer
8999 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9000 {
9001 self.selection_history
9002 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9003 cx.emit(EditorEvent::TransactionBegun {
9004 transaction_id: tx_id,
9005 })
9006 }
9007 }
9008
9009 fn end_transaction_at(
9010 &mut self,
9011 now: Instant,
9012 cx: &mut ViewContext<Self>,
9013 ) -> Option<TransactionId> {
9014 if let Some(tx_id) = self
9015 .buffer
9016 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9017 {
9018 if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
9019 *end_selections = Some(self.selections.disjoint_anchors());
9020 } else {
9021 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9022 }
9023
9024 cx.emit(EditorEvent::Edited);
9025 Some(tx_id)
9026 } else {
9027 None
9028 }
9029 }
9030
9031 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9032 let mut fold_ranges = Vec::new();
9033
9034 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9035
9036 let selections = self.selections.all_adjusted(cx);
9037 for selection in selections {
9038 let range = selection.range().sorted();
9039 let buffer_start_row = range.start.row;
9040
9041 for row in (0..=range.end.row).rev() {
9042 let fold_range = display_map.foldable_range(row);
9043
9044 if let Some(fold_range) = fold_range {
9045 if fold_range.end.row >= buffer_start_row {
9046 fold_ranges.push(fold_range);
9047 if row <= range.start.row {
9048 break;
9049 }
9050 }
9051 }
9052 }
9053 }
9054
9055 self.fold_ranges(fold_ranges, true, cx);
9056 }
9057
9058 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
9059 let buffer_row = fold_at.buffer_row;
9060 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9061
9062 if let Some(fold_range) = display_map.foldable_range(buffer_row) {
9063 let autoscroll = self
9064 .selections
9065 .all::<Point>(cx)
9066 .iter()
9067 .any(|selection| fold_range.overlaps(&selection.range()));
9068
9069 self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
9070 }
9071 }
9072
9073 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
9074 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9075 let buffer = &display_map.buffer_snapshot;
9076 let selections = self.selections.all::<Point>(cx);
9077 let ranges = selections
9078 .iter()
9079 .map(|s| {
9080 let range = s.display_range(&display_map).sorted();
9081 let mut start = range.start.to_point(&display_map);
9082 let mut end = range.end.to_point(&display_map);
9083 start.column = 0;
9084 end.column = buffer.line_len(end.row);
9085 start..end
9086 })
9087 .collect::<Vec<_>>();
9088
9089 self.unfold_ranges(ranges, true, true, cx);
9090 }
9091
9092 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
9093 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9094
9095 let intersection_range = Point::new(unfold_at.buffer_row, 0)
9096 ..Point::new(
9097 unfold_at.buffer_row,
9098 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
9099 );
9100
9101 let autoscroll = self
9102 .selections
9103 .all::<Point>(cx)
9104 .iter()
9105 .any(|selection| selection.range().overlaps(&intersection_range));
9106
9107 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
9108 }
9109
9110 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
9111 let selections = self.selections.all::<Point>(cx);
9112 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9113 let line_mode = self.selections.line_mode;
9114 let ranges = selections.into_iter().map(|s| {
9115 if line_mode {
9116 let start = Point::new(s.start.row, 0);
9117 let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
9118 start..end
9119 } else {
9120 s.start..s.end
9121 }
9122 });
9123 self.fold_ranges(ranges, true, cx);
9124 }
9125
9126 pub fn fold_ranges<T: ToOffset + Clone>(
9127 &mut self,
9128 ranges: impl IntoIterator<Item = Range<T>>,
9129 auto_scroll: bool,
9130 cx: &mut ViewContext<Self>,
9131 ) {
9132 let mut fold_ranges = Vec::new();
9133 let mut buffers_affected = HashMap::default();
9134 let multi_buffer = self.buffer().read(cx);
9135 for range in ranges {
9136 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
9137 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9138 };
9139 fold_ranges.push(range);
9140 }
9141
9142 let mut ranges = fold_ranges.into_iter().peekable();
9143 if ranges.peek().is_some() {
9144 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
9145
9146 if auto_scroll {
9147 self.request_autoscroll(Autoscroll::fit(), cx);
9148 }
9149
9150 for buffer in buffers_affected.into_values() {
9151 self.sync_expanded_diff_hunks(buffer, cx);
9152 }
9153
9154 cx.notify();
9155
9156 if let Some(active_diagnostics) = self.active_diagnostics.take() {
9157 // Clear diagnostics block when folding a range that contains it.
9158 let snapshot = self.snapshot(cx);
9159 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
9160 drop(snapshot);
9161 self.active_diagnostics = Some(active_diagnostics);
9162 self.dismiss_diagnostics(cx);
9163 } else {
9164 self.active_diagnostics = Some(active_diagnostics);
9165 }
9166 }
9167 }
9168 }
9169
9170 pub fn unfold_ranges<T: ToOffset + Clone>(
9171 &mut self,
9172 ranges: impl IntoIterator<Item = Range<T>>,
9173 inclusive: bool,
9174 auto_scroll: bool,
9175 cx: &mut ViewContext<Self>,
9176 ) {
9177 let mut unfold_ranges = Vec::new();
9178 let mut buffers_affected = HashMap::default();
9179 let multi_buffer = self.buffer().read(cx);
9180 for range in ranges {
9181 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
9182 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9183 };
9184 unfold_ranges.push(range);
9185 }
9186
9187 let mut ranges = unfold_ranges.into_iter().peekable();
9188 if ranges.peek().is_some() {
9189 self.display_map
9190 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
9191 if auto_scroll {
9192 self.request_autoscroll(Autoscroll::fit(), cx);
9193 }
9194
9195 for buffer in buffers_affected.into_values() {
9196 self.sync_expanded_diff_hunks(buffer, cx);
9197 }
9198
9199 cx.notify();
9200 }
9201 }
9202
9203 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
9204 if hovered != self.gutter_hovered {
9205 self.gutter_hovered = hovered;
9206 cx.notify();
9207 }
9208 }
9209
9210 pub fn insert_blocks(
9211 &mut self,
9212 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
9213 autoscroll: Option<Autoscroll>,
9214 cx: &mut ViewContext<Self>,
9215 ) -> Vec<BlockId> {
9216 let blocks = self
9217 .display_map
9218 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
9219 if let Some(autoscroll) = autoscroll {
9220 self.request_autoscroll(autoscroll, cx);
9221 }
9222 blocks
9223 }
9224
9225 pub fn replace_blocks(
9226 &mut self,
9227 blocks: HashMap<BlockId, RenderBlock>,
9228 autoscroll: Option<Autoscroll>,
9229 cx: &mut ViewContext<Self>,
9230 ) {
9231 self.display_map
9232 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
9233 if let Some(autoscroll) = autoscroll {
9234 self.request_autoscroll(autoscroll, cx);
9235 }
9236 }
9237
9238 pub fn remove_blocks(
9239 &mut self,
9240 block_ids: HashSet<BlockId>,
9241 autoscroll: Option<Autoscroll>,
9242 cx: &mut ViewContext<Self>,
9243 ) {
9244 self.display_map.update(cx, |display_map, cx| {
9245 display_map.remove_blocks(block_ids, cx)
9246 });
9247 if let Some(autoscroll) = autoscroll {
9248 self.request_autoscroll(autoscroll, cx);
9249 }
9250 }
9251
9252 pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
9253 self.display_map
9254 .update(cx, |map, cx| map.snapshot(cx))
9255 .longest_row()
9256 }
9257
9258 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
9259 self.display_map
9260 .update(cx, |map, cx| map.snapshot(cx))
9261 .max_point()
9262 }
9263
9264 pub fn text(&self, cx: &AppContext) -> String {
9265 self.buffer.read(cx).read(cx).text()
9266 }
9267
9268 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
9269 let text = self.text(cx);
9270 let text = text.trim();
9271
9272 if text.is_empty() {
9273 return None;
9274 }
9275
9276 Some(text.to_string())
9277 }
9278
9279 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
9280 self.transact(cx, |this, cx| {
9281 this.buffer
9282 .read(cx)
9283 .as_singleton()
9284 .expect("you can only call set_text on editors for singleton buffers")
9285 .update(cx, |buffer, cx| buffer.set_text(text, cx));
9286 });
9287 }
9288
9289 pub fn display_text(&self, cx: &mut AppContext) -> String {
9290 self.display_map
9291 .update(cx, |map, cx| map.snapshot(cx))
9292 .text()
9293 }
9294
9295 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
9296 let mut wrap_guides = smallvec::smallvec![];
9297
9298 if self.show_wrap_guides == Some(false) {
9299 return wrap_guides;
9300 }
9301
9302 let settings = self.buffer.read(cx).settings_at(0, cx);
9303 if settings.show_wrap_guides {
9304 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
9305 wrap_guides.push((soft_wrap as usize, true));
9306 }
9307 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
9308 }
9309
9310 wrap_guides
9311 }
9312
9313 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
9314 let settings = self.buffer.read(cx).settings_at(0, cx);
9315 let mode = self
9316 .soft_wrap_mode_override
9317 .unwrap_or_else(|| settings.soft_wrap);
9318 match mode {
9319 language_settings::SoftWrap::None => SoftWrap::None,
9320 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
9321 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
9322 language_settings::SoftWrap::PreferredLineLength => {
9323 SoftWrap::Column(settings.preferred_line_length)
9324 }
9325 }
9326 }
9327
9328 pub fn set_soft_wrap_mode(
9329 &mut self,
9330 mode: language_settings::SoftWrap,
9331 cx: &mut ViewContext<Self>,
9332 ) {
9333 self.soft_wrap_mode_override = Some(mode);
9334 cx.notify();
9335 }
9336
9337 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
9338 let rem_size = cx.rem_size();
9339 self.display_map.update(cx, |map, cx| {
9340 map.set_font(
9341 style.text.font(),
9342 style.text.font_size.to_pixels(rem_size),
9343 cx,
9344 )
9345 });
9346 self.style = Some(style);
9347 }
9348
9349 pub fn style(&self) -> Option<&EditorStyle> {
9350 self.style.as_ref()
9351 }
9352
9353 // Called by the element. This method is not designed to be called outside of the editor
9354 // element's layout code because it does not notify when rewrapping is computed synchronously.
9355 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
9356 self.display_map
9357 .update(cx, |map, cx| map.set_wrap_width(width, cx))
9358 }
9359
9360 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
9361 if self.soft_wrap_mode_override.is_some() {
9362 self.soft_wrap_mode_override.take();
9363 } else {
9364 let soft_wrap = match self.soft_wrap_mode(cx) {
9365 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
9366 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
9367 language_settings::SoftWrap::PreferLine
9368 }
9369 };
9370 self.soft_wrap_mode_override = Some(soft_wrap);
9371 }
9372 cx.notify();
9373 }
9374
9375 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
9376 let mut editor_settings = EditorSettings::get_global(cx).clone();
9377 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
9378 EditorSettings::override_global(editor_settings, cx);
9379 }
9380
9381 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
9382 self.show_gutter = show_gutter;
9383 cx.notify();
9384 }
9385
9386 pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
9387 self.show_wrap_guides = Some(show_gutter);
9388 cx.notify();
9389 }
9390
9391 pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
9392 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9393 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9394 cx.reveal_path(&file.abs_path(cx));
9395 }
9396 }
9397 }
9398
9399 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
9400 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9401 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9402 if let Some(path) = file.abs_path(cx).to_str() {
9403 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
9404 }
9405 }
9406 }
9407 }
9408
9409 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
9410 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9411 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9412 if let Some(path) = file.path().to_str() {
9413 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
9414 }
9415 }
9416 }
9417 }
9418
9419 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
9420 self.show_git_blame_gutter = !self.show_git_blame_gutter;
9421
9422 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
9423 self.start_git_blame(true, cx);
9424 }
9425
9426 cx.notify();
9427 }
9428
9429 pub fn toggle_git_blame_inline(
9430 &mut self,
9431 _: &ToggleGitBlameInline,
9432 cx: &mut ViewContext<Self>,
9433 ) {
9434 self.toggle_git_blame_inline_internal(true, cx);
9435 cx.notify();
9436 }
9437
9438 pub fn git_blame_inline_enabled(&self) -> bool {
9439 self.git_blame_inline_enabled
9440 }
9441
9442 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
9443 if let Some(project) = self.project.as_ref() {
9444 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
9445 return;
9446 };
9447
9448 if buffer.read(cx).file().is_none() {
9449 return;
9450 }
9451
9452 let focused = self.focus_handle(cx).contains_focused(cx);
9453
9454 let project = project.clone();
9455 let blame =
9456 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
9457 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
9458 self.blame = Some(blame);
9459 }
9460 }
9461
9462 fn toggle_git_blame_inline_internal(
9463 &mut self,
9464 user_triggered: bool,
9465 cx: &mut ViewContext<Self>,
9466 ) {
9467 if self.git_blame_inline_enabled {
9468 self.git_blame_inline_enabled = false;
9469 self.show_git_blame_inline = false;
9470 self.show_git_blame_inline_delay_task.take();
9471 } else {
9472 self.git_blame_inline_enabled = true;
9473 self.start_git_blame_inline(user_triggered, cx);
9474 }
9475
9476 cx.notify();
9477 }
9478
9479 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
9480 self.start_git_blame(user_triggered, cx);
9481
9482 if ProjectSettings::get_global(cx)
9483 .git
9484 .inline_blame_delay()
9485 .is_some()
9486 {
9487 self.start_inline_blame_timer(cx);
9488 } else {
9489 self.show_git_blame_inline = true
9490 }
9491 }
9492
9493 pub fn blame(&self) -> Option<&Model<GitBlame>> {
9494 self.blame.as_ref()
9495 }
9496
9497 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
9498 self.show_git_blame_gutter && self.has_blame_entries(cx)
9499 }
9500
9501 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
9502 self.show_git_blame_inline
9503 && self.focus_handle.is_focused(cx)
9504 && !self.newest_selection_head_on_empty_line(cx)
9505 && self.has_blame_entries(cx)
9506 }
9507
9508 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
9509 self.blame()
9510 .map_or(false, |blame| blame.read(cx).has_generated_entries())
9511 }
9512
9513 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
9514 let cursor_anchor = self.selections.newest_anchor().head();
9515
9516 let snapshot = self.buffer.read(cx).snapshot(cx);
9517 let buffer_row = cursor_anchor.to_point(&snapshot).row;
9518
9519 snapshot.line_len(buffer_row) == 0
9520 }
9521
9522 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
9523 let (path, repo) = maybe!({
9524 let project_handle = self.project.as_ref()?.clone();
9525 let project = project_handle.read(cx);
9526 let buffer = self.buffer().read(cx).as_singleton()?;
9527 let path = buffer
9528 .read(cx)
9529 .file()?
9530 .as_local()?
9531 .path()
9532 .to_str()?
9533 .to_string();
9534 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
9535 Some((path, repo))
9536 })
9537 .ok_or_else(|| anyhow!("unable to open git repository"))?;
9538
9539 const REMOTE_NAME: &str = "origin";
9540 let origin_url = repo
9541 .lock()
9542 .remote_url(REMOTE_NAME)
9543 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
9544 let sha = repo
9545 .lock()
9546 .head_sha()
9547 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
9548 let selections = self.selections.all::<Point>(cx);
9549 let selection = selections.iter().peekable().next();
9550
9551 build_permalink(BuildPermalinkParams {
9552 remote_url: &origin_url,
9553 sha: &sha,
9554 path: &path,
9555 selection: selection.map(|selection| {
9556 let range = selection.range();
9557 let start = range.start.row;
9558 let end = range.end.row;
9559 start..end
9560 }),
9561 })
9562 }
9563
9564 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
9565 let permalink = self.get_permalink_to_line(cx);
9566
9567 match permalink {
9568 Ok(permalink) => {
9569 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
9570 }
9571 Err(err) => {
9572 let message = format!("Failed to copy permalink: {err}");
9573
9574 Err::<(), anyhow::Error>(err).log_err();
9575
9576 if let Some(workspace) = self.workspace() {
9577 workspace.update(cx, |workspace, cx| {
9578 struct CopyPermalinkToLine;
9579
9580 workspace.show_toast(
9581 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
9582 cx,
9583 )
9584 })
9585 }
9586 }
9587 }
9588 }
9589
9590 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
9591 let permalink = self.get_permalink_to_line(cx);
9592
9593 match permalink {
9594 Ok(permalink) => {
9595 cx.open_url(permalink.as_ref());
9596 }
9597 Err(err) => {
9598 let message = format!("Failed to open permalink: {err}");
9599
9600 Err::<(), anyhow::Error>(err).log_err();
9601
9602 if let Some(workspace) = self.workspace() {
9603 workspace.update(cx, |workspace, cx| {
9604 struct OpenPermalinkToLine;
9605
9606 workspace.show_toast(
9607 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
9608 cx,
9609 )
9610 })
9611 }
9612 }
9613 }
9614 }
9615
9616 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
9617 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
9618 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
9619 pub fn highlight_rows<T: 'static>(
9620 &mut self,
9621 rows: Range<Anchor>,
9622 color: Option<Hsla>,
9623 cx: &mut ViewContext<Self>,
9624 ) {
9625 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
9626 match self.highlighted_rows.entry(TypeId::of::<T>()) {
9627 hash_map::Entry::Occupied(o) => {
9628 let row_highlights = o.into_mut();
9629 let existing_highlight_index =
9630 row_highlights.binary_search_by(|(_, highlight_range, _)| {
9631 highlight_range
9632 .start
9633 .cmp(&rows.start, &multi_buffer_snapshot)
9634 .then(highlight_range.end.cmp(&rows.end, &multi_buffer_snapshot))
9635 });
9636 match color {
9637 Some(color) => {
9638 let insert_index = match existing_highlight_index {
9639 Ok(i) => i,
9640 Err(i) => i,
9641 };
9642 row_highlights.insert(
9643 insert_index,
9644 (post_inc(&mut self.highlight_order), rows, color),
9645 );
9646 }
9647 None => {
9648 if let Ok(i) = existing_highlight_index {
9649 row_highlights.remove(i);
9650 }
9651 }
9652 }
9653 }
9654 hash_map::Entry::Vacant(v) => {
9655 if let Some(color) = color {
9656 v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
9657 }
9658 }
9659 }
9660 }
9661
9662 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
9663 pub fn clear_row_highlights<T: 'static>(&mut self) {
9664 self.highlighted_rows.remove(&TypeId::of::<T>());
9665 }
9666
9667 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
9668 pub fn highlighted_rows<T: 'static>(
9669 &self,
9670 ) -> Option<impl Iterator<Item = (&Range<Anchor>, &Hsla)>> {
9671 Some(
9672 self.highlighted_rows
9673 .get(&TypeId::of::<T>())?
9674 .iter()
9675 .map(|(_, range, color)| (range, color)),
9676 )
9677 }
9678
9679 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
9680 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
9681 /// Allows to ignore certain kinds of highlights.
9682 pub fn highlighted_display_rows(
9683 &mut self,
9684 exclude_highlights: HashSet<TypeId>,
9685 cx: &mut WindowContext,
9686 ) -> BTreeMap<u32, Hsla> {
9687 let snapshot = self.snapshot(cx);
9688 let mut used_highlight_orders = HashMap::default();
9689 self.highlighted_rows
9690 .iter()
9691 .filter(|(type_id, _)| !exclude_highlights.contains(type_id))
9692 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
9693 .fold(
9694 BTreeMap::<u32, Hsla>::new(),
9695 |mut unique_rows, (highlight_order, anchor_range, hsla)| {
9696 let start_row = anchor_range.start.to_display_point(&snapshot).row();
9697 let end_row = anchor_range.end.to_display_point(&snapshot).row();
9698 for row in start_row..=end_row {
9699 let used_index =
9700 used_highlight_orders.entry(row).or_insert(*highlight_order);
9701 if highlight_order >= used_index {
9702 *used_index = *highlight_order;
9703 unique_rows.insert(row, *hsla);
9704 }
9705 }
9706 unique_rows
9707 },
9708 )
9709 }
9710
9711 pub fn set_search_within_ranges(
9712 &mut self,
9713 ranges: &[Range<Anchor>],
9714 cx: &mut ViewContext<Self>,
9715 ) {
9716 self.highlight_background::<SearchWithinRange>(
9717 ranges,
9718 |colors| colors.editor_document_highlight_read_background,
9719 cx,
9720 )
9721 }
9722
9723 pub fn highlight_background<T: 'static>(
9724 &mut self,
9725 ranges: &[Range<Anchor>],
9726 color_fetcher: fn(&ThemeColors) -> Hsla,
9727 cx: &mut ViewContext<Self>,
9728 ) {
9729 let snapshot = self.snapshot(cx);
9730 // this is to try and catch a panic sooner
9731 for range in ranges {
9732 snapshot
9733 .buffer_snapshot
9734 .summary_for_anchor::<usize>(&range.start);
9735 snapshot
9736 .buffer_snapshot
9737 .summary_for_anchor::<usize>(&range.end);
9738 }
9739
9740 self.background_highlights
9741 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
9742 self.scrollbar_marker_state.dirty = true;
9743 cx.notify();
9744 }
9745
9746 pub fn clear_background_highlights<T: 'static>(
9747 &mut self,
9748 cx: &mut ViewContext<Self>,
9749 ) -> Option<BackgroundHighlight> {
9750 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
9751 if !text_highlights.1.is_empty() {
9752 self.scrollbar_marker_state.dirty = true;
9753 cx.notify();
9754 }
9755 Some(text_highlights)
9756 }
9757
9758 #[cfg(feature = "test-support")]
9759 pub fn all_text_background_highlights(
9760 &mut self,
9761 cx: &mut ViewContext<Self>,
9762 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
9763 let snapshot = self.snapshot(cx);
9764 let buffer = &snapshot.buffer_snapshot;
9765 let start = buffer.anchor_before(0);
9766 let end = buffer.anchor_after(buffer.len());
9767 let theme = cx.theme().colors();
9768 self.background_highlights_in_range(start..end, &snapshot, theme)
9769 }
9770
9771 fn document_highlights_for_position<'a>(
9772 &'a self,
9773 position: Anchor,
9774 buffer: &'a MultiBufferSnapshot,
9775 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
9776 let read_highlights = self
9777 .background_highlights
9778 .get(&TypeId::of::<DocumentHighlightRead>())
9779 .map(|h| &h.1);
9780 let write_highlights = self
9781 .background_highlights
9782 .get(&TypeId::of::<DocumentHighlightWrite>())
9783 .map(|h| &h.1);
9784 let left_position = position.bias_left(buffer);
9785 let right_position = position.bias_right(buffer);
9786 read_highlights
9787 .into_iter()
9788 .chain(write_highlights)
9789 .flat_map(move |ranges| {
9790 let start_ix = match ranges.binary_search_by(|probe| {
9791 let cmp = probe.end.cmp(&left_position, buffer);
9792 if cmp.is_ge() {
9793 Ordering::Greater
9794 } else {
9795 Ordering::Less
9796 }
9797 }) {
9798 Ok(i) | Err(i) => i,
9799 };
9800
9801 ranges[start_ix..]
9802 .iter()
9803 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
9804 })
9805 }
9806
9807 pub fn has_background_highlights<T: 'static>(&self) -> bool {
9808 self.background_highlights
9809 .get(&TypeId::of::<T>())
9810 .map_or(false, |(_, highlights)| !highlights.is_empty())
9811 }
9812
9813 pub fn background_highlights_in_range(
9814 &self,
9815 search_range: Range<Anchor>,
9816 display_snapshot: &DisplaySnapshot,
9817 theme: &ThemeColors,
9818 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
9819 let mut results = Vec::new();
9820 for (color_fetcher, ranges) in self.background_highlights.values() {
9821 let color = color_fetcher(theme);
9822 let start_ix = match ranges.binary_search_by(|probe| {
9823 let cmp = probe
9824 .end
9825 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
9826 if cmp.is_gt() {
9827 Ordering::Greater
9828 } else {
9829 Ordering::Less
9830 }
9831 }) {
9832 Ok(i) | Err(i) => i,
9833 };
9834 for range in &ranges[start_ix..] {
9835 if range
9836 .start
9837 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
9838 .is_ge()
9839 {
9840 break;
9841 }
9842
9843 let start = range.start.to_display_point(&display_snapshot);
9844 let end = range.end.to_display_point(&display_snapshot);
9845 results.push((start..end, color))
9846 }
9847 }
9848 results
9849 }
9850
9851 pub fn background_highlight_row_ranges<T: 'static>(
9852 &self,
9853 search_range: Range<Anchor>,
9854 display_snapshot: &DisplaySnapshot,
9855 count: usize,
9856 ) -> Vec<RangeInclusive<DisplayPoint>> {
9857 let mut results = Vec::new();
9858 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
9859 return vec![];
9860 };
9861
9862 let start_ix = match ranges.binary_search_by(|probe| {
9863 let cmp = probe
9864 .end
9865 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
9866 if cmp.is_gt() {
9867 Ordering::Greater
9868 } else {
9869 Ordering::Less
9870 }
9871 }) {
9872 Ok(i) | Err(i) => i,
9873 };
9874 let mut push_region = |start: Option<Point>, end: Option<Point>| {
9875 if let (Some(start_display), Some(end_display)) = (start, end) {
9876 results.push(
9877 start_display.to_display_point(display_snapshot)
9878 ..=end_display.to_display_point(display_snapshot),
9879 );
9880 }
9881 };
9882 let mut start_row: Option<Point> = None;
9883 let mut end_row: Option<Point> = None;
9884 if ranges.len() > count {
9885 return Vec::new();
9886 }
9887 for range in &ranges[start_ix..] {
9888 if range
9889 .start
9890 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
9891 .is_ge()
9892 {
9893 break;
9894 }
9895 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
9896 if let Some(current_row) = &end_row {
9897 if end.row == current_row.row {
9898 continue;
9899 }
9900 }
9901 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
9902 if start_row.is_none() {
9903 assert_eq!(end_row, None);
9904 start_row = Some(start);
9905 end_row = Some(end);
9906 continue;
9907 }
9908 if let Some(current_end) = end_row.as_mut() {
9909 if start.row > current_end.row + 1 {
9910 push_region(start_row, end_row);
9911 start_row = Some(start);
9912 end_row = Some(end);
9913 } else {
9914 // Merge two hunks.
9915 *current_end = end;
9916 }
9917 } else {
9918 unreachable!();
9919 }
9920 }
9921 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
9922 push_region(start_row, end_row);
9923 results
9924 }
9925
9926 /// Get the text ranges corresponding to the redaction query
9927 pub fn redacted_ranges(
9928 &self,
9929 search_range: Range<Anchor>,
9930 display_snapshot: &DisplaySnapshot,
9931 cx: &WindowContext,
9932 ) -> Vec<Range<DisplayPoint>> {
9933 display_snapshot
9934 .buffer_snapshot
9935 .redacted_ranges(search_range, |file| {
9936 if let Some(file) = file {
9937 file.is_private()
9938 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
9939 } else {
9940 false
9941 }
9942 })
9943 .map(|range| {
9944 range.start.to_display_point(display_snapshot)
9945 ..range.end.to_display_point(display_snapshot)
9946 })
9947 .collect()
9948 }
9949
9950 pub fn highlight_text<T: 'static>(
9951 &mut self,
9952 ranges: Vec<Range<Anchor>>,
9953 style: HighlightStyle,
9954 cx: &mut ViewContext<Self>,
9955 ) {
9956 self.display_map.update(cx, |map, _| {
9957 map.highlight_text(TypeId::of::<T>(), ranges, style)
9958 });
9959 cx.notify();
9960 }
9961
9962 pub(crate) fn highlight_inlays<T: 'static>(
9963 &mut self,
9964 highlights: Vec<InlayHighlight>,
9965 style: HighlightStyle,
9966 cx: &mut ViewContext<Self>,
9967 ) {
9968 self.display_map.update(cx, |map, _| {
9969 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
9970 });
9971 cx.notify();
9972 }
9973
9974 pub fn text_highlights<'a, T: 'static>(
9975 &'a self,
9976 cx: &'a AppContext,
9977 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
9978 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
9979 }
9980
9981 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
9982 let cleared = self
9983 .display_map
9984 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
9985 if cleared {
9986 cx.notify();
9987 }
9988 }
9989
9990 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
9991 (self.read_only(cx) || self.blink_manager.read(cx).visible())
9992 && self.focus_handle.is_focused(cx)
9993 }
9994
9995 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
9996 cx.notify();
9997 }
9998
9999 fn on_buffer_event(
10000 &mut self,
10001 multibuffer: Model<MultiBuffer>,
10002 event: &multi_buffer::Event,
10003 cx: &mut ViewContext<Self>,
10004 ) {
10005 match event {
10006 multi_buffer::Event::Edited {
10007 singleton_buffer_edited,
10008 } => {
10009 self.scrollbar_marker_state.dirty = true;
10010 self.refresh_active_diagnostics(cx);
10011 self.refresh_code_actions(cx);
10012 if self.has_active_inline_completion(cx) {
10013 self.update_visible_inline_completion(cx);
10014 }
10015 cx.emit(EditorEvent::BufferEdited);
10016 cx.emit(SearchEvent::MatchesInvalidated);
10017
10018 if *singleton_buffer_edited {
10019 if let Some(project) = &self.project {
10020 let project = project.read(cx);
10021 let languages_affected = multibuffer
10022 .read(cx)
10023 .all_buffers()
10024 .into_iter()
10025 .filter_map(|buffer| {
10026 let buffer = buffer.read(cx);
10027 let language = buffer.language()?;
10028 if project.is_local()
10029 && project.language_servers_for_buffer(buffer, cx).count() == 0
10030 {
10031 None
10032 } else {
10033 Some(language)
10034 }
10035 })
10036 .cloned()
10037 .collect::<HashSet<_>>();
10038 if !languages_affected.is_empty() {
10039 self.refresh_inlay_hints(
10040 InlayHintRefreshReason::BufferEdited(languages_affected),
10041 cx,
10042 );
10043 }
10044 }
10045 }
10046
10047 let Some(project) = &self.project else { return };
10048 let telemetry = project.read(cx).client().telemetry().clone();
10049 telemetry.log_edit_event("editor");
10050 }
10051 multi_buffer::Event::ExcerptsAdded {
10052 buffer,
10053 predecessor,
10054 excerpts,
10055 } => {
10056 cx.emit(EditorEvent::ExcerptsAdded {
10057 buffer: buffer.clone(),
10058 predecessor: *predecessor,
10059 excerpts: excerpts.clone(),
10060 });
10061 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
10062 }
10063 multi_buffer::Event::ExcerptsRemoved { ids } => {
10064 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
10065 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
10066 }
10067 multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
10068 multi_buffer::Event::LanguageChanged => {
10069 cx.emit(EditorEvent::Reparsed);
10070 cx.notify();
10071 }
10072 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
10073 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
10074 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
10075 cx.emit(EditorEvent::TitleChanged)
10076 }
10077 multi_buffer::Event::DiffBaseChanged => {
10078 self.scrollbar_marker_state.dirty = true;
10079 cx.emit(EditorEvent::DiffBaseChanged);
10080 cx.notify();
10081 }
10082 multi_buffer::Event::DiffUpdated { buffer } => {
10083 self.sync_expanded_diff_hunks(buffer.clone(), cx);
10084 cx.notify();
10085 }
10086 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
10087 multi_buffer::Event::DiagnosticsUpdated => {
10088 self.refresh_active_diagnostics(cx);
10089 self.scrollbar_marker_state.dirty = true;
10090 cx.notify();
10091 }
10092 _ => {}
10093 };
10094 }
10095
10096 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
10097 cx.notify();
10098 }
10099
10100 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
10101 self.refresh_inline_completion(true, cx);
10102 self.refresh_inlay_hints(
10103 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
10104 self.selections.newest_anchor().head(),
10105 &self.buffer.read(cx).snapshot(cx),
10106 cx,
10107 )),
10108 cx,
10109 );
10110 let editor_settings = EditorSettings::get_global(cx);
10111 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
10112 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
10113
10114 if self.mode == EditorMode::Full {
10115 let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
10116 if self.git_blame_inline_enabled != inline_blame_enabled {
10117 self.toggle_git_blame_inline_internal(false, cx);
10118 }
10119 }
10120
10121 cx.notify();
10122 }
10123
10124 pub fn set_searchable(&mut self, searchable: bool) {
10125 self.searchable = searchable;
10126 }
10127
10128 pub fn searchable(&self) -> bool {
10129 self.searchable
10130 }
10131
10132 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
10133 self.open_excerpts_common(true, cx)
10134 }
10135
10136 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
10137 self.open_excerpts_common(false, cx)
10138 }
10139
10140 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
10141 let buffer = self.buffer.read(cx);
10142 if buffer.is_singleton() {
10143 cx.propagate();
10144 return;
10145 }
10146
10147 let Some(workspace) = self.workspace() else {
10148 cx.propagate();
10149 return;
10150 };
10151
10152 let mut new_selections_by_buffer = HashMap::default();
10153 for selection in self.selections.all::<usize>(cx) {
10154 for (buffer, mut range, _) in
10155 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
10156 {
10157 if selection.reversed {
10158 mem::swap(&mut range.start, &mut range.end);
10159 }
10160 new_selections_by_buffer
10161 .entry(buffer)
10162 .or_insert(Vec::new())
10163 .push(range)
10164 }
10165 }
10166
10167 // We defer the pane interaction because we ourselves are a workspace item
10168 // and activating a new item causes the pane to call a method on us reentrantly,
10169 // which panics if we're on the stack.
10170 cx.window_context().defer(move |cx| {
10171 workspace.update(cx, |workspace, cx| {
10172 let pane = if split {
10173 workspace.adjacent_pane(cx)
10174 } else {
10175 workspace.active_pane().clone()
10176 };
10177
10178 for (buffer, ranges) in new_selections_by_buffer {
10179 let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
10180 editor.update(cx, |editor, cx| {
10181 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
10182 s.select_ranges(ranges);
10183 });
10184 });
10185 }
10186 })
10187 });
10188 }
10189
10190 fn jump(
10191 &mut self,
10192 path: ProjectPath,
10193 position: Point,
10194 anchor: language::Anchor,
10195 offset_from_top: u32,
10196 cx: &mut ViewContext<Self>,
10197 ) {
10198 let workspace = self.workspace();
10199 cx.spawn(|_, mut cx| async move {
10200 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
10201 let editor = workspace.update(&mut cx, |workspace, cx| {
10202 // Reset the preview item id before opening the new item
10203 workspace.active_pane().update(cx, |pane, cx| {
10204 pane.set_preview_item_id(None, cx);
10205 });
10206 workspace.open_path_preview(path, None, true, true, cx)
10207 })?;
10208 let editor = editor
10209 .await?
10210 .downcast::<Editor>()
10211 .ok_or_else(|| anyhow!("opened item was not an editor"))?
10212 .downgrade();
10213 editor.update(&mut cx, |editor, cx| {
10214 let buffer = editor
10215 .buffer()
10216 .read(cx)
10217 .as_singleton()
10218 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
10219 let buffer = buffer.read(cx);
10220 let cursor = if buffer.can_resolve(&anchor) {
10221 language::ToPoint::to_point(&anchor, buffer)
10222 } else {
10223 buffer.clip_point(position, Bias::Left)
10224 };
10225
10226 let nav_history = editor.nav_history.take();
10227 editor.change_selections(
10228 Some(Autoscroll::top_relative(offset_from_top as usize)),
10229 cx,
10230 |s| {
10231 s.select_ranges([cursor..cursor]);
10232 },
10233 );
10234 editor.nav_history = nav_history;
10235
10236 anyhow::Ok(())
10237 })??;
10238
10239 anyhow::Ok(())
10240 })
10241 .detach_and_log_err(cx);
10242 }
10243
10244 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
10245 let snapshot = self.buffer.read(cx).read(cx);
10246 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
10247 Some(
10248 ranges
10249 .iter()
10250 .map(move |range| {
10251 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
10252 })
10253 .collect(),
10254 )
10255 }
10256
10257 fn selection_replacement_ranges(
10258 &self,
10259 range: Range<OffsetUtf16>,
10260 cx: &AppContext,
10261 ) -> Vec<Range<OffsetUtf16>> {
10262 let selections = self.selections.all::<OffsetUtf16>(cx);
10263 let newest_selection = selections
10264 .iter()
10265 .max_by_key(|selection| selection.id)
10266 .unwrap();
10267 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
10268 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
10269 let snapshot = self.buffer.read(cx).read(cx);
10270 selections
10271 .into_iter()
10272 .map(|mut selection| {
10273 selection.start.0 =
10274 (selection.start.0 as isize).saturating_add(start_delta) as usize;
10275 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
10276 snapshot.clip_offset_utf16(selection.start, Bias::Left)
10277 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
10278 })
10279 .collect()
10280 }
10281
10282 fn report_editor_event(
10283 &self,
10284 operation: &'static str,
10285 file_extension: Option<String>,
10286 cx: &AppContext,
10287 ) {
10288 if cfg!(any(test, feature = "test-support")) {
10289 return;
10290 }
10291
10292 let Some(project) = &self.project else { return };
10293
10294 // If None, we are in a file without an extension
10295 let file = self
10296 .buffer
10297 .read(cx)
10298 .as_singleton()
10299 .and_then(|b| b.read(cx).file());
10300 let file_extension = file_extension.or(file
10301 .as_ref()
10302 .and_then(|file| Path::new(file.file_name(cx)).extension())
10303 .and_then(|e| e.to_str())
10304 .map(|a| a.to_string()));
10305
10306 let vim_mode = cx
10307 .global::<SettingsStore>()
10308 .raw_user_settings()
10309 .get("vim_mode")
10310 == Some(&serde_json::Value::Bool(true));
10311
10312 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
10313 == language::language_settings::InlineCompletionProvider::Copilot;
10314 let copilot_enabled_for_language = self
10315 .buffer
10316 .read(cx)
10317 .settings_at(0, cx)
10318 .show_inline_completions;
10319
10320 let telemetry = project.read(cx).client().telemetry().clone();
10321 telemetry.report_editor_event(
10322 file_extension,
10323 vim_mode,
10324 operation,
10325 copilot_enabled,
10326 copilot_enabled_for_language,
10327 )
10328 }
10329
10330 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
10331 /// with each line being an array of {text, highlight} objects.
10332 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
10333 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
10334 return;
10335 };
10336
10337 #[derive(Serialize)]
10338 struct Chunk<'a> {
10339 text: String,
10340 highlight: Option<&'a str>,
10341 }
10342
10343 let snapshot = buffer.read(cx).snapshot();
10344 let range = self
10345 .selected_text_range(cx)
10346 .and_then(|selected_range| {
10347 if selected_range.is_empty() {
10348 None
10349 } else {
10350 Some(selected_range)
10351 }
10352 })
10353 .unwrap_or_else(|| 0..snapshot.len());
10354
10355 let chunks = snapshot.chunks(range, true);
10356 let mut lines = Vec::new();
10357 let mut line: VecDeque<Chunk> = VecDeque::new();
10358
10359 let Some(style) = self.style.as_ref() else {
10360 return;
10361 };
10362
10363 for chunk in chunks {
10364 let highlight = chunk
10365 .syntax_highlight_id
10366 .and_then(|id| id.name(&style.syntax));
10367 let mut chunk_lines = chunk.text.split('\n').peekable();
10368 while let Some(text) = chunk_lines.next() {
10369 let mut merged_with_last_token = false;
10370 if let Some(last_token) = line.back_mut() {
10371 if last_token.highlight == highlight {
10372 last_token.text.push_str(text);
10373 merged_with_last_token = true;
10374 }
10375 }
10376
10377 if !merged_with_last_token {
10378 line.push_back(Chunk {
10379 text: text.into(),
10380 highlight,
10381 });
10382 }
10383
10384 if chunk_lines.peek().is_some() {
10385 if line.len() > 1 && line.front().unwrap().text.is_empty() {
10386 line.pop_front();
10387 }
10388 if line.len() > 1 && line.back().unwrap().text.is_empty() {
10389 line.pop_back();
10390 }
10391
10392 lines.push(mem::take(&mut line));
10393 }
10394 }
10395 }
10396
10397 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
10398 return;
10399 };
10400 cx.write_to_clipboard(ClipboardItem::new(lines));
10401 }
10402
10403 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
10404 &self.inlay_hint_cache
10405 }
10406
10407 pub fn replay_insert_event(
10408 &mut self,
10409 text: &str,
10410 relative_utf16_range: Option<Range<isize>>,
10411 cx: &mut ViewContext<Self>,
10412 ) {
10413 if !self.input_enabled {
10414 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10415 return;
10416 }
10417 if let Some(relative_utf16_range) = relative_utf16_range {
10418 let selections = self.selections.all::<OffsetUtf16>(cx);
10419 self.change_selections(None, cx, |s| {
10420 let new_ranges = selections.into_iter().map(|range| {
10421 let start = OffsetUtf16(
10422 range
10423 .head()
10424 .0
10425 .saturating_add_signed(relative_utf16_range.start),
10426 );
10427 let end = OffsetUtf16(
10428 range
10429 .head()
10430 .0
10431 .saturating_add_signed(relative_utf16_range.end),
10432 );
10433 start..end
10434 });
10435 s.select_ranges(new_ranges);
10436 });
10437 }
10438
10439 self.handle_input(text, cx);
10440 }
10441
10442 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10443 let Some(project) = self.project.as_ref() else {
10444 return false;
10445 };
10446 let project = project.read(cx);
10447
10448 let mut supports = false;
10449 self.buffer().read(cx).for_each_buffer(|buffer| {
10450 if !supports {
10451 supports = project
10452 .language_servers_for_buffer(buffer.read(cx), cx)
10453 .any(
10454 |(_, server)| match server.capabilities().inlay_hint_provider {
10455 Some(lsp::OneOf::Left(enabled)) => enabled,
10456 Some(lsp::OneOf::Right(_)) => true,
10457 None => false,
10458 },
10459 )
10460 }
10461 });
10462 supports
10463 }
10464
10465 pub fn focus(&self, cx: &mut WindowContext) {
10466 cx.focus(&self.focus_handle)
10467 }
10468
10469 pub fn is_focused(&self, cx: &WindowContext) -> bool {
10470 self.focus_handle.is_focused(cx)
10471 }
10472
10473 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
10474 cx.emit(EditorEvent::Focused);
10475
10476 if let Some(rename) = self.pending_rename.as_ref() {
10477 let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
10478 cx.focus(&rename_editor_focus_handle);
10479 } else {
10480 if let Some(blame) = self.blame.as_ref() {
10481 blame.update(cx, GitBlame::focus)
10482 }
10483
10484 self.blink_manager.update(cx, BlinkManager::enable);
10485 self.show_cursor_names(cx);
10486 self.buffer.update(cx, |buffer, cx| {
10487 buffer.finalize_last_transaction(cx);
10488 if self.leader_peer_id.is_none() {
10489 buffer.set_active_selections(
10490 &self.selections.disjoint_anchors(),
10491 self.selections.line_mode,
10492 self.cursor_shape,
10493 cx,
10494 );
10495 }
10496 });
10497 }
10498 }
10499
10500 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
10501 self.blink_manager.update(cx, BlinkManager::disable);
10502 self.buffer
10503 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
10504
10505 if let Some(blame) = self.blame.as_ref() {
10506 blame.update(cx, GitBlame::blur)
10507 }
10508 self.hide_context_menu(cx);
10509 hide_hover(self, cx);
10510 cx.emit(EditorEvent::Blurred);
10511 cx.notify();
10512 }
10513
10514 pub fn register_action<A: Action>(
10515 &mut self,
10516 listener: impl Fn(&A, &mut WindowContext) + 'static,
10517 ) -> &mut Self {
10518 let listener = Arc::new(listener);
10519
10520 self.editor_actions.push(Box::new(move |cx| {
10521 let _view = cx.view().clone();
10522 let cx = cx.window_context();
10523 let listener = listener.clone();
10524 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
10525 let action = action.downcast_ref().unwrap();
10526 if phase == DispatchPhase::Bubble {
10527 listener(action, cx)
10528 }
10529 })
10530 }));
10531 self
10532 }
10533}
10534
10535fn hunks_for_selections(
10536 multi_buffer_snapshot: &MultiBufferSnapshot,
10537 selections: &[Selection<Anchor>],
10538) -> Vec<DiffHunk<u32>> {
10539 let mut hunks = Vec::with_capacity(selections.len());
10540 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
10541 HashMap::default();
10542 let display_rows_for_selections = selections.iter().map(|selection| {
10543 let head = selection.head();
10544 let tail = selection.tail();
10545 let start = tail.to_point(&multi_buffer_snapshot).row;
10546 let end = head.to_point(&multi_buffer_snapshot).row;
10547 if start > end {
10548 end..start
10549 } else {
10550 start..end
10551 }
10552 });
10553
10554 for selected_multi_buffer_rows in display_rows_for_selections {
10555 let query_rows = selected_multi_buffer_rows.start..selected_multi_buffer_rows.end + 1;
10556 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
10557 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
10558 // when the caret is just above or just below the deleted hunk.
10559 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
10560 let related_to_selection = if allow_adjacent {
10561 hunk.associated_range.overlaps(&query_rows)
10562 || hunk.associated_range.start == query_rows.end
10563 || hunk.associated_range.end == query_rows.start
10564 } else {
10565 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
10566 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
10567 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
10568 || selected_multi_buffer_rows.end == hunk.associated_range.start
10569 };
10570 if related_to_selection {
10571 if !processed_buffer_rows
10572 .entry(hunk.buffer_id)
10573 .or_default()
10574 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
10575 {
10576 continue;
10577 }
10578 hunks.push(hunk);
10579 }
10580 }
10581 }
10582
10583 hunks
10584}
10585
10586pub trait CollaborationHub {
10587 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
10588 fn user_participant_indices<'a>(
10589 &self,
10590 cx: &'a AppContext,
10591 ) -> &'a HashMap<u64, ParticipantIndex>;
10592 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
10593}
10594
10595impl CollaborationHub for Model<Project> {
10596 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
10597 self.read(cx).collaborators()
10598 }
10599
10600 fn user_participant_indices<'a>(
10601 &self,
10602 cx: &'a AppContext,
10603 ) -> &'a HashMap<u64, ParticipantIndex> {
10604 self.read(cx).user_store().read(cx).participant_indices()
10605 }
10606
10607 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
10608 let this = self.read(cx);
10609 let user_ids = this.collaborators().values().map(|c| c.user_id);
10610 this.user_store().read_with(cx, |user_store, cx| {
10611 user_store.participant_names(user_ids, cx)
10612 })
10613 }
10614}
10615
10616pub trait CompletionProvider {
10617 fn completions(
10618 &self,
10619 buffer: &Model<Buffer>,
10620 buffer_position: text::Anchor,
10621 cx: &mut ViewContext<Editor>,
10622 ) -> Task<Result<Vec<Completion>>>;
10623
10624 fn resolve_completions(
10625 &self,
10626 buffer: Model<Buffer>,
10627 completion_indices: Vec<usize>,
10628 completions: Arc<RwLock<Box<[Completion]>>>,
10629 cx: &mut ViewContext<Editor>,
10630 ) -> Task<Result<bool>>;
10631
10632 fn apply_additional_edits_for_completion(
10633 &self,
10634 buffer: Model<Buffer>,
10635 completion: Completion,
10636 push_to_history: bool,
10637 cx: &mut ViewContext<Editor>,
10638 ) -> Task<Result<Option<language::Transaction>>>;
10639}
10640
10641impl CompletionProvider for Model<Project> {
10642 fn completions(
10643 &self,
10644 buffer: &Model<Buffer>,
10645 buffer_position: text::Anchor,
10646 cx: &mut ViewContext<Editor>,
10647 ) -> Task<Result<Vec<Completion>>> {
10648 self.update(cx, |project, cx| {
10649 project.completions(&buffer, buffer_position, cx)
10650 })
10651 }
10652
10653 fn resolve_completions(
10654 &self,
10655 buffer: Model<Buffer>,
10656 completion_indices: Vec<usize>,
10657 completions: Arc<RwLock<Box<[Completion]>>>,
10658 cx: &mut ViewContext<Editor>,
10659 ) -> Task<Result<bool>> {
10660 self.update(cx, |project, cx| {
10661 project.resolve_completions(buffer, completion_indices, completions, cx)
10662 })
10663 }
10664
10665 fn apply_additional_edits_for_completion(
10666 &self,
10667 buffer: Model<Buffer>,
10668 completion: Completion,
10669 push_to_history: bool,
10670 cx: &mut ViewContext<Editor>,
10671 ) -> Task<Result<Option<language::Transaction>>> {
10672 self.update(cx, |project, cx| {
10673 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
10674 })
10675 }
10676}
10677
10678fn inlay_hint_settings(
10679 location: Anchor,
10680 snapshot: &MultiBufferSnapshot,
10681 cx: &mut ViewContext<'_, Editor>,
10682) -> InlayHintSettings {
10683 let file = snapshot.file_at(location);
10684 let language = snapshot.language_at(location);
10685 let settings = all_language_settings(file, cx);
10686 settings
10687 .language(language.map(|l| l.name()).as_deref())
10688 .inlay_hints
10689}
10690
10691fn consume_contiguous_rows(
10692 contiguous_row_selections: &mut Vec<Selection<Point>>,
10693 selection: &Selection<Point>,
10694 display_map: &DisplaySnapshot,
10695 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
10696) -> (u32, u32) {
10697 contiguous_row_selections.push(selection.clone());
10698 let start_row = selection.start.row;
10699 let mut end_row = ending_row(selection, display_map);
10700
10701 while let Some(next_selection) = selections.peek() {
10702 if next_selection.start.row <= end_row {
10703 end_row = ending_row(next_selection, display_map);
10704 contiguous_row_selections.push(selections.next().unwrap().clone());
10705 } else {
10706 break;
10707 }
10708 }
10709 (start_row, end_row)
10710}
10711
10712fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
10713 if next_selection.end.column > 0 || next_selection.is_empty() {
10714 display_map.next_line_boundary(next_selection.end).0.row + 1
10715 } else {
10716 next_selection.end.row
10717 }
10718}
10719
10720impl EditorSnapshot {
10721 pub fn remote_selections_in_range<'a>(
10722 &'a self,
10723 range: &'a Range<Anchor>,
10724 collaboration_hub: &dyn CollaborationHub,
10725 cx: &'a AppContext,
10726 ) -> impl 'a + Iterator<Item = RemoteSelection> {
10727 let participant_names = collaboration_hub.user_names(cx);
10728 let participant_indices = collaboration_hub.user_participant_indices(cx);
10729 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
10730 let collaborators_by_replica_id = collaborators_by_peer_id
10731 .iter()
10732 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
10733 .collect::<HashMap<_, _>>();
10734 self.buffer_snapshot
10735 .remote_selections_in_range(range)
10736 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10737 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10738 let participant_index = participant_indices.get(&collaborator.user_id).copied();
10739 let user_name = participant_names.get(&collaborator.user_id).cloned();
10740 Some(RemoteSelection {
10741 replica_id,
10742 selection,
10743 cursor_shape,
10744 line_mode,
10745 participant_index,
10746 peer_id: collaborator.peer_id,
10747 user_name,
10748 })
10749 })
10750 }
10751
10752 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10753 self.display_snapshot.buffer_snapshot.language_at(position)
10754 }
10755
10756 pub fn is_focused(&self) -> bool {
10757 self.is_focused
10758 }
10759
10760 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10761 self.placeholder_text.as_ref()
10762 }
10763
10764 pub fn scroll_position(&self) -> gpui::Point<f32> {
10765 self.scroll_anchor.scroll_position(&self.display_snapshot)
10766 }
10767
10768 pub fn gutter_dimensions(
10769 &self,
10770 font_id: FontId,
10771 font_size: Pixels,
10772 em_width: Pixels,
10773 max_line_number_width: Pixels,
10774 cx: &AppContext,
10775 ) -> GutterDimensions {
10776 if !self.show_gutter {
10777 return GutterDimensions::default();
10778 }
10779 let descent = cx.text_system().descent(font_id, font_size);
10780
10781 let show_git_gutter = matches!(
10782 ProjectSettings::get_global(cx).git.git_gutter,
10783 Some(GitGutterSetting::TrackedFiles)
10784 );
10785 let gutter_settings = EditorSettings::get_global(cx).gutter;
10786 let gutter_lines_enabled = gutter_settings.line_numbers;
10787 let line_gutter_width = if gutter_lines_enabled {
10788 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10789 let min_width_for_number_on_gutter = em_width * 4.0;
10790 max_line_number_width.max(min_width_for_number_on_gutter)
10791 } else {
10792 0.0.into()
10793 };
10794
10795 let git_blame_entries_width = self
10796 .render_git_blame_gutter
10797 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
10798
10799 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
10800 left_padding += if gutter_settings.code_actions {
10801 em_width * 3.0
10802 } else if show_git_gutter && gutter_lines_enabled {
10803 em_width * 2.0
10804 } else if show_git_gutter || gutter_lines_enabled {
10805 em_width
10806 } else {
10807 px(0.)
10808 };
10809
10810 let right_padding = if gutter_settings.folds && gutter_lines_enabled {
10811 em_width * 4.0
10812 } else if gutter_settings.folds {
10813 em_width * 3.0
10814 } else if gutter_lines_enabled {
10815 em_width
10816 } else {
10817 px(0.)
10818 };
10819
10820 GutterDimensions {
10821 left_padding,
10822 right_padding,
10823 width: line_gutter_width + left_padding + right_padding,
10824 margin: -descent,
10825 git_blame_entries_width,
10826 }
10827 }
10828}
10829
10830impl Deref for EditorSnapshot {
10831 type Target = DisplaySnapshot;
10832
10833 fn deref(&self) -> &Self::Target {
10834 &self.display_snapshot
10835 }
10836}
10837
10838#[derive(Clone, Debug, PartialEq, Eq)]
10839pub enum EditorEvent {
10840 InputIgnored {
10841 text: Arc<str>,
10842 },
10843 InputHandled {
10844 utf16_range_to_replace: Option<Range<isize>>,
10845 text: Arc<str>,
10846 },
10847 ExcerptsAdded {
10848 buffer: Model<Buffer>,
10849 predecessor: ExcerptId,
10850 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
10851 },
10852 ExcerptsRemoved {
10853 ids: Vec<ExcerptId>,
10854 },
10855 BufferEdited,
10856 Edited,
10857 Reparsed,
10858 Focused,
10859 Blurred,
10860 DirtyChanged,
10861 Saved,
10862 TitleChanged,
10863 DiffBaseChanged,
10864 SelectionsChanged {
10865 local: bool,
10866 },
10867 ScrollPositionChanged {
10868 local: bool,
10869 autoscroll: bool,
10870 },
10871 Closed,
10872 TransactionUndone {
10873 transaction_id: clock::Lamport,
10874 },
10875 TransactionBegun {
10876 transaction_id: clock::Lamport,
10877 },
10878}
10879
10880impl EventEmitter<EditorEvent> for Editor {}
10881
10882impl FocusableView for Editor {
10883 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
10884 self.focus_handle.clone()
10885 }
10886}
10887
10888impl Render for Editor {
10889 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
10890 let settings = ThemeSettings::get_global(cx);
10891
10892 let text_style = match self.mode {
10893 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
10894 color: cx.theme().colors().editor_foreground,
10895 font_family: settings.ui_font.family.clone(),
10896 font_features: settings.ui_font.features.clone(),
10897 font_size: rems(0.875).into(),
10898 font_weight: FontWeight::NORMAL,
10899 font_style: FontStyle::Normal,
10900 line_height: relative(settings.buffer_line_height.value()),
10901 background_color: None,
10902 underline: None,
10903 strikethrough: None,
10904 white_space: WhiteSpace::Normal,
10905 },
10906 EditorMode::Full => TextStyle {
10907 color: cx.theme().colors().editor_foreground,
10908 font_family: settings.buffer_font.family.clone(),
10909 font_features: settings.buffer_font.features.clone(),
10910 font_size: settings.buffer_font_size(cx).into(),
10911 font_weight: FontWeight::NORMAL,
10912 font_style: FontStyle::Normal,
10913 line_height: relative(settings.buffer_line_height.value()),
10914 background_color: None,
10915 underline: None,
10916 strikethrough: None,
10917 white_space: WhiteSpace::Normal,
10918 },
10919 };
10920
10921 let background = match self.mode {
10922 EditorMode::SingleLine => cx.theme().system().transparent,
10923 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
10924 EditorMode::Full => cx.theme().colors().editor_background,
10925 };
10926
10927 EditorElement::new(
10928 cx.view(),
10929 EditorStyle {
10930 background,
10931 local_player: cx.theme().players().local(),
10932 text: text_style,
10933 scrollbar_width: px(13.),
10934 syntax: cx.theme().syntax().clone(),
10935 status: cx.theme().status().clone(),
10936 inlay_hints_style: HighlightStyle {
10937 color: Some(cx.theme().status().hint),
10938 ..HighlightStyle::default()
10939 },
10940 suggestions_style: HighlightStyle {
10941 color: Some(cx.theme().status().predictive),
10942 ..HighlightStyle::default()
10943 },
10944 },
10945 )
10946 }
10947}
10948
10949impl ViewInputHandler for Editor {
10950 fn text_for_range(
10951 &mut self,
10952 range_utf16: Range<usize>,
10953 cx: &mut ViewContext<Self>,
10954 ) -> Option<String> {
10955 Some(
10956 self.buffer
10957 .read(cx)
10958 .read(cx)
10959 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
10960 .collect(),
10961 )
10962 }
10963
10964 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10965 // Prevent the IME menu from appearing when holding down an alphabetic key
10966 // while input is disabled.
10967 if !self.input_enabled {
10968 return None;
10969 }
10970
10971 let range = self.selections.newest::<OffsetUtf16>(cx).range();
10972 Some(range.start.0..range.end.0)
10973 }
10974
10975 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10976 let snapshot = self.buffer.read(cx).read(cx);
10977 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
10978 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
10979 }
10980
10981 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
10982 self.clear_highlights::<InputComposition>(cx);
10983 self.ime_transaction.take();
10984 }
10985
10986 fn replace_text_in_range(
10987 &mut self,
10988 range_utf16: Option<Range<usize>>,
10989 text: &str,
10990 cx: &mut ViewContext<Self>,
10991 ) {
10992 if !self.input_enabled {
10993 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10994 return;
10995 }
10996
10997 self.transact(cx, |this, cx| {
10998 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
10999 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11000 Some(this.selection_replacement_ranges(range_utf16, cx))
11001 } else {
11002 this.marked_text_ranges(cx)
11003 };
11004
11005 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
11006 let newest_selection_id = this.selections.newest_anchor().id;
11007 this.selections
11008 .all::<OffsetUtf16>(cx)
11009 .iter()
11010 .zip(ranges_to_replace.iter())
11011 .find_map(|(selection, range)| {
11012 if selection.id == newest_selection_id {
11013 Some(
11014 (range.start.0 as isize - selection.head().0 as isize)
11015 ..(range.end.0 as isize - selection.head().0 as isize),
11016 )
11017 } else {
11018 None
11019 }
11020 })
11021 });
11022
11023 cx.emit(EditorEvent::InputHandled {
11024 utf16_range_to_replace: range_to_replace,
11025 text: text.into(),
11026 });
11027
11028 if let Some(new_selected_ranges) = new_selected_ranges {
11029 this.change_selections(None, cx, |selections| {
11030 selections.select_ranges(new_selected_ranges)
11031 });
11032 this.backspace(&Default::default(), cx);
11033 }
11034
11035 this.handle_input(text, cx);
11036 });
11037
11038 if let Some(transaction) = self.ime_transaction {
11039 self.buffer.update(cx, |buffer, cx| {
11040 buffer.group_until_transaction(transaction, cx);
11041 });
11042 }
11043
11044 self.unmark_text(cx);
11045 }
11046
11047 fn replace_and_mark_text_in_range(
11048 &mut self,
11049 range_utf16: Option<Range<usize>>,
11050 text: &str,
11051 new_selected_range_utf16: Option<Range<usize>>,
11052 cx: &mut ViewContext<Self>,
11053 ) {
11054 if !self.input_enabled {
11055 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11056 return;
11057 }
11058
11059 let transaction = self.transact(cx, |this, cx| {
11060 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
11061 let snapshot = this.buffer.read(cx).read(cx);
11062 if let Some(relative_range_utf16) = range_utf16.as_ref() {
11063 for marked_range in &mut marked_ranges {
11064 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
11065 marked_range.start.0 += relative_range_utf16.start;
11066 marked_range.start =
11067 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
11068 marked_range.end =
11069 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
11070 }
11071 }
11072 Some(marked_ranges)
11073 } else if let Some(range_utf16) = range_utf16 {
11074 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11075 Some(this.selection_replacement_ranges(range_utf16, cx))
11076 } else {
11077 None
11078 };
11079
11080 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
11081 let newest_selection_id = this.selections.newest_anchor().id;
11082 this.selections
11083 .all::<OffsetUtf16>(cx)
11084 .iter()
11085 .zip(ranges_to_replace.iter())
11086 .find_map(|(selection, range)| {
11087 if selection.id == newest_selection_id {
11088 Some(
11089 (range.start.0 as isize - selection.head().0 as isize)
11090 ..(range.end.0 as isize - selection.head().0 as isize),
11091 )
11092 } else {
11093 None
11094 }
11095 })
11096 });
11097
11098 cx.emit(EditorEvent::InputHandled {
11099 utf16_range_to_replace: range_to_replace,
11100 text: text.into(),
11101 });
11102
11103 if let Some(ranges) = ranges_to_replace {
11104 this.change_selections(None, cx, |s| s.select_ranges(ranges));
11105 }
11106
11107 let marked_ranges = {
11108 let snapshot = this.buffer.read(cx).read(cx);
11109 this.selections
11110 .disjoint_anchors()
11111 .iter()
11112 .map(|selection| {
11113 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
11114 })
11115 .collect::<Vec<_>>()
11116 };
11117
11118 if text.is_empty() {
11119 this.unmark_text(cx);
11120 } else {
11121 this.highlight_text::<InputComposition>(
11122 marked_ranges.clone(),
11123 HighlightStyle {
11124 underline: Some(UnderlineStyle {
11125 thickness: px(1.),
11126 color: None,
11127 wavy: false,
11128 }),
11129 ..Default::default()
11130 },
11131 cx,
11132 );
11133 }
11134
11135 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
11136 let use_autoclose = this.use_autoclose;
11137 this.set_use_autoclose(false);
11138 this.handle_input(text, cx);
11139 this.set_use_autoclose(use_autoclose);
11140
11141 if let Some(new_selected_range) = new_selected_range_utf16 {
11142 let snapshot = this.buffer.read(cx).read(cx);
11143 let new_selected_ranges = marked_ranges
11144 .into_iter()
11145 .map(|marked_range| {
11146 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
11147 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
11148 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
11149 snapshot.clip_offset_utf16(new_start, Bias::Left)
11150 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
11151 })
11152 .collect::<Vec<_>>();
11153
11154 drop(snapshot);
11155 this.change_selections(None, cx, |selections| {
11156 selections.select_ranges(new_selected_ranges)
11157 });
11158 }
11159 });
11160
11161 self.ime_transaction = self.ime_transaction.or(transaction);
11162 if let Some(transaction) = self.ime_transaction {
11163 self.buffer.update(cx, |buffer, cx| {
11164 buffer.group_until_transaction(transaction, cx);
11165 });
11166 }
11167
11168 if self.text_highlights::<InputComposition>(cx).is_none() {
11169 self.ime_transaction.take();
11170 }
11171 }
11172
11173 fn bounds_for_range(
11174 &mut self,
11175 range_utf16: Range<usize>,
11176 element_bounds: gpui::Bounds<Pixels>,
11177 cx: &mut ViewContext<Self>,
11178 ) -> Option<gpui::Bounds<Pixels>> {
11179 let text_layout_details = self.text_layout_details(cx);
11180 let style = &text_layout_details.editor_style;
11181 let font_id = cx.text_system().resolve_font(&style.text.font());
11182 let font_size = style.text.font_size.to_pixels(cx.rem_size());
11183 let line_height = style.text.line_height_in_pixels(cx.rem_size());
11184 let em_width = cx
11185 .text_system()
11186 .typographic_bounds(font_id, font_size, 'm')
11187 .unwrap()
11188 .size
11189 .width;
11190
11191 let snapshot = self.snapshot(cx);
11192 let scroll_position = snapshot.scroll_position();
11193 let scroll_left = scroll_position.x * em_width;
11194
11195 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
11196 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
11197 + self.gutter_dimensions.width;
11198 let y = line_height * (start.row() as f32 - scroll_position.y);
11199
11200 Some(Bounds {
11201 origin: element_bounds.origin + point(x, y),
11202 size: size(em_width, line_height),
11203 })
11204 }
11205}
11206
11207trait SelectionExt {
11208 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
11209 fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
11210 -> Range<u32>;
11211}
11212
11213impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
11214 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
11215 let start = self
11216 .start
11217 .to_point(&map.buffer_snapshot)
11218 .to_display_point(map);
11219 let end = self
11220 .end
11221 .to_point(&map.buffer_snapshot)
11222 .to_display_point(map);
11223 if self.reversed {
11224 end..start
11225 } else {
11226 start..end
11227 }
11228 }
11229
11230 fn spanned_rows(
11231 &self,
11232 include_end_if_at_line_start: bool,
11233 map: &DisplaySnapshot,
11234 ) -> Range<u32> {
11235 let start = self.start.to_point(&map.buffer_snapshot);
11236 let mut end = self.end.to_point(&map.buffer_snapshot);
11237 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
11238 end.row -= 1;
11239 }
11240
11241 let buffer_start = map.prev_line_boundary(start).0;
11242 let buffer_end = map.next_line_boundary(end).0;
11243 buffer_start.row..buffer_end.row + 1
11244 }
11245}
11246
11247impl<T: InvalidationRegion> InvalidationStack<T> {
11248 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
11249 where
11250 S: Clone + ToOffset,
11251 {
11252 while let Some(region) = self.last() {
11253 let all_selections_inside_invalidation_ranges =
11254 if selections.len() == region.ranges().len() {
11255 selections
11256 .iter()
11257 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
11258 .all(|(selection, invalidation_range)| {
11259 let head = selection.head().to_offset(buffer);
11260 invalidation_range.start <= head && invalidation_range.end >= head
11261 })
11262 } else {
11263 false
11264 };
11265
11266 if all_selections_inside_invalidation_ranges {
11267 break;
11268 } else {
11269 self.pop();
11270 }
11271 }
11272 }
11273}
11274
11275impl<T> Default for InvalidationStack<T> {
11276 fn default() -> Self {
11277 Self(Default::default())
11278 }
11279}
11280
11281impl<T> Deref for InvalidationStack<T> {
11282 type Target = Vec<T>;
11283
11284 fn deref(&self) -> &Self::Target {
11285 &self.0
11286 }
11287}
11288
11289impl<T> DerefMut for InvalidationStack<T> {
11290 fn deref_mut(&mut self) -> &mut Self::Target {
11291 &mut self.0
11292 }
11293}
11294
11295impl InvalidationRegion for SnippetState {
11296 fn ranges(&self) -> &[Range<Anchor>] {
11297 &self.ranges[self.active_index]
11298 }
11299}
11300
11301pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
11302 let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
11303
11304 Box::new(move |cx: &mut BlockContext| {
11305 let group_id: SharedString = cx.block_id.to_string().into();
11306
11307 let mut text_style = cx.text_style().clone();
11308 text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
11309 let theme_settings = ThemeSettings::get_global(cx);
11310 text_style.font_family = theme_settings.buffer_font.family.clone();
11311 text_style.font_style = theme_settings.buffer_font.style;
11312 text_style.font_features = theme_settings.buffer_font.features.clone();
11313 text_style.font_weight = theme_settings.buffer_font.weight;
11314
11315 let multi_line_diagnostic = diagnostic.message.contains('\n');
11316
11317 let buttons = |diagnostic: &Diagnostic, block_id: usize| {
11318 if multi_line_diagnostic {
11319 v_flex()
11320 } else {
11321 h_flex()
11322 }
11323 .children(diagnostic.is_primary.then(|| {
11324 IconButton::new(("close-block", block_id), IconName::XCircle)
11325 .icon_color(Color::Muted)
11326 .size(ButtonSize::Compact)
11327 .style(ButtonStyle::Transparent)
11328 .visible_on_hover(group_id.clone())
11329 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
11330 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
11331 }))
11332 .child(
11333 IconButton::new(("copy-block", block_id), IconName::Copy)
11334 .icon_color(Color::Muted)
11335 .size(ButtonSize::Compact)
11336 .style(ButtonStyle::Transparent)
11337 .visible_on_hover(group_id.clone())
11338 .on_click({
11339 let message = diagnostic.message.clone();
11340 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
11341 })
11342 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
11343 )
11344 };
11345
11346 let icon_size = buttons(&diagnostic, cx.block_id)
11347 .into_any_element()
11348 .layout_as_root(AvailableSpace::min_size(), cx);
11349
11350 h_flex()
11351 .id(cx.block_id)
11352 .group(group_id.clone())
11353 .relative()
11354 .size_full()
11355 .pl(cx.gutter_dimensions.width)
11356 .w(cx.max_width + cx.gutter_dimensions.width)
11357 .child(
11358 div()
11359 .flex()
11360 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
11361 .flex_shrink(),
11362 )
11363 .child(buttons(&diagnostic, cx.block_id))
11364 .child(div().flex().flex_shrink_0().child(
11365 StyledText::new(text_without_backticks.clone()).with_highlights(
11366 &text_style,
11367 code_ranges.iter().map(|range| {
11368 (
11369 range.clone(),
11370 HighlightStyle {
11371 font_weight: Some(FontWeight::BOLD),
11372 ..Default::default()
11373 },
11374 )
11375 }),
11376 ),
11377 ))
11378 .into_any_element()
11379 })
11380}
11381
11382pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
11383 let mut text_without_backticks = String::new();
11384 let mut code_ranges = Vec::new();
11385
11386 if let Some(source) = &diagnostic.source {
11387 text_without_backticks.push_str(&source);
11388 code_ranges.push(0..source.len());
11389 text_without_backticks.push_str(": ");
11390 }
11391
11392 let mut prev_offset = 0;
11393 let mut in_code_block = false;
11394 for (ix, _) in diagnostic
11395 .message
11396 .match_indices('`')
11397 .chain([(diagnostic.message.len(), "")])
11398 {
11399 let prev_len = text_without_backticks.len();
11400 text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
11401 prev_offset = ix + 1;
11402 if in_code_block {
11403 code_ranges.push(prev_len..text_without_backticks.len());
11404 in_code_block = false;
11405 } else {
11406 in_code_block = true;
11407 }
11408 }
11409
11410 (text_without_backticks.into(), code_ranges)
11411}
11412
11413fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
11414 match (severity, valid) {
11415 (DiagnosticSeverity::ERROR, true) => colors.error,
11416 (DiagnosticSeverity::ERROR, false) => colors.error,
11417 (DiagnosticSeverity::WARNING, true) => colors.warning,
11418 (DiagnosticSeverity::WARNING, false) => colors.warning,
11419 (DiagnosticSeverity::INFORMATION, true) => colors.info,
11420 (DiagnosticSeverity::INFORMATION, false) => colors.info,
11421 (DiagnosticSeverity::HINT, true) => colors.info,
11422 (DiagnosticSeverity::HINT, false) => colors.info,
11423 _ => colors.ignored,
11424 }
11425}
11426
11427pub fn styled_runs_for_code_label<'a>(
11428 label: &'a CodeLabel,
11429 syntax_theme: &'a theme::SyntaxTheme,
11430) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
11431 let fade_out = HighlightStyle {
11432 fade_out: Some(0.35),
11433 ..Default::default()
11434 };
11435
11436 let mut prev_end = label.filter_range.end;
11437 label
11438 .runs
11439 .iter()
11440 .enumerate()
11441 .flat_map(move |(ix, (range, highlight_id))| {
11442 let style = if let Some(style) = highlight_id.style(syntax_theme) {
11443 style
11444 } else {
11445 return Default::default();
11446 };
11447 let mut muted_style = style;
11448 muted_style.highlight(fade_out);
11449
11450 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
11451 if range.start >= label.filter_range.end {
11452 if range.start > prev_end {
11453 runs.push((prev_end..range.start, fade_out));
11454 }
11455 runs.push((range.clone(), muted_style));
11456 } else if range.end <= label.filter_range.end {
11457 runs.push((range.clone(), style));
11458 } else {
11459 runs.push((range.start..label.filter_range.end, style));
11460 runs.push((label.filter_range.end..range.end, muted_style));
11461 }
11462 prev_end = cmp::max(prev_end, range.end);
11463
11464 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
11465 runs.push((prev_end..label.text.len(), fade_out));
11466 }
11467
11468 runs
11469 })
11470}
11471
11472pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
11473 let mut prev_index = 0;
11474 let mut prev_codepoint: Option<char> = None;
11475 text.char_indices()
11476 .chain([(text.len(), '\0')])
11477 .filter_map(move |(index, codepoint)| {
11478 let prev_codepoint = prev_codepoint.replace(codepoint)?;
11479 let is_boundary = index == text.len()
11480 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
11481 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
11482 if is_boundary {
11483 let chunk = &text[prev_index..index];
11484 prev_index = index;
11485 Some(chunk)
11486 } else {
11487 None
11488 }
11489 })
11490}
11491
11492trait RangeToAnchorExt {
11493 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
11494}
11495
11496impl<T: ToOffset> RangeToAnchorExt for Range<T> {
11497 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
11498 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
11499 }
11500}