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::Item;
93use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};
94use rand::prelude::*;
95use rpc::proto::*;
96use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
97use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
98use serde::{Deserialize, Serialize};
99use settings::{Settings, SettingsStore};
100use smallvec::SmallVec;
101use snippet::Snippet;
102use std::{
103 any::TypeId,
104 borrow::Cow,
105 cmp::{self, Ordering, Reverse},
106 mem,
107 num::NonZeroU32,
108 ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
109 path::Path,
110 sync::Arc,
111 time::{Duration, Instant},
112};
113pub use sum_tree::Bias;
114use sum_tree::TreeMap;
115use text::{BufferId, OffsetUtf16, Rope};
116use theme::{
117 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
118 ThemeColors, ThemeSettings,
119};
120use ui::{
121 h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
122 Tooltip,
123};
124use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
125use workspace::Toast;
126use workspace::{searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace};
127
128use crate::hover_links::find_url;
129
130const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
131const MAX_LINE_LEN: usize = 1024;
132const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
133const MAX_SELECTION_HISTORY_LEN: usize = 1024;
134const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
135pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
136#[doc(hidden)]
137pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
138#[doc(hidden)]
139pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
140
141pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
142
143pub fn render_parsed_markdown(
144 element_id: impl Into<ElementId>,
145 parsed: &language::ParsedMarkdown,
146 editor_style: &EditorStyle,
147 workspace: Option<WeakView<Workspace>>,
148 cx: &mut ViewContext<Editor>,
149) -> InteractiveText {
150 let code_span_background_color = cx
151 .theme()
152 .colors()
153 .editor_document_highlight_read_background;
154
155 let highlights = gpui::combine_highlights(
156 parsed.highlights.iter().filter_map(|(range, highlight)| {
157 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
158 Some((range.clone(), highlight))
159 }),
160 parsed
161 .regions
162 .iter()
163 .zip(&parsed.region_ranges)
164 .filter_map(|(region, range)| {
165 if region.code {
166 Some((
167 range.clone(),
168 HighlightStyle {
169 background_color: Some(code_span_background_color),
170 ..Default::default()
171 },
172 ))
173 } else {
174 None
175 }
176 }),
177 );
178
179 let mut links = Vec::new();
180 let mut link_ranges = Vec::new();
181 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
182 if let Some(link) = region.link.clone() {
183 links.push(link);
184 link_ranges.push(range.clone());
185 }
186 }
187
188 InteractiveText::new(
189 element_id,
190 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
191 )
192 .on_click(link_ranges, move |clicked_range_ix, cx| {
193 match &links[clicked_range_ix] {
194 markdown::Link::Web { url } => cx.open_url(url),
195 markdown::Link::Path { path } => {
196 if let Some(workspace) = &workspace {
197 _ = workspace.update(cx, |workspace, cx| {
198 workspace.open_abs_path(path.clone(), false, cx).detach();
199 });
200 }
201 }
202 }
203 })
204}
205
206#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
207pub(crate) enum InlayId {
208 Suggestion(usize),
209 Hint(usize),
210}
211
212impl InlayId {
213 fn id(&self) -> usize {
214 match self {
215 Self::Suggestion(id) => *id,
216 Self::Hint(id) => *id,
217 }
218 }
219}
220
221enum DocumentHighlightRead {}
222enum DocumentHighlightWrite {}
223enum InputComposition {}
224
225#[derive(Copy, Clone, PartialEq, Eq)]
226pub enum Direction {
227 Prev,
228 Next,
229}
230
231pub fn init_settings(cx: &mut AppContext) {
232 EditorSettings::register(cx);
233}
234
235pub fn init(cx: &mut AppContext) {
236 init_settings(cx);
237
238 workspace::register_project_item::<Editor>(cx);
239 workspace::register_followable_item::<Editor>(cx);
240 workspace::register_deserializable_item::<Editor>(cx);
241 cx.observe_new_views(
242 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
243 workspace.register_action(Editor::new_file);
244 workspace.register_action(Editor::new_file_in_direction);
245 },
246 )
247 .detach();
248
249 cx.on_action(move |_: &workspace::NewFile, cx| {
250 let app_state = workspace::AppState::global(cx);
251 if let Some(app_state) = app_state.upgrade() {
252 workspace::open_new(&app_state, cx, |workspace, cx| {
253 Editor::new_file(workspace, &Default::default(), cx)
254 })
255 .detach();
256 }
257 });
258 cx.on_action(move |_: &workspace::NewWindow, cx| {
259 let app_state = workspace::AppState::global(cx);
260 if let Some(app_state) = app_state.upgrade() {
261 workspace::open_new(&app_state, cx, |workspace, cx| {
262 Editor::new_file(workspace, &Default::default(), cx)
263 })
264 .detach();
265 }
266 });
267}
268
269trait InvalidationRegion {
270 fn ranges(&self) -> &[Range<Anchor>];
271}
272
273#[derive(Clone, Debug, PartialEq)]
274pub enum SelectPhase {
275 Begin {
276 position: DisplayPoint,
277 add: bool,
278 click_count: usize,
279 },
280 BeginColumnar {
281 position: DisplayPoint,
282 goal_column: u32,
283 },
284 Extend {
285 position: DisplayPoint,
286 click_count: usize,
287 },
288 Update {
289 position: DisplayPoint,
290 goal_column: u32,
291 scroll_delta: gpui::Point<f32>,
292 },
293 End,
294}
295
296#[derive(Clone, Debug)]
297pub enum SelectMode {
298 Character,
299 Word(Range<Anchor>),
300 Line(Range<Anchor>),
301 All,
302}
303
304#[derive(Copy, Clone, PartialEq, Eq, Debug)]
305pub enum EditorMode {
306 SingleLine,
307 AutoHeight { max_lines: usize },
308 Full,
309}
310
311#[derive(Clone, Debug)]
312pub enum SoftWrap {
313 None,
314 EditorWidth,
315 Column(u32),
316}
317
318#[derive(Clone)]
319pub struct EditorStyle {
320 pub background: Hsla,
321 pub local_player: PlayerColor,
322 pub text: TextStyle,
323 pub scrollbar_width: Pixels,
324 pub syntax: Arc<SyntaxTheme>,
325 pub status: StatusColors,
326 pub inlays_style: HighlightStyle,
327 pub suggestions_style: HighlightStyle,
328}
329
330impl Default for EditorStyle {
331 fn default() -> Self {
332 Self {
333 background: Hsla::default(),
334 local_player: PlayerColor::default(),
335 text: TextStyle::default(),
336 scrollbar_width: Pixels::default(),
337 syntax: Default::default(),
338 // HACK: Status colors don't have a real default.
339 // We should look into removing the status colors from the editor
340 // style and retrieve them directly from the theme.
341 status: StatusColors::dark(),
342 inlays_style: HighlightStyle::default(),
343 suggestions_style: HighlightStyle::default(),
344 }
345 }
346}
347
348type CompletionId = usize;
349
350// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
351// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
352
353type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<Range<Anchor>>);
354type InlayBackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<InlayHighlight>);
355
356/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
357///
358/// See the [module level documentation](self) for more information.
359pub struct Editor {
360 focus_handle: FocusHandle,
361 /// The text buffer being edited
362 buffer: Model<MultiBuffer>,
363 /// Map of how text in the buffer should be displayed.
364 /// Handles soft wraps, folds, fake inlay text insertions, etc.
365 display_map: Model<DisplayMap>,
366 pub selections: SelectionsCollection,
367 pub scroll_manager: ScrollManager,
368 columnar_selection_tail: Option<Anchor>,
369 add_selections_state: Option<AddSelectionsState>,
370 select_next_state: Option<SelectNextState>,
371 select_prev_state: Option<SelectNextState>,
372 selection_history: SelectionHistory,
373 autoclose_regions: Vec<AutocloseRegion>,
374 snippet_stack: InvalidationStack<SnippetState>,
375 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
376 ime_transaction: Option<TransactionId>,
377 active_diagnostics: Option<ActiveDiagnosticGroup>,
378 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
379 project: Option<Model<Project>>,
380 completion_provider: Option<Box<dyn CompletionProvider>>,
381 collaboration_hub: Option<Box<dyn CollaborationHub>>,
382 blink_manager: Model<BlinkManager>,
383 show_cursor_names: bool,
384 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
385 pub show_local_selections: bool,
386 mode: EditorMode,
387 show_breadcrumbs: bool,
388 show_gutter: bool,
389 show_wrap_guides: Option<bool>,
390 placeholder_text: Option<Arc<str>>,
391 highlighted_rows: Option<Range<u32>>,
392 background_highlights: BTreeMap<TypeId, BackgroundHighlight>,
393 inlay_background_highlights: TreeMap<Option<TypeId>, InlayBackgroundHighlight>,
394 nav_history: Option<ItemNavHistory>,
395 context_menu: RwLock<Option<ContextMenu>>,
396 mouse_context_menu: Option<MouseContextMenu>,
397 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
398 next_completion_id: CompletionId,
399 completion_documentation_pre_resolve_debounce: DebouncedDelay,
400 available_code_actions: Option<(Model<Buffer>, Arc<[CodeAction]>)>,
401 code_actions_task: Option<Task<()>>,
402 document_highlights_task: Option<Task<()>>,
403 pending_rename: Option<RenameState>,
404 searchable: bool,
405 cursor_shape: CursorShape,
406 collapse_matches: bool,
407 autoindent_mode: Option<AutoindentMode>,
408 workspace: Option<(WeakView<Workspace>, i64)>,
409 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
410 input_enabled: bool,
411 use_modal_editing: bool,
412 read_only: bool,
413 leader_peer_id: Option<PeerId>,
414 remote_id: Option<ViewId>,
415 hover_state: HoverState,
416 gutter_hovered: bool,
417 hovered_link_state: Option<HoveredLinkState>,
418 copilot_state: CopilotState,
419 inlay_hint_cache: InlayHintCache,
420 next_inlay_id: usize,
421 _subscriptions: Vec<Subscription>,
422 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
423 gutter_width: Pixels,
424 style: Option<EditorStyle>,
425 editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
426 show_copilot_suggestions: bool,
427 use_autoclose: bool,
428 custom_context_menu: Option<
429 Box<
430 dyn 'static
431 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
432 >,
433 >,
434}
435
436pub struct EditorSnapshot {
437 pub mode: EditorMode,
438 show_gutter: bool,
439 pub display_snapshot: DisplaySnapshot,
440 pub placeholder_text: Option<Arc<str>>,
441 is_focused: bool,
442 scroll_anchor: ScrollAnchor,
443 ongoing_scroll: OngoingScroll,
444}
445
446pub struct GutterDimensions {
447 pub left_padding: Pixels,
448 pub right_padding: Pixels,
449 pub width: Pixels,
450 pub margin: Pixels,
451}
452
453impl Default for GutterDimensions {
454 fn default() -> Self {
455 Self {
456 left_padding: Pixels::ZERO,
457 right_padding: Pixels::ZERO,
458 width: Pixels::ZERO,
459 margin: Pixels::ZERO,
460 }
461 }
462}
463
464#[derive(Debug)]
465pub struct RemoteSelection {
466 pub replica_id: ReplicaId,
467 pub selection: Selection<Anchor>,
468 pub cursor_shape: CursorShape,
469 pub peer_id: PeerId,
470 pub line_mode: bool,
471 pub participant_index: Option<ParticipantIndex>,
472 pub user_name: Option<SharedString>,
473}
474
475#[derive(Clone, Debug)]
476struct SelectionHistoryEntry {
477 selections: Arc<[Selection<Anchor>]>,
478 select_next_state: Option<SelectNextState>,
479 select_prev_state: Option<SelectNextState>,
480 add_selections_state: Option<AddSelectionsState>,
481}
482
483enum SelectionHistoryMode {
484 Normal,
485 Undoing,
486 Redoing,
487}
488
489#[derive(Clone, PartialEq, Eq, Hash)]
490struct HoveredCursor {
491 replica_id: u16,
492 selection_id: usize,
493}
494
495impl Default for SelectionHistoryMode {
496 fn default() -> Self {
497 Self::Normal
498 }
499}
500
501#[derive(Default)]
502struct SelectionHistory {
503 #[allow(clippy::type_complexity)]
504 selections_by_transaction:
505 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
506 mode: SelectionHistoryMode,
507 undo_stack: VecDeque<SelectionHistoryEntry>,
508 redo_stack: VecDeque<SelectionHistoryEntry>,
509}
510
511impl SelectionHistory {
512 fn insert_transaction(
513 &mut self,
514 transaction_id: TransactionId,
515 selections: Arc<[Selection<Anchor>]>,
516 ) {
517 self.selections_by_transaction
518 .insert(transaction_id, (selections, None));
519 }
520
521 #[allow(clippy::type_complexity)]
522 fn transaction(
523 &self,
524 transaction_id: TransactionId,
525 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
526 self.selections_by_transaction.get(&transaction_id)
527 }
528
529 #[allow(clippy::type_complexity)]
530 fn transaction_mut(
531 &mut self,
532 transaction_id: TransactionId,
533 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
534 self.selections_by_transaction.get_mut(&transaction_id)
535 }
536
537 fn push(&mut self, entry: SelectionHistoryEntry) {
538 if !entry.selections.is_empty() {
539 match self.mode {
540 SelectionHistoryMode::Normal => {
541 self.push_undo(entry);
542 self.redo_stack.clear();
543 }
544 SelectionHistoryMode::Undoing => self.push_redo(entry),
545 SelectionHistoryMode::Redoing => self.push_undo(entry),
546 }
547 }
548 }
549
550 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
551 if self
552 .undo_stack
553 .back()
554 .map_or(true, |e| e.selections != entry.selections)
555 {
556 self.undo_stack.push_back(entry);
557 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
558 self.undo_stack.pop_front();
559 }
560 }
561 }
562
563 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
564 if self
565 .redo_stack
566 .back()
567 .map_or(true, |e| e.selections != entry.selections)
568 {
569 self.redo_stack.push_back(entry);
570 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
571 self.redo_stack.pop_front();
572 }
573 }
574 }
575}
576
577#[derive(Clone, Debug)]
578struct AddSelectionsState {
579 above: bool,
580 stack: Vec<usize>,
581}
582
583#[derive(Clone)]
584struct SelectNextState {
585 query: AhoCorasick,
586 wordwise: bool,
587 done: bool,
588}
589
590impl std::fmt::Debug for SelectNextState {
591 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
592 f.debug_struct(std::any::type_name::<Self>())
593 .field("wordwise", &self.wordwise)
594 .field("done", &self.done)
595 .finish()
596 }
597}
598
599#[derive(Debug)]
600struct AutocloseRegion {
601 selection_id: usize,
602 range: Range<Anchor>,
603 pair: BracketPair,
604}
605
606#[derive(Debug)]
607struct SnippetState {
608 ranges: Vec<Vec<Range<Anchor>>>,
609 active_index: usize,
610}
611
612#[doc(hidden)]
613pub struct RenameState {
614 pub range: Range<Anchor>,
615 pub old_name: Arc<str>,
616 pub editor: View<Editor>,
617 block_id: BlockId,
618}
619
620struct InvalidationStack<T>(Vec<T>);
621
622enum ContextMenu {
623 Completions(CompletionsMenu),
624 CodeActions(CodeActionsMenu),
625}
626
627impl ContextMenu {
628 fn select_first(
629 &mut self,
630 project: Option<&Model<Project>>,
631 cx: &mut ViewContext<Editor>,
632 ) -> bool {
633 if self.visible() {
634 match self {
635 ContextMenu::Completions(menu) => menu.select_first(project, cx),
636 ContextMenu::CodeActions(menu) => menu.select_first(cx),
637 }
638 true
639 } else {
640 false
641 }
642 }
643
644 fn select_prev(
645 &mut self,
646 project: Option<&Model<Project>>,
647 cx: &mut ViewContext<Editor>,
648 ) -> bool {
649 if self.visible() {
650 match self {
651 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
652 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
653 }
654 true
655 } else {
656 false
657 }
658 }
659
660 fn select_next(
661 &mut self,
662 project: Option<&Model<Project>>,
663 cx: &mut ViewContext<Editor>,
664 ) -> bool {
665 if self.visible() {
666 match self {
667 ContextMenu::Completions(menu) => menu.select_next(project, cx),
668 ContextMenu::CodeActions(menu) => menu.select_next(cx),
669 }
670 true
671 } else {
672 false
673 }
674 }
675
676 fn select_last(
677 &mut self,
678 project: Option<&Model<Project>>,
679 cx: &mut ViewContext<Editor>,
680 ) -> bool {
681 if self.visible() {
682 match self {
683 ContextMenu::Completions(menu) => menu.select_last(project, cx),
684 ContextMenu::CodeActions(menu) => menu.select_last(cx),
685 }
686 true
687 } else {
688 false
689 }
690 }
691
692 fn visible(&self) -> bool {
693 match self {
694 ContextMenu::Completions(menu) => menu.visible(),
695 ContextMenu::CodeActions(menu) => menu.visible(),
696 }
697 }
698
699 fn render(
700 &self,
701 cursor_position: DisplayPoint,
702 style: &EditorStyle,
703 max_height: Pixels,
704 workspace: Option<WeakView<Workspace>>,
705 cx: &mut ViewContext<Editor>,
706 ) -> (DisplayPoint, AnyElement) {
707 match self {
708 ContextMenu::Completions(menu) => (
709 cursor_position,
710 menu.render(style, max_height, workspace, cx),
711 ),
712 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
713 }
714 }
715}
716
717#[derive(Clone)]
718struct CompletionsMenu {
719 id: CompletionId,
720 initial_position: Anchor,
721 buffer: Model<Buffer>,
722 completions: Arc<RwLock<Box<[Completion]>>>,
723 match_candidates: Arc<[StringMatchCandidate]>,
724 matches: Arc<[StringMatch]>,
725 selected_item: usize,
726 scroll_handle: UniformListScrollHandle,
727 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
728}
729
730impl CompletionsMenu {
731 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
732 self.selected_item = 0;
733 self.scroll_handle.scroll_to_item(self.selected_item);
734 self.attempt_resolve_selected_completion_documentation(project, cx);
735 cx.notify();
736 }
737
738 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
739 if self.selected_item > 0 {
740 self.selected_item -= 1;
741 } else {
742 self.selected_item = self.matches.len() - 1;
743 }
744 self.scroll_handle.scroll_to_item(self.selected_item);
745 self.attempt_resolve_selected_completion_documentation(project, cx);
746 cx.notify();
747 }
748
749 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
750 if self.selected_item + 1 < self.matches.len() {
751 self.selected_item += 1;
752 } else {
753 self.selected_item = 0;
754 }
755 self.scroll_handle.scroll_to_item(self.selected_item);
756 self.attempt_resolve_selected_completion_documentation(project, cx);
757 cx.notify();
758 }
759
760 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
761 self.selected_item = self.matches.len() - 1;
762 self.scroll_handle.scroll_to_item(self.selected_item);
763 self.attempt_resolve_selected_completion_documentation(project, cx);
764 cx.notify();
765 }
766
767 fn pre_resolve_completion_documentation(
768 completions: Arc<RwLock<Box<[Completion]>>>,
769 matches: Arc<[StringMatch]>,
770 editor: &Editor,
771 cx: &mut ViewContext<Editor>,
772 ) -> Task<()> {
773 let settings = EditorSettings::get_global(cx);
774 if !settings.show_completion_documentation {
775 return Task::ready(());
776 }
777
778 let Some(provider) = editor.completion_provider.as_ref() else {
779 return Task::ready(());
780 };
781
782 let resolve_task = provider.resolve_completions(
783 matches.iter().map(|m| m.candidate_id).collect(),
784 completions.clone(),
785 cx,
786 );
787
788 return cx.spawn(move |this, mut cx| async move {
789 if let Some(true) = resolve_task.await.log_err() {
790 this.update(&mut cx, |_, cx| cx.notify()).ok();
791 }
792 });
793 }
794
795 fn attempt_resolve_selected_completion_documentation(
796 &mut self,
797 project: Option<&Model<Project>>,
798 cx: &mut ViewContext<Editor>,
799 ) {
800 let settings = EditorSettings::get_global(cx);
801 if !settings.show_completion_documentation {
802 return;
803 }
804
805 let completion_index = self.matches[self.selected_item].candidate_id;
806 let Some(project) = project else {
807 return;
808 };
809
810 let resolve_task = project.update(cx, |project, cx| {
811 project.resolve_completions(vec![completion_index], self.completions.clone(), cx)
812 });
813
814 let delay_ms =
815 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
816 let delay = Duration::from_millis(delay_ms);
817
818 self.selected_completion_documentation_resolve_debounce
819 .lock()
820 .fire_new(delay, cx, |_, cx| {
821 cx.spawn(move |this, mut cx| async move {
822 if let Some(true) = resolve_task.await.log_err() {
823 this.update(&mut cx, |_, cx| cx.notify()).ok();
824 }
825 })
826 });
827 }
828
829 fn visible(&self) -> bool {
830 !self.matches.is_empty()
831 }
832
833 fn render(
834 &self,
835 style: &EditorStyle,
836 max_height: Pixels,
837 workspace: Option<WeakView<Workspace>>,
838 cx: &mut ViewContext<Editor>,
839 ) -> AnyElement {
840 let settings = EditorSettings::get_global(cx);
841 let show_completion_documentation = settings.show_completion_documentation;
842
843 let widest_completion_ix = self
844 .matches
845 .iter()
846 .enumerate()
847 .max_by_key(|(_, mat)| {
848 let completions = self.completions.read();
849 let completion = &completions[mat.candidate_id];
850 let documentation = &completion.documentation;
851
852 let mut len = completion.label.text.chars().count();
853 if let Some(Documentation::SingleLine(text)) = documentation {
854 if show_completion_documentation {
855 len += text.chars().count();
856 }
857 }
858
859 len
860 })
861 .map(|(ix, _)| ix);
862
863 let completions = self.completions.clone();
864 let matches = self.matches.clone();
865 let selected_item = self.selected_item;
866 let style = style.clone();
867
868 let multiline_docs = if show_completion_documentation {
869 let mat = &self.matches[selected_item];
870 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
871 Some(Documentation::MultiLinePlainText(text)) => {
872 Some(div().child(SharedString::from(text.clone())))
873 }
874 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
875 Some(div().child(render_parsed_markdown(
876 "completions_markdown",
877 parsed,
878 &style,
879 workspace,
880 cx,
881 )))
882 }
883 _ => None,
884 };
885 multiline_docs.map(|div| {
886 div.id("multiline_docs")
887 .max_h(max_height)
888 .flex_1()
889 .px_1p5()
890 .py_1()
891 .min_w(px(260.))
892 .max_w(px(640.))
893 .w(px(500.))
894 .overflow_y_scroll()
895 // Prevent a mouse down on documentation from being propagated to the editor,
896 // because that would move the cursor.
897 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
898 })
899 } else {
900 None
901 };
902
903 let list = uniform_list(
904 cx.view().clone(),
905 "completions",
906 matches.len(),
907 move |_editor, range, cx| {
908 let start_ix = range.start;
909 let completions_guard = completions.read();
910
911 matches[range]
912 .iter()
913 .enumerate()
914 .map(|(ix, mat)| {
915 let item_ix = start_ix + ix;
916 let candidate_id = mat.candidate_id;
917 let completion = &completions_guard[candidate_id];
918
919 let documentation = if show_completion_documentation {
920 &completion.documentation
921 } else {
922 &None
923 };
924
925 let highlights = gpui::combine_highlights(
926 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
927 styled_runs_for_code_label(&completion.label, &style.syntax).map(
928 |(range, mut highlight)| {
929 // Ignore font weight for syntax highlighting, as we'll use it
930 // for fuzzy matches.
931 highlight.font_weight = None;
932 (range, highlight)
933 },
934 ),
935 );
936 let completion_label = StyledText::new(completion.label.text.clone())
937 .with_highlights(&style.text, highlights);
938 let documentation_label =
939 if let Some(Documentation::SingleLine(text)) = documentation {
940 if text.trim().is_empty() {
941 None
942 } else {
943 Some(
944 h_flex().ml_4().child(
945 Label::new(text.clone())
946 .size(LabelSize::Small)
947 .color(Color::Muted),
948 ),
949 )
950 }
951 } else {
952 None
953 };
954
955 div().min_w(px(220.)).max_w(px(540.)).child(
956 ListItem::new(mat.candidate_id)
957 .inset(true)
958 .selected(item_ix == selected_item)
959 .on_click(cx.listener(move |editor, _event, cx| {
960 cx.stop_propagation();
961 if let Some(task) = editor.confirm_completion(
962 &ConfirmCompletion {
963 item_ix: Some(item_ix),
964 },
965 cx,
966 ) {
967 task.detach_and_log_err(cx)
968 }
969 }))
970 .child(h_flex().overflow_hidden().child(completion_label))
971 .end_slot::<Div>(documentation_label),
972 )
973 })
974 .collect()
975 },
976 )
977 .max_h(max_height)
978 .track_scroll(self.scroll_handle.clone())
979 .with_width_from_item(widest_completion_ix);
980
981 Popover::new()
982 .child(list)
983 .when_some(multiline_docs, |popover, multiline_docs| {
984 popover.aside(multiline_docs)
985 })
986 .into_any_element()
987 }
988
989 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
990 let mut matches = if let Some(query) = query {
991 fuzzy::match_strings(
992 &self.match_candidates,
993 query,
994 query.chars().any(|c| c.is_uppercase()),
995 100,
996 &Default::default(),
997 executor,
998 )
999 .await
1000 } else {
1001 self.match_candidates
1002 .iter()
1003 .enumerate()
1004 .map(|(candidate_id, candidate)| StringMatch {
1005 candidate_id,
1006 score: Default::default(),
1007 positions: Default::default(),
1008 string: candidate.string.clone(),
1009 })
1010 .collect()
1011 };
1012
1013 // Remove all candidates where the query's start does not match the start of any word in the candidate
1014 if let Some(query) = query {
1015 if let Some(query_start) = query.chars().next() {
1016 matches.retain(|string_match| {
1017 split_words(&string_match.string).any(|word| {
1018 // Check that the first codepoint of the word as lowercase matches the first
1019 // codepoint of the query as lowercase
1020 word.chars()
1021 .flat_map(|codepoint| codepoint.to_lowercase())
1022 .zip(query_start.to_lowercase())
1023 .all(|(word_cp, query_cp)| word_cp == query_cp)
1024 })
1025 });
1026 }
1027 }
1028
1029 let completions = self.completions.read();
1030 matches.sort_unstable_by_key(|mat| {
1031 // We do want to strike a balance here between what the language server tells us
1032 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1033 // `Creat` and there is a local variable called `CreateComponent`).
1034 // So what we do is: we bucket all matches into two buckets
1035 // - Strong matches
1036 // - Weak matches
1037 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1038 // and the Weak matches are the rest.
1039 //
1040 // For the strong matches, we sort by the language-servers score first and for the weak
1041 // matches, we prefer our fuzzy finder first.
1042 //
1043 // The thinking behind that: it's useless to take the sort_text the language-server gives
1044 // us into account when it's obviously a bad match.
1045
1046 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1047 enum MatchScore<'a> {
1048 Strong {
1049 sort_text: Option<&'a str>,
1050 score: Reverse<OrderedFloat<f64>>,
1051 sort_key: (usize, &'a str),
1052 },
1053 Weak {
1054 score: Reverse<OrderedFloat<f64>>,
1055 sort_text: Option<&'a str>,
1056 sort_key: (usize, &'a str),
1057 },
1058 }
1059
1060 let completion = &completions[mat.candidate_id];
1061 let sort_key = completion.sort_key();
1062 let sort_text = completion.lsp_completion.sort_text.as_deref();
1063 let score = Reverse(OrderedFloat(mat.score));
1064
1065 if mat.score >= 0.2 {
1066 MatchScore::Strong {
1067 sort_text,
1068 score,
1069 sort_key,
1070 }
1071 } else {
1072 MatchScore::Weak {
1073 score,
1074 sort_text,
1075 sort_key,
1076 }
1077 }
1078 });
1079
1080 for mat in &mut matches {
1081 let completion = &completions[mat.candidate_id];
1082 mat.string = completion.label.text.clone();
1083 for position in &mut mat.positions {
1084 *position += completion.label.filter_range.start;
1085 }
1086 }
1087 drop(completions);
1088
1089 self.matches = matches.into();
1090 self.selected_item = 0;
1091 }
1092}
1093
1094#[derive(Clone)]
1095struct CodeActionsMenu {
1096 actions: Arc<[CodeAction]>,
1097 buffer: Model<Buffer>,
1098 selected_item: usize,
1099 scroll_handle: UniformListScrollHandle,
1100 deployed_from_indicator: bool,
1101}
1102
1103impl CodeActionsMenu {
1104 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1105 self.selected_item = 0;
1106 self.scroll_handle.scroll_to_item(self.selected_item);
1107 cx.notify()
1108 }
1109
1110 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1111 if self.selected_item > 0 {
1112 self.selected_item -= 1;
1113 } else {
1114 self.selected_item = self.actions.len() - 1;
1115 }
1116 self.scroll_handle.scroll_to_item(self.selected_item);
1117 cx.notify();
1118 }
1119
1120 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1121 if self.selected_item + 1 < self.actions.len() {
1122 self.selected_item += 1;
1123 } else {
1124 self.selected_item = 0;
1125 }
1126 self.scroll_handle.scroll_to_item(self.selected_item);
1127 cx.notify();
1128 }
1129
1130 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1131 self.selected_item = self.actions.len() - 1;
1132 self.scroll_handle.scroll_to_item(self.selected_item);
1133 cx.notify()
1134 }
1135
1136 fn visible(&self) -> bool {
1137 !self.actions.is_empty()
1138 }
1139
1140 fn render(
1141 &self,
1142 mut cursor_position: DisplayPoint,
1143 _style: &EditorStyle,
1144 max_height: Pixels,
1145 cx: &mut ViewContext<Editor>,
1146 ) -> (DisplayPoint, AnyElement) {
1147 let actions = self.actions.clone();
1148 let selected_item = self.selected_item;
1149
1150 let element = uniform_list(
1151 cx.view().clone(),
1152 "code_actions_menu",
1153 self.actions.len(),
1154 move |_this, range, cx| {
1155 actions[range.clone()]
1156 .iter()
1157 .enumerate()
1158 .map(|(ix, action)| {
1159 let item_ix = range.start + ix;
1160 let selected = selected_item == item_ix;
1161 let colors = cx.theme().colors();
1162 div()
1163 .px_2()
1164 .text_color(colors.text)
1165 .when(selected, |style| {
1166 style
1167 .bg(colors.element_active)
1168 .text_color(colors.text_accent)
1169 })
1170 .hover(|style| {
1171 style
1172 .bg(colors.element_hover)
1173 .text_color(colors.text_accent)
1174 })
1175 .on_mouse_down(
1176 MouseButton::Left,
1177 cx.listener(move |editor, _, cx| {
1178 cx.stop_propagation();
1179 if let Some(task) = editor.confirm_code_action(
1180 &ConfirmCodeAction {
1181 item_ix: Some(item_ix),
1182 },
1183 cx,
1184 ) {
1185 task.detach_and_log_err(cx)
1186 }
1187 }),
1188 )
1189 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1190 .child(SharedString::from(action.lsp_action.title.clone()))
1191 })
1192 .collect()
1193 },
1194 )
1195 .elevation_1(cx)
1196 .px_2()
1197 .py_1()
1198 .max_h(max_height)
1199 .track_scroll(self.scroll_handle.clone())
1200 .with_width_from_item(
1201 self.actions
1202 .iter()
1203 .enumerate()
1204 .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
1205 .map(|(ix, _)| ix),
1206 )
1207 .into_any_element();
1208
1209 if self.deployed_from_indicator {
1210 *cursor_position.column_mut() = 0;
1211 }
1212
1213 (cursor_position, element)
1214 }
1215}
1216
1217pub(crate) struct CopilotState {
1218 excerpt_id: Option<ExcerptId>,
1219 pending_refresh: Task<Option<()>>,
1220 pending_cycling_refresh: Task<Option<()>>,
1221 cycled: bool,
1222 completions: Vec<copilot::Completion>,
1223 active_completion_index: usize,
1224 suggestion: Option<Inlay>,
1225}
1226
1227impl Default for CopilotState {
1228 fn default() -> Self {
1229 Self {
1230 excerpt_id: None,
1231 pending_cycling_refresh: Task::ready(Some(())),
1232 pending_refresh: Task::ready(Some(())),
1233 completions: Default::default(),
1234 active_completion_index: 0,
1235 cycled: false,
1236 suggestion: None,
1237 }
1238 }
1239}
1240
1241impl CopilotState {
1242 fn active_completion(&self) -> Option<&copilot::Completion> {
1243 self.completions.get(self.active_completion_index)
1244 }
1245
1246 fn text_for_active_completion(
1247 &self,
1248 cursor: Anchor,
1249 buffer: &MultiBufferSnapshot,
1250 ) -> Option<&str> {
1251 use language::ToOffset as _;
1252
1253 let completion = self.active_completion()?;
1254 let excerpt_id = self.excerpt_id?;
1255 let completion_buffer = buffer.buffer_for_excerpt(excerpt_id)?;
1256 if excerpt_id != cursor.excerpt_id
1257 || !completion.range.start.is_valid(completion_buffer)
1258 || !completion.range.end.is_valid(completion_buffer)
1259 {
1260 return None;
1261 }
1262
1263 let mut completion_range = completion.range.to_offset(&completion_buffer);
1264 let prefix_len = Self::common_prefix(
1265 completion_buffer.chars_for_range(completion_range.clone()),
1266 completion.text.chars(),
1267 );
1268 completion_range.start += prefix_len;
1269 let suffix_len = Self::common_prefix(
1270 completion_buffer.reversed_chars_for_range(completion_range.clone()),
1271 completion.text[prefix_len..].chars().rev(),
1272 );
1273 completion_range.end = completion_range.end.saturating_sub(suffix_len);
1274
1275 if completion_range.is_empty()
1276 && completion_range.start == cursor.text_anchor.to_offset(&completion_buffer)
1277 {
1278 let completion_text = &completion.text[prefix_len..completion.text.len() - suffix_len];
1279 if completion_text.trim().is_empty() {
1280 None
1281 } else {
1282 Some(completion_text)
1283 }
1284 } else {
1285 None
1286 }
1287 }
1288
1289 fn cycle_completions(&mut self, direction: Direction) {
1290 match direction {
1291 Direction::Prev => {
1292 self.active_completion_index = if self.active_completion_index == 0 {
1293 self.completions.len().saturating_sub(1)
1294 } else {
1295 self.active_completion_index - 1
1296 };
1297 }
1298 Direction::Next => {
1299 if self.completions.len() == 0 {
1300 self.active_completion_index = 0
1301 } else {
1302 self.active_completion_index =
1303 (self.active_completion_index + 1) % self.completions.len();
1304 }
1305 }
1306 }
1307 }
1308
1309 fn push_completion(&mut self, new_completion: copilot::Completion) {
1310 for completion in &self.completions {
1311 if completion.text == new_completion.text && completion.range == new_completion.range {
1312 return;
1313 }
1314 }
1315 self.completions.push(new_completion);
1316 }
1317
1318 fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b: T2) -> usize {
1319 a.zip(b)
1320 .take_while(|(a, b)| a == b)
1321 .map(|(a, _)| a.len_utf8())
1322 .sum()
1323 }
1324}
1325
1326#[derive(Debug)]
1327struct ActiveDiagnosticGroup {
1328 primary_range: Range<Anchor>,
1329 primary_message: String,
1330 blocks: HashMap<BlockId, Diagnostic>,
1331 is_valid: bool,
1332}
1333
1334#[derive(Serialize, Deserialize)]
1335pub struct ClipboardSelection {
1336 pub len: usize,
1337 pub is_entire_line: bool,
1338 pub first_line_indent: u32,
1339}
1340
1341#[derive(Debug)]
1342pub(crate) struct NavigationData {
1343 cursor_anchor: Anchor,
1344 cursor_position: Point,
1345 scroll_anchor: ScrollAnchor,
1346 scroll_top_row: u32,
1347}
1348
1349enum GotoDefinitionKind {
1350 Symbol,
1351 Type,
1352 Implementation,
1353}
1354
1355#[derive(Debug, Clone)]
1356enum InlayHintRefreshReason {
1357 Toggle(bool),
1358 SettingsChange(InlayHintSettings),
1359 NewLinesShown,
1360 BufferEdited(HashSet<Arc<Language>>),
1361 RefreshRequested,
1362 ExcerptsRemoved(Vec<ExcerptId>),
1363}
1364
1365impl InlayHintRefreshReason {
1366 fn description(&self) -> &'static str {
1367 match self {
1368 Self::Toggle(_) => "toggle",
1369 Self::SettingsChange(_) => "settings change",
1370 Self::NewLinesShown => "new lines shown",
1371 Self::BufferEdited(_) => "buffer edited",
1372 Self::RefreshRequested => "refresh requested",
1373 Self::ExcerptsRemoved(_) => "excerpts removed",
1374 }
1375 }
1376}
1377
1378impl Editor {
1379 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1380 let buffer = cx.new_model(|cx| {
1381 Buffer::new(
1382 0,
1383 BufferId::new(cx.entity_id().as_u64()).unwrap(),
1384 String::new(),
1385 )
1386 });
1387 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1388 Self::new(EditorMode::SingleLine, buffer, None, cx)
1389 }
1390
1391 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1392 let buffer = cx.new_model(|cx| {
1393 Buffer::new(
1394 0,
1395 BufferId::new(cx.entity_id().as_u64()).unwrap(),
1396 String::new(),
1397 )
1398 });
1399 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1400 Self::new(EditorMode::Full, buffer, None, cx)
1401 }
1402
1403 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1404 let buffer = cx.new_model(|cx| {
1405 Buffer::new(
1406 0,
1407 BufferId::new(cx.entity_id().as_u64()).unwrap(),
1408 String::new(),
1409 )
1410 });
1411 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1412 Self::new(EditorMode::AutoHeight { max_lines }, buffer, None, cx)
1413 }
1414
1415 pub fn for_buffer(
1416 buffer: Model<Buffer>,
1417 project: Option<Model<Project>>,
1418 cx: &mut ViewContext<Self>,
1419 ) -> Self {
1420 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1421 Self::new(EditorMode::Full, buffer, project, cx)
1422 }
1423
1424 pub fn for_multibuffer(
1425 buffer: Model<MultiBuffer>,
1426 project: Option<Model<Project>>,
1427 cx: &mut ViewContext<Self>,
1428 ) -> Self {
1429 Self::new(EditorMode::Full, buffer, project, cx)
1430 }
1431
1432 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1433 let mut clone = Self::new(self.mode, self.buffer.clone(), self.project.clone(), cx);
1434 self.display_map.update(cx, |display_map, cx| {
1435 let snapshot = display_map.snapshot(cx);
1436 clone.display_map.update(cx, |display_map, cx| {
1437 display_map.set_state(&snapshot, cx);
1438 });
1439 });
1440 clone.selections.clone_state(&self.selections);
1441 clone.scroll_manager.clone_state(&self.scroll_manager);
1442 clone.searchable = self.searchable;
1443 clone
1444 }
1445
1446 fn new(
1447 mode: EditorMode,
1448 buffer: Model<MultiBuffer>,
1449 project: Option<Model<Project>>,
1450 cx: &mut ViewContext<Self>,
1451 ) -> Self {
1452 let style = cx.text_style();
1453 let font_size = style.font_size.to_pixels(cx.rem_size());
1454 let display_map = cx.new_model(|cx| {
1455 DisplayMap::new(buffer.clone(), style.font(), font_size, None, 2, 1, cx)
1456 });
1457
1458 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1459
1460 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1461
1462 let soft_wrap_mode_override =
1463 (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::None);
1464
1465 let mut project_subscriptions = Vec::new();
1466 if mode == EditorMode::Full {
1467 if let Some(project) = project.as_ref() {
1468 if buffer.read(cx).is_singleton() {
1469 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1470 cx.emit(EditorEvent::TitleChanged);
1471 }));
1472 }
1473 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1474 if let project::Event::RefreshInlayHints = event {
1475 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1476 };
1477 }));
1478 }
1479 }
1480
1481 let inlay_hint_settings = inlay_hint_settings(
1482 selections.newest_anchor().head(),
1483 &buffer.read(cx).snapshot(cx),
1484 cx,
1485 );
1486
1487 let focus_handle = cx.focus_handle();
1488 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1489 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1490
1491 let mut this = Self {
1492 focus_handle,
1493 buffer: buffer.clone(),
1494 display_map: display_map.clone(),
1495 selections,
1496 scroll_manager: ScrollManager::new(cx),
1497 columnar_selection_tail: None,
1498 add_selections_state: None,
1499 select_next_state: None,
1500 select_prev_state: None,
1501 selection_history: Default::default(),
1502 autoclose_regions: Default::default(),
1503 snippet_stack: Default::default(),
1504 select_larger_syntax_node_stack: Vec::new(),
1505 ime_transaction: Default::default(),
1506 active_diagnostics: None,
1507 soft_wrap_mode_override,
1508 completion_provider: project.clone().map(|project| Box::new(project) as _),
1509 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1510 project,
1511 blink_manager: blink_manager.clone(),
1512 show_local_selections: true,
1513 mode,
1514 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1515 show_gutter: mode == EditorMode::Full,
1516 show_wrap_guides: None,
1517 placeholder_text: None,
1518 highlighted_rows: None,
1519 background_highlights: Default::default(),
1520 inlay_background_highlights: Default::default(),
1521 nav_history: None,
1522 context_menu: RwLock::new(None),
1523 mouse_context_menu: None,
1524 completion_tasks: Default::default(),
1525 next_completion_id: 0,
1526 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1527 next_inlay_id: 0,
1528 available_code_actions: Default::default(),
1529 code_actions_task: Default::default(),
1530 document_highlights_task: Default::default(),
1531 pending_rename: Default::default(),
1532 searchable: true,
1533 cursor_shape: Default::default(),
1534 autoindent_mode: Some(AutoindentMode::EachLine),
1535 collapse_matches: false,
1536 workspace: None,
1537 keymap_context_layers: Default::default(),
1538 input_enabled: true,
1539 use_modal_editing: mode == EditorMode::Full,
1540 read_only: false,
1541 use_autoclose: true,
1542 leader_peer_id: None,
1543 remote_id: None,
1544 hover_state: Default::default(),
1545 hovered_link_state: Default::default(),
1546 copilot_state: Default::default(),
1547 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1548 gutter_hovered: false,
1549 pixel_position_of_newest_cursor: None,
1550 gutter_width: Default::default(),
1551 style: None,
1552 show_cursor_names: false,
1553 hovered_cursors: Default::default(),
1554 editor_actions: Default::default(),
1555 show_copilot_suggestions: mode == EditorMode::Full,
1556 custom_context_menu: None,
1557 _subscriptions: vec![
1558 cx.observe(&buffer, Self::on_buffer_changed),
1559 cx.subscribe(&buffer, Self::on_buffer_event),
1560 cx.observe(&display_map, Self::on_display_map_changed),
1561 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1562 cx.observe_global::<SettingsStore>(Self::settings_changed),
1563 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1564 cx.observe_window_activation(|editor, cx| {
1565 let active = cx.is_window_active();
1566 editor.blink_manager.update(cx, |blink_manager, cx| {
1567 if active {
1568 blink_manager.enable(cx);
1569 } else {
1570 blink_manager.show_cursor(cx);
1571 blink_manager.disable(cx);
1572 }
1573 });
1574 }),
1575 ],
1576 };
1577
1578 this._subscriptions.extend(project_subscriptions);
1579
1580 this.end_selection(cx);
1581 this.scroll_manager.show_scrollbar(cx);
1582
1583 if mode == EditorMode::Full {
1584 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1585 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1586 }
1587
1588 this.report_editor_event("open", None, cx);
1589 this
1590 }
1591
1592 fn key_context(&self, cx: &AppContext) -> KeyContext {
1593 let mut key_context = KeyContext::default();
1594 key_context.add("Editor");
1595 let mode = match self.mode {
1596 EditorMode::SingleLine => "single_line",
1597 EditorMode::AutoHeight { .. } => "auto_height",
1598 EditorMode::Full => "full",
1599 };
1600 key_context.set("mode", mode);
1601 if self.pending_rename.is_some() {
1602 key_context.add("renaming");
1603 }
1604 if self.context_menu_visible() {
1605 match self.context_menu.read().as_ref() {
1606 Some(ContextMenu::Completions(_)) => {
1607 key_context.add("menu");
1608 key_context.add("showing_completions")
1609 }
1610 Some(ContextMenu::CodeActions(_)) => {
1611 key_context.add("menu");
1612 key_context.add("showing_code_actions")
1613 }
1614 None => {}
1615 }
1616 }
1617
1618 for layer in self.keymap_context_layers.values() {
1619 key_context.extend(layer);
1620 }
1621
1622 if let Some(extension) = self
1623 .buffer
1624 .read(cx)
1625 .as_singleton()
1626 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1627 {
1628 key_context.set("extension", extension.to_string());
1629 }
1630
1631 if self.has_active_copilot_suggestion(cx) {
1632 key_context.add("copilot_suggestion");
1633 }
1634
1635 key_context
1636 }
1637
1638 pub fn new_file(
1639 workspace: &mut Workspace,
1640 _: &workspace::NewFile,
1641 cx: &mut ViewContext<Workspace>,
1642 ) {
1643 let project = workspace.project().clone();
1644 if project.read(cx).is_remote() {
1645 cx.propagate();
1646 } else if let Some(buffer) = project
1647 .update(cx, |project, cx| project.create_buffer("", None, cx))
1648 .log_err()
1649 {
1650 workspace.add_item_to_active_pane(
1651 Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1652 cx,
1653 );
1654 }
1655 }
1656
1657 pub fn new_file_in_direction(
1658 workspace: &mut Workspace,
1659 action: &workspace::NewFileInDirection,
1660 cx: &mut ViewContext<Workspace>,
1661 ) {
1662 let project = workspace.project().clone();
1663 if project.read(cx).is_remote() {
1664 cx.propagate();
1665 } else if let Some(buffer) = project
1666 .update(cx, |project, cx| project.create_buffer("", None, cx))
1667 .log_err()
1668 {
1669 workspace.split_item(
1670 action.0,
1671 Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1672 cx,
1673 );
1674 }
1675 }
1676
1677 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
1678 self.buffer.read(cx).replica_id()
1679 }
1680
1681 pub fn leader_peer_id(&self) -> Option<PeerId> {
1682 self.leader_peer_id
1683 }
1684
1685 pub fn buffer(&self) -> &Model<MultiBuffer> {
1686 &self.buffer
1687 }
1688
1689 pub fn workspace(&self) -> Option<View<Workspace>> {
1690 self.workspace.as_ref()?.0.upgrade()
1691 }
1692
1693 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1694 self.buffer().read(cx).title(cx)
1695 }
1696
1697 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1698 EditorSnapshot {
1699 mode: self.mode,
1700 show_gutter: self.show_gutter,
1701 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1702 scroll_anchor: self.scroll_manager.anchor(),
1703 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1704 placeholder_text: self.placeholder_text.clone(),
1705 is_focused: self.focus_handle.is_focused(cx),
1706 }
1707 }
1708
1709 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1710 self.buffer.read(cx).language_at(point, cx)
1711 }
1712
1713 pub fn file_at<T: ToOffset>(
1714 &self,
1715 point: T,
1716 cx: &AppContext,
1717 ) -> Option<Arc<dyn language::File>> {
1718 self.buffer.read(cx).read(cx).file_at(point).cloned()
1719 }
1720
1721 pub fn active_excerpt(
1722 &self,
1723 cx: &AppContext,
1724 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1725 self.buffer
1726 .read(cx)
1727 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1728 }
1729
1730 pub fn mode(&self) -> EditorMode {
1731 self.mode
1732 }
1733
1734 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1735 self.collaboration_hub.as_deref()
1736 }
1737
1738 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1739 self.collaboration_hub = Some(hub);
1740 }
1741
1742 pub fn set_custom_context_menu(
1743 &mut self,
1744 f: impl 'static
1745 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1746 ) {
1747 self.custom_context_menu = Some(Box::new(f))
1748 }
1749
1750 pub fn set_completion_provider(&mut self, hub: Box<dyn CompletionProvider>) {
1751 self.completion_provider = Some(hub);
1752 }
1753
1754 pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
1755 self.placeholder_text.as_deref()
1756 }
1757
1758 pub fn set_placeholder_text(
1759 &mut self,
1760 placeholder_text: impl Into<Arc<str>>,
1761 cx: &mut ViewContext<Self>,
1762 ) {
1763 let placeholder_text = Some(placeholder_text.into());
1764 if self.placeholder_text != placeholder_text {
1765 self.placeholder_text = placeholder_text;
1766 cx.notify();
1767 }
1768 }
1769
1770 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1771 self.cursor_shape = cursor_shape;
1772 cx.notify();
1773 }
1774
1775 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1776 self.collapse_matches = collapse_matches;
1777 }
1778
1779 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1780 if self.collapse_matches {
1781 return range.start..range.start;
1782 }
1783 range.clone()
1784 }
1785
1786 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1787 if self.display_map.read(cx).clip_at_line_ends != clip {
1788 self.display_map
1789 .update(cx, |map, _| map.clip_at_line_ends = clip);
1790 }
1791 }
1792
1793 pub fn set_keymap_context_layer<Tag: 'static>(
1794 &mut self,
1795 context: KeyContext,
1796 cx: &mut ViewContext<Self>,
1797 ) {
1798 self.keymap_context_layers
1799 .insert(TypeId::of::<Tag>(), context);
1800 cx.notify();
1801 }
1802
1803 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
1804 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
1805 cx.notify();
1806 }
1807
1808 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1809 self.input_enabled = input_enabled;
1810 }
1811
1812 pub fn set_autoindent(&mut self, autoindent: bool) {
1813 if autoindent {
1814 self.autoindent_mode = Some(AutoindentMode::EachLine);
1815 } else {
1816 self.autoindent_mode = None;
1817 }
1818 }
1819
1820 pub fn read_only(&self, cx: &AppContext) -> bool {
1821 self.read_only || self.buffer.read(cx).read_only()
1822 }
1823
1824 pub fn set_read_only(&mut self, read_only: bool) {
1825 self.read_only = read_only;
1826 }
1827
1828 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1829 self.use_autoclose = autoclose;
1830 }
1831
1832 pub fn set_show_copilot_suggestions(&mut self, show_copilot_suggestions: bool) {
1833 self.show_copilot_suggestions = show_copilot_suggestions;
1834 }
1835
1836 pub fn set_use_modal_editing(&mut self, to: bool) {
1837 self.use_modal_editing = to;
1838 }
1839
1840 pub fn use_modal_editing(&self) -> bool {
1841 self.use_modal_editing
1842 }
1843
1844 fn selections_did_change(
1845 &mut self,
1846 local: bool,
1847 old_cursor_position: &Anchor,
1848 cx: &mut ViewContext<Self>,
1849 ) {
1850 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1851 self.buffer.update(cx, |buffer, cx| {
1852 buffer.set_active_selections(
1853 &self.selections.disjoint_anchors(),
1854 self.selections.line_mode,
1855 self.cursor_shape,
1856 cx,
1857 )
1858 });
1859 }
1860
1861 let display_map = self
1862 .display_map
1863 .update(cx, |display_map, cx| display_map.snapshot(cx));
1864 let buffer = &display_map.buffer_snapshot;
1865 self.add_selections_state = None;
1866 self.select_next_state = None;
1867 self.select_prev_state = None;
1868 self.select_larger_syntax_node_stack.clear();
1869 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1870 self.snippet_stack
1871 .invalidate(&self.selections.disjoint_anchors(), buffer);
1872 self.take_rename(false, cx);
1873
1874 let new_cursor_position = self.selections.newest_anchor().head();
1875
1876 self.push_to_nav_history(
1877 *old_cursor_position,
1878 Some(new_cursor_position.to_point(buffer)),
1879 cx,
1880 );
1881
1882 if local {
1883 let new_cursor_position = self.selections.newest_anchor().head();
1884 let mut context_menu = self.context_menu.write();
1885 let completion_menu = match context_menu.as_ref() {
1886 Some(ContextMenu::Completions(menu)) => Some(menu),
1887
1888 _ => {
1889 *context_menu = None;
1890 None
1891 }
1892 };
1893
1894 if let Some(completion_menu) = completion_menu {
1895 let cursor_position = new_cursor_position.to_offset(buffer);
1896 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
1897 if kind == Some(CharKind::Word)
1898 && word_range.to_inclusive().contains(&cursor_position)
1899 {
1900 let mut completion_menu = completion_menu.clone();
1901 drop(context_menu);
1902
1903 let query = Self::completion_query(buffer, cursor_position);
1904 cx.spawn(move |this, mut cx| async move {
1905 completion_menu
1906 .filter(query.as_deref(), cx.background_executor().clone())
1907 .await;
1908
1909 this.update(&mut cx, |this, cx| {
1910 let mut context_menu = this.context_menu.write();
1911 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
1912 return;
1913 };
1914
1915 if menu.id > completion_menu.id {
1916 return;
1917 }
1918
1919 *context_menu = Some(ContextMenu::Completions(completion_menu));
1920 drop(context_menu);
1921 cx.notify();
1922 })
1923 })
1924 .detach();
1925
1926 self.show_completions(&ShowCompletions, cx);
1927 } else {
1928 drop(context_menu);
1929 self.hide_context_menu(cx);
1930 }
1931 } else {
1932 drop(context_menu);
1933 }
1934
1935 hide_hover(self, cx);
1936
1937 if old_cursor_position.to_display_point(&display_map).row()
1938 != new_cursor_position.to_display_point(&display_map).row()
1939 {
1940 self.available_code_actions.take();
1941 }
1942 self.refresh_code_actions(cx);
1943 self.refresh_document_highlights(cx);
1944 refresh_matching_bracket_highlights(self, cx);
1945 self.discard_copilot_suggestion(cx);
1946 }
1947
1948 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1949 cx.emit(EditorEvent::SelectionsChanged { local });
1950
1951 if self.selections.disjoint_anchors().len() == 1 {
1952 cx.emit(SearchEvent::ActiveMatchChanged)
1953 }
1954
1955 cx.notify();
1956 }
1957
1958 pub fn change_selections<R>(
1959 &mut self,
1960 autoscroll: Option<Autoscroll>,
1961 cx: &mut ViewContext<Self>,
1962 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1963 ) -> R {
1964 let old_cursor_position = self.selections.newest_anchor().head();
1965 self.push_to_selection_history();
1966
1967 let (changed, result) = self.selections.change_with(cx, change);
1968
1969 if changed {
1970 if let Some(autoscroll) = autoscroll {
1971 self.request_autoscroll(autoscroll, cx);
1972 }
1973 self.selections_did_change(true, &old_cursor_position, cx);
1974 }
1975
1976 result
1977 }
1978
1979 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
1980 where
1981 I: IntoIterator<Item = (Range<S>, T)>,
1982 S: ToOffset,
1983 T: Into<Arc<str>>,
1984 {
1985 if self.read_only(cx) {
1986 return;
1987 }
1988
1989 self.buffer
1990 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
1991 }
1992
1993 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
1994 where
1995 I: IntoIterator<Item = (Range<S>, T)>,
1996 S: ToOffset,
1997 T: Into<Arc<str>>,
1998 {
1999 if self.read_only(cx) {
2000 return;
2001 }
2002
2003 self.buffer.update(cx, |buffer, cx| {
2004 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2005 });
2006 }
2007
2008 pub fn edit_with_block_indent<I, S, T>(
2009 &mut self,
2010 edits: I,
2011 original_indent_columns: Vec<u32>,
2012 cx: &mut ViewContext<Self>,
2013 ) where
2014 I: IntoIterator<Item = (Range<S>, T)>,
2015 S: ToOffset,
2016 T: Into<Arc<str>>,
2017 {
2018 if self.read_only(cx) {
2019 return;
2020 }
2021
2022 self.buffer.update(cx, |buffer, cx| {
2023 buffer.edit(
2024 edits,
2025 Some(AutoindentMode::Block {
2026 original_indent_columns,
2027 }),
2028 cx,
2029 )
2030 });
2031 }
2032
2033 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2034 self.hide_context_menu(cx);
2035
2036 match phase {
2037 SelectPhase::Begin {
2038 position,
2039 add,
2040 click_count,
2041 } => self.begin_selection(position, add, click_count, cx),
2042 SelectPhase::BeginColumnar {
2043 position,
2044 goal_column,
2045 } => self.begin_columnar_selection(position, goal_column, cx),
2046 SelectPhase::Extend {
2047 position,
2048 click_count,
2049 } => self.extend_selection(position, click_count, cx),
2050 SelectPhase::Update {
2051 position,
2052 goal_column,
2053 scroll_delta,
2054 } => self.update_selection(position, goal_column, scroll_delta, cx),
2055 SelectPhase::End => self.end_selection(cx),
2056 }
2057 }
2058
2059 fn extend_selection(
2060 &mut self,
2061 position: DisplayPoint,
2062 click_count: usize,
2063 cx: &mut ViewContext<Self>,
2064 ) {
2065 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2066 let tail = self.selections.newest::<usize>(cx).tail();
2067 self.begin_selection(position, false, click_count, cx);
2068
2069 let position = position.to_offset(&display_map, Bias::Left);
2070 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2071
2072 let mut pending_selection = self
2073 .selections
2074 .pending_anchor()
2075 .expect("extend_selection not called with pending selection");
2076 if position >= tail {
2077 pending_selection.start = tail_anchor;
2078 } else {
2079 pending_selection.end = tail_anchor;
2080 pending_selection.reversed = true;
2081 }
2082
2083 let mut pending_mode = self.selections.pending_mode().unwrap();
2084 match &mut pending_mode {
2085 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2086 _ => {}
2087 }
2088
2089 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2090 s.set_pending(pending_selection, pending_mode)
2091 });
2092 }
2093
2094 fn begin_selection(
2095 &mut self,
2096 position: DisplayPoint,
2097 add: bool,
2098 click_count: usize,
2099 cx: &mut ViewContext<Self>,
2100 ) {
2101 if !self.focus_handle.is_focused(cx) {
2102 cx.focus(&self.focus_handle);
2103 }
2104
2105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2106 let buffer = &display_map.buffer_snapshot;
2107 let newest_selection = self.selections.newest_anchor().clone();
2108 let position = display_map.clip_point(position, Bias::Left);
2109
2110 let start;
2111 let end;
2112 let mode;
2113 let auto_scroll;
2114 match click_count {
2115 1 => {
2116 start = buffer.anchor_before(position.to_point(&display_map));
2117 end = start;
2118 mode = SelectMode::Character;
2119 auto_scroll = true;
2120 }
2121 2 => {
2122 let range = movement::surrounding_word(&display_map, position);
2123 start = buffer.anchor_before(range.start.to_point(&display_map));
2124 end = buffer.anchor_before(range.end.to_point(&display_map));
2125 mode = SelectMode::Word(start..end);
2126 auto_scroll = true;
2127 }
2128 3 => {
2129 let position = display_map
2130 .clip_point(position, Bias::Left)
2131 .to_point(&display_map);
2132 let line_start = display_map.prev_line_boundary(position).0;
2133 let next_line_start = buffer.clip_point(
2134 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2135 Bias::Left,
2136 );
2137 start = buffer.anchor_before(line_start);
2138 end = buffer.anchor_before(next_line_start);
2139 mode = SelectMode::Line(start..end);
2140 auto_scroll = true;
2141 }
2142 _ => {
2143 start = buffer.anchor_before(0);
2144 end = buffer.anchor_before(buffer.len());
2145 mode = SelectMode::All;
2146 auto_scroll = false;
2147 }
2148 }
2149
2150 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2151 if !add {
2152 s.clear_disjoint();
2153 } else if click_count > 1 {
2154 s.delete(newest_selection.id)
2155 }
2156
2157 s.set_pending_anchor_range(start..end, mode);
2158 });
2159 }
2160
2161 fn begin_columnar_selection(
2162 &mut self,
2163 position: DisplayPoint,
2164 goal_column: u32,
2165 cx: &mut ViewContext<Self>,
2166 ) {
2167 if !self.focus_handle.is_focused(cx) {
2168 cx.focus(&self.focus_handle);
2169 }
2170
2171 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2172 let tail = self.selections.newest::<Point>(cx).tail();
2173 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2174
2175 self.select_columns(
2176 tail.to_display_point(&display_map),
2177 position,
2178 goal_column,
2179 &display_map,
2180 cx,
2181 );
2182 }
2183
2184 fn update_selection(
2185 &mut self,
2186 position: DisplayPoint,
2187 goal_column: u32,
2188 scroll_delta: gpui::Point<f32>,
2189 cx: &mut ViewContext<Self>,
2190 ) {
2191 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2192
2193 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2194 let tail = tail.to_display_point(&display_map);
2195 self.select_columns(tail, position, goal_column, &display_map, cx);
2196 } else if let Some(mut pending) = self.selections.pending_anchor() {
2197 let buffer = self.buffer.read(cx).snapshot(cx);
2198 let head;
2199 let tail;
2200 let mode = self.selections.pending_mode().unwrap();
2201 match &mode {
2202 SelectMode::Character => {
2203 head = position.to_point(&display_map);
2204 tail = pending.tail().to_point(&buffer);
2205 }
2206 SelectMode::Word(original_range) => {
2207 let original_display_range = original_range.start.to_display_point(&display_map)
2208 ..original_range.end.to_display_point(&display_map);
2209 let original_buffer_range = original_display_range.start.to_point(&display_map)
2210 ..original_display_range.end.to_point(&display_map);
2211 if movement::is_inside_word(&display_map, position)
2212 || original_display_range.contains(&position)
2213 {
2214 let word_range = movement::surrounding_word(&display_map, position);
2215 if word_range.start < original_display_range.start {
2216 head = word_range.start.to_point(&display_map);
2217 } else {
2218 head = word_range.end.to_point(&display_map);
2219 }
2220 } else {
2221 head = position.to_point(&display_map);
2222 }
2223
2224 if head <= original_buffer_range.start {
2225 tail = original_buffer_range.end;
2226 } else {
2227 tail = original_buffer_range.start;
2228 }
2229 }
2230 SelectMode::Line(original_range) => {
2231 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2232
2233 let position = display_map
2234 .clip_point(position, Bias::Left)
2235 .to_point(&display_map);
2236 let line_start = display_map.prev_line_boundary(position).0;
2237 let next_line_start = buffer.clip_point(
2238 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2239 Bias::Left,
2240 );
2241
2242 if line_start < original_range.start {
2243 head = line_start
2244 } else {
2245 head = next_line_start
2246 }
2247
2248 if head <= original_range.start {
2249 tail = original_range.end;
2250 } else {
2251 tail = original_range.start;
2252 }
2253 }
2254 SelectMode::All => {
2255 return;
2256 }
2257 };
2258
2259 if head < tail {
2260 pending.start = buffer.anchor_before(head);
2261 pending.end = buffer.anchor_before(tail);
2262 pending.reversed = true;
2263 } else {
2264 pending.start = buffer.anchor_before(tail);
2265 pending.end = buffer.anchor_before(head);
2266 pending.reversed = false;
2267 }
2268
2269 self.change_selections(None, cx, |s| {
2270 s.set_pending(pending, mode);
2271 });
2272 } else {
2273 log::error!("update_selection dispatched with no pending selection");
2274 return;
2275 }
2276
2277 self.apply_scroll_delta(scroll_delta, cx);
2278 cx.notify();
2279 }
2280
2281 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2282 self.columnar_selection_tail.take();
2283 if self.selections.pending_anchor().is_some() {
2284 let selections = self.selections.all::<usize>(cx);
2285 self.change_selections(None, cx, |s| {
2286 s.select(selections);
2287 s.clear_pending();
2288 });
2289 }
2290 }
2291
2292 fn select_columns(
2293 &mut self,
2294 tail: DisplayPoint,
2295 head: DisplayPoint,
2296 goal_column: u32,
2297 display_map: &DisplaySnapshot,
2298 cx: &mut ViewContext<Self>,
2299 ) {
2300 let start_row = cmp::min(tail.row(), head.row());
2301 let end_row = cmp::max(tail.row(), head.row());
2302 let start_column = cmp::min(tail.column(), goal_column);
2303 let end_column = cmp::max(tail.column(), goal_column);
2304 let reversed = start_column < tail.column();
2305
2306 let selection_ranges = (start_row..=end_row)
2307 .filter_map(|row| {
2308 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2309 let start = display_map
2310 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2311 .to_point(display_map);
2312 let end = display_map
2313 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2314 .to_point(display_map);
2315 if reversed {
2316 Some(end..start)
2317 } else {
2318 Some(start..end)
2319 }
2320 } else {
2321 None
2322 }
2323 })
2324 .collect::<Vec<_>>();
2325
2326 self.change_selections(None, cx, |s| {
2327 s.select_ranges(selection_ranges);
2328 });
2329 cx.notify();
2330 }
2331
2332 pub fn has_pending_nonempty_selection(&self) -> bool {
2333 let pending_nonempty_selection = match self.selections.pending_anchor() {
2334 Some(Selection { start, end, .. }) => start != end,
2335 None => false,
2336 };
2337 pending_nonempty_selection || self.columnar_selection_tail.is_some()
2338 }
2339
2340 pub fn has_pending_selection(&self) -> bool {
2341 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2342 }
2343
2344 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2345 if self.dismiss_menus_and_popups(cx) {
2346 return;
2347 }
2348
2349 if self.mode == EditorMode::Full {
2350 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2351 return;
2352 }
2353 }
2354
2355 cx.propagate();
2356 }
2357
2358 pub fn dismiss_menus_and_popups(&mut self, cx: &mut ViewContext<Self>) -> bool {
2359 if self.take_rename(false, cx).is_some() {
2360 return true;
2361 }
2362
2363 if hide_hover(self, cx) {
2364 return true;
2365 }
2366
2367 if self.hide_context_menu(cx).is_some() {
2368 return true;
2369 }
2370
2371 if self.discard_copilot_suggestion(cx) {
2372 return true;
2373 }
2374
2375 if self.snippet_stack.pop().is_some() {
2376 return true;
2377 }
2378
2379 if self.mode == EditorMode::Full {
2380 if self.active_diagnostics.is_some() {
2381 self.dismiss_diagnostics(cx);
2382 return true;
2383 }
2384 }
2385
2386 false
2387 }
2388
2389 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2390 let text: Arc<str> = text.into();
2391
2392 if self.read_only(cx) {
2393 return;
2394 }
2395
2396 let selections = self.selections.all_adjusted(cx);
2397 let mut brace_inserted = false;
2398 let mut edits = Vec::new();
2399 let mut new_selections = Vec::with_capacity(selections.len());
2400 let mut new_autoclose_regions = Vec::new();
2401 let snapshot = self.buffer.read(cx).read(cx);
2402
2403 for (selection, autoclose_region) in
2404 self.selections_with_autoclose_regions(selections, &snapshot)
2405 {
2406 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2407 // Determine if the inserted text matches the opening or closing
2408 // bracket of any of this language's bracket pairs.
2409 let mut bracket_pair = None;
2410 let mut is_bracket_pair_start = false;
2411 if !text.is_empty() {
2412 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2413 // and they are removing the character that triggered IME popup.
2414 for (pair, enabled) in scope.brackets() {
2415 if enabled && pair.close && pair.start.ends_with(text.as_ref()) {
2416 bracket_pair = Some(pair.clone());
2417 is_bracket_pair_start = true;
2418 break;
2419 } else if pair.end.as_str() == text.as_ref() {
2420 bracket_pair = Some(pair.clone());
2421 break;
2422 }
2423 }
2424 }
2425
2426 if let Some(bracket_pair) = bracket_pair {
2427 if selection.is_empty() {
2428 if is_bracket_pair_start {
2429 let prefix_len = bracket_pair.start.len() - text.len();
2430
2431 // If the inserted text is a suffix of an opening bracket and the
2432 // selection is preceded by the rest of the opening bracket, then
2433 // insert the closing bracket.
2434 let following_text_allows_autoclose = snapshot
2435 .chars_at(selection.start)
2436 .next()
2437 .map_or(true, |c| scope.should_autoclose_before(c));
2438 let preceding_text_matches_prefix = prefix_len == 0
2439 || (selection.start.column >= (prefix_len as u32)
2440 && snapshot.contains_str_at(
2441 Point::new(
2442 selection.start.row,
2443 selection.start.column - (prefix_len as u32),
2444 ),
2445 &bracket_pair.start[..prefix_len],
2446 ));
2447 let autoclose = self.use_autoclose
2448 && snapshot.settings_at(selection.start, cx).use_autoclose;
2449 if autoclose
2450 && following_text_allows_autoclose
2451 && preceding_text_matches_prefix
2452 {
2453 let anchor = snapshot.anchor_before(selection.end);
2454 new_selections.push((selection.map(|_| anchor), text.len()));
2455 new_autoclose_regions.push((
2456 anchor,
2457 text.len(),
2458 selection.id,
2459 bracket_pair.clone(),
2460 ));
2461 edits.push((
2462 selection.range(),
2463 format!("{}{}", text, bracket_pair.end).into(),
2464 ));
2465 brace_inserted = true;
2466 continue;
2467 }
2468 }
2469
2470 if let Some(region) = autoclose_region {
2471 // If the selection is followed by an auto-inserted closing bracket,
2472 // then don't insert that closing bracket again; just move the selection
2473 // past the closing bracket.
2474 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2475 && text.as_ref() == region.pair.end.as_str();
2476 if should_skip {
2477 let anchor = snapshot.anchor_after(selection.end);
2478 new_selections
2479 .push((selection.map(|_| anchor), region.pair.end.len()));
2480 continue;
2481 }
2482 }
2483 }
2484 // If an opening bracket is 1 character long and is typed while
2485 // text is selected, then surround that text with the bracket pair.
2486 else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
2487 edits.push((selection.start..selection.start, text.clone()));
2488 edits.push((
2489 selection.end..selection.end,
2490 bracket_pair.end.as_str().into(),
2491 ));
2492 brace_inserted = true;
2493 new_selections.push((
2494 Selection {
2495 id: selection.id,
2496 start: snapshot.anchor_after(selection.start),
2497 end: snapshot.anchor_before(selection.end),
2498 reversed: selection.reversed,
2499 goal: selection.goal,
2500 },
2501 0,
2502 ));
2503 continue;
2504 }
2505 }
2506 }
2507
2508 // If not handling any auto-close operation, then just replace the selected
2509 // text with the given input and move the selection to the end of the
2510 // newly inserted text.
2511 let anchor = snapshot.anchor_after(selection.end);
2512 new_selections.push((selection.map(|_| anchor), 0));
2513 edits.push((selection.start..selection.end, text.clone()));
2514 }
2515
2516 drop(snapshot);
2517 self.transact(cx, |this, cx| {
2518 this.buffer.update(cx, |buffer, cx| {
2519 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2520 });
2521
2522 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2523 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2524 let snapshot = this.buffer.read(cx).read(cx);
2525 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
2526 .zip(new_selection_deltas)
2527 .map(|(selection, delta)| Selection {
2528 id: selection.id,
2529 start: selection.start + delta,
2530 end: selection.end + delta,
2531 reversed: selection.reversed,
2532 goal: SelectionGoal::None,
2533 })
2534 .collect::<Vec<_>>();
2535
2536 let mut i = 0;
2537 for (position, delta, selection_id, pair) in new_autoclose_regions {
2538 let position = position.to_offset(&snapshot) + delta;
2539 let start = snapshot.anchor_before(position);
2540 let end = snapshot.anchor_after(position);
2541 while let Some(existing_state) = this.autoclose_regions.get(i) {
2542 match existing_state.range.start.cmp(&start, &snapshot) {
2543 Ordering::Less => i += 1,
2544 Ordering::Greater => break,
2545 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
2546 Ordering::Less => i += 1,
2547 Ordering::Equal => break,
2548 Ordering::Greater => break,
2549 },
2550 }
2551 }
2552 this.autoclose_regions.insert(
2553 i,
2554 AutocloseRegion {
2555 selection_id,
2556 range: start..end,
2557 pair,
2558 },
2559 );
2560 }
2561
2562 drop(snapshot);
2563 let had_active_copilot_suggestion = this.has_active_copilot_suggestion(cx);
2564 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2565
2566 if brace_inserted {
2567 // If we inserted a brace while composing text (i.e. typing `"` on a
2568 // Brazilian keyboard), exit the composing state because most likely
2569 // the user wanted to surround the selection.
2570 this.unmark_text(cx);
2571 } else if EditorSettings::get_global(cx).use_on_type_format {
2572 if let Some(on_type_format_task) =
2573 this.trigger_on_type_formatting(text.to_string(), cx)
2574 {
2575 on_type_format_task.detach_and_log_err(cx);
2576 }
2577 }
2578
2579 if had_active_copilot_suggestion {
2580 this.refresh_copilot_suggestions(true, cx);
2581 if !this.has_active_copilot_suggestion(cx) {
2582 this.trigger_completion_on_input(&text, cx);
2583 }
2584 } else {
2585 this.trigger_completion_on_input(&text, cx);
2586 this.refresh_copilot_suggestions(true, cx);
2587 }
2588 });
2589 }
2590
2591 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2592 self.transact(cx, |this, cx| {
2593 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2594 let selections = this.selections.all::<usize>(cx);
2595 let multi_buffer = this.buffer.read(cx);
2596 let buffer = multi_buffer.snapshot(cx);
2597 selections
2598 .iter()
2599 .map(|selection| {
2600 let start_point = selection.start.to_point(&buffer);
2601 let mut indent = buffer.indent_size_for_line(start_point.row);
2602 indent.len = cmp::min(indent.len, start_point.column);
2603 let start = selection.start;
2604 let end = selection.end;
2605 let is_cursor = start == end;
2606 let language_scope = buffer.language_scope_at(start);
2607 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2608 &language_scope
2609 {
2610 let leading_whitespace_len = buffer
2611 .reversed_chars_at(start)
2612 .take_while(|c| c.is_whitespace() && *c != '\n')
2613 .map(|c| c.len_utf8())
2614 .sum::<usize>();
2615
2616 let trailing_whitespace_len = buffer
2617 .chars_at(end)
2618 .take_while(|c| c.is_whitespace() && *c != '\n')
2619 .map(|c| c.len_utf8())
2620 .sum::<usize>();
2621
2622 let insert_extra_newline =
2623 language.brackets().any(|(pair, enabled)| {
2624 let pair_start = pair.start.trim_end();
2625 let pair_end = pair.end.trim_start();
2626
2627 enabled
2628 && pair.newline
2629 && buffer.contains_str_at(
2630 end + trailing_whitespace_len,
2631 pair_end,
2632 )
2633 && buffer.contains_str_at(
2634 (start - leading_whitespace_len)
2635 .saturating_sub(pair_start.len()),
2636 pair_start,
2637 )
2638 });
2639 // Comment extension on newline is allowed only for cursor selections
2640 let comment_delimiter = language.line_comment_prefixes().filter(|_| {
2641 let is_comment_extension_enabled =
2642 multi_buffer.settings_at(0, cx).extend_comment_on_newline;
2643 is_cursor && is_comment_extension_enabled
2644 });
2645 let get_comment_delimiter = |delimiters: &[Arc<str>]| {
2646 let max_len_of_delimiter =
2647 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2648 let (snapshot, range) =
2649 buffer.buffer_line_for_row(start_point.row)?;
2650
2651 let mut index_of_first_non_whitespace = 0;
2652 let comment_candidate = snapshot
2653 .chars_for_range(range)
2654 .skip_while(|c| {
2655 let should_skip = c.is_whitespace();
2656 if should_skip {
2657 index_of_first_non_whitespace += 1;
2658 }
2659 should_skip
2660 })
2661 .take(max_len_of_delimiter)
2662 .collect::<String>();
2663 let comment_prefix = delimiters.iter().find(|comment_prefix| {
2664 comment_candidate.starts_with(comment_prefix.as_ref())
2665 })?;
2666 let cursor_is_placed_after_comment_marker =
2667 index_of_first_non_whitespace + comment_prefix.len()
2668 <= start_point.column as usize;
2669 if cursor_is_placed_after_comment_marker {
2670 Some(comment_prefix.clone())
2671 } else {
2672 None
2673 }
2674 };
2675 let comment_delimiter = if let Some(delimiters) = comment_delimiter {
2676 get_comment_delimiter(delimiters)
2677 } else {
2678 None
2679 };
2680 (comment_delimiter, insert_extra_newline)
2681 } else {
2682 (None, false)
2683 };
2684
2685 let capacity_for_delimiter = comment_delimiter
2686 .as_deref()
2687 .map(str::len)
2688 .unwrap_or_default();
2689 let mut new_text =
2690 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
2691 new_text.push_str("\n");
2692 new_text.extend(indent.chars());
2693 if let Some(delimiter) = &comment_delimiter {
2694 new_text.push_str(&delimiter);
2695 }
2696 if insert_extra_newline {
2697 new_text = new_text.repeat(2);
2698 }
2699
2700 let anchor = buffer.anchor_after(end);
2701 let new_selection = selection.map(|_| anchor);
2702 (
2703 (start..end, new_text),
2704 (insert_extra_newline, new_selection),
2705 )
2706 })
2707 .unzip()
2708 };
2709
2710 this.edit_with_autoindent(edits, cx);
2711 let buffer = this.buffer.read(cx).snapshot(cx);
2712 let new_selections = selection_fixup_info
2713 .into_iter()
2714 .map(|(extra_newline_inserted, new_selection)| {
2715 let mut cursor = new_selection.end.to_point(&buffer);
2716 if extra_newline_inserted {
2717 cursor.row -= 1;
2718 cursor.column = buffer.line_len(cursor.row);
2719 }
2720 new_selection.map(|_| cursor)
2721 })
2722 .collect();
2723
2724 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2725 this.refresh_copilot_suggestions(true, cx);
2726 });
2727 }
2728
2729 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
2730 let buffer = self.buffer.read(cx);
2731 let snapshot = buffer.snapshot(cx);
2732
2733 let mut edits = Vec::new();
2734 let mut rows = Vec::new();
2735
2736 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
2737 let cursor = selection.head();
2738 let row = cursor.row;
2739
2740 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
2741
2742 let newline = "\n".to_string();
2743 edits.push((start_of_line..start_of_line, newline));
2744
2745 rows.push(row + rows_inserted as u32);
2746 }
2747
2748 self.transact(cx, |editor, cx| {
2749 editor.edit(edits, cx);
2750
2751 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
2752 let mut index = 0;
2753 s.move_cursors_with(|map, _, _| {
2754 let row = rows[index];
2755 index += 1;
2756
2757 let point = Point::new(row, 0);
2758 let boundary = map.next_line_boundary(point).1;
2759 let clipped = map.clip_point(boundary, Bias::Left);
2760
2761 (clipped, SelectionGoal::None)
2762 });
2763 });
2764
2765 let mut indent_edits = Vec::new();
2766 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
2767 for row in rows {
2768 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
2769 for (row, indent) in indents {
2770 if indent.len == 0 {
2771 continue;
2772 }
2773
2774 let text = match indent.kind {
2775 IndentKind::Space => " ".repeat(indent.len as usize),
2776 IndentKind::Tab => "\t".repeat(indent.len as usize),
2777 };
2778 let point = Point::new(row, 0);
2779 indent_edits.push((point..point, text));
2780 }
2781 }
2782 editor.edit(indent_edits, cx);
2783 });
2784 }
2785
2786 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
2787 let buffer = self.buffer.read(cx);
2788 let snapshot = buffer.snapshot(cx);
2789
2790 let mut edits = Vec::new();
2791 let mut rows = Vec::new();
2792 let mut rows_inserted = 0;
2793
2794 for selection in self.selections.all_adjusted(cx) {
2795 let cursor = selection.head();
2796 let row = cursor.row;
2797
2798 let point = Point::new(row + 1, 0);
2799 let start_of_line = snapshot.clip_point(point, Bias::Left);
2800
2801 let newline = "\n".to_string();
2802 edits.push((start_of_line..start_of_line, newline));
2803
2804 rows_inserted += 1;
2805 rows.push(row + rows_inserted);
2806 }
2807
2808 self.transact(cx, |editor, cx| {
2809 editor.edit(edits, cx);
2810
2811 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
2812 let mut index = 0;
2813 s.move_cursors_with(|map, _, _| {
2814 let row = rows[index];
2815 index += 1;
2816
2817 let point = Point::new(row, 0);
2818 let boundary = map.next_line_boundary(point).1;
2819 let clipped = map.clip_point(boundary, Bias::Left);
2820
2821 (clipped, SelectionGoal::None)
2822 });
2823 });
2824
2825 let mut indent_edits = Vec::new();
2826 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
2827 for row in rows {
2828 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
2829 for (row, indent) in indents {
2830 if indent.len == 0 {
2831 continue;
2832 }
2833
2834 let text = match indent.kind {
2835 IndentKind::Space => " ".repeat(indent.len as usize),
2836 IndentKind::Tab => "\t".repeat(indent.len as usize),
2837 };
2838 let point = Point::new(row, 0);
2839 indent_edits.push((point..point, text));
2840 }
2841 }
2842 editor.edit(indent_edits, cx);
2843 });
2844 }
2845
2846 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2847 self.insert_with_autoindent_mode(
2848 text,
2849 Some(AutoindentMode::Block {
2850 original_indent_columns: Vec::new(),
2851 }),
2852 cx,
2853 );
2854 }
2855
2856 fn insert_with_autoindent_mode(
2857 &mut self,
2858 text: &str,
2859 autoindent_mode: Option<AutoindentMode>,
2860 cx: &mut ViewContext<Self>,
2861 ) {
2862 if self.read_only(cx) {
2863 return;
2864 }
2865
2866 let text: Arc<str> = text.into();
2867 self.transact(cx, |this, cx| {
2868 let old_selections = this.selections.all_adjusted(cx);
2869 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
2870 let anchors = {
2871 let snapshot = buffer.read(cx);
2872 old_selections
2873 .iter()
2874 .map(|s| {
2875 let anchor = snapshot.anchor_after(s.head());
2876 s.map(|_| anchor)
2877 })
2878 .collect::<Vec<_>>()
2879 };
2880 buffer.edit(
2881 old_selections
2882 .iter()
2883 .map(|s| (s.start..s.end, text.clone())),
2884 autoindent_mode,
2885 cx,
2886 );
2887 anchors
2888 });
2889
2890 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
2891 s.select_anchors(selection_anchors);
2892 })
2893 });
2894 }
2895
2896 fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2897 if !EditorSettings::get_global(cx).show_completions_on_input {
2898 return;
2899 }
2900
2901 let selection = self.selections.newest_anchor();
2902 if self
2903 .buffer
2904 .read(cx)
2905 .is_completion_trigger(selection.head(), text, cx)
2906 {
2907 self.show_completions(&ShowCompletions, cx);
2908 } else {
2909 self.hide_context_menu(cx);
2910 }
2911 }
2912
2913 /// If any empty selections is touching the start of its innermost containing autoclose
2914 /// region, expand it to select the brackets.
2915 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
2916 let selections = self.selections.all::<usize>(cx);
2917 let buffer = self.buffer.read(cx).read(cx);
2918 let mut new_selections = Vec::new();
2919 for (mut selection, region) in self.selections_with_autoclose_regions(selections, &buffer) {
2920 if let (Some(region), true) = (region, selection.is_empty()) {
2921 let mut range = region.range.to_offset(&buffer);
2922 if selection.start == range.start {
2923 if range.start >= region.pair.start.len() {
2924 range.start -= region.pair.start.len();
2925 if buffer.contains_str_at(range.start, ®ion.pair.start) {
2926 if buffer.contains_str_at(range.end, ®ion.pair.end) {
2927 range.end += region.pair.end.len();
2928 selection.start = range.start;
2929 selection.end = range.end;
2930 }
2931 }
2932 }
2933 }
2934 }
2935 new_selections.push(selection);
2936 }
2937
2938 drop(buffer);
2939 self.change_selections(None, cx, |selections| selections.select(new_selections));
2940 }
2941
2942 /// Iterate the given selections, and for each one, find the smallest surrounding
2943 /// autoclose region. This uses the ordering of the selections and the autoclose
2944 /// regions to avoid repeated comparisons.
2945 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
2946 &'a self,
2947 selections: impl IntoIterator<Item = Selection<D>>,
2948 buffer: &'a MultiBufferSnapshot,
2949 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
2950 let mut i = 0;
2951 let mut regions = self.autoclose_regions.as_slice();
2952 selections.into_iter().map(move |selection| {
2953 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
2954
2955 let mut enclosing = None;
2956 while let Some(pair_state) = regions.get(i) {
2957 if pair_state.range.end.to_offset(buffer) < range.start {
2958 regions = ®ions[i + 1..];
2959 i = 0;
2960 } else if pair_state.range.start.to_offset(buffer) > range.end {
2961 break;
2962 } else {
2963 if pair_state.selection_id == selection.id {
2964 enclosing = Some(pair_state);
2965 }
2966 i += 1;
2967 }
2968 }
2969
2970 (selection.clone(), enclosing)
2971 })
2972 }
2973
2974 /// Remove any autoclose regions that no longer contain their selection.
2975 fn invalidate_autoclose_regions(
2976 &mut self,
2977 mut selections: &[Selection<Anchor>],
2978 buffer: &MultiBufferSnapshot,
2979 ) {
2980 self.autoclose_regions.retain(|state| {
2981 let mut i = 0;
2982 while let Some(selection) = selections.get(i) {
2983 if selection.end.cmp(&state.range.start, buffer).is_lt() {
2984 selections = &selections[1..];
2985 continue;
2986 }
2987 if selection.start.cmp(&state.range.end, buffer).is_gt() {
2988 break;
2989 }
2990 if selection.id == state.selection_id {
2991 return true;
2992 } else {
2993 i += 1;
2994 }
2995 }
2996 false
2997 });
2998 }
2999
3000 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3001 let offset = position.to_offset(buffer);
3002 let (word_range, kind) = buffer.surrounding_word(offset);
3003 if offset > word_range.start && kind == Some(CharKind::Word) {
3004 Some(
3005 buffer
3006 .text_for_range(word_range.start..offset)
3007 .collect::<String>(),
3008 )
3009 } else {
3010 None
3011 }
3012 }
3013
3014 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3015 self.refresh_inlay_hints(
3016 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3017 cx,
3018 );
3019 }
3020
3021 pub fn inlay_hints_enabled(&self) -> bool {
3022 self.inlay_hint_cache.enabled
3023 }
3024
3025 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3026 if self.project.is_none() || self.mode != EditorMode::Full {
3027 return;
3028 }
3029
3030 let reason_description = reason.description();
3031 let ignore_debounce = matches!(
3032 reason,
3033 InlayHintRefreshReason::SettingsChange(_)
3034 | InlayHintRefreshReason::Toggle(_)
3035 | InlayHintRefreshReason::ExcerptsRemoved(_)
3036 );
3037 let (invalidate_cache, required_languages) = match reason {
3038 InlayHintRefreshReason::Toggle(enabled) => {
3039 self.inlay_hint_cache.enabled = enabled;
3040 if enabled {
3041 (InvalidationStrategy::RefreshRequested, None)
3042 } else {
3043 self.inlay_hint_cache.clear();
3044 self.splice_inlay_hints(
3045 self.visible_inlay_hints(cx)
3046 .iter()
3047 .map(|inlay| inlay.id)
3048 .collect(),
3049 Vec::new(),
3050 cx,
3051 );
3052 return;
3053 }
3054 }
3055 InlayHintRefreshReason::SettingsChange(new_settings) => {
3056 match self.inlay_hint_cache.update_settings(
3057 &self.buffer,
3058 new_settings,
3059 self.visible_inlay_hints(cx),
3060 cx,
3061 ) {
3062 ControlFlow::Break(Some(InlaySplice {
3063 to_remove,
3064 to_insert,
3065 })) => {
3066 self.splice_inlay_hints(to_remove, to_insert, cx);
3067 return;
3068 }
3069 ControlFlow::Break(None) => return,
3070 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3071 }
3072 }
3073 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3074 if let Some(InlaySplice {
3075 to_remove,
3076 to_insert,
3077 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3078 {
3079 self.splice_inlay_hints(to_remove, to_insert, cx);
3080 }
3081 return;
3082 }
3083 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3084 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3085 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3086 }
3087 InlayHintRefreshReason::RefreshRequested => {
3088 (InvalidationStrategy::RefreshRequested, None)
3089 }
3090 };
3091
3092 if let Some(InlaySplice {
3093 to_remove,
3094 to_insert,
3095 }) = self.inlay_hint_cache.spawn_hint_refresh(
3096 reason_description,
3097 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3098 invalidate_cache,
3099 ignore_debounce,
3100 cx,
3101 ) {
3102 self.splice_inlay_hints(to_remove, to_insert, cx);
3103 }
3104 }
3105
3106 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3107 self.display_map
3108 .read(cx)
3109 .current_inlays()
3110 .filter(move |inlay| {
3111 Some(inlay.id) != self.copilot_state.suggestion.as_ref().map(|h| h.id)
3112 })
3113 .cloned()
3114 .collect()
3115 }
3116
3117 pub fn excerpts_for_inlay_hints_query(
3118 &self,
3119 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3120 cx: &mut ViewContext<Editor>,
3121 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3122 let Some(project) = self.project.as_ref() else {
3123 return HashMap::default();
3124 };
3125 let project = project.read(cx);
3126 let multi_buffer = self.buffer().read(cx);
3127 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3128 let multi_buffer_visible_start = self
3129 .scroll_manager
3130 .anchor()
3131 .anchor
3132 .to_point(&multi_buffer_snapshot);
3133 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3134 multi_buffer_visible_start
3135 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3136 Bias::Left,
3137 );
3138 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3139 multi_buffer
3140 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3141 .into_iter()
3142 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3143 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3144 let buffer = buffer_handle.read(cx);
3145 let buffer_file = project::worktree::File::from_dyn(buffer.file())?;
3146 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3147 let worktree_entry = buffer_worktree
3148 .read(cx)
3149 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3150 if worktree_entry.is_ignored {
3151 return None;
3152 }
3153
3154 let language = buffer.language()?;
3155 if let Some(restrict_to_languages) = restrict_to_languages {
3156 if !restrict_to_languages.contains(language) {
3157 return None;
3158 }
3159 }
3160 Some((
3161 excerpt_id,
3162 (
3163 buffer_handle,
3164 buffer.version().clone(),
3165 excerpt_visible_range,
3166 ),
3167 ))
3168 })
3169 .collect()
3170 }
3171
3172 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3173 TextLayoutDetails {
3174 text_system: cx.text_system().clone(),
3175 editor_style: self.style.clone().unwrap(),
3176 rem_size: cx.rem_size(),
3177 scroll_anchor: self.scroll_manager.anchor(),
3178 visible_rows: self.visible_line_count(),
3179 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3180 }
3181 }
3182
3183 fn splice_inlay_hints(
3184 &self,
3185 to_remove: Vec<InlayId>,
3186 to_insert: Vec<Inlay>,
3187 cx: &mut ViewContext<Self>,
3188 ) {
3189 self.display_map.update(cx, |display_map, cx| {
3190 display_map.splice_inlays(to_remove, to_insert, cx);
3191 });
3192 cx.notify();
3193 }
3194
3195 fn trigger_on_type_formatting(
3196 &self,
3197 input: String,
3198 cx: &mut ViewContext<Self>,
3199 ) -> Option<Task<Result<()>>> {
3200 if input.len() != 1 {
3201 return None;
3202 }
3203
3204 let project = self.project.as_ref()?;
3205 let position = self.selections.newest_anchor().head();
3206 let (buffer, buffer_position) = self
3207 .buffer
3208 .read(cx)
3209 .text_anchor_for_position(position, cx)?;
3210
3211 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3212 // hence we do LSP request & edit on host side only — add formats to host's history.
3213 let push_to_lsp_host_history = true;
3214 // If this is not the host, append its history with new edits.
3215 let push_to_client_history = project.read(cx).is_remote();
3216
3217 let on_type_formatting = project.update(cx, |project, cx| {
3218 project.on_type_format(
3219 buffer.clone(),
3220 buffer_position,
3221 input,
3222 push_to_lsp_host_history,
3223 cx,
3224 )
3225 });
3226 Some(cx.spawn(|editor, mut cx| async move {
3227 if let Some(transaction) = on_type_formatting.await? {
3228 if push_to_client_history {
3229 buffer
3230 .update(&mut cx, |buffer, _| {
3231 buffer.push_transaction(transaction, Instant::now());
3232 })
3233 .ok();
3234 }
3235 editor.update(&mut cx, |editor, cx| {
3236 editor.refresh_document_highlights(cx);
3237 })?;
3238 }
3239 Ok(())
3240 }))
3241 }
3242
3243 fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
3244 if self.pending_rename.is_some() {
3245 return;
3246 }
3247
3248 let Some(provider) = self.completion_provider.as_ref() else {
3249 return;
3250 };
3251
3252 let position = self.selections.newest_anchor().head();
3253 let (buffer, buffer_position) =
3254 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3255 output
3256 } else {
3257 return;
3258 };
3259
3260 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3261 let completions = provider.completions(&buffer, buffer_position, cx);
3262
3263 let id = post_inc(&mut self.next_completion_id);
3264 let task = cx.spawn(|this, mut cx| {
3265 async move {
3266 let completions = completions.await.log_err();
3267 let menu = if let Some(completions) = completions {
3268 let mut menu = CompletionsMenu {
3269 id,
3270 initial_position: position,
3271 match_candidates: completions
3272 .iter()
3273 .enumerate()
3274 .map(|(id, completion)| {
3275 StringMatchCandidate::new(
3276 id,
3277 completion.label.text[completion.label.filter_range.clone()]
3278 .into(),
3279 )
3280 })
3281 .collect(),
3282 buffer,
3283 completions: Arc::new(RwLock::new(completions.into())),
3284 matches: Vec::new().into(),
3285 selected_item: 0,
3286 scroll_handle: UniformListScrollHandle::new(),
3287 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
3288 DebouncedDelay::new(),
3289 )),
3290 };
3291 menu.filter(query.as_deref(), cx.background_executor().clone())
3292 .await;
3293
3294 if menu.matches.is_empty() {
3295 None
3296 } else {
3297 this.update(&mut cx, |editor, cx| {
3298 let completions = menu.completions.clone();
3299 let matches = menu.matches.clone();
3300
3301 let delay_ms = EditorSettings::get_global(cx)
3302 .completion_documentation_secondary_query_debounce;
3303 let delay = Duration::from_millis(delay_ms);
3304
3305 editor
3306 .completion_documentation_pre_resolve_debounce
3307 .fire_new(delay, cx, |editor, cx| {
3308 CompletionsMenu::pre_resolve_completion_documentation(
3309 completions,
3310 matches,
3311 editor,
3312 cx,
3313 )
3314 });
3315 })
3316 .ok();
3317 Some(menu)
3318 }
3319 } else {
3320 None
3321 };
3322
3323 this.update(&mut cx, |this, cx| {
3324 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3325
3326 let mut context_menu = this.context_menu.write();
3327 match context_menu.as_ref() {
3328 None => {}
3329
3330 Some(ContextMenu::Completions(prev_menu)) => {
3331 if prev_menu.id > id {
3332 return;
3333 }
3334 }
3335
3336 _ => return,
3337 }
3338
3339 if this.focus_handle.is_focused(cx) && menu.is_some() {
3340 let menu = menu.unwrap();
3341 *context_menu = Some(ContextMenu::Completions(menu));
3342 drop(context_menu);
3343 this.discard_copilot_suggestion(cx);
3344 cx.notify();
3345 } else if this.completion_tasks.len() <= 1 {
3346 // If there are no more completion tasks and the last menu was
3347 // empty, we should hide it. If it was already hidden, we should
3348 // also show the copilot suggestion when available.
3349 drop(context_menu);
3350 if this.hide_context_menu(cx).is_none() {
3351 this.update_visible_copilot_suggestion(cx);
3352 }
3353 }
3354 })?;
3355
3356 Ok::<_, anyhow::Error>(())
3357 }
3358 .log_err()
3359 });
3360
3361 self.completion_tasks.push((id, task));
3362 }
3363
3364 pub fn confirm_completion(
3365 &mut self,
3366 action: &ConfirmCompletion,
3367 cx: &mut ViewContext<Self>,
3368 ) -> Option<Task<Result<()>>> {
3369 use language::ToOffset as _;
3370
3371 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3372 menu
3373 } else {
3374 return None;
3375 };
3376
3377 let mat = completions_menu
3378 .matches
3379 .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
3380 let buffer_handle = completions_menu.buffer;
3381 let completions = completions_menu.completions.read();
3382 let completion = completions.get(mat.candidate_id)?;
3383 cx.stop_propagation();
3384
3385 let snippet;
3386 let text;
3387 if completion.is_snippet() {
3388 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3389 text = snippet.as_ref().unwrap().text.clone();
3390 } else {
3391 snippet = None;
3392 text = completion.new_text.clone();
3393 };
3394 let selections = self.selections.all::<usize>(cx);
3395 let buffer = buffer_handle.read(cx);
3396 let old_range = completion.old_range.to_offset(buffer);
3397 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3398
3399 let newest_selection = self.selections.newest_anchor();
3400 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3401 return None;
3402 }
3403
3404 let lookbehind = newest_selection
3405 .start
3406 .text_anchor
3407 .to_offset(buffer)
3408 .saturating_sub(old_range.start);
3409 let lookahead = old_range
3410 .end
3411 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3412 let mut common_prefix_len = old_text
3413 .bytes()
3414 .zip(text.bytes())
3415 .take_while(|(a, b)| a == b)
3416 .count();
3417
3418 let snapshot = self.buffer.read(cx).snapshot(cx);
3419 let mut range_to_replace: Option<Range<isize>> = None;
3420 let mut ranges = Vec::new();
3421 for selection in &selections {
3422 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3423 let start = selection.start.saturating_sub(lookbehind);
3424 let end = selection.end + lookahead;
3425 if selection.id == newest_selection.id {
3426 range_to_replace = Some(
3427 ((start + common_prefix_len) as isize - selection.start as isize)
3428 ..(end as isize - selection.start as isize),
3429 );
3430 }
3431 ranges.push(start + common_prefix_len..end);
3432 } else {
3433 common_prefix_len = 0;
3434 ranges.clear();
3435 ranges.extend(selections.iter().map(|s| {
3436 if s.id == newest_selection.id {
3437 range_to_replace = Some(
3438 old_range.start.to_offset_utf16(&snapshot).0 as isize
3439 - selection.start as isize
3440 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3441 - selection.start as isize,
3442 );
3443 old_range.clone()
3444 } else {
3445 s.start..s.end
3446 }
3447 }));
3448 break;
3449 }
3450 }
3451 let text = &text[common_prefix_len..];
3452
3453 cx.emit(EditorEvent::InputHandled {
3454 utf16_range_to_replace: range_to_replace,
3455 text: text.into(),
3456 });
3457
3458 self.transact(cx, |this, cx| {
3459 if let Some(mut snippet) = snippet {
3460 snippet.text = text.to_string();
3461 for tabstop in snippet.tabstops.iter_mut().flatten() {
3462 tabstop.start -= common_prefix_len as isize;
3463 tabstop.end -= common_prefix_len as isize;
3464 }
3465
3466 this.insert_snippet(&ranges, snippet, cx).log_err();
3467 } else {
3468 this.buffer.update(cx, |buffer, cx| {
3469 buffer.edit(
3470 ranges.iter().map(|range| (range.clone(), text)),
3471 this.autoindent_mode.clone(),
3472 cx,
3473 );
3474 });
3475 }
3476
3477 this.refresh_copilot_suggestions(true, cx);
3478 });
3479
3480 let provider = self.completion_provider.as_ref()?;
3481 let apply_edits = provider.apply_additional_edits_for_completion(
3482 buffer_handle,
3483 completion.clone(),
3484 true,
3485 cx,
3486 );
3487 Some(cx.foreground_executor().spawn(async move {
3488 apply_edits.await?;
3489 Ok(())
3490 }))
3491 }
3492
3493 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3494 let mut context_menu = self.context_menu.write();
3495 if matches!(context_menu.as_ref(), Some(ContextMenu::CodeActions(_))) {
3496 *context_menu = None;
3497 cx.notify();
3498 return;
3499 }
3500 drop(context_menu);
3501
3502 let deployed_from_indicator = action.deployed_from_indicator;
3503 let mut task = self.code_actions_task.take();
3504 cx.spawn(|this, mut cx| async move {
3505 while let Some(prev_task) = task {
3506 prev_task.await;
3507 task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
3508 }
3509
3510 this.update(&mut cx, |this, cx| {
3511 if this.focus_handle.is_focused(cx) {
3512 if let Some((buffer, actions)) = this.available_code_actions.clone() {
3513 this.completion_tasks.clear();
3514 this.discard_copilot_suggestion(cx);
3515 *this.context_menu.write() =
3516 Some(ContextMenu::CodeActions(CodeActionsMenu {
3517 buffer,
3518 actions,
3519 selected_item: Default::default(),
3520 scroll_handle: UniformListScrollHandle::default(),
3521 deployed_from_indicator,
3522 }));
3523 cx.notify();
3524 }
3525 }
3526 })?;
3527
3528 Ok::<_, anyhow::Error>(())
3529 })
3530 .detach_and_log_err(cx);
3531 }
3532
3533 pub fn confirm_code_action(
3534 &mut self,
3535 action: &ConfirmCodeAction,
3536 cx: &mut ViewContext<Self>,
3537 ) -> Option<Task<Result<()>>> {
3538 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
3539 menu
3540 } else {
3541 return None;
3542 };
3543 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
3544 let action = actions_menu.actions.get(action_ix)?.clone();
3545 let title = action.lsp_action.title.clone();
3546 let buffer = actions_menu.buffer;
3547 let workspace = self.workspace()?;
3548
3549 let apply_code_actions = workspace
3550 .read(cx)
3551 .project()
3552 .clone()
3553 .update(cx, |project, cx| {
3554 project.apply_code_action(buffer, action, true, cx)
3555 });
3556 let workspace = workspace.downgrade();
3557 Some(cx.spawn(|editor, cx| async move {
3558 let project_transaction = apply_code_actions.await?;
3559 Self::open_project_transaction(&editor, workspace, project_transaction, title, cx).await
3560 }))
3561 }
3562
3563 async fn open_project_transaction(
3564 this: &WeakView<Editor>,
3565 workspace: WeakView<Workspace>,
3566 transaction: ProjectTransaction,
3567 title: String,
3568 mut cx: AsyncWindowContext,
3569 ) -> Result<()> {
3570 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
3571
3572 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
3573 cx.update(|cx| {
3574 entries.sort_unstable_by_key(|(buffer, _)| {
3575 buffer.read(cx).file().map(|f| f.path().clone())
3576 });
3577 })?;
3578
3579 // If the project transaction's edits are all contained within this editor, then
3580 // avoid opening a new editor to display them.
3581
3582 if let Some((buffer, transaction)) = entries.first() {
3583 if entries.len() == 1 {
3584 let excerpt = this.update(&mut cx, |editor, cx| {
3585 editor
3586 .buffer()
3587 .read(cx)
3588 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
3589 })?;
3590 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
3591 if excerpted_buffer == *buffer {
3592 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
3593 let excerpt_range = excerpt_range.to_offset(buffer);
3594 buffer
3595 .edited_ranges_for_transaction::<usize>(transaction)
3596 .all(|range| {
3597 excerpt_range.start <= range.start
3598 && excerpt_range.end >= range.end
3599 })
3600 })?;
3601
3602 if all_edits_within_excerpt {
3603 return Ok(());
3604 }
3605 }
3606 }
3607 }
3608 } else {
3609 return Ok(());
3610 }
3611
3612 let mut ranges_to_highlight = Vec::new();
3613 let excerpt_buffer = cx.new_model(|cx| {
3614 let mut multibuffer =
3615 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
3616 for (buffer_handle, transaction) in &entries {
3617 let buffer = buffer_handle.read(cx);
3618 ranges_to_highlight.extend(
3619 multibuffer.push_excerpts_with_context_lines(
3620 buffer_handle.clone(),
3621 buffer
3622 .edited_ranges_for_transaction::<usize>(transaction)
3623 .collect(),
3624 1,
3625 cx,
3626 ),
3627 );
3628 }
3629 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
3630 multibuffer
3631 })?;
3632
3633 workspace.update(&mut cx, |workspace, cx| {
3634 let project = workspace.project().clone();
3635 let editor =
3636 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
3637 workspace.add_item_to_active_pane(Box::new(editor.clone()), cx);
3638 editor.update(cx, |editor, cx| {
3639 editor.highlight_background::<Self>(
3640 ranges_to_highlight,
3641 |theme| theme.editor_highlighted_line_background,
3642 cx,
3643 );
3644 });
3645 })?;
3646
3647 Ok(())
3648 }
3649
3650 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3651 let project = self.project.clone()?;
3652 let buffer = self.buffer.read(cx);
3653 let newest_selection = self.selections.newest_anchor().clone();
3654 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
3655 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
3656 if start_buffer != end_buffer {
3657 return None;
3658 }
3659
3660 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
3661 cx.background_executor()
3662 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
3663 .await;
3664
3665 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
3666 project.code_actions(&start_buffer, start..end, cx)
3667 }) {
3668 code_actions.await.log_err()
3669 } else {
3670 None
3671 };
3672
3673 this.update(&mut cx, |this, cx| {
3674 this.available_code_actions = actions.and_then(|actions| {
3675 if actions.is_empty() {
3676 None
3677 } else {
3678 Some((start_buffer, actions.into()))
3679 }
3680 });
3681 cx.notify();
3682 })
3683 .log_err();
3684 }));
3685 None
3686 }
3687
3688 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3689 if self.pending_rename.is_some() {
3690 return None;
3691 }
3692
3693 let project = self.project.clone()?;
3694 let buffer = self.buffer.read(cx);
3695 let newest_selection = self.selections.newest_anchor().clone();
3696 let cursor_position = newest_selection.head();
3697 let (cursor_buffer, cursor_buffer_position) =
3698 buffer.text_anchor_for_position(cursor_position, cx)?;
3699 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
3700 if cursor_buffer != tail_buffer {
3701 return None;
3702 }
3703
3704 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
3705 cx.background_executor()
3706 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
3707 .await;
3708
3709 let highlights = if let Some(highlights) = project
3710 .update(&mut cx, |project, cx| {
3711 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
3712 })
3713 .log_err()
3714 {
3715 highlights.await.log_err()
3716 } else {
3717 None
3718 };
3719
3720 if let Some(highlights) = highlights {
3721 this.update(&mut cx, |this, cx| {
3722 if this.pending_rename.is_some() {
3723 return;
3724 }
3725
3726 let buffer_id = cursor_position.buffer_id;
3727 let buffer = this.buffer.read(cx);
3728 if !buffer
3729 .text_anchor_for_position(cursor_position, cx)
3730 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
3731 {
3732 return;
3733 }
3734
3735 let cursor_buffer_snapshot = cursor_buffer.read(cx);
3736 let mut write_ranges = Vec::new();
3737 let mut read_ranges = Vec::new();
3738 for highlight in highlights {
3739 for (excerpt_id, excerpt_range) in
3740 buffer.excerpts_for_buffer(&cursor_buffer, cx)
3741 {
3742 let start = highlight
3743 .range
3744 .start
3745 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
3746 let end = highlight
3747 .range
3748 .end
3749 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
3750 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
3751 continue;
3752 }
3753
3754 let range = Anchor {
3755 buffer_id,
3756 excerpt_id: excerpt_id,
3757 text_anchor: start,
3758 }..Anchor {
3759 buffer_id,
3760 excerpt_id,
3761 text_anchor: end,
3762 };
3763 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
3764 write_ranges.push(range);
3765 } else {
3766 read_ranges.push(range);
3767 }
3768 }
3769 }
3770
3771 this.highlight_background::<DocumentHighlightRead>(
3772 read_ranges,
3773 |theme| theme.editor_document_highlight_read_background,
3774 cx,
3775 );
3776 this.highlight_background::<DocumentHighlightWrite>(
3777 write_ranges,
3778 |theme| theme.editor_document_highlight_write_background,
3779 cx,
3780 );
3781 cx.notify();
3782 })
3783 .log_err();
3784 }
3785 }));
3786 None
3787 }
3788
3789 fn refresh_copilot_suggestions(
3790 &mut self,
3791 debounce: bool,
3792 cx: &mut ViewContext<Self>,
3793 ) -> Option<()> {
3794 let copilot = Copilot::global(cx)?;
3795 if !self.show_copilot_suggestions || !copilot.read(cx).status().is_authorized() {
3796 self.clear_copilot_suggestions(cx);
3797 return None;
3798 }
3799 self.update_visible_copilot_suggestion(cx);
3800
3801 let snapshot = self.buffer.read(cx).snapshot(cx);
3802 let cursor = self.selections.newest_anchor().head();
3803 if !self.is_copilot_enabled_at(cursor, &snapshot, cx) {
3804 self.clear_copilot_suggestions(cx);
3805 return None;
3806 }
3807
3808 let (buffer, buffer_position) =
3809 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
3810 self.copilot_state.pending_refresh = cx.spawn(|this, mut cx| async move {
3811 if debounce {
3812 cx.background_executor()
3813 .timer(COPILOT_DEBOUNCE_TIMEOUT)
3814 .await;
3815 }
3816
3817 let completions = copilot
3818 .update(&mut cx, |copilot, cx| {
3819 copilot.completions(&buffer, buffer_position, cx)
3820 })
3821 .log_err()
3822 .unwrap_or(Task::ready(Ok(Vec::new())))
3823 .await
3824 .log_err()
3825 .into_iter()
3826 .flatten()
3827 .collect_vec();
3828
3829 this.update(&mut cx, |this, cx| {
3830 if !completions.is_empty() {
3831 this.copilot_state.cycled = false;
3832 this.copilot_state.pending_cycling_refresh = Task::ready(None);
3833 this.copilot_state.completions.clear();
3834 this.copilot_state.active_completion_index = 0;
3835 this.copilot_state.excerpt_id = Some(cursor.excerpt_id);
3836 for completion in completions {
3837 this.copilot_state.push_completion(completion);
3838 }
3839 this.update_visible_copilot_suggestion(cx);
3840 }
3841 })
3842 .log_err()?;
3843 Some(())
3844 });
3845
3846 Some(())
3847 }
3848
3849 fn cycle_copilot_suggestions(
3850 &mut self,
3851 direction: Direction,
3852 cx: &mut ViewContext<Self>,
3853 ) -> Option<()> {
3854 let copilot = Copilot::global(cx)?;
3855 if !self.show_copilot_suggestions || !copilot.read(cx).status().is_authorized() {
3856 return None;
3857 }
3858
3859 if self.copilot_state.cycled {
3860 self.copilot_state.cycle_completions(direction);
3861 self.update_visible_copilot_suggestion(cx);
3862 } else {
3863 let cursor = self.selections.newest_anchor().head();
3864 let (buffer, buffer_position) =
3865 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
3866 self.copilot_state.pending_cycling_refresh = cx.spawn(|this, mut cx| async move {
3867 let completions = copilot
3868 .update(&mut cx, |copilot, cx| {
3869 copilot.completions_cycling(&buffer, buffer_position, cx)
3870 })
3871 .log_err()?
3872 .await;
3873
3874 this.update(&mut cx, |this, cx| {
3875 this.copilot_state.cycled = true;
3876 for completion in completions.log_err().into_iter().flatten() {
3877 this.copilot_state.push_completion(completion);
3878 }
3879 this.copilot_state.cycle_completions(direction);
3880 this.update_visible_copilot_suggestion(cx);
3881 })
3882 .log_err()?;
3883
3884 Some(())
3885 });
3886 }
3887
3888 Some(())
3889 }
3890
3891 fn copilot_suggest(&mut self, _: &copilot::Suggest, cx: &mut ViewContext<Self>) {
3892 if !self.has_active_copilot_suggestion(cx) {
3893 self.refresh_copilot_suggestions(false, cx);
3894 return;
3895 }
3896
3897 self.update_visible_copilot_suggestion(cx);
3898 }
3899
3900 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
3901 self.show_cursor_names(cx);
3902 }
3903
3904 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
3905 self.show_cursor_names = true;
3906 cx.notify();
3907 cx.spawn(|this, mut cx| async move {
3908 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
3909 this.update(&mut cx, |this, cx| {
3910 this.show_cursor_names = false;
3911 cx.notify()
3912 })
3913 .ok()
3914 })
3915 .detach();
3916 }
3917
3918 fn next_copilot_suggestion(&mut self, _: &copilot::NextSuggestion, cx: &mut ViewContext<Self>) {
3919 if self.has_active_copilot_suggestion(cx) {
3920 self.cycle_copilot_suggestions(Direction::Next, cx);
3921 } else {
3922 let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
3923 if is_copilot_disabled {
3924 cx.propagate();
3925 }
3926 }
3927 }
3928
3929 fn previous_copilot_suggestion(
3930 &mut self,
3931 _: &copilot::PreviousSuggestion,
3932 cx: &mut ViewContext<Self>,
3933 ) {
3934 if self.has_active_copilot_suggestion(cx) {
3935 self.cycle_copilot_suggestions(Direction::Prev, cx);
3936 } else {
3937 let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
3938 if is_copilot_disabled {
3939 cx.propagate();
3940 }
3941 }
3942 }
3943
3944 fn accept_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
3945 if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
3946 if let Some((copilot, completion)) =
3947 Copilot::global(cx).zip(self.copilot_state.active_completion())
3948 {
3949 copilot
3950 .update(cx, |copilot, cx| copilot.accept_completion(completion, cx))
3951 .detach_and_log_err(cx);
3952
3953 self.report_copilot_event(Some(completion.uuid.clone()), true, cx)
3954 }
3955 cx.emit(EditorEvent::InputHandled {
3956 utf16_range_to_replace: None,
3957 text: suggestion.text.to_string().into(),
3958 });
3959 self.insert_with_autoindent_mode(&suggestion.text.to_string(), None, cx);
3960 cx.notify();
3961 true
3962 } else {
3963 false
3964 }
3965 }
3966
3967 fn accept_partial_copilot_suggestion(
3968 &mut self,
3969 _: &AcceptPartialCopilotSuggestion,
3970 cx: &mut ViewContext<Self>,
3971 ) {
3972 if self.selections.count() == 1 && self.has_active_copilot_suggestion(cx) {
3973 if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
3974 let mut partial_suggestion = suggestion
3975 .text
3976 .chars()
3977 .by_ref()
3978 .take_while(|c| c.is_alphabetic())
3979 .collect::<String>();
3980 if partial_suggestion.is_empty() {
3981 partial_suggestion = suggestion
3982 .text
3983 .chars()
3984 .by_ref()
3985 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
3986 .collect::<String>();
3987 }
3988
3989 cx.emit(EditorEvent::InputHandled {
3990 utf16_range_to_replace: None,
3991 text: partial_suggestion.clone().into(),
3992 });
3993 self.insert_with_autoindent_mode(&partial_suggestion, None, cx);
3994 self.refresh_copilot_suggestions(true, cx);
3995 cx.notify();
3996 }
3997 }
3998 }
3999
4000 fn discard_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
4001 if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
4002 if let Some(copilot) = Copilot::global(cx) {
4003 copilot
4004 .update(cx, |copilot, cx| {
4005 copilot.discard_completions(&self.copilot_state.completions, cx)
4006 })
4007 .detach_and_log_err(cx);
4008
4009 self.report_copilot_event(None, false, cx)
4010 }
4011
4012 self.display_map.update(cx, |map, cx| {
4013 map.splice_inlays(vec![suggestion.id], Vec::new(), cx)
4014 });
4015 cx.notify();
4016 true
4017 } else {
4018 false
4019 }
4020 }
4021
4022 fn is_copilot_enabled_at(
4023 &self,
4024 location: Anchor,
4025 snapshot: &MultiBufferSnapshot,
4026 cx: &mut ViewContext<Self>,
4027 ) -> bool {
4028 let file = snapshot.file_at(location);
4029 let language = snapshot.language_at(location);
4030 let settings = all_language_settings(file, cx);
4031 self.show_copilot_suggestions
4032 && settings.copilot_enabled(language, file.map(|f| f.path().as_ref()))
4033 }
4034
4035 fn has_active_copilot_suggestion(&self, cx: &AppContext) -> bool {
4036 if let Some(suggestion) = self.copilot_state.suggestion.as_ref() {
4037 let buffer = self.buffer.read(cx).read(cx);
4038 suggestion.position.is_valid(&buffer)
4039 } else {
4040 false
4041 }
4042 }
4043
4044 fn take_active_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
4045 let suggestion = self.copilot_state.suggestion.take()?;
4046 self.display_map.update(cx, |map, cx| {
4047 map.splice_inlays(vec![suggestion.id], Default::default(), cx);
4048 });
4049 let buffer = self.buffer.read(cx).read(cx);
4050
4051 if suggestion.position.is_valid(&buffer) {
4052 Some(suggestion)
4053 } else {
4054 None
4055 }
4056 }
4057
4058 fn update_visible_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) {
4059 let snapshot = self.buffer.read(cx).snapshot(cx);
4060 let selection = self.selections.newest_anchor();
4061 let cursor = selection.head();
4062
4063 if self.context_menu.read().is_some()
4064 || !self.completion_tasks.is_empty()
4065 || selection.start != selection.end
4066 {
4067 self.discard_copilot_suggestion(cx);
4068 } else if let Some(text) = self
4069 .copilot_state
4070 .text_for_active_completion(cursor, &snapshot)
4071 {
4072 let text = Rope::from(text);
4073 let mut to_remove = Vec::new();
4074 if let Some(suggestion) = self.copilot_state.suggestion.take() {
4075 to_remove.push(suggestion.id);
4076 }
4077
4078 let suggestion_inlay =
4079 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
4080 self.copilot_state.suggestion = Some(suggestion_inlay.clone());
4081 self.display_map.update(cx, move |map, cx| {
4082 map.splice_inlays(to_remove, vec![suggestion_inlay], cx)
4083 });
4084 cx.notify();
4085 } else {
4086 self.discard_copilot_suggestion(cx);
4087 }
4088 }
4089
4090 fn clear_copilot_suggestions(&mut self, cx: &mut ViewContext<Self>) {
4091 self.copilot_state = Default::default();
4092 self.discard_copilot_suggestion(cx);
4093 }
4094
4095 pub fn render_code_actions_indicator(
4096 &self,
4097 _style: &EditorStyle,
4098 is_active: bool,
4099 cx: &mut ViewContext<Self>,
4100 ) -> Option<IconButton> {
4101 if self.available_code_actions.is_some() {
4102 Some(
4103 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4104 .icon_size(IconSize::XSmall)
4105 .size(ui::ButtonSize::None)
4106 .icon_color(Color::Muted)
4107 .selected(is_active)
4108 .on_click(cx.listener(|editor, _e, cx| {
4109 editor.toggle_code_actions(
4110 &ToggleCodeActions {
4111 deployed_from_indicator: true,
4112 },
4113 cx,
4114 );
4115 })),
4116 )
4117 } else {
4118 None
4119 }
4120 }
4121
4122 pub fn render_fold_indicators(
4123 &self,
4124 fold_data: Vec<Option<(FoldStatus, u32, bool)>>,
4125 _style: &EditorStyle,
4126 gutter_hovered: bool,
4127 _line_height: Pixels,
4128 _gutter_margin: Pixels,
4129 editor_view: View<Editor>,
4130 ) -> Vec<Option<IconButton>> {
4131 fold_data
4132 .iter()
4133 .enumerate()
4134 .map(|(ix, fold_data)| {
4135 fold_data
4136 .map(|(fold_status, buffer_row, active)| {
4137 (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
4138 IconButton::new(ix, ui::IconName::ChevronDown)
4139 .on_click({
4140 let view = editor_view.clone();
4141 move |_e, cx| {
4142 view.update(cx, |editor, cx| match fold_status {
4143 FoldStatus::Folded => {
4144 editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4145 }
4146 FoldStatus::Foldable => {
4147 editor.fold_at(&FoldAt { buffer_row }, cx);
4148 }
4149 })
4150 }
4151 })
4152 .icon_color(ui::Color::Muted)
4153 .icon_size(ui::IconSize::Small)
4154 .selected(fold_status == FoldStatus::Folded)
4155 .selected_icon(ui::IconName::ChevronRight)
4156 .size(ui::ButtonSize::None)
4157 })
4158 })
4159 .flatten()
4160 })
4161 .collect()
4162 }
4163
4164 pub fn context_menu_visible(&self) -> bool {
4165 self.context_menu
4166 .read()
4167 .as_ref()
4168 .map_or(false, |menu| menu.visible())
4169 }
4170
4171 pub fn render_context_menu(
4172 &self,
4173 cursor_position: DisplayPoint,
4174 style: &EditorStyle,
4175 max_height: Pixels,
4176 cx: &mut ViewContext<Editor>,
4177 ) -> Option<(DisplayPoint, AnyElement)> {
4178 self.context_menu.read().as_ref().map(|menu| {
4179 menu.render(
4180 cursor_position,
4181 style,
4182 max_height,
4183 self.workspace.as_ref().map(|(w, _)| w.clone()),
4184 cx,
4185 )
4186 })
4187 }
4188
4189 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
4190 cx.notify();
4191 self.completion_tasks.clear();
4192 let context_menu = self.context_menu.write().take();
4193 if context_menu.is_some() {
4194 self.update_visible_copilot_suggestion(cx);
4195 }
4196 context_menu
4197 }
4198
4199 pub fn insert_snippet(
4200 &mut self,
4201 insertion_ranges: &[Range<usize>],
4202 snippet: Snippet,
4203 cx: &mut ViewContext<Self>,
4204 ) -> Result<()> {
4205 let tabstops = self.buffer.update(cx, |buffer, cx| {
4206 let snippet_text: Arc<str> = snippet.text.clone().into();
4207 buffer.edit(
4208 insertion_ranges
4209 .iter()
4210 .cloned()
4211 .map(|range| (range, snippet_text.clone())),
4212 Some(AutoindentMode::EachLine),
4213 cx,
4214 );
4215
4216 let snapshot = &*buffer.read(cx);
4217 let snippet = &snippet;
4218 snippet
4219 .tabstops
4220 .iter()
4221 .map(|tabstop| {
4222 let mut tabstop_ranges = tabstop
4223 .iter()
4224 .flat_map(|tabstop_range| {
4225 let mut delta = 0_isize;
4226 insertion_ranges.iter().map(move |insertion_range| {
4227 let insertion_start = insertion_range.start as isize + delta;
4228 delta +=
4229 snippet.text.len() as isize - insertion_range.len() as isize;
4230
4231 let start = snapshot.anchor_before(
4232 (insertion_start + tabstop_range.start) as usize,
4233 );
4234 let end = snapshot
4235 .anchor_after((insertion_start + tabstop_range.end) as usize);
4236 start..end
4237 })
4238 })
4239 .collect::<Vec<_>>();
4240 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
4241 tabstop_ranges
4242 })
4243 .collect::<Vec<_>>()
4244 });
4245
4246 if let Some(tabstop) = tabstops.first() {
4247 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4248 s.select_ranges(tabstop.iter().cloned());
4249 });
4250 self.snippet_stack.push(SnippetState {
4251 active_index: 0,
4252 ranges: tabstops,
4253 });
4254
4255 // Check whether the just-entered snippet ends with an auto-closable bracket.
4256 if self.autoclose_regions.is_empty() {
4257 let snapshot = self.buffer.read(cx).snapshot(cx);
4258 for selection in &mut self.selections.all::<Point>(cx) {
4259 let selection_head = selection.head();
4260 let Some(scope) = snapshot.language_scope_at(selection_head) else {
4261 continue;
4262 };
4263
4264 let mut bracket_pair = None;
4265 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
4266 let prev_chars = snapshot
4267 .reversed_chars_at(selection_head)
4268 .collect::<String>();
4269 for (pair, enabled) in scope.brackets() {
4270 if enabled
4271 && pair.close
4272 && prev_chars.starts_with(pair.start.as_str())
4273 && next_chars.starts_with(pair.end.as_str())
4274 {
4275 bracket_pair = Some(pair.clone());
4276 break;
4277 }
4278 }
4279 if let Some(pair) = bracket_pair {
4280 let start = snapshot.anchor_after(selection_head);
4281 let end = snapshot.anchor_after(selection_head);
4282 self.autoclose_regions.push(AutocloseRegion {
4283 selection_id: selection.id,
4284 range: start..end,
4285 pair,
4286 });
4287 }
4288 }
4289 }
4290 }
4291 Ok(())
4292 }
4293
4294 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4295 self.move_to_snippet_tabstop(Bias::Right, cx)
4296 }
4297
4298 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4299 self.move_to_snippet_tabstop(Bias::Left, cx)
4300 }
4301
4302 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
4303 if let Some(mut snippet) = self.snippet_stack.pop() {
4304 match bias {
4305 Bias::Left => {
4306 if snippet.active_index > 0 {
4307 snippet.active_index -= 1;
4308 } else {
4309 self.snippet_stack.push(snippet);
4310 return false;
4311 }
4312 }
4313 Bias::Right => {
4314 if snippet.active_index + 1 < snippet.ranges.len() {
4315 snippet.active_index += 1;
4316 } else {
4317 self.snippet_stack.push(snippet);
4318 return false;
4319 }
4320 }
4321 }
4322 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
4323 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4324 s.select_anchor_ranges(current_ranges.iter().cloned())
4325 });
4326 // If snippet state is not at the last tabstop, push it back on the stack
4327 if snippet.active_index + 1 < snippet.ranges.len() {
4328 self.snippet_stack.push(snippet);
4329 }
4330 return true;
4331 }
4332 }
4333
4334 false
4335 }
4336
4337 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
4338 self.transact(cx, |this, cx| {
4339 this.select_all(&SelectAll, cx);
4340 this.insert("", cx);
4341 });
4342 }
4343
4344 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
4345 self.transact(cx, |this, cx| {
4346 this.select_autoclose_pair(cx);
4347 let mut selections = this.selections.all::<Point>(cx);
4348 if !this.selections.line_mode {
4349 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
4350 for selection in &mut selections {
4351 if selection.is_empty() {
4352 let old_head = selection.head();
4353 let mut new_head =
4354 movement::left(&display_map, old_head.to_display_point(&display_map))
4355 .to_point(&display_map);
4356 if let Some((buffer, line_buffer_range)) = display_map
4357 .buffer_snapshot
4358 .buffer_line_for_row(old_head.row)
4359 {
4360 let indent_size =
4361 buffer.indent_size_for_line(line_buffer_range.start.row);
4362 let indent_len = match indent_size.kind {
4363 IndentKind::Space => {
4364 buffer.settings_at(line_buffer_range.start, cx).tab_size
4365 }
4366 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
4367 };
4368 if old_head.column <= indent_size.len && old_head.column > 0 {
4369 let indent_len = indent_len.get();
4370 new_head = cmp::min(
4371 new_head,
4372 Point::new(
4373 old_head.row,
4374 ((old_head.column - 1) / indent_len) * indent_len,
4375 ),
4376 );
4377 }
4378 }
4379
4380 selection.set_head(new_head, SelectionGoal::None);
4381 }
4382 }
4383 }
4384
4385 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4386 this.insert("", cx);
4387 this.refresh_copilot_suggestions(true, cx);
4388 });
4389 }
4390
4391 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
4392 self.transact(cx, |this, cx| {
4393 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4394 let line_mode = s.line_mode;
4395 s.move_with(|map, selection| {
4396 if selection.is_empty() && !line_mode {
4397 let cursor = movement::right(map, selection.head());
4398 selection.end = cursor;
4399 selection.reversed = true;
4400 selection.goal = SelectionGoal::None;
4401 }
4402 })
4403 });
4404 this.insert("", cx);
4405 this.refresh_copilot_suggestions(true, cx);
4406 });
4407 }
4408
4409 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
4410 if self.move_to_prev_snippet_tabstop(cx) {
4411 return;
4412 }
4413
4414 self.outdent(&Outdent, cx);
4415 }
4416
4417 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
4418 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
4419 return;
4420 }
4421
4422 let mut selections = self.selections.all_adjusted(cx);
4423 let buffer = self.buffer.read(cx);
4424 let snapshot = buffer.snapshot(cx);
4425 let rows_iter = selections.iter().map(|s| s.head().row);
4426 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
4427
4428 let mut edits = Vec::new();
4429 let mut prev_edited_row = 0;
4430 let mut row_delta = 0;
4431 for selection in &mut selections {
4432 if selection.start.row != prev_edited_row {
4433 row_delta = 0;
4434 }
4435 prev_edited_row = selection.end.row;
4436
4437 // If the selection is non-empty, then increase the indentation of the selected lines.
4438 if !selection.is_empty() {
4439 row_delta =
4440 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4441 continue;
4442 }
4443
4444 // If the selection is empty and the cursor is in the leading whitespace before the
4445 // suggested indentation, then auto-indent the line.
4446 let cursor = selection.head();
4447 let current_indent = snapshot.indent_size_for_line(cursor.row);
4448 if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
4449 if cursor.column < suggested_indent.len
4450 && cursor.column <= current_indent.len
4451 && current_indent.len <= suggested_indent.len
4452 {
4453 selection.start = Point::new(cursor.row, suggested_indent.len);
4454 selection.end = selection.start;
4455 if row_delta == 0 {
4456 edits.extend(Buffer::edit_for_indent_size_adjustment(
4457 cursor.row,
4458 current_indent,
4459 suggested_indent,
4460 ));
4461 row_delta = suggested_indent.len - current_indent.len;
4462 }
4463 continue;
4464 }
4465 }
4466
4467 // Accept copilot suggestion if there is only one selection and the cursor is not
4468 // in the leading whitespace.
4469 if self.selections.count() == 1
4470 && cursor.column >= current_indent.len
4471 && self.has_active_copilot_suggestion(cx)
4472 {
4473 self.accept_copilot_suggestion(cx);
4474 return;
4475 }
4476
4477 // Otherwise, insert a hard or soft tab.
4478 let settings = buffer.settings_at(cursor, cx);
4479 let tab_size = if settings.hard_tabs {
4480 IndentSize::tab()
4481 } else {
4482 let tab_size = settings.tab_size.get();
4483 let char_column = snapshot
4484 .text_for_range(Point::new(cursor.row, 0)..cursor)
4485 .flat_map(str::chars)
4486 .count()
4487 + row_delta as usize;
4488 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
4489 IndentSize::spaces(chars_to_next_tab_stop)
4490 };
4491 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
4492 selection.end = selection.start;
4493 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
4494 row_delta += tab_size.len;
4495 }
4496
4497 self.transact(cx, |this, cx| {
4498 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4499 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4500 this.refresh_copilot_suggestions(true, cx);
4501 });
4502 }
4503
4504 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
4505 if self.read_only(cx) {
4506 return;
4507 }
4508 let mut selections = self.selections.all::<Point>(cx);
4509 let mut prev_edited_row = 0;
4510 let mut row_delta = 0;
4511 let mut edits = Vec::new();
4512 let buffer = self.buffer.read(cx);
4513 let snapshot = buffer.snapshot(cx);
4514 for selection in &mut selections {
4515 if selection.start.row != prev_edited_row {
4516 row_delta = 0;
4517 }
4518 prev_edited_row = selection.end.row;
4519
4520 row_delta =
4521 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4522 }
4523
4524 self.transact(cx, |this, cx| {
4525 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4526 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4527 });
4528 }
4529
4530 fn indent_selection(
4531 buffer: &MultiBuffer,
4532 snapshot: &MultiBufferSnapshot,
4533 selection: &mut Selection<Point>,
4534 edits: &mut Vec<(Range<Point>, String)>,
4535 delta_for_start_row: u32,
4536 cx: &AppContext,
4537 ) -> u32 {
4538 let settings = buffer.settings_at(selection.start, cx);
4539 let tab_size = settings.tab_size.get();
4540 let indent_kind = if settings.hard_tabs {
4541 IndentKind::Tab
4542 } else {
4543 IndentKind::Space
4544 };
4545 let mut start_row = selection.start.row;
4546 let mut end_row = selection.end.row + 1;
4547
4548 // If a selection ends at the beginning of a line, don't indent
4549 // that last line.
4550 if selection.end.column == 0 && selection.end.row > selection.start.row {
4551 end_row -= 1;
4552 }
4553
4554 // Avoid re-indenting a row that has already been indented by a
4555 // previous selection, but still update this selection's column
4556 // to reflect that indentation.
4557 if delta_for_start_row > 0 {
4558 start_row += 1;
4559 selection.start.column += delta_for_start_row;
4560 if selection.end.row == selection.start.row {
4561 selection.end.column += delta_for_start_row;
4562 }
4563 }
4564
4565 let mut delta_for_end_row = 0;
4566 for row in start_row..end_row {
4567 let current_indent = snapshot.indent_size_for_line(row);
4568 let indent_delta = match (current_indent.kind, indent_kind) {
4569 (IndentKind::Space, IndentKind::Space) => {
4570 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
4571 IndentSize::spaces(columns_to_next_tab_stop)
4572 }
4573 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
4574 (_, IndentKind::Tab) => IndentSize::tab(),
4575 };
4576
4577 let row_start = Point::new(row, 0);
4578 edits.push((
4579 row_start..row_start,
4580 indent_delta.chars().collect::<String>(),
4581 ));
4582
4583 // Update this selection's endpoints to reflect the indentation.
4584 if row == selection.start.row {
4585 selection.start.column += indent_delta.len;
4586 }
4587 if row == selection.end.row {
4588 selection.end.column += indent_delta.len;
4589 delta_for_end_row = indent_delta.len;
4590 }
4591 }
4592
4593 if selection.start.row == selection.end.row {
4594 delta_for_start_row + delta_for_end_row
4595 } else {
4596 delta_for_end_row
4597 }
4598 }
4599
4600 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
4601 if self.read_only(cx) {
4602 return;
4603 }
4604 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4605 let selections = self.selections.all::<Point>(cx);
4606 let mut deletion_ranges = Vec::new();
4607 let mut last_outdent = None;
4608 {
4609 let buffer = self.buffer.read(cx);
4610 let snapshot = buffer.snapshot(cx);
4611 for selection in &selections {
4612 let settings = buffer.settings_at(selection.start, cx);
4613 let tab_size = settings.tab_size.get();
4614 let mut rows = selection.spanned_rows(false, &display_map);
4615
4616 // Avoid re-outdenting a row that has already been outdented by a
4617 // previous selection.
4618 if let Some(last_row) = last_outdent {
4619 if last_row == rows.start {
4620 rows.start += 1;
4621 }
4622 }
4623
4624 for row in rows {
4625 let indent_size = snapshot.indent_size_for_line(row);
4626 if indent_size.len > 0 {
4627 let deletion_len = match indent_size.kind {
4628 IndentKind::Space => {
4629 let columns_to_prev_tab_stop = indent_size.len % tab_size;
4630 if columns_to_prev_tab_stop == 0 {
4631 tab_size
4632 } else {
4633 columns_to_prev_tab_stop
4634 }
4635 }
4636 IndentKind::Tab => 1,
4637 };
4638 deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
4639 last_outdent = Some(row);
4640 }
4641 }
4642 }
4643 }
4644
4645 self.transact(cx, |this, cx| {
4646 this.buffer.update(cx, |buffer, cx| {
4647 let empty_str: Arc<str> = "".into();
4648 buffer.edit(
4649 deletion_ranges
4650 .into_iter()
4651 .map(|range| (range, empty_str.clone())),
4652 None,
4653 cx,
4654 );
4655 });
4656 let selections = this.selections.all::<usize>(cx);
4657 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4658 });
4659 }
4660
4661 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
4662 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4663 let selections = self.selections.all::<Point>(cx);
4664
4665 let mut new_cursors = Vec::new();
4666 let mut edit_ranges = Vec::new();
4667 let mut selections = selections.iter().peekable();
4668 while let Some(selection) = selections.next() {
4669 let mut rows = selection.spanned_rows(false, &display_map);
4670 let goal_display_column = selection.head().to_display_point(&display_map).column();
4671
4672 // Accumulate contiguous regions of rows that we want to delete.
4673 while let Some(next_selection) = selections.peek() {
4674 let next_rows = next_selection.spanned_rows(false, &display_map);
4675 if next_rows.start <= rows.end {
4676 rows.end = next_rows.end;
4677 selections.next().unwrap();
4678 } else {
4679 break;
4680 }
4681 }
4682
4683 let buffer = &display_map.buffer_snapshot;
4684 let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
4685 let edit_end;
4686 let cursor_buffer_row;
4687 if buffer.max_point().row >= rows.end {
4688 // If there's a line after the range, delete the \n from the end of the row range
4689 // and position the cursor on the next line.
4690 edit_end = Point::new(rows.end, 0).to_offset(buffer);
4691 cursor_buffer_row = rows.end;
4692 } else {
4693 // If there isn't a line after the range, delete the \n from the line before the
4694 // start of the row range and position the cursor there.
4695 edit_start = edit_start.saturating_sub(1);
4696 edit_end = buffer.len();
4697 cursor_buffer_row = rows.start.saturating_sub(1);
4698 }
4699
4700 let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
4701 *cursor.column_mut() =
4702 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
4703
4704 new_cursors.push((
4705 selection.id,
4706 buffer.anchor_after(cursor.to_point(&display_map)),
4707 ));
4708 edit_ranges.push(edit_start..edit_end);
4709 }
4710
4711 self.transact(cx, |this, cx| {
4712 let buffer = this.buffer.update(cx, |buffer, cx| {
4713 let empty_str: Arc<str> = "".into();
4714 buffer.edit(
4715 edit_ranges
4716 .into_iter()
4717 .map(|range| (range, empty_str.clone())),
4718 None,
4719 cx,
4720 );
4721 buffer.snapshot(cx)
4722 });
4723 let new_selections = new_cursors
4724 .into_iter()
4725 .map(|(id, cursor)| {
4726 let cursor = cursor.to_point(&buffer);
4727 Selection {
4728 id,
4729 start: cursor,
4730 end: cursor,
4731 reversed: false,
4732 goal: SelectionGoal::None,
4733 }
4734 })
4735 .collect();
4736
4737 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4738 s.select(new_selections);
4739 });
4740 });
4741 }
4742
4743 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
4744 if self.read_only(cx) {
4745 return;
4746 }
4747 let mut row_ranges = Vec::<Range<u32>>::new();
4748 for selection in self.selections.all::<Point>(cx) {
4749 let start = selection.start.row;
4750 let end = if selection.start.row == selection.end.row {
4751 selection.start.row + 1
4752 } else {
4753 selection.end.row
4754 };
4755
4756 if let Some(last_row_range) = row_ranges.last_mut() {
4757 if start <= last_row_range.end {
4758 last_row_range.end = end;
4759 continue;
4760 }
4761 }
4762 row_ranges.push(start..end);
4763 }
4764
4765 let snapshot = self.buffer.read(cx).snapshot(cx);
4766 let mut cursor_positions = Vec::new();
4767 for row_range in &row_ranges {
4768 let anchor = snapshot.anchor_before(Point::new(
4769 row_range.end - 1,
4770 snapshot.line_len(row_range.end - 1),
4771 ));
4772 cursor_positions.push(anchor..anchor);
4773 }
4774
4775 self.transact(cx, |this, cx| {
4776 for row_range in row_ranges.into_iter().rev() {
4777 for row in row_range.rev() {
4778 let end_of_line = Point::new(row, snapshot.line_len(row));
4779 let indent = snapshot.indent_size_for_line(row + 1);
4780 let start_of_next_line = Point::new(row + 1, indent.len);
4781
4782 let replace = if snapshot.line_len(row + 1) > indent.len {
4783 " "
4784 } else {
4785 ""
4786 };
4787
4788 this.buffer.update(cx, |buffer, cx| {
4789 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
4790 });
4791 }
4792 }
4793
4794 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4795 s.select_anchor_ranges(cursor_positions)
4796 });
4797 });
4798 }
4799
4800 pub fn sort_lines_case_sensitive(
4801 &mut self,
4802 _: &SortLinesCaseSensitive,
4803 cx: &mut ViewContext<Self>,
4804 ) {
4805 self.manipulate_lines(cx, |lines| lines.sort())
4806 }
4807
4808 pub fn sort_lines_case_insensitive(
4809 &mut self,
4810 _: &SortLinesCaseInsensitive,
4811 cx: &mut ViewContext<Self>,
4812 ) {
4813 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
4814 }
4815
4816 pub fn unique_lines_case_insensitive(
4817 &mut self,
4818 _: &UniqueLinesCaseInsensitive,
4819 cx: &mut ViewContext<Self>,
4820 ) {
4821 self.manipulate_lines(cx, |lines| {
4822 let mut seen = HashSet::default();
4823 lines.retain(|line| seen.insert(line.to_lowercase()));
4824 })
4825 }
4826
4827 pub fn unique_lines_case_sensitive(
4828 &mut self,
4829 _: &UniqueLinesCaseSensitive,
4830 cx: &mut ViewContext<Self>,
4831 ) {
4832 self.manipulate_lines(cx, |lines| {
4833 let mut seen = HashSet::default();
4834 lines.retain(|line| seen.insert(*line));
4835 })
4836 }
4837
4838 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
4839 self.manipulate_lines(cx, |lines| lines.reverse())
4840 }
4841
4842 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
4843 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
4844 }
4845
4846 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
4847 where
4848 Fn: FnMut(&mut Vec<&str>),
4849 {
4850 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4851 let buffer = self.buffer.read(cx).snapshot(cx);
4852
4853 let mut edits = Vec::new();
4854
4855 let selections = self.selections.all::<Point>(cx);
4856 let mut selections = selections.iter().peekable();
4857 let mut contiguous_row_selections = Vec::new();
4858 let mut new_selections = Vec::new();
4859 let mut added_lines = 0;
4860 let mut removed_lines = 0;
4861
4862 while let Some(selection) = selections.next() {
4863 let (start_row, end_row) = consume_contiguous_rows(
4864 &mut contiguous_row_selections,
4865 selection,
4866 &display_map,
4867 &mut selections,
4868 );
4869
4870 let start_point = Point::new(start_row, 0);
4871 let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
4872 let text = buffer
4873 .text_for_range(start_point..end_point)
4874 .collect::<String>();
4875
4876 let mut lines = text.split('\n').collect_vec();
4877
4878 let lines_before = lines.len();
4879 callback(&mut lines);
4880 let lines_after = lines.len();
4881
4882 edits.push((start_point..end_point, lines.join("\n")));
4883
4884 // Selections must change based on added and removed line count
4885 let start_row = start_point.row + added_lines as u32 - removed_lines as u32;
4886 let end_row = start_row + lines_after.saturating_sub(1) as u32;
4887 new_selections.push(Selection {
4888 id: selection.id,
4889 start: start_row,
4890 end: end_row,
4891 goal: SelectionGoal::None,
4892 reversed: selection.reversed,
4893 });
4894
4895 if lines_after > lines_before {
4896 added_lines += lines_after - lines_before;
4897 } else if lines_before > lines_after {
4898 removed_lines += lines_before - lines_after;
4899 }
4900 }
4901
4902 self.transact(cx, |this, cx| {
4903 let buffer = this.buffer.update(cx, |buffer, cx| {
4904 buffer.edit(edits, None, cx);
4905 buffer.snapshot(cx)
4906 });
4907
4908 // Recalculate offsets on newly edited buffer
4909 let new_selections = new_selections
4910 .iter()
4911 .map(|s| {
4912 let start_point = Point::new(s.start, 0);
4913 let end_point = Point::new(s.end, buffer.line_len(s.end));
4914 Selection {
4915 id: s.id,
4916 start: buffer.point_to_offset(start_point),
4917 end: buffer.point_to_offset(end_point),
4918 goal: s.goal,
4919 reversed: s.reversed,
4920 }
4921 })
4922 .collect();
4923
4924 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4925 s.select(new_selections);
4926 });
4927
4928 this.request_autoscroll(Autoscroll::fit(), cx);
4929 });
4930 }
4931
4932 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
4933 self.manipulate_text(cx, |text| text.to_uppercase())
4934 }
4935
4936 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
4937 self.manipulate_text(cx, |text| text.to_lowercase())
4938 }
4939
4940 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
4941 self.manipulate_text(cx, |text| {
4942 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
4943 // https://github.com/rutrum/convert-case/issues/16
4944 text.split('\n')
4945 .map(|line| line.to_case(Case::Title))
4946 .join("\n")
4947 })
4948 }
4949
4950 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
4951 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
4952 }
4953
4954 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
4955 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
4956 }
4957
4958 pub fn convert_to_upper_camel_case(
4959 &mut self,
4960 _: &ConvertToUpperCamelCase,
4961 cx: &mut ViewContext<Self>,
4962 ) {
4963 self.manipulate_text(cx, |text| {
4964 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
4965 // https://github.com/rutrum/convert-case/issues/16
4966 text.split('\n')
4967 .map(|line| line.to_case(Case::UpperCamel))
4968 .join("\n")
4969 })
4970 }
4971
4972 pub fn convert_to_lower_camel_case(
4973 &mut self,
4974 _: &ConvertToLowerCamelCase,
4975 cx: &mut ViewContext<Self>,
4976 ) {
4977 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
4978 }
4979
4980 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
4981 where
4982 Fn: FnMut(&str) -> String,
4983 {
4984 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4985 let buffer = self.buffer.read(cx).snapshot(cx);
4986
4987 let mut new_selections = Vec::new();
4988 let mut edits = Vec::new();
4989 let mut selection_adjustment = 0i32;
4990
4991 for selection in self.selections.all::<usize>(cx) {
4992 let selection_is_empty = selection.is_empty();
4993
4994 let (start, end) = if selection_is_empty {
4995 let word_range = movement::surrounding_word(
4996 &display_map,
4997 selection.start.to_display_point(&display_map),
4998 );
4999 let start = word_range.start.to_offset(&display_map, Bias::Left);
5000 let end = word_range.end.to_offset(&display_map, Bias::Left);
5001 (start, end)
5002 } else {
5003 (selection.start, selection.end)
5004 };
5005
5006 let text = buffer.text_for_range(start..end).collect::<String>();
5007 let old_length = text.len() as i32;
5008 let text = callback(&text);
5009
5010 new_selections.push(Selection {
5011 start: (start as i32 - selection_adjustment) as usize,
5012 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
5013 goal: SelectionGoal::None,
5014 ..selection
5015 });
5016
5017 selection_adjustment += old_length - text.len() as i32;
5018
5019 edits.push((start..end, text));
5020 }
5021
5022 self.transact(cx, |this, cx| {
5023 this.buffer.update(cx, |buffer, cx| {
5024 buffer.edit(edits, None, cx);
5025 });
5026
5027 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5028 s.select(new_selections);
5029 });
5030
5031 this.request_autoscroll(Autoscroll::fit(), cx);
5032 });
5033 }
5034
5035 pub fn duplicate_line(&mut self, action: &DuplicateLine, cx: &mut ViewContext<Self>) {
5036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5037 let buffer = &display_map.buffer_snapshot;
5038 let selections = self.selections.all::<Point>(cx);
5039
5040 let mut edits = Vec::new();
5041 let mut selections_iter = selections.iter().peekable();
5042 while let Some(selection) = selections_iter.next() {
5043 // Avoid duplicating the same lines twice.
5044 let mut rows = selection.spanned_rows(false, &display_map);
5045
5046 while let Some(next_selection) = selections_iter.peek() {
5047 let next_rows = next_selection.spanned_rows(false, &display_map);
5048 if next_rows.start < rows.end {
5049 rows.end = next_rows.end;
5050 selections_iter.next().unwrap();
5051 } else {
5052 break;
5053 }
5054 }
5055
5056 // Copy the text from the selected row region and splice it either at the start
5057 // or end of the region.
5058 let start = Point::new(rows.start, 0);
5059 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
5060 let text = buffer
5061 .text_for_range(start..end)
5062 .chain(Some("\n"))
5063 .collect::<String>();
5064 let insert_location = if action.move_upwards {
5065 Point::new(rows.end, 0)
5066 } else {
5067 start
5068 };
5069 edits.push((insert_location..insert_location, text));
5070 }
5071
5072 self.transact(cx, |this, cx| {
5073 this.buffer.update(cx, |buffer, cx| {
5074 buffer.edit(edits, None, cx);
5075 });
5076
5077 this.request_autoscroll(Autoscroll::fit(), cx);
5078 });
5079 }
5080
5081 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
5082 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5083 let buffer = self.buffer.read(cx).snapshot(cx);
5084
5085 let mut edits = Vec::new();
5086 let mut unfold_ranges = Vec::new();
5087 let mut refold_ranges = Vec::new();
5088
5089 let selections = self.selections.all::<Point>(cx);
5090 let mut selections = selections.iter().peekable();
5091 let mut contiguous_row_selections = Vec::new();
5092 let mut new_selections = Vec::new();
5093
5094 while let Some(selection) = selections.next() {
5095 // Find all the selections that span a contiguous row range
5096 let (start_row, end_row) = consume_contiguous_rows(
5097 &mut contiguous_row_selections,
5098 selection,
5099 &display_map,
5100 &mut selections,
5101 );
5102
5103 // Move the text spanned by the row range to be before the line preceding the row range
5104 if start_row > 0 {
5105 let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
5106 ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
5107 let insertion_point = display_map
5108 .prev_line_boundary(Point::new(start_row - 1, 0))
5109 .0;
5110
5111 // Don't move lines across excerpts
5112 if buffer
5113 .excerpt_boundaries_in_range((
5114 Bound::Excluded(insertion_point),
5115 Bound::Included(range_to_move.end),
5116 ))
5117 .next()
5118 .is_none()
5119 {
5120 let text = buffer
5121 .text_for_range(range_to_move.clone())
5122 .flat_map(|s| s.chars())
5123 .skip(1)
5124 .chain(['\n'])
5125 .collect::<String>();
5126
5127 edits.push((
5128 buffer.anchor_after(range_to_move.start)
5129 ..buffer.anchor_before(range_to_move.end),
5130 String::new(),
5131 ));
5132 let insertion_anchor = buffer.anchor_after(insertion_point);
5133 edits.push((insertion_anchor..insertion_anchor, text));
5134
5135 let row_delta = range_to_move.start.row - insertion_point.row + 1;
5136
5137 // Move selections up
5138 new_selections.extend(contiguous_row_selections.drain(..).map(
5139 |mut selection| {
5140 selection.start.row -= row_delta;
5141 selection.end.row -= row_delta;
5142 selection
5143 },
5144 ));
5145
5146 // Move folds up
5147 unfold_ranges.push(range_to_move.clone());
5148 for fold in display_map.folds_in_range(
5149 buffer.anchor_before(range_to_move.start)
5150 ..buffer.anchor_after(range_to_move.end),
5151 ) {
5152 let mut start = fold.range.start.to_point(&buffer);
5153 let mut end = fold.range.end.to_point(&buffer);
5154 start.row -= row_delta;
5155 end.row -= row_delta;
5156 refold_ranges.push(start..end);
5157 }
5158 }
5159 }
5160
5161 // If we didn't move line(s), preserve the existing selections
5162 new_selections.append(&mut contiguous_row_selections);
5163 }
5164
5165 self.transact(cx, |this, cx| {
5166 this.unfold_ranges(unfold_ranges, true, true, cx);
5167 this.buffer.update(cx, |buffer, cx| {
5168 for (range, text) in edits {
5169 buffer.edit([(range, text)], None, cx);
5170 }
5171 });
5172 this.fold_ranges(refold_ranges, true, cx);
5173 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5174 s.select(new_selections);
5175 })
5176 });
5177 }
5178
5179 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5180 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5181 let buffer = self.buffer.read(cx).snapshot(cx);
5182
5183 let mut edits = Vec::new();
5184 let mut unfold_ranges = Vec::new();
5185 let mut refold_ranges = Vec::new();
5186
5187 let selections = self.selections.all::<Point>(cx);
5188 let mut selections = selections.iter().peekable();
5189 let mut contiguous_row_selections = Vec::new();
5190 let mut new_selections = Vec::new();
5191
5192 while let Some(selection) = selections.next() {
5193 // Find all the selections that span a contiguous row range
5194 let (start_row, end_row) = consume_contiguous_rows(
5195 &mut contiguous_row_selections,
5196 selection,
5197 &display_map,
5198 &mut selections,
5199 );
5200
5201 // Move the text spanned by the row range to be after the last line of the row range
5202 if end_row <= buffer.max_point().row {
5203 let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
5204 let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
5205
5206 // Don't move lines across excerpt boundaries
5207 if buffer
5208 .excerpt_boundaries_in_range((
5209 Bound::Excluded(range_to_move.start),
5210 Bound::Included(insertion_point),
5211 ))
5212 .next()
5213 .is_none()
5214 {
5215 let mut text = String::from("\n");
5216 text.extend(buffer.text_for_range(range_to_move.clone()));
5217 text.pop(); // Drop trailing newline
5218 edits.push((
5219 buffer.anchor_after(range_to_move.start)
5220 ..buffer.anchor_before(range_to_move.end),
5221 String::new(),
5222 ));
5223 let insertion_anchor = buffer.anchor_after(insertion_point);
5224 edits.push((insertion_anchor..insertion_anchor, text));
5225
5226 let row_delta = insertion_point.row - range_to_move.end.row + 1;
5227
5228 // Move selections down
5229 new_selections.extend(contiguous_row_selections.drain(..).map(
5230 |mut selection| {
5231 selection.start.row += row_delta;
5232 selection.end.row += row_delta;
5233 selection
5234 },
5235 ));
5236
5237 // Move folds down
5238 unfold_ranges.push(range_to_move.clone());
5239 for fold in display_map.folds_in_range(
5240 buffer.anchor_before(range_to_move.start)
5241 ..buffer.anchor_after(range_to_move.end),
5242 ) {
5243 let mut start = fold.range.start.to_point(&buffer);
5244 let mut end = fold.range.end.to_point(&buffer);
5245 start.row += row_delta;
5246 end.row += row_delta;
5247 refold_ranges.push(start..end);
5248 }
5249 }
5250 }
5251
5252 // If we didn't move line(s), preserve the existing selections
5253 new_selections.append(&mut contiguous_row_selections);
5254 }
5255
5256 self.transact(cx, |this, cx| {
5257 this.unfold_ranges(unfold_ranges, true, true, cx);
5258 this.buffer.update(cx, |buffer, cx| {
5259 for (range, text) in edits {
5260 buffer.edit([(range, text)], None, cx);
5261 }
5262 });
5263 this.fold_ranges(refold_ranges, true, cx);
5264 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
5265 });
5266 }
5267
5268 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
5269 let text_layout_details = &self.text_layout_details(cx);
5270 self.transact(cx, |this, cx| {
5271 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5272 let mut edits: Vec<(Range<usize>, String)> = Default::default();
5273 let line_mode = s.line_mode;
5274 s.move_with(|display_map, selection| {
5275 if !selection.is_empty() || line_mode {
5276 return;
5277 }
5278
5279 let mut head = selection.head();
5280 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
5281 if head.column() == display_map.line_len(head.row()) {
5282 transpose_offset = display_map
5283 .buffer_snapshot
5284 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5285 }
5286
5287 if transpose_offset == 0 {
5288 return;
5289 }
5290
5291 *head.column_mut() += 1;
5292 head = display_map.clip_point(head, Bias::Right);
5293 let goal = SelectionGoal::HorizontalPosition(
5294 display_map
5295 .x_for_display_point(head, &text_layout_details)
5296 .into(),
5297 );
5298 selection.collapse_to(head, goal);
5299
5300 let transpose_start = display_map
5301 .buffer_snapshot
5302 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5303 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
5304 let transpose_end = display_map
5305 .buffer_snapshot
5306 .clip_offset(transpose_offset + 1, Bias::Right);
5307 if let Some(ch) =
5308 display_map.buffer_snapshot.chars_at(transpose_start).next()
5309 {
5310 edits.push((transpose_start..transpose_offset, String::new()));
5311 edits.push((transpose_end..transpose_end, ch.to_string()));
5312 }
5313 }
5314 });
5315 edits
5316 });
5317 this.buffer
5318 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
5319 let selections = this.selections.all::<usize>(cx);
5320 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5321 s.select(selections);
5322 });
5323 });
5324 }
5325
5326 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
5327 let mut text = String::new();
5328 let buffer = self.buffer.read(cx).snapshot(cx);
5329 let mut selections = self.selections.all::<Point>(cx);
5330 let mut clipboard_selections = Vec::with_capacity(selections.len());
5331 {
5332 let max_point = buffer.max_point();
5333 let mut is_first = true;
5334 for selection in &mut selections {
5335 let is_entire_line = selection.is_empty() || self.selections.line_mode;
5336 if is_entire_line {
5337 selection.start = Point::new(selection.start.row, 0);
5338 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
5339 selection.goal = SelectionGoal::None;
5340 }
5341 if is_first {
5342 is_first = false;
5343 } else {
5344 text += "\n";
5345 }
5346 let mut len = 0;
5347 for chunk in buffer.text_for_range(selection.start..selection.end) {
5348 text.push_str(chunk);
5349 len += chunk.len();
5350 }
5351 clipboard_selections.push(ClipboardSelection {
5352 len,
5353 is_entire_line,
5354 first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
5355 });
5356 }
5357 }
5358
5359 self.transact(cx, |this, cx| {
5360 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5361 s.select(selections);
5362 });
5363 this.insert("", cx);
5364 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5365 });
5366 }
5367
5368 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
5369 let selections = self.selections.all::<Point>(cx);
5370 let buffer = self.buffer.read(cx).read(cx);
5371 let mut text = String::new();
5372
5373 let mut clipboard_selections = Vec::with_capacity(selections.len());
5374 {
5375 let max_point = buffer.max_point();
5376 let mut is_first = true;
5377 for selection in selections.iter() {
5378 let mut start = selection.start;
5379 let mut end = selection.end;
5380 let is_entire_line = selection.is_empty() || self.selections.line_mode;
5381 if is_entire_line {
5382 start = Point::new(start.row, 0);
5383 end = cmp::min(max_point, Point::new(end.row + 1, 0));
5384 }
5385 if is_first {
5386 is_first = false;
5387 } else {
5388 text += "\n";
5389 }
5390 let mut len = 0;
5391 for chunk in buffer.text_for_range(start..end) {
5392 text.push_str(chunk);
5393 len += chunk.len();
5394 }
5395 clipboard_selections.push(ClipboardSelection {
5396 len,
5397 is_entire_line,
5398 first_line_indent: buffer.indent_size_for_line(start.row).len,
5399 });
5400 }
5401 }
5402
5403 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5404 }
5405
5406 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
5407 if self.read_only(cx) {
5408 return;
5409 }
5410
5411 self.transact(cx, |this, cx| {
5412 if let Some(item) = cx.read_from_clipboard() {
5413 let clipboard_text = Cow::Borrowed(item.text());
5414 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
5415 let old_selections = this.selections.all::<usize>(cx);
5416 let all_selections_were_entire_line =
5417 clipboard_selections.iter().all(|s| s.is_entire_line);
5418 let first_selection_indent_column =
5419 clipboard_selections.first().map(|s| s.first_line_indent);
5420 if clipboard_selections.len() != old_selections.len() {
5421 clipboard_selections.drain(..);
5422 }
5423
5424 this.buffer.update(cx, |buffer, cx| {
5425 let snapshot = buffer.read(cx);
5426 let mut start_offset = 0;
5427 let mut edits = Vec::new();
5428 let mut original_indent_columns = Vec::new();
5429 let line_mode = this.selections.line_mode;
5430 for (ix, selection) in old_selections.iter().enumerate() {
5431 let to_insert;
5432 let entire_line;
5433 let original_indent_column;
5434 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
5435 let end_offset = start_offset + clipboard_selection.len;
5436 to_insert = &clipboard_text[start_offset..end_offset];
5437 entire_line = clipboard_selection.is_entire_line;
5438 start_offset = end_offset + 1;
5439 original_indent_column =
5440 Some(clipboard_selection.first_line_indent);
5441 } else {
5442 to_insert = clipboard_text.as_str();
5443 entire_line = all_selections_were_entire_line;
5444 original_indent_column = first_selection_indent_column
5445 }
5446
5447 // If the corresponding selection was empty when this slice of the
5448 // clipboard text was written, then the entire line containing the
5449 // selection was copied. If this selection is also currently empty,
5450 // then paste the line before the current line of the buffer.
5451 let range = if selection.is_empty() && !line_mode && entire_line {
5452 let column = selection.start.to_point(&snapshot).column as usize;
5453 let line_start = selection.start - column;
5454 line_start..line_start
5455 } else {
5456 selection.range()
5457 };
5458
5459 edits.push((range, to_insert));
5460 original_indent_columns.extend(original_indent_column);
5461 }
5462 drop(snapshot);
5463
5464 buffer.edit(
5465 edits,
5466 Some(AutoindentMode::Block {
5467 original_indent_columns,
5468 }),
5469 cx,
5470 );
5471 });
5472
5473 let selections = this.selections.all::<usize>(cx);
5474 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5475 } else {
5476 this.insert(&clipboard_text, cx);
5477 }
5478 }
5479 });
5480 }
5481
5482 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
5483 if self.read_only(cx) {
5484 return;
5485 }
5486
5487 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
5488 if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
5489 self.change_selections(None, cx, |s| {
5490 s.select_anchors(selections.to_vec());
5491 });
5492 }
5493 self.request_autoscroll(Autoscroll::fit(), cx);
5494 self.unmark_text(cx);
5495 self.refresh_copilot_suggestions(true, cx);
5496 cx.emit(EditorEvent::Edited);
5497 }
5498 }
5499
5500 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
5501 if self.read_only(cx) {
5502 return;
5503 }
5504
5505 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
5506 if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
5507 {
5508 self.change_selections(None, cx, |s| {
5509 s.select_anchors(selections.to_vec());
5510 });
5511 }
5512 self.request_autoscroll(Autoscroll::fit(), cx);
5513 self.unmark_text(cx);
5514 self.refresh_copilot_suggestions(true, cx);
5515 cx.emit(EditorEvent::Edited);
5516 }
5517 }
5518
5519 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
5520 self.buffer
5521 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
5522 }
5523
5524 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
5525 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5526 let line_mode = s.line_mode;
5527 s.move_with(|map, selection| {
5528 let cursor = if selection.is_empty() && !line_mode {
5529 movement::left(map, selection.start)
5530 } else {
5531 selection.start
5532 };
5533 selection.collapse_to(cursor, SelectionGoal::None);
5534 });
5535 })
5536 }
5537
5538 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
5539 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5540 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
5541 })
5542 }
5543
5544 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
5545 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5546 let line_mode = s.line_mode;
5547 s.move_with(|map, selection| {
5548 let cursor = if selection.is_empty() && !line_mode {
5549 movement::right(map, selection.end)
5550 } else {
5551 selection.end
5552 };
5553 selection.collapse_to(cursor, SelectionGoal::None)
5554 });
5555 })
5556 }
5557
5558 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
5559 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5560 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
5561 })
5562 }
5563
5564 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
5565 if self.take_rename(true, cx).is_some() {
5566 return;
5567 }
5568
5569 if matches!(self.mode, EditorMode::SingleLine) {
5570 cx.propagate();
5571 return;
5572 }
5573
5574 let text_layout_details = &self.text_layout_details(cx);
5575
5576 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5577 let line_mode = s.line_mode;
5578 s.move_with(|map, selection| {
5579 if !selection.is_empty() && !line_mode {
5580 selection.goal = SelectionGoal::None;
5581 }
5582 let (cursor, goal) = movement::up(
5583 map,
5584 selection.start,
5585 selection.goal,
5586 false,
5587 &text_layout_details,
5588 );
5589 selection.collapse_to(cursor, goal);
5590 });
5591 })
5592 }
5593
5594 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
5595 if self.take_rename(true, cx).is_some() {
5596 return;
5597 }
5598
5599 if matches!(self.mode, EditorMode::SingleLine) {
5600 cx.propagate();
5601 return;
5602 }
5603
5604 let text_layout_details = &self.text_layout_details(cx);
5605
5606 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5607 let line_mode = s.line_mode;
5608 s.move_with(|map, selection| {
5609 if !selection.is_empty() && !line_mode {
5610 selection.goal = SelectionGoal::None;
5611 }
5612 let (cursor, goal) = movement::up_by_rows(
5613 map,
5614 selection.start,
5615 action.lines,
5616 selection.goal,
5617 false,
5618 &text_layout_details,
5619 );
5620 selection.collapse_to(cursor, goal);
5621 });
5622 })
5623 }
5624
5625 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
5626 if self.take_rename(true, cx).is_some() {
5627 return;
5628 }
5629
5630 if matches!(self.mode, EditorMode::SingleLine) {
5631 cx.propagate();
5632 return;
5633 }
5634
5635 let text_layout_details = &self.text_layout_details(cx);
5636
5637 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5638 let line_mode = s.line_mode;
5639 s.move_with(|map, selection| {
5640 if !selection.is_empty() && !line_mode {
5641 selection.goal = SelectionGoal::None;
5642 }
5643 let (cursor, goal) = movement::down_by_rows(
5644 map,
5645 selection.start,
5646 action.lines,
5647 selection.goal,
5648 false,
5649 &text_layout_details,
5650 );
5651 selection.collapse_to(cursor, goal);
5652 });
5653 })
5654 }
5655
5656 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
5657 let text_layout_details = &self.text_layout_details(cx);
5658 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5659 s.move_heads_with(|map, head, goal| {
5660 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
5661 })
5662 })
5663 }
5664
5665 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
5666 let text_layout_details = &self.text_layout_details(cx);
5667 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5668 s.move_heads_with(|map, head, goal| {
5669 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
5670 })
5671 })
5672 }
5673
5674 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
5675 if self.take_rename(true, cx).is_some() {
5676 return;
5677 }
5678
5679 if matches!(self.mode, EditorMode::SingleLine) {
5680 cx.propagate();
5681 return;
5682 }
5683
5684 let row_count = if let Some(row_count) = self.visible_line_count() {
5685 row_count as u32 - 1
5686 } else {
5687 return;
5688 };
5689
5690 let autoscroll = if action.center_cursor {
5691 Autoscroll::center()
5692 } else {
5693 Autoscroll::fit()
5694 };
5695
5696 let text_layout_details = &self.text_layout_details(cx);
5697
5698 self.change_selections(Some(autoscroll), cx, |s| {
5699 let line_mode = s.line_mode;
5700 s.move_with(|map, selection| {
5701 if !selection.is_empty() && !line_mode {
5702 selection.goal = SelectionGoal::None;
5703 }
5704 let (cursor, goal) = movement::up_by_rows(
5705 map,
5706 selection.end,
5707 row_count,
5708 selection.goal,
5709 false,
5710 &text_layout_details,
5711 );
5712 selection.collapse_to(cursor, goal);
5713 });
5714 });
5715 }
5716
5717 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
5718 let text_layout_details = &self.text_layout_details(cx);
5719 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5720 s.move_heads_with(|map, head, goal| {
5721 movement::up(map, head, goal, false, &text_layout_details)
5722 })
5723 })
5724 }
5725
5726 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
5727 self.take_rename(true, cx);
5728
5729 if self.mode == EditorMode::SingleLine {
5730 cx.propagate();
5731 return;
5732 }
5733
5734 let text_layout_details = &self.text_layout_details(cx);
5735 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5736 let line_mode = s.line_mode;
5737 s.move_with(|map, selection| {
5738 if !selection.is_empty() && !line_mode {
5739 selection.goal = SelectionGoal::None;
5740 }
5741 let (cursor, goal) = movement::down(
5742 map,
5743 selection.end,
5744 selection.goal,
5745 false,
5746 &text_layout_details,
5747 );
5748 selection.collapse_to(cursor, goal);
5749 });
5750 });
5751 }
5752
5753 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
5754 if self.take_rename(true, cx).is_some() {
5755 return;
5756 }
5757
5758 if self
5759 .context_menu
5760 .write()
5761 .as_mut()
5762 .map(|menu| menu.select_last(self.project.as_ref(), cx))
5763 .unwrap_or(false)
5764 {
5765 return;
5766 }
5767
5768 if matches!(self.mode, EditorMode::SingleLine) {
5769 cx.propagate();
5770 return;
5771 }
5772
5773 let row_count = if let Some(row_count) = self.visible_line_count() {
5774 row_count as u32 - 1
5775 } else {
5776 return;
5777 };
5778
5779 let autoscroll = if action.center_cursor {
5780 Autoscroll::center()
5781 } else {
5782 Autoscroll::fit()
5783 };
5784
5785 let text_layout_details = &self.text_layout_details(cx);
5786 self.change_selections(Some(autoscroll), cx, |s| {
5787 let line_mode = s.line_mode;
5788 s.move_with(|map, selection| {
5789 if !selection.is_empty() && !line_mode {
5790 selection.goal = SelectionGoal::None;
5791 }
5792 let (cursor, goal) = movement::down_by_rows(
5793 map,
5794 selection.end,
5795 row_count,
5796 selection.goal,
5797 false,
5798 &text_layout_details,
5799 );
5800 selection.collapse_to(cursor, goal);
5801 });
5802 });
5803 }
5804
5805 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
5806 let text_layout_details = &self.text_layout_details(cx);
5807 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5808 s.move_heads_with(|map, head, goal| {
5809 movement::down(map, head, goal, false, &text_layout_details)
5810 })
5811 });
5812 }
5813
5814 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
5815 if let Some(context_menu) = self.context_menu.write().as_mut() {
5816 context_menu.select_first(self.project.as_ref(), cx);
5817 }
5818 }
5819
5820 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
5821 if let Some(context_menu) = self.context_menu.write().as_mut() {
5822 context_menu.select_prev(self.project.as_ref(), cx);
5823 }
5824 }
5825
5826 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
5827 if let Some(context_menu) = self.context_menu.write().as_mut() {
5828 context_menu.select_next(self.project.as_ref(), cx);
5829 }
5830 }
5831
5832 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
5833 if let Some(context_menu) = self.context_menu.write().as_mut() {
5834 context_menu.select_last(self.project.as_ref(), cx);
5835 }
5836 }
5837
5838 pub fn move_to_previous_word_start(
5839 &mut self,
5840 _: &MoveToPreviousWordStart,
5841 cx: &mut ViewContext<Self>,
5842 ) {
5843 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5844 s.move_cursors_with(|map, head, _| {
5845 (
5846 movement::previous_word_start(map, head),
5847 SelectionGoal::None,
5848 )
5849 });
5850 })
5851 }
5852
5853 pub fn move_to_previous_subword_start(
5854 &mut self,
5855 _: &MoveToPreviousSubwordStart,
5856 cx: &mut ViewContext<Self>,
5857 ) {
5858 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5859 s.move_cursors_with(|map, head, _| {
5860 (
5861 movement::previous_subword_start(map, head),
5862 SelectionGoal::None,
5863 )
5864 });
5865 })
5866 }
5867
5868 pub fn select_to_previous_word_start(
5869 &mut self,
5870 _: &SelectToPreviousWordStart,
5871 cx: &mut ViewContext<Self>,
5872 ) {
5873 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5874 s.move_heads_with(|map, head, _| {
5875 (
5876 movement::previous_word_start(map, head),
5877 SelectionGoal::None,
5878 )
5879 });
5880 })
5881 }
5882
5883 pub fn select_to_previous_subword_start(
5884 &mut self,
5885 _: &SelectToPreviousSubwordStart,
5886 cx: &mut ViewContext<Self>,
5887 ) {
5888 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5889 s.move_heads_with(|map, head, _| {
5890 (
5891 movement::previous_subword_start(map, head),
5892 SelectionGoal::None,
5893 )
5894 });
5895 })
5896 }
5897
5898 pub fn delete_to_previous_word_start(
5899 &mut self,
5900 _: &DeleteToPreviousWordStart,
5901 cx: &mut ViewContext<Self>,
5902 ) {
5903 self.transact(cx, |this, cx| {
5904 this.select_autoclose_pair(cx);
5905 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5906 let line_mode = s.line_mode;
5907 s.move_with(|map, selection| {
5908 if selection.is_empty() && !line_mode {
5909 let cursor = movement::previous_word_start(map, selection.head());
5910 selection.set_head(cursor, SelectionGoal::None);
5911 }
5912 });
5913 });
5914 this.insert("", cx);
5915 });
5916 }
5917
5918 pub fn delete_to_previous_subword_start(
5919 &mut self,
5920 _: &DeleteToPreviousSubwordStart,
5921 cx: &mut ViewContext<Self>,
5922 ) {
5923 self.transact(cx, |this, cx| {
5924 this.select_autoclose_pair(cx);
5925 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5926 let line_mode = s.line_mode;
5927 s.move_with(|map, selection| {
5928 if selection.is_empty() && !line_mode {
5929 let cursor = movement::previous_subword_start(map, selection.head());
5930 selection.set_head(cursor, SelectionGoal::None);
5931 }
5932 });
5933 });
5934 this.insert("", cx);
5935 });
5936 }
5937
5938 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
5939 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5940 s.move_cursors_with(|map, head, _| {
5941 (movement::next_word_end(map, head), SelectionGoal::None)
5942 });
5943 })
5944 }
5945
5946 pub fn move_to_next_subword_end(
5947 &mut self,
5948 _: &MoveToNextSubwordEnd,
5949 cx: &mut ViewContext<Self>,
5950 ) {
5951 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5952 s.move_cursors_with(|map, head, _| {
5953 (movement::next_subword_end(map, head), SelectionGoal::None)
5954 });
5955 })
5956 }
5957
5958 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
5959 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5960 s.move_heads_with(|map, head, _| {
5961 (movement::next_word_end(map, head), SelectionGoal::None)
5962 });
5963 })
5964 }
5965
5966 pub fn select_to_next_subword_end(
5967 &mut self,
5968 _: &SelectToNextSubwordEnd,
5969 cx: &mut ViewContext<Self>,
5970 ) {
5971 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5972 s.move_heads_with(|map, head, _| {
5973 (movement::next_subword_end(map, head), SelectionGoal::None)
5974 });
5975 })
5976 }
5977
5978 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
5979 self.transact(cx, |this, cx| {
5980 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5981 let line_mode = s.line_mode;
5982 s.move_with(|map, selection| {
5983 if selection.is_empty() && !line_mode {
5984 let cursor = movement::next_word_end(map, selection.head());
5985 selection.set_head(cursor, SelectionGoal::None);
5986 }
5987 });
5988 });
5989 this.insert("", cx);
5990 });
5991 }
5992
5993 pub fn delete_to_next_subword_end(
5994 &mut self,
5995 _: &DeleteToNextSubwordEnd,
5996 cx: &mut ViewContext<Self>,
5997 ) {
5998 self.transact(cx, |this, cx| {
5999 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6000 s.move_with(|map, selection| {
6001 if selection.is_empty() {
6002 let cursor = movement::next_subword_end(map, selection.head());
6003 selection.set_head(cursor, SelectionGoal::None);
6004 }
6005 });
6006 });
6007 this.insert("", cx);
6008 });
6009 }
6010
6011 pub fn move_to_beginning_of_line(
6012 &mut self,
6013 _: &MoveToBeginningOfLine,
6014 cx: &mut ViewContext<Self>,
6015 ) {
6016 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6017 s.move_cursors_with(|map, head, _| {
6018 (
6019 movement::indented_line_beginning(map, head, true),
6020 SelectionGoal::None,
6021 )
6022 });
6023 })
6024 }
6025
6026 pub fn select_to_beginning_of_line(
6027 &mut self,
6028 action: &SelectToBeginningOfLine,
6029 cx: &mut ViewContext<Self>,
6030 ) {
6031 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6032 s.move_heads_with(|map, head, _| {
6033 (
6034 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6035 SelectionGoal::None,
6036 )
6037 });
6038 });
6039 }
6040
6041 pub fn delete_to_beginning_of_line(
6042 &mut self,
6043 _: &DeleteToBeginningOfLine,
6044 cx: &mut ViewContext<Self>,
6045 ) {
6046 self.transact(cx, |this, cx| {
6047 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6048 s.move_with(|_, selection| {
6049 selection.reversed = true;
6050 });
6051 });
6052
6053 this.select_to_beginning_of_line(
6054 &SelectToBeginningOfLine {
6055 stop_at_soft_wraps: false,
6056 },
6057 cx,
6058 );
6059 this.backspace(&Backspace, cx);
6060 });
6061 }
6062
6063 pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
6064 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6065 s.move_cursors_with(|map, head, _| {
6066 (movement::line_end(map, head, true), SelectionGoal::None)
6067 });
6068 })
6069 }
6070
6071 pub fn select_to_end_of_line(
6072 &mut self,
6073 action: &SelectToEndOfLine,
6074 cx: &mut ViewContext<Self>,
6075 ) {
6076 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6077 s.move_heads_with(|map, head, _| {
6078 (
6079 movement::line_end(map, head, action.stop_at_soft_wraps),
6080 SelectionGoal::None,
6081 )
6082 });
6083 })
6084 }
6085
6086 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
6087 self.transact(cx, |this, cx| {
6088 this.select_to_end_of_line(
6089 &SelectToEndOfLine {
6090 stop_at_soft_wraps: false,
6091 },
6092 cx,
6093 );
6094 this.delete(&Delete, cx);
6095 });
6096 }
6097
6098 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
6099 self.transact(cx, |this, cx| {
6100 this.select_to_end_of_line(
6101 &SelectToEndOfLine {
6102 stop_at_soft_wraps: false,
6103 },
6104 cx,
6105 );
6106 this.cut(&Cut, cx);
6107 });
6108 }
6109
6110 pub fn move_to_start_of_paragraph(
6111 &mut self,
6112 _: &MoveToStartOfParagraph,
6113 cx: &mut ViewContext<Self>,
6114 ) {
6115 if matches!(self.mode, EditorMode::SingleLine) {
6116 cx.propagate();
6117 return;
6118 }
6119
6120 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6121 s.move_with(|map, selection| {
6122 selection.collapse_to(
6123 movement::start_of_paragraph(map, selection.head(), 1),
6124 SelectionGoal::None,
6125 )
6126 });
6127 })
6128 }
6129
6130 pub fn move_to_end_of_paragraph(
6131 &mut self,
6132 _: &MoveToEndOfParagraph,
6133 cx: &mut ViewContext<Self>,
6134 ) {
6135 if matches!(self.mode, EditorMode::SingleLine) {
6136 cx.propagate();
6137 return;
6138 }
6139
6140 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6141 s.move_with(|map, selection| {
6142 selection.collapse_to(
6143 movement::end_of_paragraph(map, selection.head(), 1),
6144 SelectionGoal::None,
6145 )
6146 });
6147 })
6148 }
6149
6150 pub fn select_to_start_of_paragraph(
6151 &mut self,
6152 _: &SelectToStartOfParagraph,
6153 cx: &mut ViewContext<Self>,
6154 ) {
6155 if matches!(self.mode, EditorMode::SingleLine) {
6156 cx.propagate();
6157 return;
6158 }
6159
6160 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6161 s.move_heads_with(|map, head, _| {
6162 (
6163 movement::start_of_paragraph(map, head, 1),
6164 SelectionGoal::None,
6165 )
6166 });
6167 })
6168 }
6169
6170 pub fn select_to_end_of_paragraph(
6171 &mut self,
6172 _: &SelectToEndOfParagraph,
6173 cx: &mut ViewContext<Self>,
6174 ) {
6175 if matches!(self.mode, EditorMode::SingleLine) {
6176 cx.propagate();
6177 return;
6178 }
6179
6180 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6181 s.move_heads_with(|map, head, _| {
6182 (
6183 movement::end_of_paragraph(map, head, 1),
6184 SelectionGoal::None,
6185 )
6186 });
6187 })
6188 }
6189
6190 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
6191 if matches!(self.mode, EditorMode::SingleLine) {
6192 cx.propagate();
6193 return;
6194 }
6195
6196 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6197 s.select_ranges(vec![0..0]);
6198 });
6199 }
6200
6201 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
6202 let mut selection = self.selections.last::<Point>(cx);
6203 selection.set_head(Point::zero(), SelectionGoal::None);
6204
6205 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6206 s.select(vec![selection]);
6207 });
6208 }
6209
6210 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
6211 if matches!(self.mode, EditorMode::SingleLine) {
6212 cx.propagate();
6213 return;
6214 }
6215
6216 let cursor = self.buffer.read(cx).read(cx).len();
6217 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6218 s.select_ranges(vec![cursor..cursor])
6219 });
6220 }
6221
6222 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
6223 self.nav_history = nav_history;
6224 }
6225
6226 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
6227 self.nav_history.as_ref()
6228 }
6229
6230 fn push_to_nav_history(
6231 &mut self,
6232 cursor_anchor: Anchor,
6233 new_position: Option<Point>,
6234 cx: &mut ViewContext<Self>,
6235 ) {
6236 if let Some(nav_history) = self.nav_history.as_mut() {
6237 let buffer = self.buffer.read(cx).read(cx);
6238 let cursor_position = cursor_anchor.to_point(&buffer);
6239 let scroll_state = self.scroll_manager.anchor();
6240 let scroll_top_row = scroll_state.top_row(&buffer);
6241 drop(buffer);
6242
6243 if let Some(new_position) = new_position {
6244 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
6245 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
6246 return;
6247 }
6248 }
6249
6250 nav_history.push(
6251 Some(NavigationData {
6252 cursor_anchor,
6253 cursor_position,
6254 scroll_anchor: scroll_state,
6255 scroll_top_row,
6256 }),
6257 cx,
6258 );
6259 }
6260 }
6261
6262 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
6263 let buffer = self.buffer.read(cx).snapshot(cx);
6264 let mut selection = self.selections.first::<usize>(cx);
6265 selection.set_head(buffer.len(), SelectionGoal::None);
6266 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6267 s.select(vec![selection]);
6268 });
6269 }
6270
6271 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
6272 let end = self.buffer.read(cx).read(cx).len();
6273 self.change_selections(None, cx, |s| {
6274 s.select_ranges(vec![0..end]);
6275 });
6276 }
6277
6278 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
6279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6280 let mut selections = self.selections.all::<Point>(cx);
6281 let max_point = display_map.buffer_snapshot.max_point();
6282 for selection in &mut selections {
6283 let rows = selection.spanned_rows(true, &display_map);
6284 selection.start = Point::new(rows.start, 0);
6285 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
6286 selection.reversed = false;
6287 }
6288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6289 s.select(selections);
6290 });
6291 }
6292
6293 pub fn split_selection_into_lines(
6294 &mut self,
6295 _: &SplitSelectionIntoLines,
6296 cx: &mut ViewContext<Self>,
6297 ) {
6298 let mut to_unfold = Vec::new();
6299 let mut new_selection_ranges = Vec::new();
6300 {
6301 let selections = self.selections.all::<Point>(cx);
6302 let buffer = self.buffer.read(cx).read(cx);
6303 for selection in selections {
6304 for row in selection.start.row..selection.end.row {
6305 let cursor = Point::new(row, buffer.line_len(row));
6306 new_selection_ranges.push(cursor..cursor);
6307 }
6308 new_selection_ranges.push(selection.end..selection.end);
6309 to_unfold.push(selection.start..selection.end);
6310 }
6311 }
6312 self.unfold_ranges(to_unfold, true, true, cx);
6313 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6314 s.select_ranges(new_selection_ranges);
6315 });
6316 }
6317
6318 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
6319 self.add_selection(true, cx);
6320 }
6321
6322 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
6323 self.add_selection(false, cx);
6324 }
6325
6326 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
6327 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6328 let mut selections = self.selections.all::<Point>(cx);
6329 let text_layout_details = self.text_layout_details(cx);
6330 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
6331 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
6332 let range = oldest_selection.display_range(&display_map).sorted();
6333
6334 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
6335 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
6336 let positions = start_x.min(end_x)..start_x.max(end_x);
6337
6338 selections.clear();
6339 let mut stack = Vec::new();
6340 for row in range.start.row()..=range.end.row() {
6341 if let Some(selection) = self.selections.build_columnar_selection(
6342 &display_map,
6343 row,
6344 &positions,
6345 oldest_selection.reversed,
6346 &text_layout_details,
6347 ) {
6348 stack.push(selection.id);
6349 selections.push(selection);
6350 }
6351 }
6352
6353 if above {
6354 stack.reverse();
6355 }
6356
6357 AddSelectionsState { above, stack }
6358 });
6359
6360 let last_added_selection = *state.stack.last().unwrap();
6361 let mut new_selections = Vec::new();
6362 if above == state.above {
6363 let end_row = if above {
6364 0
6365 } else {
6366 display_map.max_point().row()
6367 };
6368
6369 'outer: for selection in selections {
6370 if selection.id == last_added_selection {
6371 let range = selection.display_range(&display_map).sorted();
6372 debug_assert_eq!(range.start.row(), range.end.row());
6373 let mut row = range.start.row();
6374 let positions =
6375 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
6376 px(start)..px(end)
6377 } else {
6378 let start_x =
6379 display_map.x_for_display_point(range.start, &text_layout_details);
6380 let end_x =
6381 display_map.x_for_display_point(range.end, &text_layout_details);
6382 start_x.min(end_x)..start_x.max(end_x)
6383 };
6384
6385 while row != end_row {
6386 if above {
6387 row -= 1;
6388 } else {
6389 row += 1;
6390 }
6391
6392 if let Some(new_selection) = self.selections.build_columnar_selection(
6393 &display_map,
6394 row,
6395 &positions,
6396 selection.reversed,
6397 &text_layout_details,
6398 ) {
6399 state.stack.push(new_selection.id);
6400 if above {
6401 new_selections.push(new_selection);
6402 new_selections.push(selection);
6403 } else {
6404 new_selections.push(selection);
6405 new_selections.push(new_selection);
6406 }
6407
6408 continue 'outer;
6409 }
6410 }
6411 }
6412
6413 new_selections.push(selection);
6414 }
6415 } else {
6416 new_selections = selections;
6417 new_selections.retain(|s| s.id != last_added_selection);
6418 state.stack.pop();
6419 }
6420
6421 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6422 s.select(new_selections);
6423 });
6424 if state.stack.len() > 1 {
6425 self.add_selections_state = Some(state);
6426 }
6427 }
6428
6429 pub fn select_next_match_internal(
6430 &mut self,
6431 display_map: &DisplaySnapshot,
6432 replace_newest: bool,
6433 autoscroll: Option<Autoscroll>,
6434 cx: &mut ViewContext<Self>,
6435 ) -> Result<()> {
6436 fn select_next_match_ranges(
6437 this: &mut Editor,
6438 range: Range<usize>,
6439 replace_newest: bool,
6440 auto_scroll: Option<Autoscroll>,
6441 cx: &mut ViewContext<Editor>,
6442 ) {
6443 this.unfold_ranges([range.clone()], false, true, cx);
6444 this.change_selections(auto_scroll, cx, |s| {
6445 if replace_newest {
6446 s.delete(s.newest_anchor().id);
6447 }
6448 s.insert_range(range.clone());
6449 });
6450 }
6451
6452 let buffer = &display_map.buffer_snapshot;
6453 let mut selections = self.selections.all::<usize>(cx);
6454 if let Some(mut select_next_state) = self.select_next_state.take() {
6455 let query = &select_next_state.query;
6456 if !select_next_state.done {
6457 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6458 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6459 let mut next_selected_range = None;
6460
6461 let bytes_after_last_selection =
6462 buffer.bytes_in_range(last_selection.end..buffer.len());
6463 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
6464 let query_matches = query
6465 .stream_find_iter(bytes_after_last_selection)
6466 .map(|result| (last_selection.end, result))
6467 .chain(
6468 query
6469 .stream_find_iter(bytes_before_first_selection)
6470 .map(|result| (0, result)),
6471 );
6472
6473 for (start_offset, query_match) in query_matches {
6474 let query_match = query_match.unwrap(); // can only fail due to I/O
6475 let offset_range =
6476 start_offset + query_match.start()..start_offset + query_match.end();
6477 let display_range = offset_range.start.to_display_point(&display_map)
6478 ..offset_range.end.to_display_point(&display_map);
6479
6480 if !select_next_state.wordwise
6481 || (!movement::is_inside_word(&display_map, display_range.start)
6482 && !movement::is_inside_word(&display_map, display_range.end))
6483 {
6484 // TODO: This is n^2, because we might check all the selections
6485 if !selections
6486 .iter()
6487 .any(|selection| selection.range().overlaps(&offset_range))
6488 {
6489 next_selected_range = Some(offset_range);
6490 break;
6491 }
6492 }
6493 }
6494
6495 if let Some(next_selected_range) = next_selected_range {
6496 select_next_match_ranges(
6497 self,
6498 next_selected_range,
6499 replace_newest,
6500 autoscroll,
6501 cx,
6502 );
6503 } else {
6504 select_next_state.done = true;
6505 }
6506 }
6507
6508 self.select_next_state = Some(select_next_state);
6509 } else {
6510 let mut only_carets = true;
6511 let mut same_text_selected = true;
6512 let mut selected_text = None;
6513
6514 let mut selections_iter = selections.iter().peekable();
6515 while let Some(selection) = selections_iter.next() {
6516 if selection.start != selection.end {
6517 only_carets = false;
6518 }
6519
6520 if same_text_selected {
6521 if selected_text.is_none() {
6522 selected_text =
6523 Some(buffer.text_for_range(selection.range()).collect::<String>());
6524 }
6525
6526 if let Some(next_selection) = selections_iter.peek() {
6527 if next_selection.range().len() == selection.range().len() {
6528 let next_selected_text = buffer
6529 .text_for_range(next_selection.range())
6530 .collect::<String>();
6531 if Some(next_selected_text) != selected_text {
6532 same_text_selected = false;
6533 selected_text = None;
6534 }
6535 } else {
6536 same_text_selected = false;
6537 selected_text = None;
6538 }
6539 }
6540 }
6541 }
6542
6543 if only_carets {
6544 for selection in &mut selections {
6545 let word_range = movement::surrounding_word(
6546 &display_map,
6547 selection.start.to_display_point(&display_map),
6548 );
6549 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6550 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6551 selection.goal = SelectionGoal::None;
6552 selection.reversed = false;
6553 select_next_match_ranges(
6554 self,
6555 selection.start..selection.end,
6556 replace_newest,
6557 autoscroll,
6558 cx,
6559 );
6560 }
6561
6562 if selections.len() == 1 {
6563 let selection = selections
6564 .last()
6565 .expect("ensured that there's only one selection");
6566 let query = buffer
6567 .text_for_range(selection.start..selection.end)
6568 .collect::<String>();
6569 let is_empty = query.is_empty();
6570 let select_state = SelectNextState {
6571 query: AhoCorasick::new(&[query])?,
6572 wordwise: true,
6573 done: is_empty,
6574 };
6575 self.select_next_state = Some(select_state);
6576 } else {
6577 self.select_next_state = None;
6578 }
6579 } else if let Some(selected_text) = selected_text {
6580 self.select_next_state = Some(SelectNextState {
6581 query: AhoCorasick::new(&[selected_text])?,
6582 wordwise: false,
6583 done: false,
6584 });
6585 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
6586 }
6587 }
6588 Ok(())
6589 }
6590
6591 pub fn select_all_matches(
6592 &mut self,
6593 _action: &SelectAllMatches,
6594 cx: &mut ViewContext<Self>,
6595 ) -> Result<()> {
6596 self.push_to_selection_history();
6597 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6598
6599 self.select_next_match_internal(&display_map, false, None, cx)?;
6600 let Some(select_next_state) = self.select_next_state.as_mut() else {
6601 return Ok(());
6602 };
6603 if select_next_state.done {
6604 return Ok(());
6605 }
6606
6607 let mut new_selections = self.selections.all::<usize>(cx);
6608
6609 let buffer = &display_map.buffer_snapshot;
6610 let query_matches = select_next_state
6611 .query
6612 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
6613
6614 for query_match in query_matches {
6615 let query_match = query_match.unwrap(); // can only fail due to I/O
6616 let offset_range = query_match.start()..query_match.end();
6617 let display_range = offset_range.start.to_display_point(&display_map)
6618 ..offset_range.end.to_display_point(&display_map);
6619
6620 if !select_next_state.wordwise
6621 || (!movement::is_inside_word(&display_map, display_range.start)
6622 && !movement::is_inside_word(&display_map, display_range.end))
6623 {
6624 self.selections.change_with(cx, |selections| {
6625 new_selections.push(Selection {
6626 id: selections.new_selection_id(),
6627 start: offset_range.start,
6628 end: offset_range.end,
6629 reversed: false,
6630 goal: SelectionGoal::None,
6631 });
6632 });
6633 }
6634 }
6635
6636 new_selections.sort_by_key(|selection| selection.start);
6637 let mut ix = 0;
6638 while ix + 1 < new_selections.len() {
6639 let current_selection = &new_selections[ix];
6640 let next_selection = &new_selections[ix + 1];
6641 if current_selection.range().overlaps(&next_selection.range()) {
6642 if current_selection.id < next_selection.id {
6643 new_selections.remove(ix + 1);
6644 } else {
6645 new_selections.remove(ix);
6646 }
6647 } else {
6648 ix += 1;
6649 }
6650 }
6651
6652 select_next_state.done = true;
6653 self.unfold_ranges(
6654 new_selections.iter().map(|selection| selection.range()),
6655 false,
6656 false,
6657 cx,
6658 );
6659 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
6660 selections.select(new_selections)
6661 });
6662
6663 Ok(())
6664 }
6665
6666 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
6667 self.push_to_selection_history();
6668 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6669 self.select_next_match_internal(
6670 &display_map,
6671 action.replace_newest,
6672 Some(Autoscroll::newest()),
6673 cx,
6674 )?;
6675 Ok(())
6676 }
6677
6678 pub fn select_previous(
6679 &mut self,
6680 action: &SelectPrevious,
6681 cx: &mut ViewContext<Self>,
6682 ) -> Result<()> {
6683 self.push_to_selection_history();
6684 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6685 let buffer = &display_map.buffer_snapshot;
6686 let mut selections = self.selections.all::<usize>(cx);
6687 if let Some(mut select_prev_state) = self.select_prev_state.take() {
6688 let query = &select_prev_state.query;
6689 if !select_prev_state.done {
6690 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6691 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6692 let mut next_selected_range = None;
6693 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
6694 let bytes_before_last_selection =
6695 buffer.reversed_bytes_in_range(0..last_selection.start);
6696 let bytes_after_first_selection =
6697 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
6698 let query_matches = query
6699 .stream_find_iter(bytes_before_last_selection)
6700 .map(|result| (last_selection.start, result))
6701 .chain(
6702 query
6703 .stream_find_iter(bytes_after_first_selection)
6704 .map(|result| (buffer.len(), result)),
6705 );
6706 for (end_offset, query_match) in query_matches {
6707 let query_match = query_match.unwrap(); // can only fail due to I/O
6708 let offset_range =
6709 end_offset - query_match.end()..end_offset - query_match.start();
6710 let display_range = offset_range.start.to_display_point(&display_map)
6711 ..offset_range.end.to_display_point(&display_map);
6712
6713 if !select_prev_state.wordwise
6714 || (!movement::is_inside_word(&display_map, display_range.start)
6715 && !movement::is_inside_word(&display_map, display_range.end))
6716 {
6717 next_selected_range = Some(offset_range);
6718 break;
6719 }
6720 }
6721
6722 if let Some(next_selected_range) = next_selected_range {
6723 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
6724 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6725 if action.replace_newest {
6726 s.delete(s.newest_anchor().id);
6727 }
6728 s.insert_range(next_selected_range);
6729 });
6730 } else {
6731 select_prev_state.done = true;
6732 }
6733 }
6734
6735 self.select_prev_state = Some(select_prev_state);
6736 } else {
6737 let mut only_carets = true;
6738 let mut same_text_selected = true;
6739 let mut selected_text = None;
6740
6741 let mut selections_iter = selections.iter().peekable();
6742 while let Some(selection) = selections_iter.next() {
6743 if selection.start != selection.end {
6744 only_carets = false;
6745 }
6746
6747 if same_text_selected {
6748 if selected_text.is_none() {
6749 selected_text =
6750 Some(buffer.text_for_range(selection.range()).collect::<String>());
6751 }
6752
6753 if let Some(next_selection) = selections_iter.peek() {
6754 if next_selection.range().len() == selection.range().len() {
6755 let next_selected_text = buffer
6756 .text_for_range(next_selection.range())
6757 .collect::<String>();
6758 if Some(next_selected_text) != selected_text {
6759 same_text_selected = false;
6760 selected_text = None;
6761 }
6762 } else {
6763 same_text_selected = false;
6764 selected_text = None;
6765 }
6766 }
6767 }
6768 }
6769
6770 if only_carets {
6771 for selection in &mut selections {
6772 let word_range = movement::surrounding_word(
6773 &display_map,
6774 selection.start.to_display_point(&display_map),
6775 );
6776 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6777 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6778 selection.goal = SelectionGoal::None;
6779 selection.reversed = false;
6780 }
6781 if selections.len() == 1 {
6782 let selection = selections
6783 .last()
6784 .expect("ensured that there's only one selection");
6785 let query = buffer
6786 .text_for_range(selection.start..selection.end)
6787 .collect::<String>();
6788 let is_empty = query.is_empty();
6789 let select_state = SelectNextState {
6790 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
6791 wordwise: true,
6792 done: is_empty,
6793 };
6794 self.select_prev_state = Some(select_state);
6795 } else {
6796 self.select_prev_state = None;
6797 }
6798
6799 self.unfold_ranges(
6800 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
6801 false,
6802 true,
6803 cx,
6804 );
6805 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6806 s.select(selections);
6807 });
6808 } else if let Some(selected_text) = selected_text {
6809 self.select_prev_state = Some(SelectNextState {
6810 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
6811 wordwise: false,
6812 done: false,
6813 });
6814 self.select_previous(action, cx)?;
6815 }
6816 }
6817 Ok(())
6818 }
6819
6820 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
6821 let text_layout_details = &self.text_layout_details(cx);
6822 self.transact(cx, |this, cx| {
6823 let mut selections = this.selections.all::<Point>(cx);
6824 let mut edits = Vec::new();
6825 let mut selection_edit_ranges = Vec::new();
6826 let mut last_toggled_row = None;
6827 let snapshot = this.buffer.read(cx).read(cx);
6828 let empty_str: Arc<str> = "".into();
6829 let mut suffixes_inserted = Vec::new();
6830
6831 fn comment_prefix_range(
6832 snapshot: &MultiBufferSnapshot,
6833 row: u32,
6834 comment_prefix: &str,
6835 comment_prefix_whitespace: &str,
6836 ) -> Range<Point> {
6837 let start = Point::new(row, snapshot.indent_size_for_line(row).len);
6838
6839 let mut line_bytes = snapshot
6840 .bytes_in_range(start..snapshot.max_point())
6841 .flatten()
6842 .copied();
6843
6844 // If this line currently begins with the line comment prefix, then record
6845 // the range containing the prefix.
6846 if line_bytes
6847 .by_ref()
6848 .take(comment_prefix.len())
6849 .eq(comment_prefix.bytes())
6850 {
6851 // Include any whitespace that matches the comment prefix.
6852 let matching_whitespace_len = line_bytes
6853 .zip(comment_prefix_whitespace.bytes())
6854 .take_while(|(a, b)| a == b)
6855 .count() as u32;
6856 let end = Point::new(
6857 start.row,
6858 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
6859 );
6860 start..end
6861 } else {
6862 start..start
6863 }
6864 }
6865
6866 fn comment_suffix_range(
6867 snapshot: &MultiBufferSnapshot,
6868 row: u32,
6869 comment_suffix: &str,
6870 comment_suffix_has_leading_space: bool,
6871 ) -> Range<Point> {
6872 let end = Point::new(row, snapshot.line_len(row));
6873 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
6874
6875 let mut line_end_bytes = snapshot
6876 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
6877 .flatten()
6878 .copied();
6879
6880 let leading_space_len = if suffix_start_column > 0
6881 && line_end_bytes.next() == Some(b' ')
6882 && comment_suffix_has_leading_space
6883 {
6884 1
6885 } else {
6886 0
6887 };
6888
6889 // If this line currently begins with the line comment prefix, then record
6890 // the range containing the prefix.
6891 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
6892 let start = Point::new(end.row, suffix_start_column - leading_space_len);
6893 start..end
6894 } else {
6895 end..end
6896 }
6897 }
6898
6899 // TODO: Handle selections that cross excerpts
6900 for selection in &mut selections {
6901 let start_column = snapshot.indent_size_for_line(selection.start.row).len;
6902 let language = if let Some(language) =
6903 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
6904 {
6905 language
6906 } else {
6907 continue;
6908 };
6909
6910 selection_edit_ranges.clear();
6911
6912 // If multiple selections contain a given row, avoid processing that
6913 // row more than once.
6914 let mut start_row = selection.start.row;
6915 if last_toggled_row == Some(start_row) {
6916 start_row += 1;
6917 }
6918 let end_row =
6919 if selection.end.row > selection.start.row && selection.end.column == 0 {
6920 selection.end.row - 1
6921 } else {
6922 selection.end.row
6923 };
6924 last_toggled_row = Some(end_row);
6925
6926 if start_row > end_row {
6927 continue;
6928 }
6929
6930 // If the language has line comments, toggle those.
6931 if let Some(full_comment_prefix) = language
6932 .line_comment_prefixes()
6933 .and_then(|prefixes| prefixes.first())
6934 {
6935 // Split the comment prefix's trailing whitespace into a separate string,
6936 // as that portion won't be used for detecting if a line is a comment.
6937 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6938 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6939 let mut all_selection_lines_are_comments = true;
6940
6941 for row in start_row..=end_row {
6942 if start_row < end_row && snapshot.is_line_blank(row) {
6943 continue;
6944 }
6945
6946 let prefix_range = comment_prefix_range(
6947 snapshot.deref(),
6948 row,
6949 comment_prefix,
6950 comment_prefix_whitespace,
6951 );
6952 if prefix_range.is_empty() {
6953 all_selection_lines_are_comments = false;
6954 }
6955 selection_edit_ranges.push(prefix_range);
6956 }
6957
6958 if all_selection_lines_are_comments {
6959 edits.extend(
6960 selection_edit_ranges
6961 .iter()
6962 .cloned()
6963 .map(|range| (range, empty_str.clone())),
6964 );
6965 } else {
6966 let min_column = selection_edit_ranges
6967 .iter()
6968 .map(|r| r.start.column)
6969 .min()
6970 .unwrap_or(0);
6971 edits.extend(selection_edit_ranges.iter().map(|range| {
6972 let position = Point::new(range.start.row, min_column);
6973 (position..position, full_comment_prefix.clone())
6974 }));
6975 }
6976 } else if let Some((full_comment_prefix, comment_suffix)) =
6977 language.block_comment_delimiters()
6978 {
6979 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6980 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6981 let prefix_range = comment_prefix_range(
6982 snapshot.deref(),
6983 start_row,
6984 comment_prefix,
6985 comment_prefix_whitespace,
6986 );
6987 let suffix_range = comment_suffix_range(
6988 snapshot.deref(),
6989 end_row,
6990 comment_suffix.trim_start_matches(' '),
6991 comment_suffix.starts_with(' '),
6992 );
6993
6994 if prefix_range.is_empty() || suffix_range.is_empty() {
6995 edits.push((
6996 prefix_range.start..prefix_range.start,
6997 full_comment_prefix.clone(),
6998 ));
6999 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
7000 suffixes_inserted.push((end_row, comment_suffix.len()));
7001 } else {
7002 edits.push((prefix_range, empty_str.clone()));
7003 edits.push((suffix_range, empty_str.clone()));
7004 }
7005 } else {
7006 continue;
7007 }
7008 }
7009
7010 drop(snapshot);
7011 this.buffer.update(cx, |buffer, cx| {
7012 buffer.edit(edits, None, cx);
7013 });
7014
7015 // Adjust selections so that they end before any comment suffixes that
7016 // were inserted.
7017 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
7018 let mut selections = this.selections.all::<Point>(cx);
7019 let snapshot = this.buffer.read(cx).read(cx);
7020 for selection in &mut selections {
7021 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
7022 match row.cmp(&selection.end.row) {
7023 Ordering::Less => {
7024 suffixes_inserted.next();
7025 continue;
7026 }
7027 Ordering::Greater => break,
7028 Ordering::Equal => {
7029 if selection.end.column == snapshot.line_len(row) {
7030 if selection.is_empty() {
7031 selection.start.column -= suffix_len as u32;
7032 }
7033 selection.end.column -= suffix_len as u32;
7034 }
7035 break;
7036 }
7037 }
7038 }
7039 }
7040
7041 drop(snapshot);
7042 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7043
7044 let selections = this.selections.all::<Point>(cx);
7045 let selections_on_single_row = selections.windows(2).all(|selections| {
7046 selections[0].start.row == selections[1].start.row
7047 && selections[0].end.row == selections[1].end.row
7048 && selections[0].start.row == selections[0].end.row
7049 });
7050 let selections_selecting = selections
7051 .iter()
7052 .any(|selection| selection.start != selection.end);
7053 let advance_downwards = action.advance_downwards
7054 && selections_on_single_row
7055 && !selections_selecting
7056 && this.mode != EditorMode::SingleLine;
7057
7058 if advance_downwards {
7059 let snapshot = this.buffer.read(cx).snapshot(cx);
7060
7061 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7062 s.move_cursors_with(|display_snapshot, display_point, _| {
7063 let mut point = display_point.to_point(display_snapshot);
7064 point.row += 1;
7065 point = snapshot.clip_point(point, Bias::Left);
7066 let display_point = point.to_display_point(display_snapshot);
7067 let goal = SelectionGoal::HorizontalPosition(
7068 display_snapshot
7069 .x_for_display_point(display_point, &text_layout_details)
7070 .into(),
7071 );
7072 (display_point, goal)
7073 })
7074 });
7075 }
7076 });
7077 }
7078
7079 pub fn select_larger_syntax_node(
7080 &mut self,
7081 _: &SelectLargerSyntaxNode,
7082 cx: &mut ViewContext<Self>,
7083 ) {
7084 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7085 let buffer = self.buffer.read(cx).snapshot(cx);
7086 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
7087
7088 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7089 let mut selected_larger_node = false;
7090 let new_selections = old_selections
7091 .iter()
7092 .map(|selection| {
7093 let old_range = selection.start..selection.end;
7094 let mut new_range = old_range.clone();
7095 while let Some(containing_range) =
7096 buffer.range_for_syntax_ancestor(new_range.clone())
7097 {
7098 new_range = containing_range;
7099 if !display_map.intersects_fold(new_range.start)
7100 && !display_map.intersects_fold(new_range.end)
7101 {
7102 break;
7103 }
7104 }
7105
7106 selected_larger_node |= new_range != old_range;
7107 Selection {
7108 id: selection.id,
7109 start: new_range.start,
7110 end: new_range.end,
7111 goal: SelectionGoal::None,
7112 reversed: selection.reversed,
7113 }
7114 })
7115 .collect::<Vec<_>>();
7116
7117 if selected_larger_node {
7118 stack.push(old_selections);
7119 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7120 s.select(new_selections);
7121 });
7122 }
7123 self.select_larger_syntax_node_stack = stack;
7124 }
7125
7126 pub fn select_smaller_syntax_node(
7127 &mut self,
7128 _: &SelectSmallerSyntaxNode,
7129 cx: &mut ViewContext<Self>,
7130 ) {
7131 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7132 if let Some(selections) = stack.pop() {
7133 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7134 s.select(selections.to_vec());
7135 });
7136 }
7137 self.select_larger_syntax_node_stack = stack;
7138 }
7139
7140 pub fn move_to_enclosing_bracket(
7141 &mut self,
7142 _: &MoveToEnclosingBracket,
7143 cx: &mut ViewContext<Self>,
7144 ) {
7145 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7146 s.move_offsets_with(|snapshot, selection| {
7147 let Some(enclosing_bracket_ranges) =
7148 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
7149 else {
7150 return;
7151 };
7152
7153 let mut best_length = usize::MAX;
7154 let mut best_inside = false;
7155 let mut best_in_bracket_range = false;
7156 let mut best_destination = None;
7157 for (open, close) in enclosing_bracket_ranges {
7158 let close = close.to_inclusive();
7159 let length = close.end() - open.start;
7160 let inside = selection.start >= open.end && selection.end <= *close.start();
7161 let in_bracket_range = open.to_inclusive().contains(&selection.head())
7162 || close.contains(&selection.head());
7163
7164 // If best is next to a bracket and current isn't, skip
7165 if !in_bracket_range && best_in_bracket_range {
7166 continue;
7167 }
7168
7169 // Prefer smaller lengths unless best is inside and current isn't
7170 if length > best_length && (best_inside || !inside) {
7171 continue;
7172 }
7173
7174 best_length = length;
7175 best_inside = inside;
7176 best_in_bracket_range = in_bracket_range;
7177 best_destination = Some(
7178 if close.contains(&selection.start) && close.contains(&selection.end) {
7179 if inside {
7180 open.end
7181 } else {
7182 open.start
7183 }
7184 } else {
7185 if inside {
7186 *close.start()
7187 } else {
7188 *close.end()
7189 }
7190 },
7191 );
7192 }
7193
7194 if let Some(destination) = best_destination {
7195 selection.collapse_to(destination, SelectionGoal::None);
7196 }
7197 })
7198 });
7199 }
7200
7201 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
7202 self.end_selection(cx);
7203 self.selection_history.mode = SelectionHistoryMode::Undoing;
7204 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
7205 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7206 self.select_next_state = entry.select_next_state;
7207 self.select_prev_state = entry.select_prev_state;
7208 self.add_selections_state = entry.add_selections_state;
7209 self.request_autoscroll(Autoscroll::newest(), cx);
7210 }
7211 self.selection_history.mode = SelectionHistoryMode::Normal;
7212 }
7213
7214 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
7215 self.end_selection(cx);
7216 self.selection_history.mode = SelectionHistoryMode::Redoing;
7217 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
7218 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7219 self.select_next_state = entry.select_next_state;
7220 self.select_prev_state = entry.select_prev_state;
7221 self.add_selections_state = entry.add_selections_state;
7222 self.request_autoscroll(Autoscroll::newest(), cx);
7223 }
7224 self.selection_history.mode = SelectionHistoryMode::Normal;
7225 }
7226
7227 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
7228 self.go_to_diagnostic_impl(Direction::Next, cx)
7229 }
7230
7231 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
7232 self.go_to_diagnostic_impl(Direction::Prev, cx)
7233 }
7234
7235 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
7236 let buffer = self.buffer.read(cx).snapshot(cx);
7237 let selection = self.selections.newest::<usize>(cx);
7238
7239 // If there is an active Diagnostic Popover jump to its diagnostic instead.
7240 if direction == Direction::Next {
7241 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
7242 let (group_id, jump_to) = popover.activation_info();
7243 if self.activate_diagnostics(group_id, cx) {
7244 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7245 let mut new_selection = s.newest_anchor().clone();
7246 new_selection.collapse_to(jump_to, SelectionGoal::None);
7247 s.select_anchors(vec![new_selection.clone()]);
7248 });
7249 }
7250 return;
7251 }
7252 }
7253
7254 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
7255 active_diagnostics
7256 .primary_range
7257 .to_offset(&buffer)
7258 .to_inclusive()
7259 });
7260 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
7261 if active_primary_range.contains(&selection.head()) {
7262 *active_primary_range.end()
7263 } else {
7264 selection.head()
7265 }
7266 } else {
7267 selection.head()
7268 };
7269
7270 loop {
7271 let mut diagnostics = if direction == Direction::Prev {
7272 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
7273 } else {
7274 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
7275 };
7276 let group = diagnostics.find_map(|entry| {
7277 if entry.diagnostic.is_primary
7278 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
7279 && !entry.range.is_empty()
7280 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
7281 && !entry.range.contains(&search_start)
7282 {
7283 Some((entry.range, entry.diagnostic.group_id))
7284 } else {
7285 None
7286 }
7287 });
7288
7289 if let Some((primary_range, group_id)) = group {
7290 if self.activate_diagnostics(group_id, cx) {
7291 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7292 s.select(vec![Selection {
7293 id: selection.id,
7294 start: primary_range.start,
7295 end: primary_range.start,
7296 reversed: false,
7297 goal: SelectionGoal::None,
7298 }]);
7299 });
7300 }
7301 break;
7302 } else {
7303 // Cycle around to the start of the buffer, potentially moving back to the start of
7304 // the currently active diagnostic.
7305 active_primary_range.take();
7306 if direction == Direction::Prev {
7307 if search_start == buffer.len() {
7308 break;
7309 } else {
7310 search_start = buffer.len();
7311 }
7312 } else if search_start == 0 {
7313 break;
7314 } else {
7315 search_start = 0;
7316 }
7317 }
7318 }
7319 }
7320
7321 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
7322 let snapshot = self
7323 .display_map
7324 .update(cx, |display_map, cx| display_map.snapshot(cx));
7325 let selection = self.selections.newest::<Point>(cx);
7326
7327 if !self.seek_in_direction(
7328 &snapshot,
7329 selection.head(),
7330 false,
7331 snapshot
7332 .buffer_snapshot
7333 .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
7334 cx,
7335 ) {
7336 let wrapped_point = Point::zero();
7337 self.seek_in_direction(
7338 &snapshot,
7339 wrapped_point,
7340 true,
7341 snapshot
7342 .buffer_snapshot
7343 .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
7344 cx,
7345 );
7346 }
7347 }
7348
7349 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
7350 let snapshot = self
7351 .display_map
7352 .update(cx, |display_map, cx| display_map.snapshot(cx));
7353 let selection = self.selections.newest::<Point>(cx);
7354
7355 if !self.seek_in_direction(
7356 &snapshot,
7357 selection.head(),
7358 false,
7359 snapshot
7360 .buffer_snapshot
7361 .git_diff_hunks_in_range_rev(0..selection.head().row),
7362 cx,
7363 ) {
7364 let wrapped_point = snapshot.buffer_snapshot.max_point();
7365 self.seek_in_direction(
7366 &snapshot,
7367 wrapped_point,
7368 true,
7369 snapshot
7370 .buffer_snapshot
7371 .git_diff_hunks_in_range_rev(0..wrapped_point.row),
7372 cx,
7373 );
7374 }
7375 }
7376
7377 fn seek_in_direction(
7378 &mut self,
7379 snapshot: &DisplaySnapshot,
7380 initial_point: Point,
7381 is_wrapped: bool,
7382 hunks: impl Iterator<Item = DiffHunk<u32>>,
7383 cx: &mut ViewContext<Editor>,
7384 ) -> bool {
7385 let display_point = initial_point.to_display_point(snapshot);
7386 let mut hunks = hunks
7387 .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
7388 .filter(|hunk| {
7389 if is_wrapped {
7390 true
7391 } else {
7392 !hunk.contains_display_row(display_point.row())
7393 }
7394 })
7395 .dedup();
7396
7397 if let Some(hunk) = hunks.next() {
7398 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7399 let row = hunk.start_display_row();
7400 let point = DisplayPoint::new(row, 0);
7401 s.select_display_ranges([point..point]);
7402 });
7403
7404 true
7405 } else {
7406 false
7407 }
7408 }
7409
7410 pub fn go_to_definition(&mut self, _: &GoToDefinition, cx: &mut ViewContext<Self>) {
7411 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
7412 }
7413
7414 pub fn go_to_implementation(&mut self, _: &GoToImplementation, cx: &mut ViewContext<Self>) {
7415 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx);
7416 }
7417
7418 pub fn go_to_implementation_split(
7419 &mut self,
7420 _: &GoToImplementationSplit,
7421 cx: &mut ViewContext<Self>,
7422 ) {
7423 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx);
7424 }
7425
7426 pub fn go_to_type_definition(&mut self, _: &GoToTypeDefinition, cx: &mut ViewContext<Self>) {
7427 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx);
7428 }
7429
7430 pub fn go_to_definition_split(&mut self, _: &GoToDefinitionSplit, cx: &mut ViewContext<Self>) {
7431 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx);
7432 }
7433
7434 pub fn go_to_type_definition_split(
7435 &mut self,
7436 _: &GoToTypeDefinitionSplit,
7437 cx: &mut ViewContext<Self>,
7438 ) {
7439 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx);
7440 }
7441
7442 fn go_to_definition_of_kind(
7443 &mut self,
7444 kind: GotoDefinitionKind,
7445 split: bool,
7446 cx: &mut ViewContext<Self>,
7447 ) {
7448 let Some(workspace) = self.workspace() else {
7449 return;
7450 };
7451 let buffer = self.buffer.read(cx);
7452 let head = self.selections.newest::<usize>(cx).head();
7453 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
7454 text_anchor
7455 } else {
7456 return;
7457 };
7458
7459 let project = workspace.read(cx).project().clone();
7460 let definitions = project.update(cx, |project, cx| match kind {
7461 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
7462 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
7463 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
7464 });
7465
7466 cx.spawn(|editor, mut cx| async move {
7467 let definitions = definitions.await?;
7468 editor.update(&mut cx, |editor, cx| {
7469 editor.navigate_to_hover_links(
7470 Some(kind),
7471 definitions.into_iter().map(HoverLink::Text).collect(),
7472 split,
7473 cx,
7474 );
7475 })?;
7476 Ok::<(), anyhow::Error>(())
7477 })
7478 .detach_and_log_err(cx);
7479 }
7480
7481 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
7482 let position = self.selections.newest_anchor().head();
7483 let Some((buffer, buffer_position)) =
7484 self.buffer.read(cx).text_anchor_for_position(position, cx)
7485 else {
7486 return;
7487 };
7488
7489 cx.spawn(|editor, mut cx| async move {
7490 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
7491 editor.update(&mut cx, |_, cx| {
7492 cx.open_url(&url);
7493 })
7494 } else {
7495 Ok(())
7496 }
7497 })
7498 .detach();
7499 }
7500
7501 pub(crate) fn navigate_to_hover_links(
7502 &mut self,
7503 kind: Option<GotoDefinitionKind>,
7504 mut definitions: Vec<HoverLink>,
7505 split: bool,
7506 cx: &mut ViewContext<Editor>,
7507 ) {
7508 // If there is one definition, just open it directly
7509 if definitions.len() == 1 {
7510 let definition = definitions.pop().unwrap();
7511 let target_task = match definition {
7512 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7513 HoverLink::InlayHint(lsp_location, server_id) => {
7514 self.compute_target_location(lsp_location, server_id, cx)
7515 }
7516 HoverLink::Url(url) => {
7517 cx.open_url(&url);
7518 Task::ready(Ok(None))
7519 }
7520 };
7521 cx.spawn(|editor, mut cx| async move {
7522 let target = target_task.await.context("target resolution task")?;
7523 if let Some(target) = target {
7524 editor.update(&mut cx, |editor, cx| {
7525 let Some(workspace) = editor.workspace() else {
7526 return;
7527 };
7528 let pane = workspace.read(cx).active_pane().clone();
7529
7530 let range = target.range.to_offset(target.buffer.read(cx));
7531 let range = editor.range_for_match(&range);
7532 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
7533 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
7534 s.select_ranges([range]);
7535 });
7536 } else {
7537 cx.window_context().defer(move |cx| {
7538 let target_editor: View<Self> =
7539 workspace.update(cx, |workspace, cx| {
7540 let pane = if split {
7541 workspace.adjacent_pane(cx)
7542 } else {
7543 workspace.active_pane().clone()
7544 };
7545
7546 workspace.open_project_item(pane, target.buffer.clone(), cx)
7547 });
7548 target_editor.update(cx, |target_editor, cx| {
7549 // When selecting a definition in a different buffer, disable the nav history
7550 // to avoid creating a history entry at the previous cursor location.
7551 pane.update(cx, |pane, _| pane.disable_history());
7552 target_editor.change_selections(
7553 Some(Autoscroll::fit()),
7554 cx,
7555 |s| {
7556 s.select_ranges([range]);
7557 },
7558 );
7559 pane.update(cx, |pane, _| pane.enable_history());
7560 });
7561 });
7562 }
7563 })
7564 } else {
7565 Ok(())
7566 }
7567 })
7568 .detach_and_log_err(cx);
7569 } else if !definitions.is_empty() {
7570 let replica_id = self.replica_id(cx);
7571 cx.spawn(|editor, mut cx| async move {
7572 let (title, location_tasks, workspace) = editor
7573 .update(&mut cx, |editor, cx| {
7574 let tab_kind = match kind {
7575 Some(GotoDefinitionKind::Implementation) => "Implementations",
7576 _ => "Definitions",
7577 };
7578 let title = definitions
7579 .iter()
7580 .find_map(|definition| match definition {
7581 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
7582 let buffer = origin.buffer.read(cx);
7583 format!(
7584 "{} for {}",
7585 tab_kind,
7586 buffer
7587 .text_for_range(origin.range.clone())
7588 .collect::<String>()
7589 )
7590 }),
7591 HoverLink::InlayHint(_, _) => None,
7592 HoverLink::Url(_) => None,
7593 })
7594 .unwrap_or(tab_kind.to_string());
7595 let location_tasks = definitions
7596 .into_iter()
7597 .map(|definition| match definition {
7598 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7599 HoverLink::InlayHint(lsp_location, server_id) => {
7600 editor.compute_target_location(lsp_location, server_id, cx)
7601 }
7602 HoverLink::Url(_) => Task::ready(Ok(None)),
7603 })
7604 .collect::<Vec<_>>();
7605 (title, location_tasks, editor.workspace().clone())
7606 })
7607 .context("location tasks preparation")?;
7608
7609 let locations = futures::future::join_all(location_tasks)
7610 .await
7611 .into_iter()
7612 .filter_map(|location| location.transpose())
7613 .collect::<Result<_>>()
7614 .context("location tasks")?;
7615
7616 let Some(workspace) = workspace else {
7617 return Ok(());
7618 };
7619 workspace
7620 .update(&mut cx, |workspace, cx| {
7621 Self::open_locations_in_multibuffer(
7622 workspace, locations, replica_id, title, split, cx,
7623 )
7624 })
7625 .ok();
7626
7627 anyhow::Ok(())
7628 })
7629 .detach_and_log_err(cx);
7630 }
7631 }
7632
7633 fn compute_target_location(
7634 &self,
7635 lsp_location: lsp::Location,
7636 server_id: LanguageServerId,
7637 cx: &mut ViewContext<Editor>,
7638 ) -> Task<anyhow::Result<Option<Location>>> {
7639 let Some(project) = self.project.clone() else {
7640 return Task::Ready(Some(Ok(None)));
7641 };
7642
7643 cx.spawn(move |editor, mut cx| async move {
7644 let location_task = editor.update(&mut cx, |editor, cx| {
7645 project.update(cx, |project, cx| {
7646 let language_server_name =
7647 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
7648 project
7649 .language_server_for_buffer(buffer.read(cx), server_id, cx)
7650 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
7651 });
7652 language_server_name.map(|language_server_name| {
7653 project.open_local_buffer_via_lsp(
7654 lsp_location.uri.clone(),
7655 server_id,
7656 language_server_name,
7657 cx,
7658 )
7659 })
7660 })
7661 })?;
7662 let location = match location_task {
7663 Some(task) => Some({
7664 let target_buffer_handle = task.await.context("open local buffer")?;
7665 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
7666 let target_start = target_buffer
7667 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
7668 let target_end = target_buffer
7669 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
7670 target_buffer.anchor_after(target_start)
7671 ..target_buffer.anchor_before(target_end)
7672 })?;
7673 Location {
7674 buffer: target_buffer_handle,
7675 range,
7676 }
7677 }),
7678 None => None,
7679 };
7680 Ok(location)
7681 })
7682 }
7683
7684 pub fn find_all_references(
7685 &mut self,
7686 _: &FindAllReferences,
7687 cx: &mut ViewContext<Self>,
7688 ) -> Option<Task<Result<()>>> {
7689 let buffer = self.buffer.read(cx);
7690 let head = self.selections.newest::<usize>(cx).head();
7691 let (buffer, head) = buffer.text_anchor_for_position(head, cx)?;
7692 let replica_id = self.replica_id(cx);
7693
7694 let workspace = self.workspace()?;
7695 let project = workspace.read(cx).project().clone();
7696 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
7697 Some(cx.spawn(|editor, mut cx| async move {
7698 let mut locations = references.await?;
7699 let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
7700 let head_offset = text::ToOffset::to_offset(&head, &snapshot);
7701
7702 // LSP may return references that contain the item itself we requested `find_all_references` for (eg. rust-analyzer)
7703 // So we will remove it from locations
7704 // If there is only one reference, we will not do this filter cause it may make locations empty
7705 if locations.len() > 1 {
7706 cx.update(|cx| {
7707 locations.retain(|location| {
7708 // fn foo(x : i64) {
7709 // ^
7710 // println!(x);
7711 // }
7712 // It is ok to find reference when caret being at ^ (the end of the word)
7713 // So we turn offset into inclusive to include the end of the word
7714 !location
7715 .range
7716 .to_offset(location.buffer.read(cx))
7717 .to_inclusive()
7718 .contains(&head_offset)
7719 });
7720 })?;
7721 }
7722
7723 if locations.is_empty() {
7724 return Ok(());
7725 }
7726
7727 // If there is one reference, just open it directly
7728 if locations.len() == 1 {
7729 let target = locations.pop().unwrap();
7730
7731 return editor.update(&mut cx, |editor, cx| {
7732 let range = target.range.to_offset(target.buffer.read(cx));
7733 let range = editor.range_for_match(&range);
7734
7735 if Some(&target.buffer) == editor.buffer().read(cx).as_singleton().as_ref() {
7736 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
7737 s.select_ranges([range]);
7738 });
7739 } else {
7740 cx.window_context().defer(move |cx| {
7741 let target_editor: View<Self> =
7742 workspace.update(cx, |workspace, cx| {
7743 workspace.open_project_item(
7744 workspace.active_pane().clone(),
7745 target.buffer.clone(),
7746 cx,
7747 )
7748 });
7749 target_editor.update(cx, |target_editor, cx| {
7750 target_editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
7751 s.select_ranges([range]);
7752 })
7753 })
7754 })
7755 }
7756 });
7757 }
7758
7759 workspace.update(&mut cx, |workspace, cx| {
7760 let title = locations
7761 .first()
7762 .as_ref()
7763 .map(|location| {
7764 let buffer = location.buffer.read(cx);
7765 format!(
7766 "References to `{}`",
7767 buffer
7768 .text_for_range(location.range.clone())
7769 .collect::<String>()
7770 )
7771 })
7772 .unwrap();
7773 Self::open_locations_in_multibuffer(
7774 workspace, locations, replica_id, title, false, cx,
7775 );
7776 })?;
7777
7778 Ok(())
7779 }))
7780 }
7781
7782 /// Opens a multibuffer with the given project locations in it
7783 pub fn open_locations_in_multibuffer(
7784 workspace: &mut Workspace,
7785 mut locations: Vec<Location>,
7786 replica_id: ReplicaId,
7787 title: String,
7788 split: bool,
7789 cx: &mut ViewContext<Workspace>,
7790 ) {
7791 // If there are multiple definitions, open them in a multibuffer
7792 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
7793 let mut locations = locations.into_iter().peekable();
7794 let mut ranges_to_highlight = Vec::new();
7795 let capability = workspace.project().read(cx).capability();
7796
7797 let excerpt_buffer = cx.new_model(|cx| {
7798 let mut multibuffer = MultiBuffer::new(replica_id, capability);
7799 while let Some(location) = locations.next() {
7800 let buffer = location.buffer.read(cx);
7801 let mut ranges_for_buffer = Vec::new();
7802 let range = location.range.to_offset(buffer);
7803 ranges_for_buffer.push(range.clone());
7804
7805 while let Some(next_location) = locations.peek() {
7806 if next_location.buffer == location.buffer {
7807 ranges_for_buffer.push(next_location.range.to_offset(buffer));
7808 locations.next();
7809 } else {
7810 break;
7811 }
7812 }
7813
7814 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
7815 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
7816 location.buffer.clone(),
7817 ranges_for_buffer,
7818 1,
7819 cx,
7820 ))
7821 }
7822
7823 multibuffer.with_title(title)
7824 });
7825
7826 let editor = cx.new_view(|cx| {
7827 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
7828 });
7829 editor.update(cx, |editor, cx| {
7830 editor.highlight_background::<Self>(
7831 ranges_to_highlight,
7832 |theme| theme.editor_highlighted_line_background,
7833 cx,
7834 );
7835 });
7836 if split {
7837 workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
7838 } else {
7839 workspace.add_item_to_active_pane(Box::new(editor), cx);
7840 }
7841 }
7842
7843 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7844 use language::ToOffset as _;
7845
7846 let project = self.project.clone()?;
7847 let selection = self.selections.newest_anchor().clone();
7848 let (cursor_buffer, cursor_buffer_position) = self
7849 .buffer
7850 .read(cx)
7851 .text_anchor_for_position(selection.head(), cx)?;
7852 let (tail_buffer, _) = self
7853 .buffer
7854 .read(cx)
7855 .text_anchor_for_position(selection.tail(), cx)?;
7856 if tail_buffer != cursor_buffer {
7857 return None;
7858 }
7859
7860 let snapshot = cursor_buffer.read(cx).snapshot();
7861 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
7862 let prepare_rename = project.update(cx, |project, cx| {
7863 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
7864 });
7865 drop(snapshot);
7866
7867 Some(cx.spawn(|this, mut cx| async move {
7868 let rename_range = if let Some(range) = prepare_rename.await? {
7869 Some(range)
7870 } else {
7871 this.update(&mut cx, |this, cx| {
7872 let buffer = this.buffer.read(cx).snapshot(cx);
7873 let mut buffer_highlights = this
7874 .document_highlights_for_position(selection.head(), &buffer)
7875 .filter(|highlight| {
7876 highlight.start.excerpt_id == selection.head().excerpt_id
7877 && highlight.end.excerpt_id == selection.head().excerpt_id
7878 });
7879 buffer_highlights
7880 .next()
7881 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
7882 })?
7883 };
7884 if let Some(rename_range) = rename_range {
7885 this.update(&mut cx, |this, cx| {
7886 let snapshot = cursor_buffer.read(cx).snapshot();
7887 let rename_buffer_range = rename_range.to_offset(&snapshot);
7888 let cursor_offset_in_rename_range =
7889 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
7890
7891 this.take_rename(false, cx);
7892 let buffer = this.buffer.read(cx).read(cx);
7893 let cursor_offset = selection.head().to_offset(&buffer);
7894 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
7895 let rename_end = rename_start + rename_buffer_range.len();
7896 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
7897 let mut old_highlight_id = None;
7898 let old_name: Arc<str> = buffer
7899 .chunks(rename_start..rename_end, true)
7900 .map(|chunk| {
7901 if old_highlight_id.is_none() {
7902 old_highlight_id = chunk.syntax_highlight_id;
7903 }
7904 chunk.text
7905 })
7906 .collect::<String>()
7907 .into();
7908
7909 drop(buffer);
7910
7911 // Position the selection in the rename editor so that it matches the current selection.
7912 this.show_local_selections = false;
7913 let rename_editor = cx.new_view(|cx| {
7914 let mut editor = Editor::single_line(cx);
7915 editor.buffer.update(cx, |buffer, cx| {
7916 buffer.edit([(0..0, old_name.clone())], None, cx)
7917 });
7918 editor.select_all(&SelectAll, cx);
7919 editor
7920 });
7921
7922 let ranges = this
7923 .clear_background_highlights::<DocumentHighlightWrite>(cx)
7924 .into_iter()
7925 .flat_map(|(_, ranges)| ranges.into_iter())
7926 .chain(
7927 this.clear_background_highlights::<DocumentHighlightRead>(cx)
7928 .into_iter()
7929 .flat_map(|(_, ranges)| ranges.into_iter()),
7930 )
7931 .collect();
7932
7933 this.highlight_text::<Rename>(
7934 ranges,
7935 HighlightStyle {
7936 fade_out: Some(0.6),
7937 ..Default::default()
7938 },
7939 cx,
7940 );
7941 let rename_focus_handle = rename_editor.focus_handle(cx);
7942 cx.focus(&rename_focus_handle);
7943 let block_id = this.insert_blocks(
7944 [BlockProperties {
7945 style: BlockStyle::Flex,
7946 position: range.start,
7947 height: 1,
7948 render: Arc::new({
7949 let rename_editor = rename_editor.clone();
7950 move |cx: &mut BlockContext| {
7951 let mut text_style = cx.editor_style.text.clone();
7952 if let Some(highlight_style) = old_highlight_id
7953 .and_then(|h| h.style(&cx.editor_style.syntax))
7954 {
7955 text_style = text_style.highlight(highlight_style);
7956 }
7957 div()
7958 .pl(cx.anchor_x)
7959 .child(EditorElement::new(
7960 &rename_editor,
7961 EditorStyle {
7962 background: cx.theme().system().transparent,
7963 local_player: cx.editor_style.local_player,
7964 text: text_style,
7965 scrollbar_width: cx.editor_style.scrollbar_width,
7966 syntax: cx.editor_style.syntax.clone(),
7967 status: cx.editor_style.status.clone(),
7968 inlays_style: HighlightStyle {
7969 color: Some(cx.theme().status().hint),
7970 font_weight: Some(FontWeight::BOLD),
7971 ..HighlightStyle::default()
7972 },
7973 suggestions_style: HighlightStyle {
7974 color: Some(cx.theme().status().predictive),
7975 ..HighlightStyle::default()
7976 },
7977 },
7978 ))
7979 .into_any_element()
7980 }
7981 }),
7982 disposition: BlockDisposition::Below,
7983 }],
7984 Some(Autoscroll::fit()),
7985 cx,
7986 )[0];
7987 this.pending_rename = Some(RenameState {
7988 range,
7989 old_name,
7990 editor: rename_editor,
7991 block_id,
7992 });
7993 })?;
7994 }
7995
7996 Ok(())
7997 }))
7998 }
7999
8000 pub fn confirm_rename(
8001 &mut self,
8002 _: &ConfirmRename,
8003 cx: &mut ViewContext<Self>,
8004 ) -> Option<Task<Result<()>>> {
8005 let rename = self.take_rename(false, cx)?;
8006 let workspace = self.workspace()?;
8007 let (start_buffer, start) = self
8008 .buffer
8009 .read(cx)
8010 .text_anchor_for_position(rename.range.start, cx)?;
8011 let (end_buffer, end) = self
8012 .buffer
8013 .read(cx)
8014 .text_anchor_for_position(rename.range.end, cx)?;
8015 if start_buffer != end_buffer {
8016 return None;
8017 }
8018
8019 let buffer = start_buffer;
8020 let range = start..end;
8021 let old_name = rename.old_name;
8022 let new_name = rename.editor.read(cx).text(cx);
8023
8024 let rename = workspace
8025 .read(cx)
8026 .project()
8027 .clone()
8028 .update(cx, |project, cx| {
8029 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
8030 });
8031 let workspace = workspace.downgrade();
8032
8033 Some(cx.spawn(|editor, mut cx| async move {
8034 let project_transaction = rename.await?;
8035 Self::open_project_transaction(
8036 &editor,
8037 workspace,
8038 project_transaction,
8039 format!("Rename: {} → {}", old_name, new_name),
8040 cx.clone(),
8041 )
8042 .await?;
8043
8044 editor.update(&mut cx, |editor, cx| {
8045 editor.refresh_document_highlights(cx);
8046 })?;
8047 Ok(())
8048 }))
8049 }
8050
8051 fn take_rename(
8052 &mut self,
8053 moving_cursor: bool,
8054 cx: &mut ViewContext<Self>,
8055 ) -> Option<RenameState> {
8056 let rename = self.pending_rename.take()?;
8057 if rename.editor.focus_handle(cx).is_focused(cx) {
8058 cx.focus(&self.focus_handle);
8059 }
8060
8061 self.remove_blocks(
8062 [rename.block_id].into_iter().collect(),
8063 Some(Autoscroll::fit()),
8064 cx,
8065 );
8066 self.clear_highlights::<Rename>(cx);
8067 self.show_local_selections = true;
8068
8069 if moving_cursor {
8070 let rename_editor = rename.editor.read(cx);
8071 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
8072
8073 // Update the selection to match the position of the selection inside
8074 // the rename editor.
8075 let snapshot = self.buffer.read(cx).read(cx);
8076 let rename_range = rename.range.to_offset(&snapshot);
8077 let cursor_in_editor = snapshot
8078 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
8079 .min(rename_range.end);
8080 drop(snapshot);
8081
8082 self.change_selections(None, cx, |s| {
8083 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
8084 });
8085 } else {
8086 self.refresh_document_highlights(cx);
8087 }
8088
8089 Some(rename)
8090 }
8091
8092 pub fn pending_rename(&self) -> Option<&RenameState> {
8093 self.pending_rename.as_ref()
8094 }
8095
8096 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8097 let project = match &self.project {
8098 Some(project) => project.clone(),
8099 None => return None,
8100 };
8101
8102 Some(self.perform_format(project, FormatTrigger::Manual, cx))
8103 }
8104
8105 fn perform_format(
8106 &mut self,
8107 project: Model<Project>,
8108 trigger: FormatTrigger,
8109 cx: &mut ViewContext<Self>,
8110 ) -> Task<Result<()>> {
8111 let buffer = self.buffer().clone();
8112 let buffers = buffer.read(cx).all_buffers();
8113
8114 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
8115 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
8116
8117 cx.spawn(|_, mut cx| async move {
8118 let transaction = futures::select_biased! {
8119 _ = timeout => {
8120 log::warn!("timed out waiting for formatting");
8121 None
8122 }
8123 transaction = format.log_err().fuse() => transaction,
8124 };
8125
8126 buffer
8127 .update(&mut cx, |buffer, cx| {
8128 if let Some(transaction) = transaction {
8129 if !buffer.is_singleton() {
8130 buffer.push_transaction(&transaction.0, cx);
8131 }
8132 }
8133
8134 cx.notify();
8135 })
8136 .ok();
8137
8138 Ok(())
8139 })
8140 }
8141
8142 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
8143 if let Some(project) = self.project.clone() {
8144 self.buffer.update(cx, |multi_buffer, cx| {
8145 project.update(cx, |project, cx| {
8146 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
8147 });
8148 })
8149 }
8150 }
8151
8152 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
8153 cx.show_character_palette();
8154 }
8155
8156 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
8157 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
8158 let buffer = self.buffer.read(cx).snapshot(cx);
8159 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
8160 let is_valid = buffer
8161 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
8162 .any(|entry| {
8163 entry.diagnostic.is_primary
8164 && !entry.range.is_empty()
8165 && entry.range.start == primary_range_start
8166 && entry.diagnostic.message == active_diagnostics.primary_message
8167 });
8168
8169 if is_valid != active_diagnostics.is_valid {
8170 active_diagnostics.is_valid = is_valid;
8171 let mut new_styles = HashMap::default();
8172 for (block_id, diagnostic) in &active_diagnostics.blocks {
8173 new_styles.insert(
8174 *block_id,
8175 diagnostic_block_renderer(diagnostic.clone(), is_valid),
8176 );
8177 }
8178 self.display_map
8179 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
8180 }
8181 }
8182 }
8183
8184 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
8185 self.dismiss_diagnostics(cx);
8186 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
8187 let buffer = self.buffer.read(cx).snapshot(cx);
8188
8189 let mut primary_range = None;
8190 let mut primary_message = None;
8191 let mut group_end = Point::zero();
8192 let diagnostic_group = buffer
8193 .diagnostic_group::<Point>(group_id)
8194 .map(|entry| {
8195 if entry.range.end > group_end {
8196 group_end = entry.range.end;
8197 }
8198 if entry.diagnostic.is_primary {
8199 primary_range = Some(entry.range.clone());
8200 primary_message = Some(entry.diagnostic.message.clone());
8201 }
8202 entry
8203 })
8204 .collect::<Vec<_>>();
8205 let primary_range = primary_range?;
8206 let primary_message = primary_message?;
8207 let primary_range =
8208 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
8209
8210 let blocks = display_map
8211 .insert_blocks(
8212 diagnostic_group.iter().map(|entry| {
8213 let diagnostic = entry.diagnostic.clone();
8214 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
8215 BlockProperties {
8216 style: BlockStyle::Fixed,
8217 position: buffer.anchor_after(entry.range.start),
8218 height: message_height,
8219 render: diagnostic_block_renderer(diagnostic, true),
8220 disposition: BlockDisposition::Below,
8221 }
8222 }),
8223 cx,
8224 )
8225 .into_iter()
8226 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
8227 .collect();
8228
8229 Some(ActiveDiagnosticGroup {
8230 primary_range,
8231 primary_message,
8232 blocks,
8233 is_valid: true,
8234 })
8235 });
8236 self.active_diagnostics.is_some()
8237 }
8238
8239 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
8240 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
8241 self.display_map.update(cx, |display_map, cx| {
8242 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
8243 });
8244 cx.notify();
8245 }
8246 }
8247
8248 pub fn set_selections_from_remote(
8249 &mut self,
8250 selections: Vec<Selection<Anchor>>,
8251 pending_selection: Option<Selection<Anchor>>,
8252 cx: &mut ViewContext<Self>,
8253 ) {
8254 let old_cursor_position = self.selections.newest_anchor().head();
8255 self.selections.change_with(cx, |s| {
8256 s.select_anchors(selections);
8257 if let Some(pending_selection) = pending_selection {
8258 s.set_pending(pending_selection, SelectMode::Character);
8259 } else {
8260 s.clear_pending();
8261 }
8262 });
8263 self.selections_did_change(false, &old_cursor_position, cx);
8264 }
8265
8266 fn push_to_selection_history(&mut self) {
8267 self.selection_history.push(SelectionHistoryEntry {
8268 selections: self.selections.disjoint_anchors(),
8269 select_next_state: self.select_next_state.clone(),
8270 select_prev_state: self.select_prev_state.clone(),
8271 add_selections_state: self.add_selections_state.clone(),
8272 });
8273 }
8274
8275 pub fn transact(
8276 &mut self,
8277 cx: &mut ViewContext<Self>,
8278 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
8279 ) -> Option<TransactionId> {
8280 self.start_transaction_at(Instant::now(), cx);
8281 update(self, cx);
8282 self.end_transaction_at(Instant::now(), cx)
8283 }
8284
8285 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
8286 self.end_selection(cx);
8287 if let Some(tx_id) = self
8288 .buffer
8289 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
8290 {
8291 self.selection_history
8292 .insert_transaction(tx_id, self.selections.disjoint_anchors());
8293 }
8294 }
8295
8296 fn end_transaction_at(
8297 &mut self,
8298 now: Instant,
8299 cx: &mut ViewContext<Self>,
8300 ) -> Option<TransactionId> {
8301 if let Some(tx_id) = self
8302 .buffer
8303 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
8304 {
8305 if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
8306 *end_selections = Some(self.selections.disjoint_anchors());
8307 } else {
8308 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
8309 }
8310
8311 cx.emit(EditorEvent::Edited);
8312 Some(tx_id)
8313 } else {
8314 None
8315 }
8316 }
8317
8318 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
8319 let mut fold_ranges = Vec::new();
8320
8321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8322
8323 let selections = self.selections.all_adjusted(cx);
8324 for selection in selections {
8325 let range = selection.range().sorted();
8326 let buffer_start_row = range.start.row;
8327
8328 for row in (0..=range.end.row).rev() {
8329 let fold_range = display_map.foldable_range(row);
8330
8331 if let Some(fold_range) = fold_range {
8332 if fold_range.end.row >= buffer_start_row {
8333 fold_ranges.push(fold_range);
8334 if row <= range.start.row {
8335 break;
8336 }
8337 }
8338 }
8339 }
8340 }
8341
8342 self.fold_ranges(fold_ranges, true, cx);
8343 }
8344
8345 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
8346 let buffer_row = fold_at.buffer_row;
8347 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8348
8349 if let Some(fold_range) = display_map.foldable_range(buffer_row) {
8350 let autoscroll = self
8351 .selections
8352 .all::<Point>(cx)
8353 .iter()
8354 .any(|selection| fold_range.overlaps(&selection.range()));
8355
8356 self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
8357 }
8358 }
8359
8360 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
8361 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8362 let buffer = &display_map.buffer_snapshot;
8363 let selections = self.selections.all::<Point>(cx);
8364 let ranges = selections
8365 .iter()
8366 .map(|s| {
8367 let range = s.display_range(&display_map).sorted();
8368 let mut start = range.start.to_point(&display_map);
8369 let mut end = range.end.to_point(&display_map);
8370 start.column = 0;
8371 end.column = buffer.line_len(end.row);
8372 start..end
8373 })
8374 .collect::<Vec<_>>();
8375
8376 self.unfold_ranges(ranges, true, true, cx);
8377 }
8378
8379 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
8380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8381
8382 let intersection_range = Point::new(unfold_at.buffer_row, 0)
8383 ..Point::new(
8384 unfold_at.buffer_row,
8385 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
8386 );
8387
8388 let autoscroll = self
8389 .selections
8390 .all::<Point>(cx)
8391 .iter()
8392 .any(|selection| selection.range().overlaps(&intersection_range));
8393
8394 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
8395 }
8396
8397 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
8398 let selections = self.selections.all::<Point>(cx);
8399 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8400 let line_mode = self.selections.line_mode;
8401 let ranges = selections.into_iter().map(|s| {
8402 if line_mode {
8403 let start = Point::new(s.start.row, 0);
8404 let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
8405 start..end
8406 } else {
8407 s.start..s.end
8408 }
8409 });
8410 self.fold_ranges(ranges, true, cx);
8411 }
8412
8413 pub fn fold_ranges<T: ToOffset + Clone>(
8414 &mut self,
8415 ranges: impl IntoIterator<Item = Range<T>>,
8416 auto_scroll: bool,
8417 cx: &mut ViewContext<Self>,
8418 ) {
8419 let mut ranges = ranges.into_iter().peekable();
8420 if ranges.peek().is_some() {
8421 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
8422
8423 if auto_scroll {
8424 self.request_autoscroll(Autoscroll::fit(), cx);
8425 }
8426
8427 cx.notify();
8428 }
8429 }
8430
8431 pub fn unfold_ranges<T: ToOffset + Clone>(
8432 &mut self,
8433 ranges: impl IntoIterator<Item = Range<T>>,
8434 inclusive: bool,
8435 auto_scroll: bool,
8436 cx: &mut ViewContext<Self>,
8437 ) {
8438 let mut ranges = ranges.into_iter().peekable();
8439 if ranges.peek().is_some() {
8440 self.display_map
8441 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
8442 if auto_scroll {
8443 self.request_autoscroll(Autoscroll::fit(), cx);
8444 }
8445
8446 cx.notify();
8447 }
8448 }
8449
8450 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
8451 if hovered != self.gutter_hovered {
8452 self.gutter_hovered = hovered;
8453 cx.notify();
8454 }
8455 }
8456
8457 pub fn insert_blocks(
8458 &mut self,
8459 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
8460 autoscroll: Option<Autoscroll>,
8461 cx: &mut ViewContext<Self>,
8462 ) -> Vec<BlockId> {
8463 let blocks = self
8464 .display_map
8465 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
8466 if let Some(autoscroll) = autoscroll {
8467 self.request_autoscroll(autoscroll, cx);
8468 }
8469 blocks
8470 }
8471
8472 pub fn replace_blocks(
8473 &mut self,
8474 blocks: HashMap<BlockId, RenderBlock>,
8475 autoscroll: Option<Autoscroll>,
8476 cx: &mut ViewContext<Self>,
8477 ) {
8478 self.display_map
8479 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
8480 if let Some(autoscroll) = autoscroll {
8481 self.request_autoscroll(autoscroll, cx);
8482 }
8483 }
8484
8485 pub fn remove_blocks(
8486 &mut self,
8487 block_ids: HashSet<BlockId>,
8488 autoscroll: Option<Autoscroll>,
8489 cx: &mut ViewContext<Self>,
8490 ) {
8491 self.display_map.update(cx, |display_map, cx| {
8492 display_map.remove_blocks(block_ids, cx)
8493 });
8494 if let Some(autoscroll) = autoscroll {
8495 self.request_autoscroll(autoscroll, cx);
8496 }
8497 }
8498
8499 pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
8500 self.display_map
8501 .update(cx, |map, cx| map.snapshot(cx))
8502 .longest_row()
8503 }
8504
8505 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
8506 self.display_map
8507 .update(cx, |map, cx| map.snapshot(cx))
8508 .max_point()
8509 }
8510
8511 pub fn text(&self, cx: &AppContext) -> String {
8512 self.buffer.read(cx).read(cx).text()
8513 }
8514
8515 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
8516 let text = self.text(cx);
8517 let text = text.trim();
8518
8519 if text.is_empty() {
8520 return None;
8521 }
8522
8523 Some(text.to_string())
8524 }
8525
8526 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
8527 self.transact(cx, |this, cx| {
8528 this.buffer
8529 .read(cx)
8530 .as_singleton()
8531 .expect("you can only call set_text on editors for singleton buffers")
8532 .update(cx, |buffer, cx| buffer.set_text(text, cx));
8533 });
8534 }
8535
8536 pub fn display_text(&self, cx: &mut AppContext) -> String {
8537 self.display_map
8538 .update(cx, |map, cx| map.snapshot(cx))
8539 .text()
8540 }
8541
8542 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
8543 let mut wrap_guides = smallvec::smallvec![];
8544
8545 if self.show_wrap_guides == Some(false) {
8546 return wrap_guides;
8547 }
8548
8549 let settings = self.buffer.read(cx).settings_at(0, cx);
8550 if settings.show_wrap_guides {
8551 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
8552 wrap_guides.push((soft_wrap as usize, true));
8553 }
8554 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
8555 }
8556
8557 wrap_guides
8558 }
8559
8560 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
8561 let settings = self.buffer.read(cx).settings_at(0, cx);
8562 let mode = self
8563 .soft_wrap_mode_override
8564 .unwrap_or_else(|| settings.soft_wrap);
8565 match mode {
8566 language_settings::SoftWrap::None => SoftWrap::None,
8567 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
8568 language_settings::SoftWrap::PreferredLineLength => {
8569 SoftWrap::Column(settings.preferred_line_length)
8570 }
8571 }
8572 }
8573
8574 pub fn set_soft_wrap_mode(
8575 &mut self,
8576 mode: language_settings::SoftWrap,
8577 cx: &mut ViewContext<Self>,
8578 ) {
8579 self.soft_wrap_mode_override = Some(mode);
8580 cx.notify();
8581 }
8582
8583 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
8584 let rem_size = cx.rem_size();
8585 self.display_map.update(cx, |map, cx| {
8586 map.set_font(
8587 style.text.font(),
8588 style.text.font_size.to_pixels(rem_size),
8589 cx,
8590 )
8591 });
8592 self.style = Some(style);
8593 }
8594
8595 #[cfg(any(test, feature = "test-support"))]
8596 pub fn style(&self) -> Option<&EditorStyle> {
8597 self.style.as_ref()
8598 }
8599
8600 // Called by the element. This method is not designed to be called outside of the editor
8601 // element's layout code because it does not notify when rewrapping is computed synchronously.
8602 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
8603 self.display_map
8604 .update(cx, |map, cx| map.set_wrap_width(width, cx))
8605 }
8606
8607 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
8608 if self.soft_wrap_mode_override.is_some() {
8609 self.soft_wrap_mode_override.take();
8610 } else {
8611 let soft_wrap = match self.soft_wrap_mode(cx) {
8612 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
8613 SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
8614 };
8615 self.soft_wrap_mode_override = Some(soft_wrap);
8616 }
8617 cx.notify();
8618 }
8619
8620 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
8621 let mut editor_settings = EditorSettings::get_global(cx).clone();
8622 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
8623 EditorSettings::override_global(editor_settings, cx);
8624 }
8625
8626 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8627 self.show_gutter = show_gutter;
8628 cx.notify();
8629 }
8630
8631 pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8632 self.show_wrap_guides = Some(show_gutter);
8633 cx.notify();
8634 }
8635
8636 pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
8637 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8638 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8639 cx.reveal_path(&file.abs_path(cx));
8640 }
8641 }
8642 }
8643
8644 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
8645 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8646 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8647 if let Some(path) = file.abs_path(cx).to_str() {
8648 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8649 }
8650 }
8651 }
8652 }
8653
8654 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
8655 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8656 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8657 if let Some(path) = file.path().to_str() {
8658 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8659 }
8660 }
8661 }
8662 }
8663
8664 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
8665 use git::permalink::{build_permalink, BuildPermalinkParams};
8666
8667 let (path, repo) = maybe!({
8668 let project_handle = self.project.as_ref()?.clone();
8669 let project = project_handle.read(cx);
8670 let buffer = self.buffer().read(cx).as_singleton()?;
8671 let path = buffer
8672 .read(cx)
8673 .file()?
8674 .as_local()?
8675 .path()
8676 .to_str()?
8677 .to_string();
8678 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
8679 Some((path, repo))
8680 })
8681 .ok_or_else(|| anyhow!("unable to open git repository"))?;
8682
8683 const REMOTE_NAME: &str = "origin";
8684 let origin_url = repo
8685 .lock()
8686 .remote_url(REMOTE_NAME)
8687 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
8688 let sha = repo
8689 .lock()
8690 .head_sha()
8691 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
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.as_ref());
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}