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