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