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