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