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