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