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