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