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