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