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