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