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