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