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