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