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