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