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 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5196 where
5197 Fn: FnMut(&str) -> String,
5198 {
5199 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5200 let buffer = self.buffer.read(cx).snapshot(cx);
5201
5202 let mut new_selections = Vec::new();
5203 let mut edits = Vec::new();
5204 let mut selection_adjustment = 0i32;
5205
5206 for selection in self.selections.all::<usize>(cx) {
5207 let selection_is_empty = selection.is_empty();
5208
5209 let (start, end) = if selection_is_empty {
5210 let word_range = movement::surrounding_word(
5211 &display_map,
5212 selection.start.to_display_point(&display_map),
5213 );
5214 let start = word_range.start.to_offset(&display_map, Bias::Left);
5215 let end = word_range.end.to_offset(&display_map, Bias::Left);
5216 (start, end)
5217 } else {
5218 (selection.start, selection.end)
5219 };
5220
5221 let text = buffer.text_for_range(start..end).collect::<String>();
5222 let old_length = text.len() as i32;
5223 let text = callback(&text);
5224
5225 new_selections.push(Selection {
5226 start: (start as i32 - selection_adjustment) as usize,
5227 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
5228 goal: SelectionGoal::None,
5229 ..selection
5230 });
5231
5232 selection_adjustment += old_length - text.len() as i32;
5233
5234 edits.push((start..end, text));
5235 }
5236
5237 self.transact(cx, |this, cx| {
5238 this.buffer.update(cx, |buffer, cx| {
5239 buffer.edit(edits, None, cx);
5240 });
5241
5242 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5243 s.select(new_selections);
5244 });
5245
5246 this.request_autoscroll(Autoscroll::fit(), cx);
5247 });
5248 }
5249
5250 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
5251 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5252 let buffer = &display_map.buffer_snapshot;
5253 let selections = self.selections.all::<Point>(cx);
5254
5255 let mut edits = Vec::new();
5256 let mut selections_iter = selections.iter().peekable();
5257 while let Some(selection) = selections_iter.next() {
5258 // Avoid duplicating the same lines twice.
5259 let mut rows = selection.spanned_rows(false, &display_map);
5260
5261 while let Some(next_selection) = selections_iter.peek() {
5262 let next_rows = next_selection.spanned_rows(false, &display_map);
5263 if next_rows.start < rows.end {
5264 rows.end = next_rows.end;
5265 selections_iter.next().unwrap();
5266 } else {
5267 break;
5268 }
5269 }
5270
5271 // Copy the text from the selected row region and splice it either at the start
5272 // or end of the region.
5273 let start = Point::new(rows.start, 0);
5274 let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
5275 let text = buffer
5276 .text_for_range(start..end)
5277 .chain(Some("\n"))
5278 .collect::<String>();
5279 let insert_location = if upwards {
5280 Point::new(rows.end, 0)
5281 } else {
5282 start
5283 };
5284 edits.push((insert_location..insert_location, text));
5285 }
5286
5287 self.transact(cx, |this, cx| {
5288 this.buffer.update(cx, |buffer, cx| {
5289 buffer.edit(edits, None, cx);
5290 });
5291
5292 this.request_autoscroll(Autoscroll::fit(), cx);
5293 });
5294 }
5295
5296 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
5297 self.duplicate_line(true, cx);
5298 }
5299
5300 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
5301 self.duplicate_line(false, cx);
5302 }
5303
5304 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
5305 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5306 let buffer = self.buffer.read(cx).snapshot(cx);
5307
5308 let mut edits = Vec::new();
5309 let mut unfold_ranges = Vec::new();
5310 let mut refold_ranges = Vec::new();
5311
5312 let selections = self.selections.all::<Point>(cx);
5313 let mut selections = selections.iter().peekable();
5314 let mut contiguous_row_selections = Vec::new();
5315 let mut new_selections = Vec::new();
5316
5317 while let Some(selection) = selections.next() {
5318 // Find all the selections that span a contiguous row range
5319 let (start_row, end_row) = consume_contiguous_rows(
5320 &mut contiguous_row_selections,
5321 selection,
5322 &display_map,
5323 &mut selections,
5324 );
5325
5326 // Move the text spanned by the row range to be before the line preceding the row range
5327 if start_row > 0 {
5328 let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
5329 ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
5330 let insertion_point = display_map
5331 .prev_line_boundary(Point::new(start_row - 1, 0))
5332 .0;
5333
5334 // Don't move lines across excerpts
5335 if buffer
5336 .excerpt_boundaries_in_range((
5337 Bound::Excluded(insertion_point),
5338 Bound::Included(range_to_move.end),
5339 ))
5340 .next()
5341 .is_none()
5342 {
5343 let text = buffer
5344 .text_for_range(range_to_move.clone())
5345 .flat_map(|s| s.chars())
5346 .skip(1)
5347 .chain(['\n'])
5348 .collect::<String>();
5349
5350 edits.push((
5351 buffer.anchor_after(range_to_move.start)
5352 ..buffer.anchor_before(range_to_move.end),
5353 String::new(),
5354 ));
5355 let insertion_anchor = buffer.anchor_after(insertion_point);
5356 edits.push((insertion_anchor..insertion_anchor, text));
5357
5358 let row_delta = range_to_move.start.row - insertion_point.row + 1;
5359
5360 // Move selections up
5361 new_selections.extend(contiguous_row_selections.drain(..).map(
5362 |mut selection| {
5363 selection.start.row -= row_delta;
5364 selection.end.row -= row_delta;
5365 selection
5366 },
5367 ));
5368
5369 // Move folds up
5370 unfold_ranges.push(range_to_move.clone());
5371 for fold in display_map.folds_in_range(
5372 buffer.anchor_before(range_to_move.start)
5373 ..buffer.anchor_after(range_to_move.end),
5374 ) {
5375 let mut start = fold.range.start.to_point(&buffer);
5376 let mut end = fold.range.end.to_point(&buffer);
5377 start.row -= row_delta;
5378 end.row -= row_delta;
5379 refold_ranges.push(start..end);
5380 }
5381 }
5382 }
5383
5384 // If we didn't move line(s), preserve the existing selections
5385 new_selections.append(&mut contiguous_row_selections);
5386 }
5387
5388 self.transact(cx, |this, cx| {
5389 this.unfold_ranges(unfold_ranges, true, true, cx);
5390 this.buffer.update(cx, |buffer, cx| {
5391 for (range, text) in edits {
5392 buffer.edit([(range, text)], None, cx);
5393 }
5394 });
5395 this.fold_ranges(refold_ranges, true, cx);
5396 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5397 s.select(new_selections);
5398 })
5399 });
5400 }
5401
5402 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5403 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5404 let buffer = self.buffer.read(cx).snapshot(cx);
5405
5406 let mut edits = Vec::new();
5407 let mut unfold_ranges = Vec::new();
5408 let mut refold_ranges = Vec::new();
5409
5410 let selections = self.selections.all::<Point>(cx);
5411 let mut selections = selections.iter().peekable();
5412 let mut contiguous_row_selections = Vec::new();
5413 let mut new_selections = Vec::new();
5414
5415 while let Some(selection) = selections.next() {
5416 // Find all the selections that span a contiguous row range
5417 let (start_row, end_row) = consume_contiguous_rows(
5418 &mut contiguous_row_selections,
5419 selection,
5420 &display_map,
5421 &mut selections,
5422 );
5423
5424 // Move the text spanned by the row range to be after the last line of the row range
5425 if end_row <= buffer.max_point().row {
5426 let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
5427 let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
5428
5429 // Don't move lines across excerpt boundaries
5430 if buffer
5431 .excerpt_boundaries_in_range((
5432 Bound::Excluded(range_to_move.start),
5433 Bound::Included(insertion_point),
5434 ))
5435 .next()
5436 .is_none()
5437 {
5438 let mut text = String::from("\n");
5439 text.extend(buffer.text_for_range(range_to_move.clone()));
5440 text.pop(); // Drop trailing newline
5441 edits.push((
5442 buffer.anchor_after(range_to_move.start)
5443 ..buffer.anchor_before(range_to_move.end),
5444 String::new(),
5445 ));
5446 let insertion_anchor = buffer.anchor_after(insertion_point);
5447 edits.push((insertion_anchor..insertion_anchor, text));
5448
5449 let row_delta = insertion_point.row - range_to_move.end.row + 1;
5450
5451 // Move selections down
5452 new_selections.extend(contiguous_row_selections.drain(..).map(
5453 |mut selection| {
5454 selection.start.row += row_delta;
5455 selection.end.row += row_delta;
5456 selection
5457 },
5458 ));
5459
5460 // Move folds down
5461 unfold_ranges.push(range_to_move.clone());
5462 for fold in display_map.folds_in_range(
5463 buffer.anchor_before(range_to_move.start)
5464 ..buffer.anchor_after(range_to_move.end),
5465 ) {
5466 let mut start = fold.range.start.to_point(&buffer);
5467 let mut end = fold.range.end.to_point(&buffer);
5468 start.row += row_delta;
5469 end.row += row_delta;
5470 refold_ranges.push(start..end);
5471 }
5472 }
5473 }
5474
5475 // If we didn't move line(s), preserve the existing selections
5476 new_selections.append(&mut contiguous_row_selections);
5477 }
5478
5479 self.transact(cx, |this, cx| {
5480 this.unfold_ranges(unfold_ranges, true, true, cx);
5481 this.buffer.update(cx, |buffer, cx| {
5482 for (range, text) in edits {
5483 buffer.edit([(range, text)], None, cx);
5484 }
5485 });
5486 this.fold_ranges(refold_ranges, true, cx);
5487 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
5488 });
5489 }
5490
5491 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
5492 let text_layout_details = &self.text_layout_details(cx);
5493 self.transact(cx, |this, cx| {
5494 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5495 let mut edits: Vec<(Range<usize>, String)> = Default::default();
5496 let line_mode = s.line_mode;
5497 s.move_with(|display_map, selection| {
5498 if !selection.is_empty() || line_mode {
5499 return;
5500 }
5501
5502 let mut head = selection.head();
5503 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
5504 if head.column() == display_map.line_len(head.row()) {
5505 transpose_offset = display_map
5506 .buffer_snapshot
5507 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5508 }
5509
5510 if transpose_offset == 0 {
5511 return;
5512 }
5513
5514 *head.column_mut() += 1;
5515 head = display_map.clip_point(head, Bias::Right);
5516 let goal = SelectionGoal::HorizontalPosition(
5517 display_map
5518 .x_for_display_point(head, &text_layout_details)
5519 .into(),
5520 );
5521 selection.collapse_to(head, goal);
5522
5523 let transpose_start = display_map
5524 .buffer_snapshot
5525 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5526 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
5527 let transpose_end = display_map
5528 .buffer_snapshot
5529 .clip_offset(transpose_offset + 1, Bias::Right);
5530 if let Some(ch) =
5531 display_map.buffer_snapshot.chars_at(transpose_start).next()
5532 {
5533 edits.push((transpose_start..transpose_offset, String::new()));
5534 edits.push((transpose_end..transpose_end, ch.to_string()));
5535 }
5536 }
5537 });
5538 edits
5539 });
5540 this.buffer
5541 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
5542 let selections = this.selections.all::<usize>(cx);
5543 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5544 s.select(selections);
5545 });
5546 });
5547 }
5548
5549 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
5550 let mut text = String::new();
5551 let buffer = self.buffer.read(cx).snapshot(cx);
5552 let mut selections = self.selections.all::<Point>(cx);
5553 let mut clipboard_selections = Vec::with_capacity(selections.len());
5554 {
5555 let max_point = buffer.max_point();
5556 let mut is_first = true;
5557 for selection in &mut selections {
5558 let is_entire_line = selection.is_empty() || self.selections.line_mode;
5559 if is_entire_line {
5560 selection.start = Point::new(selection.start.row, 0);
5561 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
5562 selection.goal = SelectionGoal::None;
5563 }
5564 if is_first {
5565 is_first = false;
5566 } else {
5567 text += "\n";
5568 }
5569 let mut len = 0;
5570 for chunk in buffer.text_for_range(selection.start..selection.end) {
5571 text.push_str(chunk);
5572 len += chunk.len();
5573 }
5574 clipboard_selections.push(ClipboardSelection {
5575 len,
5576 is_entire_line,
5577 first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
5578 });
5579 }
5580 }
5581
5582 self.transact(cx, |this, cx| {
5583 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5584 s.select(selections);
5585 });
5586 this.insert("", cx);
5587 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5588 });
5589 }
5590
5591 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
5592 let selections = self.selections.all::<Point>(cx);
5593 let buffer = self.buffer.read(cx).read(cx);
5594 let mut text = String::new();
5595
5596 let mut clipboard_selections = Vec::with_capacity(selections.len());
5597 {
5598 let max_point = buffer.max_point();
5599 let mut is_first = true;
5600 for selection in selections.iter() {
5601 let mut start = selection.start;
5602 let mut end = selection.end;
5603 let is_entire_line = selection.is_empty() || self.selections.line_mode;
5604 if is_entire_line {
5605 start = Point::new(start.row, 0);
5606 end = cmp::min(max_point, Point::new(end.row + 1, 0));
5607 }
5608 if is_first {
5609 is_first = false;
5610 } else {
5611 text += "\n";
5612 }
5613 let mut len = 0;
5614 for chunk in buffer.text_for_range(start..end) {
5615 text.push_str(chunk);
5616 len += chunk.len();
5617 }
5618 clipboard_selections.push(ClipboardSelection {
5619 len,
5620 is_entire_line,
5621 first_line_indent: buffer.indent_size_for_line(start.row).len,
5622 });
5623 }
5624 }
5625
5626 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5627 }
5628
5629 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
5630 if self.read_only(cx) {
5631 return;
5632 }
5633
5634 self.transact(cx, |this, cx| {
5635 if let Some(item) = cx.read_from_clipboard() {
5636 let clipboard_text = Cow::Borrowed(item.text());
5637 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
5638 let old_selections = this.selections.all::<usize>(cx);
5639 let all_selections_were_entire_line =
5640 clipboard_selections.iter().all(|s| s.is_entire_line);
5641 let first_selection_indent_column =
5642 clipboard_selections.first().map(|s| s.first_line_indent);
5643 if clipboard_selections.len() != old_selections.len() {
5644 clipboard_selections.drain(..);
5645 }
5646
5647 this.buffer.update(cx, |buffer, cx| {
5648 let snapshot = buffer.read(cx);
5649 let mut start_offset = 0;
5650 let mut edits = Vec::new();
5651 let mut original_indent_columns = Vec::new();
5652 let line_mode = this.selections.line_mode;
5653 for (ix, selection) in old_selections.iter().enumerate() {
5654 let to_insert;
5655 let entire_line;
5656 let original_indent_column;
5657 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
5658 let end_offset = start_offset + clipboard_selection.len;
5659 to_insert = &clipboard_text[start_offset..end_offset];
5660 entire_line = clipboard_selection.is_entire_line;
5661 start_offset = end_offset + 1;
5662 original_indent_column =
5663 Some(clipboard_selection.first_line_indent);
5664 } else {
5665 to_insert = clipboard_text.as_str();
5666 entire_line = all_selections_were_entire_line;
5667 original_indent_column = first_selection_indent_column
5668 }
5669
5670 // If the corresponding selection was empty when this slice of the
5671 // clipboard text was written, then the entire line containing the
5672 // selection was copied. If this selection is also currently empty,
5673 // then paste the line before the current line of the buffer.
5674 let range = if selection.is_empty() && !line_mode && entire_line {
5675 let column = selection.start.to_point(&snapshot).column as usize;
5676 let line_start = selection.start - column;
5677 line_start..line_start
5678 } else {
5679 selection.range()
5680 };
5681
5682 edits.push((range, to_insert));
5683 original_indent_columns.extend(original_indent_column);
5684 }
5685 drop(snapshot);
5686
5687 buffer.edit(
5688 edits,
5689 Some(AutoindentMode::Block {
5690 original_indent_columns,
5691 }),
5692 cx,
5693 );
5694 });
5695
5696 let selections = this.selections.all::<usize>(cx);
5697 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5698 } else {
5699 this.insert(&clipboard_text, cx);
5700 }
5701 }
5702 });
5703 }
5704
5705 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
5706 if self.read_only(cx) {
5707 return;
5708 }
5709
5710 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
5711 if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
5712 self.change_selections(None, cx, |s| {
5713 s.select_anchors(selections.to_vec());
5714 });
5715 }
5716 self.request_autoscroll(Autoscroll::fit(), cx);
5717 self.unmark_text(cx);
5718 self.refresh_inline_completion(true, cx);
5719 cx.emit(EditorEvent::Edited);
5720 cx.emit(EditorEvent::TransactionUndone {
5721 transaction_id: tx_id,
5722 });
5723 }
5724 }
5725
5726 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
5727 if self.read_only(cx) {
5728 return;
5729 }
5730
5731 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
5732 if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
5733 {
5734 self.change_selections(None, cx, |s| {
5735 s.select_anchors(selections.to_vec());
5736 });
5737 }
5738 self.request_autoscroll(Autoscroll::fit(), cx);
5739 self.unmark_text(cx);
5740 self.refresh_inline_completion(true, cx);
5741 cx.emit(EditorEvent::Edited);
5742 }
5743 }
5744
5745 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
5746 self.buffer
5747 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
5748 }
5749
5750 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
5751 self.buffer
5752 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
5753 }
5754
5755 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
5756 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5757 let line_mode = s.line_mode;
5758 s.move_with(|map, selection| {
5759 let cursor = if selection.is_empty() && !line_mode {
5760 movement::left(map, selection.start)
5761 } else {
5762 selection.start
5763 };
5764 selection.collapse_to(cursor, SelectionGoal::None);
5765 });
5766 })
5767 }
5768
5769 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
5770 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5771 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
5772 })
5773 }
5774
5775 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
5776 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5777 let line_mode = s.line_mode;
5778 s.move_with(|map, selection| {
5779 let cursor = if selection.is_empty() && !line_mode {
5780 movement::right(map, selection.end)
5781 } else {
5782 selection.end
5783 };
5784 selection.collapse_to(cursor, SelectionGoal::None)
5785 });
5786 })
5787 }
5788
5789 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
5790 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5791 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
5792 })
5793 }
5794
5795 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
5796 if self.take_rename(true, cx).is_some() {
5797 return;
5798 }
5799
5800 if matches!(self.mode, EditorMode::SingleLine) {
5801 cx.propagate();
5802 return;
5803 }
5804
5805 let text_layout_details = &self.text_layout_details(cx);
5806
5807 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5808 let line_mode = s.line_mode;
5809 s.move_with(|map, selection| {
5810 if !selection.is_empty() && !line_mode {
5811 selection.goal = SelectionGoal::None;
5812 }
5813 let (cursor, goal) = movement::up(
5814 map,
5815 selection.start,
5816 selection.goal,
5817 false,
5818 &text_layout_details,
5819 );
5820 selection.collapse_to(cursor, goal);
5821 });
5822 })
5823 }
5824
5825 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
5826 if self.take_rename(true, cx).is_some() {
5827 return;
5828 }
5829
5830 if matches!(self.mode, EditorMode::SingleLine) {
5831 cx.propagate();
5832 return;
5833 }
5834
5835 let text_layout_details = &self.text_layout_details(cx);
5836
5837 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5838 let line_mode = s.line_mode;
5839 s.move_with(|map, selection| {
5840 if !selection.is_empty() && !line_mode {
5841 selection.goal = SelectionGoal::None;
5842 }
5843 let (cursor, goal) = movement::up_by_rows(
5844 map,
5845 selection.start,
5846 action.lines,
5847 selection.goal,
5848 false,
5849 &text_layout_details,
5850 );
5851 selection.collapse_to(cursor, goal);
5852 });
5853 })
5854 }
5855
5856 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
5857 if self.take_rename(true, cx).is_some() {
5858 return;
5859 }
5860
5861 if matches!(self.mode, EditorMode::SingleLine) {
5862 cx.propagate();
5863 return;
5864 }
5865
5866 let text_layout_details = &self.text_layout_details(cx);
5867
5868 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5869 let line_mode = s.line_mode;
5870 s.move_with(|map, selection| {
5871 if !selection.is_empty() && !line_mode {
5872 selection.goal = SelectionGoal::None;
5873 }
5874 let (cursor, goal) = movement::down_by_rows(
5875 map,
5876 selection.start,
5877 action.lines,
5878 selection.goal,
5879 false,
5880 &text_layout_details,
5881 );
5882 selection.collapse_to(cursor, goal);
5883 });
5884 })
5885 }
5886
5887 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
5888 let text_layout_details = &self.text_layout_details(cx);
5889 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5890 s.move_heads_with(|map, head, goal| {
5891 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
5892 })
5893 })
5894 }
5895
5896 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
5897 let text_layout_details = &self.text_layout_details(cx);
5898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5899 s.move_heads_with(|map, head, goal| {
5900 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
5901 })
5902 })
5903 }
5904
5905 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
5906 if self.take_rename(true, cx).is_some() {
5907 return;
5908 }
5909
5910 if matches!(self.mode, EditorMode::SingleLine) {
5911 cx.propagate();
5912 return;
5913 }
5914
5915 let row_count = if let Some(row_count) = self.visible_line_count() {
5916 row_count as u32 - 1
5917 } else {
5918 return;
5919 };
5920
5921 let autoscroll = if action.center_cursor {
5922 Autoscroll::center()
5923 } else {
5924 Autoscroll::fit()
5925 };
5926
5927 let text_layout_details = &self.text_layout_details(cx);
5928
5929 self.change_selections(Some(autoscroll), cx, |s| {
5930 let line_mode = s.line_mode;
5931 s.move_with(|map, selection| {
5932 if !selection.is_empty() && !line_mode {
5933 selection.goal = SelectionGoal::None;
5934 }
5935 let (cursor, goal) = movement::up_by_rows(
5936 map,
5937 selection.end,
5938 row_count,
5939 selection.goal,
5940 false,
5941 &text_layout_details,
5942 );
5943 selection.collapse_to(cursor, goal);
5944 });
5945 });
5946 }
5947
5948 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
5949 let text_layout_details = &self.text_layout_details(cx);
5950 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5951 s.move_heads_with(|map, head, goal| {
5952 movement::up(map, head, goal, false, &text_layout_details)
5953 })
5954 })
5955 }
5956
5957 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
5958 self.take_rename(true, cx);
5959
5960 if self.mode == EditorMode::SingleLine {
5961 cx.propagate();
5962 return;
5963 }
5964
5965 let text_layout_details = &self.text_layout_details(cx);
5966 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5967 let line_mode = s.line_mode;
5968 s.move_with(|map, selection| {
5969 if !selection.is_empty() && !line_mode {
5970 selection.goal = SelectionGoal::None;
5971 }
5972 let (cursor, goal) = movement::down(
5973 map,
5974 selection.end,
5975 selection.goal,
5976 false,
5977 &text_layout_details,
5978 );
5979 selection.collapse_to(cursor, goal);
5980 });
5981 });
5982 }
5983
5984 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
5985 if self.take_rename(true, cx).is_some() {
5986 return;
5987 }
5988
5989 if self
5990 .context_menu
5991 .write()
5992 .as_mut()
5993 .map(|menu| menu.select_last(self.project.as_ref(), cx))
5994 .unwrap_or(false)
5995 {
5996 return;
5997 }
5998
5999 if matches!(self.mode, EditorMode::SingleLine) {
6000 cx.propagate();
6001 return;
6002 }
6003
6004 let row_count = if let Some(row_count) = self.visible_line_count() {
6005 row_count as u32 - 1
6006 } else {
6007 return;
6008 };
6009
6010 let autoscroll = if action.center_cursor {
6011 Autoscroll::center()
6012 } else {
6013 Autoscroll::fit()
6014 };
6015
6016 let text_layout_details = &self.text_layout_details(cx);
6017 self.change_selections(Some(autoscroll), cx, |s| {
6018 let line_mode = s.line_mode;
6019 s.move_with(|map, selection| {
6020 if !selection.is_empty() && !line_mode {
6021 selection.goal = SelectionGoal::None;
6022 }
6023 let (cursor, goal) = movement::down_by_rows(
6024 map,
6025 selection.end,
6026 row_count,
6027 selection.goal,
6028 false,
6029 &text_layout_details,
6030 );
6031 selection.collapse_to(cursor, goal);
6032 });
6033 });
6034 }
6035
6036 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
6037 let text_layout_details = &self.text_layout_details(cx);
6038 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6039 s.move_heads_with(|map, head, goal| {
6040 movement::down(map, head, goal, false, &text_layout_details)
6041 })
6042 });
6043 }
6044
6045 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
6046 if let Some(context_menu) = self.context_menu.write().as_mut() {
6047 context_menu.select_first(self.project.as_ref(), cx);
6048 }
6049 }
6050
6051 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
6052 if let Some(context_menu) = self.context_menu.write().as_mut() {
6053 context_menu.select_prev(self.project.as_ref(), cx);
6054 }
6055 }
6056
6057 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
6058 if let Some(context_menu) = self.context_menu.write().as_mut() {
6059 context_menu.select_next(self.project.as_ref(), cx);
6060 }
6061 }
6062
6063 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
6064 if let Some(context_menu) = self.context_menu.write().as_mut() {
6065 context_menu.select_last(self.project.as_ref(), cx);
6066 }
6067 }
6068
6069 pub fn move_to_previous_word_start(
6070 &mut self,
6071 _: &MoveToPreviousWordStart,
6072 cx: &mut ViewContext<Self>,
6073 ) {
6074 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6075 s.move_cursors_with(|map, head, _| {
6076 (
6077 movement::previous_word_start(map, head),
6078 SelectionGoal::None,
6079 )
6080 });
6081 })
6082 }
6083
6084 pub fn move_to_previous_subword_start(
6085 &mut self,
6086 _: &MoveToPreviousSubwordStart,
6087 cx: &mut ViewContext<Self>,
6088 ) {
6089 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6090 s.move_cursors_with(|map, head, _| {
6091 (
6092 movement::previous_subword_start(map, head),
6093 SelectionGoal::None,
6094 )
6095 });
6096 })
6097 }
6098
6099 pub fn select_to_previous_word_start(
6100 &mut self,
6101 _: &SelectToPreviousWordStart,
6102 cx: &mut ViewContext<Self>,
6103 ) {
6104 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6105 s.move_heads_with(|map, head, _| {
6106 (
6107 movement::previous_word_start(map, head),
6108 SelectionGoal::None,
6109 )
6110 });
6111 })
6112 }
6113
6114 pub fn select_to_previous_subword_start(
6115 &mut self,
6116 _: &SelectToPreviousSubwordStart,
6117 cx: &mut ViewContext<Self>,
6118 ) {
6119 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6120 s.move_heads_with(|map, head, _| {
6121 (
6122 movement::previous_subword_start(map, head),
6123 SelectionGoal::None,
6124 )
6125 });
6126 })
6127 }
6128
6129 pub fn delete_to_previous_word_start(
6130 &mut self,
6131 _: &DeleteToPreviousWordStart,
6132 cx: &mut ViewContext<Self>,
6133 ) {
6134 self.transact(cx, |this, cx| {
6135 this.select_autoclose_pair(cx);
6136 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6137 let line_mode = s.line_mode;
6138 s.move_with(|map, selection| {
6139 if selection.is_empty() && !line_mode {
6140 let cursor = movement::previous_word_start(map, selection.head());
6141 selection.set_head(cursor, SelectionGoal::None);
6142 }
6143 });
6144 });
6145 this.insert("", cx);
6146 });
6147 }
6148
6149 pub fn delete_to_previous_subword_start(
6150 &mut self,
6151 _: &DeleteToPreviousSubwordStart,
6152 cx: &mut ViewContext<Self>,
6153 ) {
6154 self.transact(cx, |this, cx| {
6155 this.select_autoclose_pair(cx);
6156 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6157 let line_mode = s.line_mode;
6158 s.move_with(|map, selection| {
6159 if selection.is_empty() && !line_mode {
6160 let cursor = movement::previous_subword_start(map, selection.head());
6161 selection.set_head(cursor, SelectionGoal::None);
6162 }
6163 });
6164 });
6165 this.insert("", cx);
6166 });
6167 }
6168
6169 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
6170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6171 s.move_cursors_with(|map, head, _| {
6172 (movement::next_word_end(map, head), SelectionGoal::None)
6173 });
6174 })
6175 }
6176
6177 pub fn move_to_next_subword_end(
6178 &mut self,
6179 _: &MoveToNextSubwordEnd,
6180 cx: &mut ViewContext<Self>,
6181 ) {
6182 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6183 s.move_cursors_with(|map, head, _| {
6184 (movement::next_subword_end(map, head), SelectionGoal::None)
6185 });
6186 })
6187 }
6188
6189 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
6190 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6191 s.move_heads_with(|map, head, _| {
6192 (movement::next_word_end(map, head), SelectionGoal::None)
6193 });
6194 })
6195 }
6196
6197 pub fn select_to_next_subword_end(
6198 &mut self,
6199 _: &SelectToNextSubwordEnd,
6200 cx: &mut ViewContext<Self>,
6201 ) {
6202 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6203 s.move_heads_with(|map, head, _| {
6204 (movement::next_subword_end(map, head), SelectionGoal::None)
6205 });
6206 })
6207 }
6208
6209 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
6210 self.transact(cx, |this, cx| {
6211 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6212 let line_mode = s.line_mode;
6213 s.move_with(|map, selection| {
6214 if selection.is_empty() && !line_mode {
6215 let cursor = movement::next_word_end(map, selection.head());
6216 selection.set_head(cursor, SelectionGoal::None);
6217 }
6218 });
6219 });
6220 this.insert("", cx);
6221 });
6222 }
6223
6224 pub fn delete_to_next_subword_end(
6225 &mut self,
6226 _: &DeleteToNextSubwordEnd,
6227 cx: &mut ViewContext<Self>,
6228 ) {
6229 self.transact(cx, |this, cx| {
6230 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6231 s.move_with(|map, selection| {
6232 if selection.is_empty() {
6233 let cursor = movement::next_subword_end(map, selection.head());
6234 selection.set_head(cursor, SelectionGoal::None);
6235 }
6236 });
6237 });
6238 this.insert("", cx);
6239 });
6240 }
6241
6242 pub fn move_to_beginning_of_line(
6243 &mut self,
6244 action: &MoveToBeginningOfLine,
6245 cx: &mut ViewContext<Self>,
6246 ) {
6247 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6248 s.move_cursors_with(|map, head, _| {
6249 (
6250 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6251 SelectionGoal::None,
6252 )
6253 });
6254 })
6255 }
6256
6257 pub fn select_to_beginning_of_line(
6258 &mut self,
6259 action: &SelectToBeginningOfLine,
6260 cx: &mut ViewContext<Self>,
6261 ) {
6262 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6263 s.move_heads_with(|map, head, _| {
6264 (
6265 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6266 SelectionGoal::None,
6267 )
6268 });
6269 });
6270 }
6271
6272 pub fn delete_to_beginning_of_line(
6273 &mut self,
6274 _: &DeleteToBeginningOfLine,
6275 cx: &mut ViewContext<Self>,
6276 ) {
6277 self.transact(cx, |this, cx| {
6278 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6279 s.move_with(|_, selection| {
6280 selection.reversed = true;
6281 });
6282 });
6283
6284 this.select_to_beginning_of_line(
6285 &SelectToBeginningOfLine {
6286 stop_at_soft_wraps: false,
6287 },
6288 cx,
6289 );
6290 this.backspace(&Backspace, cx);
6291 });
6292 }
6293
6294 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
6295 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6296 s.move_cursors_with(|map, head, _| {
6297 (
6298 movement::line_end(map, head, action.stop_at_soft_wraps),
6299 SelectionGoal::None,
6300 )
6301 });
6302 })
6303 }
6304
6305 pub fn select_to_end_of_line(
6306 &mut self,
6307 action: &SelectToEndOfLine,
6308 cx: &mut ViewContext<Self>,
6309 ) {
6310 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6311 s.move_heads_with(|map, head, _| {
6312 (
6313 movement::line_end(map, head, action.stop_at_soft_wraps),
6314 SelectionGoal::None,
6315 )
6316 });
6317 })
6318 }
6319
6320 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
6321 self.transact(cx, |this, cx| {
6322 this.select_to_end_of_line(
6323 &SelectToEndOfLine {
6324 stop_at_soft_wraps: false,
6325 },
6326 cx,
6327 );
6328 this.delete(&Delete, cx);
6329 });
6330 }
6331
6332 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
6333 self.transact(cx, |this, cx| {
6334 this.select_to_end_of_line(
6335 &SelectToEndOfLine {
6336 stop_at_soft_wraps: false,
6337 },
6338 cx,
6339 );
6340 this.cut(&Cut, cx);
6341 });
6342 }
6343
6344 pub fn move_to_start_of_paragraph(
6345 &mut self,
6346 _: &MoveToStartOfParagraph,
6347 cx: &mut ViewContext<Self>,
6348 ) {
6349 if matches!(self.mode, EditorMode::SingleLine) {
6350 cx.propagate();
6351 return;
6352 }
6353
6354 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6355 s.move_with(|map, selection| {
6356 selection.collapse_to(
6357 movement::start_of_paragraph(map, selection.head(), 1),
6358 SelectionGoal::None,
6359 )
6360 });
6361 })
6362 }
6363
6364 pub fn move_to_end_of_paragraph(
6365 &mut self,
6366 _: &MoveToEndOfParagraph,
6367 cx: &mut ViewContext<Self>,
6368 ) {
6369 if matches!(self.mode, EditorMode::SingleLine) {
6370 cx.propagate();
6371 return;
6372 }
6373
6374 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6375 s.move_with(|map, selection| {
6376 selection.collapse_to(
6377 movement::end_of_paragraph(map, selection.head(), 1),
6378 SelectionGoal::None,
6379 )
6380 });
6381 })
6382 }
6383
6384 pub fn select_to_start_of_paragraph(
6385 &mut self,
6386 _: &SelectToStartOfParagraph,
6387 cx: &mut ViewContext<Self>,
6388 ) {
6389 if matches!(self.mode, EditorMode::SingleLine) {
6390 cx.propagate();
6391 return;
6392 }
6393
6394 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6395 s.move_heads_with(|map, head, _| {
6396 (
6397 movement::start_of_paragraph(map, head, 1),
6398 SelectionGoal::None,
6399 )
6400 });
6401 })
6402 }
6403
6404 pub fn select_to_end_of_paragraph(
6405 &mut self,
6406 _: &SelectToEndOfParagraph,
6407 cx: &mut ViewContext<Self>,
6408 ) {
6409 if matches!(self.mode, EditorMode::SingleLine) {
6410 cx.propagate();
6411 return;
6412 }
6413
6414 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6415 s.move_heads_with(|map, head, _| {
6416 (
6417 movement::end_of_paragraph(map, head, 1),
6418 SelectionGoal::None,
6419 )
6420 });
6421 })
6422 }
6423
6424 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
6425 if matches!(self.mode, EditorMode::SingleLine) {
6426 cx.propagate();
6427 return;
6428 }
6429
6430 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6431 s.select_ranges(vec![0..0]);
6432 });
6433 }
6434
6435 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
6436 let mut selection = self.selections.last::<Point>(cx);
6437 selection.set_head(Point::zero(), SelectionGoal::None);
6438
6439 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6440 s.select(vec![selection]);
6441 });
6442 }
6443
6444 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
6445 if matches!(self.mode, EditorMode::SingleLine) {
6446 cx.propagate();
6447 return;
6448 }
6449
6450 let cursor = self.buffer.read(cx).read(cx).len();
6451 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6452 s.select_ranges(vec![cursor..cursor])
6453 });
6454 }
6455
6456 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
6457 self.nav_history = nav_history;
6458 }
6459
6460 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
6461 self.nav_history.as_ref()
6462 }
6463
6464 fn push_to_nav_history(
6465 &mut self,
6466 cursor_anchor: Anchor,
6467 new_position: Option<Point>,
6468 cx: &mut ViewContext<Self>,
6469 ) {
6470 if let Some(nav_history) = self.nav_history.as_mut() {
6471 let buffer = self.buffer.read(cx).read(cx);
6472 let cursor_position = cursor_anchor.to_point(&buffer);
6473 let scroll_state = self.scroll_manager.anchor();
6474 let scroll_top_row = scroll_state.top_row(&buffer);
6475 drop(buffer);
6476
6477 if let Some(new_position) = new_position {
6478 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
6479 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
6480 return;
6481 }
6482 }
6483
6484 nav_history.push(
6485 Some(NavigationData {
6486 cursor_anchor,
6487 cursor_position,
6488 scroll_anchor: scroll_state,
6489 scroll_top_row,
6490 }),
6491 cx,
6492 );
6493 }
6494 }
6495
6496 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
6497 let buffer = self.buffer.read(cx).snapshot(cx);
6498 let mut selection = self.selections.first::<usize>(cx);
6499 selection.set_head(buffer.len(), SelectionGoal::None);
6500 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6501 s.select(vec![selection]);
6502 });
6503 }
6504
6505 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
6506 let end = self.buffer.read(cx).read(cx).len();
6507 self.change_selections(None, cx, |s| {
6508 s.select_ranges(vec![0..end]);
6509 });
6510 }
6511
6512 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
6513 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6514 let mut selections = self.selections.all::<Point>(cx);
6515 let max_point = display_map.buffer_snapshot.max_point();
6516 for selection in &mut selections {
6517 let rows = selection.spanned_rows(true, &display_map);
6518 selection.start = Point::new(rows.start, 0);
6519 selection.end = cmp::min(max_point, Point::new(rows.end, 0));
6520 selection.reversed = false;
6521 }
6522 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6523 s.select(selections);
6524 });
6525 }
6526
6527 pub fn split_selection_into_lines(
6528 &mut self,
6529 _: &SplitSelectionIntoLines,
6530 cx: &mut ViewContext<Self>,
6531 ) {
6532 let mut to_unfold = Vec::new();
6533 let mut new_selection_ranges = Vec::new();
6534 {
6535 let selections = self.selections.all::<Point>(cx);
6536 let buffer = self.buffer.read(cx).read(cx);
6537 for selection in selections {
6538 for row in selection.start.row..selection.end.row {
6539 let cursor = Point::new(row, buffer.line_len(row));
6540 new_selection_ranges.push(cursor..cursor);
6541 }
6542 new_selection_ranges.push(selection.end..selection.end);
6543 to_unfold.push(selection.start..selection.end);
6544 }
6545 }
6546 self.unfold_ranges(to_unfold, true, true, cx);
6547 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6548 s.select_ranges(new_selection_ranges);
6549 });
6550 }
6551
6552 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
6553 self.add_selection(true, cx);
6554 }
6555
6556 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
6557 self.add_selection(false, cx);
6558 }
6559
6560 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
6561 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6562 let mut selections = self.selections.all::<Point>(cx);
6563 let text_layout_details = self.text_layout_details(cx);
6564 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
6565 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
6566 let range = oldest_selection.display_range(&display_map).sorted();
6567
6568 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
6569 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
6570 let positions = start_x.min(end_x)..start_x.max(end_x);
6571
6572 selections.clear();
6573 let mut stack = Vec::new();
6574 for row in range.start.row()..=range.end.row() {
6575 if let Some(selection) = self.selections.build_columnar_selection(
6576 &display_map,
6577 row,
6578 &positions,
6579 oldest_selection.reversed,
6580 &text_layout_details,
6581 ) {
6582 stack.push(selection.id);
6583 selections.push(selection);
6584 }
6585 }
6586
6587 if above {
6588 stack.reverse();
6589 }
6590
6591 AddSelectionsState { above, stack }
6592 });
6593
6594 let last_added_selection = *state.stack.last().unwrap();
6595 let mut new_selections = Vec::new();
6596 if above == state.above {
6597 let end_row = if above {
6598 0
6599 } else {
6600 display_map.max_point().row()
6601 };
6602
6603 'outer: for selection in selections {
6604 if selection.id == last_added_selection {
6605 let range = selection.display_range(&display_map).sorted();
6606 debug_assert_eq!(range.start.row(), range.end.row());
6607 let mut row = range.start.row();
6608 let positions =
6609 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
6610 px(start)..px(end)
6611 } else {
6612 let start_x =
6613 display_map.x_for_display_point(range.start, &text_layout_details);
6614 let end_x =
6615 display_map.x_for_display_point(range.end, &text_layout_details);
6616 start_x.min(end_x)..start_x.max(end_x)
6617 };
6618
6619 while row != end_row {
6620 if above {
6621 row -= 1;
6622 } else {
6623 row += 1;
6624 }
6625
6626 if let Some(new_selection) = self.selections.build_columnar_selection(
6627 &display_map,
6628 row,
6629 &positions,
6630 selection.reversed,
6631 &text_layout_details,
6632 ) {
6633 state.stack.push(new_selection.id);
6634 if above {
6635 new_selections.push(new_selection);
6636 new_selections.push(selection);
6637 } else {
6638 new_selections.push(selection);
6639 new_selections.push(new_selection);
6640 }
6641
6642 continue 'outer;
6643 }
6644 }
6645 }
6646
6647 new_selections.push(selection);
6648 }
6649 } else {
6650 new_selections = selections;
6651 new_selections.retain(|s| s.id != last_added_selection);
6652 state.stack.pop();
6653 }
6654
6655 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6656 s.select(new_selections);
6657 });
6658 if state.stack.len() > 1 {
6659 self.add_selections_state = Some(state);
6660 }
6661 }
6662
6663 pub fn select_next_match_internal(
6664 &mut self,
6665 display_map: &DisplaySnapshot,
6666 replace_newest: bool,
6667 autoscroll: Option<Autoscroll>,
6668 cx: &mut ViewContext<Self>,
6669 ) -> Result<()> {
6670 fn select_next_match_ranges(
6671 this: &mut Editor,
6672 range: Range<usize>,
6673 replace_newest: bool,
6674 auto_scroll: Option<Autoscroll>,
6675 cx: &mut ViewContext<Editor>,
6676 ) {
6677 this.unfold_ranges([range.clone()], false, true, cx);
6678 this.change_selections(auto_scroll, cx, |s| {
6679 if replace_newest {
6680 s.delete(s.newest_anchor().id);
6681 }
6682 s.insert_range(range.clone());
6683 });
6684 }
6685
6686 let buffer = &display_map.buffer_snapshot;
6687 let mut selections = self.selections.all::<usize>(cx);
6688 if let Some(mut select_next_state) = self.select_next_state.take() {
6689 let query = &select_next_state.query;
6690 if !select_next_state.done {
6691 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6692 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6693 let mut next_selected_range = None;
6694
6695 let bytes_after_last_selection =
6696 buffer.bytes_in_range(last_selection.end..buffer.len());
6697 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
6698 let query_matches = query
6699 .stream_find_iter(bytes_after_last_selection)
6700 .map(|result| (last_selection.end, result))
6701 .chain(
6702 query
6703 .stream_find_iter(bytes_before_first_selection)
6704 .map(|result| (0, result)),
6705 );
6706
6707 for (start_offset, query_match) in query_matches {
6708 let query_match = query_match.unwrap(); // can only fail due to I/O
6709 let offset_range =
6710 start_offset + query_match.start()..start_offset + query_match.end();
6711 let display_range = offset_range.start.to_display_point(&display_map)
6712 ..offset_range.end.to_display_point(&display_map);
6713
6714 if !select_next_state.wordwise
6715 || (!movement::is_inside_word(&display_map, display_range.start)
6716 && !movement::is_inside_word(&display_map, display_range.end))
6717 {
6718 // TODO: This is n^2, because we might check all the selections
6719 if !selections
6720 .iter()
6721 .any(|selection| selection.range().overlaps(&offset_range))
6722 {
6723 next_selected_range = Some(offset_range);
6724 break;
6725 }
6726 }
6727 }
6728
6729 if let Some(next_selected_range) = next_selected_range {
6730 select_next_match_ranges(
6731 self,
6732 next_selected_range,
6733 replace_newest,
6734 autoscroll,
6735 cx,
6736 );
6737 } else {
6738 select_next_state.done = true;
6739 }
6740 }
6741
6742 self.select_next_state = Some(select_next_state);
6743 } else {
6744 let mut only_carets = true;
6745 let mut same_text_selected = true;
6746 let mut selected_text = None;
6747
6748 let mut selections_iter = selections.iter().peekable();
6749 while let Some(selection) = selections_iter.next() {
6750 if selection.start != selection.end {
6751 only_carets = false;
6752 }
6753
6754 if same_text_selected {
6755 if selected_text.is_none() {
6756 selected_text =
6757 Some(buffer.text_for_range(selection.range()).collect::<String>());
6758 }
6759
6760 if let Some(next_selection) = selections_iter.peek() {
6761 if next_selection.range().len() == selection.range().len() {
6762 let next_selected_text = buffer
6763 .text_for_range(next_selection.range())
6764 .collect::<String>();
6765 if Some(next_selected_text) != selected_text {
6766 same_text_selected = false;
6767 selected_text = None;
6768 }
6769 } else {
6770 same_text_selected = false;
6771 selected_text = None;
6772 }
6773 }
6774 }
6775 }
6776
6777 if only_carets {
6778 for selection in &mut selections {
6779 let word_range = movement::surrounding_word(
6780 &display_map,
6781 selection.start.to_display_point(&display_map),
6782 );
6783 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6784 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6785 selection.goal = SelectionGoal::None;
6786 selection.reversed = false;
6787 select_next_match_ranges(
6788 self,
6789 selection.start..selection.end,
6790 replace_newest,
6791 autoscroll,
6792 cx,
6793 );
6794 }
6795
6796 if selections.len() == 1 {
6797 let selection = selections
6798 .last()
6799 .expect("ensured that there's only one selection");
6800 let query = buffer
6801 .text_for_range(selection.start..selection.end)
6802 .collect::<String>();
6803 let is_empty = query.is_empty();
6804 let select_state = SelectNextState {
6805 query: AhoCorasick::new(&[query])?,
6806 wordwise: true,
6807 done: is_empty,
6808 };
6809 self.select_next_state = Some(select_state);
6810 } else {
6811 self.select_next_state = None;
6812 }
6813 } else if let Some(selected_text) = selected_text {
6814 self.select_next_state = Some(SelectNextState {
6815 query: AhoCorasick::new(&[selected_text])?,
6816 wordwise: false,
6817 done: false,
6818 });
6819 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
6820 }
6821 }
6822 Ok(())
6823 }
6824
6825 pub fn select_all_matches(
6826 &mut self,
6827 _action: &SelectAllMatches,
6828 cx: &mut ViewContext<Self>,
6829 ) -> Result<()> {
6830 self.push_to_selection_history();
6831 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6832
6833 self.select_next_match_internal(&display_map, false, None, cx)?;
6834 let Some(select_next_state) = self.select_next_state.as_mut() else {
6835 return Ok(());
6836 };
6837 if select_next_state.done {
6838 return Ok(());
6839 }
6840
6841 let mut new_selections = self.selections.all::<usize>(cx);
6842
6843 let buffer = &display_map.buffer_snapshot;
6844 let query_matches = select_next_state
6845 .query
6846 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
6847
6848 for query_match in query_matches {
6849 let query_match = query_match.unwrap(); // can only fail due to I/O
6850 let offset_range = query_match.start()..query_match.end();
6851 let display_range = offset_range.start.to_display_point(&display_map)
6852 ..offset_range.end.to_display_point(&display_map);
6853
6854 if !select_next_state.wordwise
6855 || (!movement::is_inside_word(&display_map, display_range.start)
6856 && !movement::is_inside_word(&display_map, display_range.end))
6857 {
6858 self.selections.change_with(cx, |selections| {
6859 new_selections.push(Selection {
6860 id: selections.new_selection_id(),
6861 start: offset_range.start,
6862 end: offset_range.end,
6863 reversed: false,
6864 goal: SelectionGoal::None,
6865 });
6866 });
6867 }
6868 }
6869
6870 new_selections.sort_by_key(|selection| selection.start);
6871 let mut ix = 0;
6872 while ix + 1 < new_selections.len() {
6873 let current_selection = &new_selections[ix];
6874 let next_selection = &new_selections[ix + 1];
6875 if current_selection.range().overlaps(&next_selection.range()) {
6876 if current_selection.id < next_selection.id {
6877 new_selections.remove(ix + 1);
6878 } else {
6879 new_selections.remove(ix);
6880 }
6881 } else {
6882 ix += 1;
6883 }
6884 }
6885
6886 select_next_state.done = true;
6887 self.unfold_ranges(
6888 new_selections.iter().map(|selection| selection.range()),
6889 false,
6890 false,
6891 cx,
6892 );
6893 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
6894 selections.select(new_selections)
6895 });
6896
6897 Ok(())
6898 }
6899
6900 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
6901 self.push_to_selection_history();
6902 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6903 self.select_next_match_internal(
6904 &display_map,
6905 action.replace_newest,
6906 Some(Autoscroll::newest()),
6907 cx,
6908 )?;
6909 Ok(())
6910 }
6911
6912 pub fn select_previous(
6913 &mut self,
6914 action: &SelectPrevious,
6915 cx: &mut ViewContext<Self>,
6916 ) -> Result<()> {
6917 self.push_to_selection_history();
6918 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6919 let buffer = &display_map.buffer_snapshot;
6920 let mut selections = self.selections.all::<usize>(cx);
6921 if let Some(mut select_prev_state) = self.select_prev_state.take() {
6922 let query = &select_prev_state.query;
6923 if !select_prev_state.done {
6924 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6925 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6926 let mut next_selected_range = None;
6927 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
6928 let bytes_before_last_selection =
6929 buffer.reversed_bytes_in_range(0..last_selection.start);
6930 let bytes_after_first_selection =
6931 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
6932 let query_matches = query
6933 .stream_find_iter(bytes_before_last_selection)
6934 .map(|result| (last_selection.start, result))
6935 .chain(
6936 query
6937 .stream_find_iter(bytes_after_first_selection)
6938 .map(|result| (buffer.len(), result)),
6939 );
6940 for (end_offset, query_match) in query_matches {
6941 let query_match = query_match.unwrap(); // can only fail due to I/O
6942 let offset_range =
6943 end_offset - query_match.end()..end_offset - query_match.start();
6944 let display_range = offset_range.start.to_display_point(&display_map)
6945 ..offset_range.end.to_display_point(&display_map);
6946
6947 if !select_prev_state.wordwise
6948 || (!movement::is_inside_word(&display_map, display_range.start)
6949 && !movement::is_inside_word(&display_map, display_range.end))
6950 {
6951 next_selected_range = Some(offset_range);
6952 break;
6953 }
6954 }
6955
6956 if let Some(next_selected_range) = next_selected_range {
6957 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
6958 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6959 if action.replace_newest {
6960 s.delete(s.newest_anchor().id);
6961 }
6962 s.insert_range(next_selected_range);
6963 });
6964 } else {
6965 select_prev_state.done = true;
6966 }
6967 }
6968
6969 self.select_prev_state = Some(select_prev_state);
6970 } else {
6971 let mut only_carets = true;
6972 let mut same_text_selected = true;
6973 let mut selected_text = None;
6974
6975 let mut selections_iter = selections.iter().peekable();
6976 while let Some(selection) = selections_iter.next() {
6977 if selection.start != selection.end {
6978 only_carets = false;
6979 }
6980
6981 if same_text_selected {
6982 if selected_text.is_none() {
6983 selected_text =
6984 Some(buffer.text_for_range(selection.range()).collect::<String>());
6985 }
6986
6987 if let Some(next_selection) = selections_iter.peek() {
6988 if next_selection.range().len() == selection.range().len() {
6989 let next_selected_text = buffer
6990 .text_for_range(next_selection.range())
6991 .collect::<String>();
6992 if Some(next_selected_text) != selected_text {
6993 same_text_selected = false;
6994 selected_text = None;
6995 }
6996 } else {
6997 same_text_selected = false;
6998 selected_text = None;
6999 }
7000 }
7001 }
7002 }
7003
7004 if only_carets {
7005 for selection in &mut selections {
7006 let word_range = movement::surrounding_word(
7007 &display_map,
7008 selection.start.to_display_point(&display_map),
7009 );
7010 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7011 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7012 selection.goal = SelectionGoal::None;
7013 selection.reversed = false;
7014 }
7015 if selections.len() == 1 {
7016 let selection = selections
7017 .last()
7018 .expect("ensured that there's only one selection");
7019 let query = buffer
7020 .text_for_range(selection.start..selection.end)
7021 .collect::<String>();
7022 let is_empty = query.is_empty();
7023 let select_state = SelectNextState {
7024 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
7025 wordwise: true,
7026 done: is_empty,
7027 };
7028 self.select_prev_state = Some(select_state);
7029 } else {
7030 self.select_prev_state = None;
7031 }
7032
7033 self.unfold_ranges(
7034 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
7035 false,
7036 true,
7037 cx,
7038 );
7039 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7040 s.select(selections);
7041 });
7042 } else if let Some(selected_text) = selected_text {
7043 self.select_prev_state = Some(SelectNextState {
7044 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
7045 wordwise: false,
7046 done: false,
7047 });
7048 self.select_previous(action, cx)?;
7049 }
7050 }
7051 Ok(())
7052 }
7053
7054 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
7055 let text_layout_details = &self.text_layout_details(cx);
7056 self.transact(cx, |this, cx| {
7057 let mut selections = this.selections.all::<Point>(cx);
7058 let mut edits = Vec::new();
7059 let mut selection_edit_ranges = Vec::new();
7060 let mut last_toggled_row = None;
7061 let snapshot = this.buffer.read(cx).read(cx);
7062 let empty_str: Arc<str> = "".into();
7063 let mut suffixes_inserted = Vec::new();
7064
7065 fn comment_prefix_range(
7066 snapshot: &MultiBufferSnapshot,
7067 row: u32,
7068 comment_prefix: &str,
7069 comment_prefix_whitespace: &str,
7070 ) -> Range<Point> {
7071 let start = Point::new(row, snapshot.indent_size_for_line(row).len);
7072
7073 let mut line_bytes = snapshot
7074 .bytes_in_range(start..snapshot.max_point())
7075 .flatten()
7076 .copied();
7077
7078 // If this line currently begins with the line comment prefix, then record
7079 // the range containing the prefix.
7080 if line_bytes
7081 .by_ref()
7082 .take(comment_prefix.len())
7083 .eq(comment_prefix.bytes())
7084 {
7085 // Include any whitespace that matches the comment prefix.
7086 let matching_whitespace_len = line_bytes
7087 .zip(comment_prefix_whitespace.bytes())
7088 .take_while(|(a, b)| a == b)
7089 .count() as u32;
7090 let end = Point::new(
7091 start.row,
7092 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
7093 );
7094 start..end
7095 } else {
7096 start..start
7097 }
7098 }
7099
7100 fn comment_suffix_range(
7101 snapshot: &MultiBufferSnapshot,
7102 row: u32,
7103 comment_suffix: &str,
7104 comment_suffix_has_leading_space: bool,
7105 ) -> Range<Point> {
7106 let end = Point::new(row, snapshot.line_len(row));
7107 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
7108
7109 let mut line_end_bytes = snapshot
7110 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
7111 .flatten()
7112 .copied();
7113
7114 let leading_space_len = if suffix_start_column > 0
7115 && line_end_bytes.next() == Some(b' ')
7116 && comment_suffix_has_leading_space
7117 {
7118 1
7119 } else {
7120 0
7121 };
7122
7123 // If this line currently begins with the line comment prefix, then record
7124 // the range containing the prefix.
7125 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
7126 let start = Point::new(end.row, suffix_start_column - leading_space_len);
7127 start..end
7128 } else {
7129 end..end
7130 }
7131 }
7132
7133 // TODO: Handle selections that cross excerpts
7134 for selection in &mut selections {
7135 let start_column = snapshot.indent_size_for_line(selection.start.row).len;
7136 let language = if let Some(language) =
7137 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
7138 {
7139 language
7140 } else {
7141 continue;
7142 };
7143
7144 selection_edit_ranges.clear();
7145
7146 // If multiple selections contain a given row, avoid processing that
7147 // row more than once.
7148 let mut start_row = selection.start.row;
7149 if last_toggled_row == Some(start_row) {
7150 start_row += 1;
7151 }
7152 let end_row =
7153 if selection.end.row > selection.start.row && selection.end.column == 0 {
7154 selection.end.row - 1
7155 } else {
7156 selection.end.row
7157 };
7158 last_toggled_row = Some(end_row);
7159
7160 if start_row > end_row {
7161 continue;
7162 }
7163
7164 // If the language has line comments, toggle those.
7165 if let Some(full_comment_prefixes) = language
7166 .line_comment_prefixes()
7167 .filter(|prefixes| !prefixes.is_empty())
7168 {
7169 let first_prefix = full_comment_prefixes
7170 .first()
7171 .expect("prefixes is non-empty");
7172 let prefix_trimmed_lengths = full_comment_prefixes
7173 .iter()
7174 .map(|p| p.trim_end_matches(' ').len())
7175 .collect::<SmallVec<[usize; 4]>>();
7176
7177 let mut all_selection_lines_are_comments = true;
7178
7179 for row in start_row..=end_row {
7180 if start_row < end_row && snapshot.is_line_blank(row) {
7181 continue;
7182 }
7183
7184 let prefix_range = full_comment_prefixes
7185 .iter()
7186 .zip(prefix_trimmed_lengths.iter().copied())
7187 .map(|(prefix, trimmed_prefix_len)| {
7188 comment_prefix_range(
7189 snapshot.deref(),
7190 row,
7191 &prefix[..trimmed_prefix_len],
7192 &prefix[trimmed_prefix_len..],
7193 )
7194 })
7195 .max_by_key(|range| range.end.column - range.start.column)
7196 .expect("prefixes is non-empty");
7197
7198 if prefix_range.is_empty() {
7199 all_selection_lines_are_comments = false;
7200 }
7201
7202 selection_edit_ranges.push(prefix_range);
7203 }
7204
7205 if all_selection_lines_are_comments {
7206 edits.extend(
7207 selection_edit_ranges
7208 .iter()
7209 .cloned()
7210 .map(|range| (range, empty_str.clone())),
7211 );
7212 } else {
7213 let min_column = selection_edit_ranges
7214 .iter()
7215 .map(|range| range.start.column)
7216 .min()
7217 .unwrap_or(0);
7218 edits.extend(selection_edit_ranges.iter().map(|range| {
7219 let position = Point::new(range.start.row, min_column);
7220 (position..position, first_prefix.clone())
7221 }));
7222 }
7223 } else if let Some((full_comment_prefix, comment_suffix)) =
7224 language.block_comment_delimiters()
7225 {
7226 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
7227 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
7228 let prefix_range = comment_prefix_range(
7229 snapshot.deref(),
7230 start_row,
7231 comment_prefix,
7232 comment_prefix_whitespace,
7233 );
7234 let suffix_range = comment_suffix_range(
7235 snapshot.deref(),
7236 end_row,
7237 comment_suffix.trim_start_matches(' '),
7238 comment_suffix.starts_with(' '),
7239 );
7240
7241 if prefix_range.is_empty() || suffix_range.is_empty() {
7242 edits.push((
7243 prefix_range.start..prefix_range.start,
7244 full_comment_prefix.clone(),
7245 ));
7246 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
7247 suffixes_inserted.push((end_row, comment_suffix.len()));
7248 } else {
7249 edits.push((prefix_range, empty_str.clone()));
7250 edits.push((suffix_range, empty_str.clone()));
7251 }
7252 } else {
7253 continue;
7254 }
7255 }
7256
7257 drop(snapshot);
7258 this.buffer.update(cx, |buffer, cx| {
7259 buffer.edit(edits, None, cx);
7260 });
7261
7262 // Adjust selections so that they end before any comment suffixes that
7263 // were inserted.
7264 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
7265 let mut selections = this.selections.all::<Point>(cx);
7266 let snapshot = this.buffer.read(cx).read(cx);
7267 for selection in &mut selections {
7268 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
7269 match row.cmp(&selection.end.row) {
7270 Ordering::Less => {
7271 suffixes_inserted.next();
7272 continue;
7273 }
7274 Ordering::Greater => break,
7275 Ordering::Equal => {
7276 if selection.end.column == snapshot.line_len(row) {
7277 if selection.is_empty() {
7278 selection.start.column -= suffix_len as u32;
7279 }
7280 selection.end.column -= suffix_len as u32;
7281 }
7282 break;
7283 }
7284 }
7285 }
7286 }
7287
7288 drop(snapshot);
7289 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7290
7291 let selections = this.selections.all::<Point>(cx);
7292 let selections_on_single_row = selections.windows(2).all(|selections| {
7293 selections[0].start.row == selections[1].start.row
7294 && selections[0].end.row == selections[1].end.row
7295 && selections[0].start.row == selections[0].end.row
7296 });
7297 let selections_selecting = selections
7298 .iter()
7299 .any(|selection| selection.start != selection.end);
7300 let advance_downwards = action.advance_downwards
7301 && selections_on_single_row
7302 && !selections_selecting
7303 && this.mode != EditorMode::SingleLine;
7304
7305 if advance_downwards {
7306 let snapshot = this.buffer.read(cx).snapshot(cx);
7307
7308 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7309 s.move_cursors_with(|display_snapshot, display_point, _| {
7310 let mut point = display_point.to_point(display_snapshot);
7311 point.row += 1;
7312 point = snapshot.clip_point(point, Bias::Left);
7313 let display_point = point.to_display_point(display_snapshot);
7314 let goal = SelectionGoal::HorizontalPosition(
7315 display_snapshot
7316 .x_for_display_point(display_point, &text_layout_details)
7317 .into(),
7318 );
7319 (display_point, goal)
7320 })
7321 });
7322 }
7323 });
7324 }
7325
7326 pub fn select_larger_syntax_node(
7327 &mut self,
7328 _: &SelectLargerSyntaxNode,
7329 cx: &mut ViewContext<Self>,
7330 ) {
7331 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7332 let buffer = self.buffer.read(cx).snapshot(cx);
7333 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
7334
7335 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7336 let mut selected_larger_node = false;
7337 let new_selections = old_selections
7338 .iter()
7339 .map(|selection| {
7340 let old_range = selection.start..selection.end;
7341 let mut new_range = old_range.clone();
7342 while let Some(containing_range) =
7343 buffer.range_for_syntax_ancestor(new_range.clone())
7344 {
7345 new_range = containing_range;
7346 if !display_map.intersects_fold(new_range.start)
7347 && !display_map.intersects_fold(new_range.end)
7348 {
7349 break;
7350 }
7351 }
7352
7353 selected_larger_node |= new_range != old_range;
7354 Selection {
7355 id: selection.id,
7356 start: new_range.start,
7357 end: new_range.end,
7358 goal: SelectionGoal::None,
7359 reversed: selection.reversed,
7360 }
7361 })
7362 .collect::<Vec<_>>();
7363
7364 if selected_larger_node {
7365 stack.push(old_selections);
7366 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7367 s.select(new_selections);
7368 });
7369 }
7370 self.select_larger_syntax_node_stack = stack;
7371 }
7372
7373 pub fn select_smaller_syntax_node(
7374 &mut self,
7375 _: &SelectSmallerSyntaxNode,
7376 cx: &mut ViewContext<Self>,
7377 ) {
7378 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7379 if let Some(selections) = stack.pop() {
7380 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7381 s.select(selections.to_vec());
7382 });
7383 }
7384 self.select_larger_syntax_node_stack = stack;
7385 }
7386
7387 pub fn move_to_enclosing_bracket(
7388 &mut self,
7389 _: &MoveToEnclosingBracket,
7390 cx: &mut ViewContext<Self>,
7391 ) {
7392 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7393 s.move_offsets_with(|snapshot, selection| {
7394 let Some(enclosing_bracket_ranges) =
7395 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
7396 else {
7397 return;
7398 };
7399
7400 let mut best_length = usize::MAX;
7401 let mut best_inside = false;
7402 let mut best_in_bracket_range = false;
7403 let mut best_destination = None;
7404 for (open, close) in enclosing_bracket_ranges {
7405 let close = close.to_inclusive();
7406 let length = close.end() - open.start;
7407 let inside = selection.start >= open.end && selection.end <= *close.start();
7408 let in_bracket_range = open.to_inclusive().contains(&selection.head())
7409 || close.contains(&selection.head());
7410
7411 // If best is next to a bracket and current isn't, skip
7412 if !in_bracket_range && best_in_bracket_range {
7413 continue;
7414 }
7415
7416 // Prefer smaller lengths unless best is inside and current isn't
7417 if length > best_length && (best_inside || !inside) {
7418 continue;
7419 }
7420
7421 best_length = length;
7422 best_inside = inside;
7423 best_in_bracket_range = in_bracket_range;
7424 best_destination = Some(
7425 if close.contains(&selection.start) && close.contains(&selection.end) {
7426 if inside {
7427 open.end
7428 } else {
7429 open.start
7430 }
7431 } else {
7432 if inside {
7433 *close.start()
7434 } else {
7435 *close.end()
7436 }
7437 },
7438 );
7439 }
7440
7441 if let Some(destination) = best_destination {
7442 selection.collapse_to(destination, SelectionGoal::None);
7443 }
7444 })
7445 });
7446 }
7447
7448 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
7449 self.end_selection(cx);
7450 self.selection_history.mode = SelectionHistoryMode::Undoing;
7451 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
7452 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7453 self.select_next_state = entry.select_next_state;
7454 self.select_prev_state = entry.select_prev_state;
7455 self.add_selections_state = entry.add_selections_state;
7456 self.request_autoscroll(Autoscroll::newest(), cx);
7457 }
7458 self.selection_history.mode = SelectionHistoryMode::Normal;
7459 }
7460
7461 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
7462 self.end_selection(cx);
7463 self.selection_history.mode = SelectionHistoryMode::Redoing;
7464 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
7465 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7466 self.select_next_state = entry.select_next_state;
7467 self.select_prev_state = entry.select_prev_state;
7468 self.add_selections_state = entry.add_selections_state;
7469 self.request_autoscroll(Autoscroll::newest(), cx);
7470 }
7471 self.selection_history.mode = SelectionHistoryMode::Normal;
7472 }
7473
7474 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
7475 let selections = self.selections.disjoint_anchors();
7476
7477 let lines = if action.lines == 0 { 3 } else { action.lines };
7478
7479 self.buffer.update(cx, |buffer, cx| {
7480 buffer.expand_excerpts(
7481 selections
7482 .into_iter()
7483 .map(|selection| selection.head().excerpt_id)
7484 .dedup(),
7485 lines,
7486 cx,
7487 )
7488 })
7489 }
7490
7491 pub fn expand_excerpt(&mut self, excerpt: ExcerptId, cx: &mut ViewContext<Self>) {
7492 self.buffer
7493 .update(cx, |buffer, cx| buffer.expand_excerpts([excerpt], 3, cx))
7494 }
7495
7496 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
7497 self.go_to_diagnostic_impl(Direction::Next, cx)
7498 }
7499
7500 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
7501 self.go_to_diagnostic_impl(Direction::Prev, cx)
7502 }
7503
7504 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
7505 let buffer = self.buffer.read(cx).snapshot(cx);
7506 let selection = self.selections.newest::<usize>(cx);
7507
7508 // If there is an active Diagnostic Popover jump to its diagnostic instead.
7509 if direction == Direction::Next {
7510 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
7511 let (group_id, jump_to) = popover.activation_info();
7512 if self.activate_diagnostics(group_id, cx) {
7513 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7514 let mut new_selection = s.newest_anchor().clone();
7515 new_selection.collapse_to(jump_to, SelectionGoal::None);
7516 s.select_anchors(vec![new_selection.clone()]);
7517 });
7518 }
7519 return;
7520 }
7521 }
7522
7523 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
7524 active_diagnostics
7525 .primary_range
7526 .to_offset(&buffer)
7527 .to_inclusive()
7528 });
7529 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
7530 if active_primary_range.contains(&selection.head()) {
7531 *active_primary_range.end()
7532 } else {
7533 selection.head()
7534 }
7535 } else {
7536 selection.head()
7537 };
7538 let snapshot = self.snapshot(cx);
7539 loop {
7540 let mut diagnostics = if direction == Direction::Prev {
7541 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
7542 } else {
7543 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
7544 }
7545 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
7546 let group = diagnostics.find_map(|entry| {
7547 if entry.diagnostic.is_primary
7548 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
7549 && !entry.range.is_empty()
7550 && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
7551 && !entry.range.contains(&search_start)
7552 {
7553 Some((entry.range, entry.diagnostic.group_id))
7554 } else {
7555 None
7556 }
7557 });
7558
7559 if let Some((primary_range, group_id)) = group {
7560 if self.activate_diagnostics(group_id, cx) {
7561 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7562 s.select(vec![Selection {
7563 id: selection.id,
7564 start: primary_range.start,
7565 end: primary_range.start,
7566 reversed: false,
7567 goal: SelectionGoal::None,
7568 }]);
7569 });
7570 }
7571 break;
7572 } else {
7573 // Cycle around to the start of the buffer, potentially moving back to the start of
7574 // the currently active diagnostic.
7575 active_primary_range.take();
7576 if direction == Direction::Prev {
7577 if search_start == buffer.len() {
7578 break;
7579 } else {
7580 search_start = buffer.len();
7581 }
7582 } else if search_start == 0 {
7583 break;
7584 } else {
7585 search_start = 0;
7586 }
7587 }
7588 }
7589 }
7590
7591 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
7592 let snapshot = self
7593 .display_map
7594 .update(cx, |display_map, cx| display_map.snapshot(cx));
7595 let selection = self.selections.newest::<Point>(cx);
7596
7597 if !self.seek_in_direction(
7598 &snapshot,
7599 selection.head(),
7600 false,
7601 snapshot
7602 .buffer_snapshot
7603 .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
7604 cx,
7605 ) {
7606 let wrapped_point = Point::zero();
7607 self.seek_in_direction(
7608 &snapshot,
7609 wrapped_point,
7610 true,
7611 snapshot
7612 .buffer_snapshot
7613 .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
7614 cx,
7615 );
7616 }
7617 }
7618
7619 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
7620 let snapshot = self
7621 .display_map
7622 .update(cx, |display_map, cx| display_map.snapshot(cx));
7623 let selection = self.selections.newest::<Point>(cx);
7624
7625 if !self.seek_in_direction(
7626 &snapshot,
7627 selection.head(),
7628 false,
7629 snapshot
7630 .buffer_snapshot
7631 .git_diff_hunks_in_range_rev(0..selection.head().row),
7632 cx,
7633 ) {
7634 let wrapped_point = snapshot.buffer_snapshot.max_point();
7635 self.seek_in_direction(
7636 &snapshot,
7637 wrapped_point,
7638 true,
7639 snapshot
7640 .buffer_snapshot
7641 .git_diff_hunks_in_range_rev(0..wrapped_point.row),
7642 cx,
7643 );
7644 }
7645 }
7646
7647 fn seek_in_direction(
7648 &mut self,
7649 snapshot: &DisplaySnapshot,
7650 initial_point: Point,
7651 is_wrapped: bool,
7652 hunks: impl Iterator<Item = DiffHunk<u32>>,
7653 cx: &mut ViewContext<Editor>,
7654 ) -> bool {
7655 let display_point = initial_point.to_display_point(snapshot);
7656 let mut hunks = hunks
7657 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
7658 .filter(|hunk| {
7659 if is_wrapped {
7660 true
7661 } else {
7662 !hunk.contains_display_row(display_point.row())
7663 }
7664 })
7665 .dedup();
7666
7667 if let Some(hunk) = hunks.next() {
7668 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7669 let row = hunk.start_display_row();
7670 let point = DisplayPoint::new(row, 0);
7671 s.select_display_ranges([point..point]);
7672 });
7673
7674 true
7675 } else {
7676 false
7677 }
7678 }
7679
7680 pub fn go_to_definition(
7681 &mut self,
7682 _: &GoToDefinition,
7683 cx: &mut ViewContext<Self>,
7684 ) -> Task<Result<bool>> {
7685 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
7686 }
7687
7688 pub fn go_to_implementation(
7689 &mut self,
7690 _: &GoToImplementation,
7691 cx: &mut ViewContext<Self>,
7692 ) -> Task<Result<bool>> {
7693 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
7694 }
7695
7696 pub fn go_to_implementation_split(
7697 &mut self,
7698 _: &GoToImplementationSplit,
7699 cx: &mut ViewContext<Self>,
7700 ) -> Task<Result<bool>> {
7701 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
7702 }
7703
7704 pub fn go_to_type_definition(
7705 &mut self,
7706 _: &GoToTypeDefinition,
7707 cx: &mut ViewContext<Self>,
7708 ) -> Task<Result<bool>> {
7709 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
7710 }
7711
7712 pub fn go_to_definition_split(
7713 &mut self,
7714 _: &GoToDefinitionSplit,
7715 cx: &mut ViewContext<Self>,
7716 ) -> Task<Result<bool>> {
7717 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
7718 }
7719
7720 pub fn go_to_type_definition_split(
7721 &mut self,
7722 _: &GoToTypeDefinitionSplit,
7723 cx: &mut ViewContext<Self>,
7724 ) -> Task<Result<bool>> {
7725 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
7726 }
7727
7728 fn go_to_definition_of_kind(
7729 &mut self,
7730 kind: GotoDefinitionKind,
7731 split: bool,
7732 cx: &mut ViewContext<Self>,
7733 ) -> Task<Result<bool>> {
7734 let Some(workspace) = self.workspace() else {
7735 return Task::ready(Ok(false));
7736 };
7737 let buffer = self.buffer.read(cx);
7738 let head = self.selections.newest::<usize>(cx).head();
7739 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
7740 text_anchor
7741 } else {
7742 return Task::ready(Ok(false));
7743 };
7744
7745 let project = workspace.read(cx).project().clone();
7746 let definitions = project.update(cx, |project, cx| match kind {
7747 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
7748 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
7749 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
7750 });
7751
7752 cx.spawn(|editor, mut cx| async move {
7753 let definitions = definitions.await?;
7754 let navigated = editor
7755 .update(&mut cx, |editor, cx| {
7756 editor.navigate_to_hover_links(
7757 Some(kind),
7758 definitions
7759 .into_iter()
7760 .filter(|location| {
7761 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
7762 })
7763 .map(HoverLink::Text)
7764 .collect::<Vec<_>>(),
7765 split,
7766 cx,
7767 )
7768 })?
7769 .await?;
7770 anyhow::Ok(navigated)
7771 })
7772 }
7773
7774 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
7775 let position = self.selections.newest_anchor().head();
7776 let Some((buffer, buffer_position)) =
7777 self.buffer.read(cx).text_anchor_for_position(position, cx)
7778 else {
7779 return;
7780 };
7781
7782 cx.spawn(|editor, mut cx| async move {
7783 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
7784 editor.update(&mut cx, |_, cx| {
7785 cx.open_url(&url);
7786 })
7787 } else {
7788 Ok(())
7789 }
7790 })
7791 .detach();
7792 }
7793
7794 pub(crate) fn navigate_to_hover_links(
7795 &mut self,
7796 kind: Option<GotoDefinitionKind>,
7797 mut definitions: Vec<HoverLink>,
7798 split: bool,
7799 cx: &mut ViewContext<Editor>,
7800 ) -> Task<Result<bool>> {
7801 // If there is one definition, just open it directly
7802 if definitions.len() == 1 {
7803 let definition = definitions.pop().unwrap();
7804 let target_task = match definition {
7805 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7806 HoverLink::InlayHint(lsp_location, server_id) => {
7807 self.compute_target_location(lsp_location, server_id, cx)
7808 }
7809 HoverLink::Url(url) => {
7810 cx.open_url(&url);
7811 Task::ready(Ok(None))
7812 }
7813 };
7814 cx.spawn(|editor, mut cx| async move {
7815 let target = target_task.await.context("target resolution task")?;
7816 if let Some(target) = target {
7817 editor.update(&mut cx, |editor, cx| {
7818 let Some(workspace) = editor.workspace() else {
7819 return false;
7820 };
7821 let pane = workspace.read(cx).active_pane().clone();
7822
7823 let range = target.range.to_offset(target.buffer.read(cx));
7824 let range = editor.range_for_match(&range);
7825 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
7826 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
7827 s.select_ranges([range]);
7828 });
7829 } else {
7830 cx.window_context().defer(move |cx| {
7831 let target_editor: View<Self> =
7832 workspace.update(cx, |workspace, cx| {
7833 let pane = if split {
7834 workspace.adjacent_pane(cx)
7835 } else {
7836 workspace.active_pane().clone()
7837 };
7838
7839 workspace.open_project_item(pane, target.buffer.clone(), cx)
7840 });
7841 target_editor.update(cx, |target_editor, cx| {
7842 // When selecting a definition in a different buffer, disable the nav history
7843 // to avoid creating a history entry at the previous cursor location.
7844 pane.update(cx, |pane, _| pane.disable_history());
7845 target_editor.change_selections(
7846 Some(Autoscroll::focused()),
7847 cx,
7848 |s| {
7849 s.select_ranges([range]);
7850 },
7851 );
7852 pane.update(cx, |pane, _| pane.enable_history());
7853 });
7854 });
7855 }
7856 true
7857 })
7858 } else {
7859 Ok(false)
7860 }
7861 })
7862 } else if !definitions.is_empty() {
7863 let replica_id = self.replica_id(cx);
7864 cx.spawn(|editor, mut cx| async move {
7865 let (title, location_tasks, workspace) = editor
7866 .update(&mut cx, |editor, cx| {
7867 let tab_kind = match kind {
7868 Some(GotoDefinitionKind::Implementation) => "Implementations",
7869 _ => "Definitions",
7870 };
7871 let title = definitions
7872 .iter()
7873 .find_map(|definition| match definition {
7874 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
7875 let buffer = origin.buffer.read(cx);
7876 format!(
7877 "{} for {}",
7878 tab_kind,
7879 buffer
7880 .text_for_range(origin.range.clone())
7881 .collect::<String>()
7882 )
7883 }),
7884 HoverLink::InlayHint(_, _) => None,
7885 HoverLink::Url(_) => None,
7886 })
7887 .unwrap_or(tab_kind.to_string());
7888 let location_tasks = definitions
7889 .into_iter()
7890 .map(|definition| match definition {
7891 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7892 HoverLink::InlayHint(lsp_location, server_id) => {
7893 editor.compute_target_location(lsp_location, server_id, cx)
7894 }
7895 HoverLink::Url(_) => Task::ready(Ok(None)),
7896 })
7897 .collect::<Vec<_>>();
7898 (title, location_tasks, editor.workspace().clone())
7899 })
7900 .context("location tasks preparation")?;
7901
7902 let locations = futures::future::join_all(location_tasks)
7903 .await
7904 .into_iter()
7905 .filter_map(|location| location.transpose())
7906 .collect::<Result<_>>()
7907 .context("location tasks")?;
7908
7909 let Some(workspace) = workspace else {
7910 return Ok(false);
7911 };
7912 let opened = workspace
7913 .update(&mut cx, |workspace, cx| {
7914 Self::open_locations_in_multibuffer(
7915 workspace, locations, replica_id, title, split, cx,
7916 )
7917 })
7918 .ok();
7919
7920 anyhow::Ok(opened.is_some())
7921 })
7922 } else {
7923 Task::ready(Ok(false))
7924 }
7925 }
7926
7927 fn compute_target_location(
7928 &self,
7929 lsp_location: lsp::Location,
7930 server_id: LanguageServerId,
7931 cx: &mut ViewContext<Editor>,
7932 ) -> Task<anyhow::Result<Option<Location>>> {
7933 let Some(project) = self.project.clone() else {
7934 return Task::Ready(Some(Ok(None)));
7935 };
7936
7937 cx.spawn(move |editor, mut cx| async move {
7938 let location_task = editor.update(&mut cx, |editor, cx| {
7939 project.update(cx, |project, cx| {
7940 let language_server_name =
7941 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
7942 project
7943 .language_server_for_buffer(buffer.read(cx), server_id, cx)
7944 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
7945 });
7946 language_server_name.map(|language_server_name| {
7947 project.open_local_buffer_via_lsp(
7948 lsp_location.uri.clone(),
7949 server_id,
7950 language_server_name,
7951 cx,
7952 )
7953 })
7954 })
7955 })?;
7956 let location = match location_task {
7957 Some(task) => Some({
7958 let target_buffer_handle = task.await.context("open local buffer")?;
7959 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
7960 let target_start = target_buffer
7961 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
7962 let target_end = target_buffer
7963 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
7964 target_buffer.anchor_after(target_start)
7965 ..target_buffer.anchor_before(target_end)
7966 })?;
7967 Location {
7968 buffer: target_buffer_handle,
7969 range,
7970 }
7971 }),
7972 None => None,
7973 };
7974 Ok(location)
7975 })
7976 }
7977
7978 pub fn find_all_references(
7979 &mut self,
7980 _: &FindAllReferences,
7981 cx: &mut ViewContext<Self>,
7982 ) -> Option<Task<Result<()>>> {
7983 let multi_buffer = self.buffer.read(cx);
7984 let selection = self.selections.newest::<usize>(cx);
7985 let head = selection.head();
7986
7987 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
7988 let head_anchor = multi_buffer_snapshot.anchor_at(
7989 head,
7990 if head < selection.tail() {
7991 Bias::Right
7992 } else {
7993 Bias::Left
7994 },
7995 );
7996
7997 match self
7998 .find_all_references_task_sources
7999 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
8000 {
8001 Ok(_) => {
8002 log::info!(
8003 "Ignoring repeated FindAllReferences invocation with the position of already running task"
8004 );
8005 return None;
8006 }
8007 Err(i) => {
8008 self.find_all_references_task_sources.insert(i, head_anchor);
8009 }
8010 }
8011
8012 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
8013 let replica_id = self.replica_id(cx);
8014 let workspace = self.workspace()?;
8015 let project = workspace.read(cx).project().clone();
8016 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
8017 Some(cx.spawn(|editor, mut cx| async move {
8018 let _cleanup = defer({
8019 let mut cx = cx.clone();
8020 move || {
8021 let _ = editor.update(&mut cx, |editor, _| {
8022 if let Ok(i) =
8023 editor
8024 .find_all_references_task_sources
8025 .binary_search_by(|anchor| {
8026 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
8027 })
8028 {
8029 editor.find_all_references_task_sources.remove(i);
8030 }
8031 });
8032 }
8033 });
8034
8035 let locations = references.await?;
8036 if locations.is_empty() {
8037 return anyhow::Ok(());
8038 }
8039
8040 workspace.update(&mut cx, |workspace, cx| {
8041 let title = locations
8042 .first()
8043 .as_ref()
8044 .map(|location| {
8045 let buffer = location.buffer.read(cx);
8046 format!(
8047 "References to `{}`",
8048 buffer
8049 .text_for_range(location.range.clone())
8050 .collect::<String>()
8051 )
8052 })
8053 .unwrap();
8054 Self::open_locations_in_multibuffer(
8055 workspace, locations, replica_id, title, false, cx,
8056 );
8057 })
8058 }))
8059 }
8060
8061 /// Opens a multibuffer with the given project locations in it
8062 pub fn open_locations_in_multibuffer(
8063 workspace: &mut Workspace,
8064 mut locations: Vec<Location>,
8065 replica_id: ReplicaId,
8066 title: String,
8067 split: bool,
8068 cx: &mut ViewContext<Workspace>,
8069 ) {
8070 // If there are multiple definitions, open them in a multibuffer
8071 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
8072 let mut locations = locations.into_iter().peekable();
8073 let mut ranges_to_highlight = Vec::new();
8074 let capability = workspace.project().read(cx).capability();
8075
8076 let excerpt_buffer = cx.new_model(|cx| {
8077 let mut multibuffer = MultiBuffer::new(replica_id, capability);
8078 while let Some(location) = locations.next() {
8079 let buffer = location.buffer.read(cx);
8080 let mut ranges_for_buffer = Vec::new();
8081 let range = location.range.to_offset(buffer);
8082 ranges_for_buffer.push(range.clone());
8083
8084 while let Some(next_location) = locations.peek() {
8085 if next_location.buffer == location.buffer {
8086 ranges_for_buffer.push(next_location.range.to_offset(buffer));
8087 locations.next();
8088 } else {
8089 break;
8090 }
8091 }
8092
8093 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
8094 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
8095 location.buffer.clone(),
8096 ranges_for_buffer,
8097 DEFAULT_MULTIBUFFER_CONTEXT,
8098 cx,
8099 ))
8100 }
8101
8102 multibuffer.with_title(title)
8103 });
8104
8105 let editor = cx.new_view(|cx| {
8106 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
8107 });
8108 editor.update(cx, |editor, cx| {
8109 editor.highlight_background::<Self>(
8110 &ranges_to_highlight,
8111 |theme| theme.editor_highlighted_line_background,
8112 cx,
8113 );
8114 });
8115
8116 let item = Box::new(editor);
8117 let item_id = item.item_id();
8118
8119 if split {
8120 workspace.split_item(SplitDirection::Right, item.clone(), cx);
8121 } else {
8122 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
8123 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
8124 pane.close_current_preview_item(cx)
8125 } else {
8126 None
8127 }
8128 });
8129 workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
8130 }
8131 workspace.active_pane().update(cx, |pane, cx| {
8132 pane.set_preview_item_id(Some(item_id), cx);
8133 });
8134 }
8135
8136 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8137 use language::ToOffset as _;
8138
8139 let project = self.project.clone()?;
8140 let selection = self.selections.newest_anchor().clone();
8141 let (cursor_buffer, cursor_buffer_position) = self
8142 .buffer
8143 .read(cx)
8144 .text_anchor_for_position(selection.head(), cx)?;
8145 let (tail_buffer, cursor_buffer_position_end) = self
8146 .buffer
8147 .read(cx)
8148 .text_anchor_for_position(selection.tail(), cx)?;
8149 if tail_buffer != cursor_buffer {
8150 return None;
8151 }
8152
8153 let snapshot = cursor_buffer.read(cx).snapshot();
8154 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
8155 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
8156 let prepare_rename = project.update(cx, |project, cx| {
8157 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
8158 });
8159 drop(snapshot);
8160
8161 Some(cx.spawn(|this, mut cx| async move {
8162 let rename_range = if let Some(range) = prepare_rename.await? {
8163 Some(range)
8164 } else {
8165 this.update(&mut cx, |this, cx| {
8166 let buffer = this.buffer.read(cx).snapshot(cx);
8167 let mut buffer_highlights = this
8168 .document_highlights_for_position(selection.head(), &buffer)
8169 .filter(|highlight| {
8170 highlight.start.excerpt_id == selection.head().excerpt_id
8171 && highlight.end.excerpt_id == selection.head().excerpt_id
8172 });
8173 buffer_highlights
8174 .next()
8175 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
8176 })?
8177 };
8178 if let Some(rename_range) = rename_range {
8179 this.update(&mut cx, |this, cx| {
8180 let snapshot = cursor_buffer.read(cx).snapshot();
8181 let rename_buffer_range = rename_range.to_offset(&snapshot);
8182 let cursor_offset_in_rename_range =
8183 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
8184 let cursor_offset_in_rename_range_end =
8185 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
8186
8187 this.take_rename(false, cx);
8188 let buffer = this.buffer.read(cx).read(cx);
8189 let cursor_offset = selection.head().to_offset(&buffer);
8190 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
8191 let rename_end = rename_start + rename_buffer_range.len();
8192 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
8193 let mut old_highlight_id = None;
8194 let old_name: Arc<str> = buffer
8195 .chunks(rename_start..rename_end, true)
8196 .map(|chunk| {
8197 if old_highlight_id.is_none() {
8198 old_highlight_id = chunk.syntax_highlight_id;
8199 }
8200 chunk.text
8201 })
8202 .collect::<String>()
8203 .into();
8204
8205 drop(buffer);
8206
8207 // Position the selection in the rename editor so that it matches the current selection.
8208 this.show_local_selections = false;
8209 let rename_editor = cx.new_view(|cx| {
8210 let mut editor = Editor::single_line(cx);
8211 editor.buffer.update(cx, |buffer, cx| {
8212 buffer.edit([(0..0, old_name.clone())], None, cx)
8213 });
8214 let rename_selection_range = match cursor_offset_in_rename_range
8215 .cmp(&cursor_offset_in_rename_range_end)
8216 {
8217 Ordering::Equal => {
8218 editor.select_all(&SelectAll, cx);
8219 return editor;
8220 }
8221 Ordering::Less => {
8222 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
8223 }
8224 Ordering::Greater => {
8225 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
8226 }
8227 };
8228 if rename_selection_range.end > old_name.len() {
8229 editor.select_all(&SelectAll, cx);
8230 } else {
8231 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
8232 s.select_ranges([rename_selection_range]);
8233 });
8234 }
8235 editor
8236 });
8237
8238 let write_highlights =
8239 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
8240 let read_highlights =
8241 this.clear_background_highlights::<DocumentHighlightRead>(cx);
8242 let ranges = write_highlights
8243 .iter()
8244 .flat_map(|(_, ranges)| ranges.iter())
8245 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
8246 .cloned()
8247 .collect();
8248
8249 this.highlight_text::<Rename>(
8250 ranges,
8251 HighlightStyle {
8252 fade_out: Some(0.6),
8253 ..Default::default()
8254 },
8255 cx,
8256 );
8257 let rename_focus_handle = rename_editor.focus_handle(cx);
8258 cx.focus(&rename_focus_handle);
8259 let block_id = this.insert_blocks(
8260 [BlockProperties {
8261 style: BlockStyle::Flex,
8262 position: range.start,
8263 height: 1,
8264 render: Box::new({
8265 let rename_editor = rename_editor.clone();
8266 move |cx: &mut BlockContext| {
8267 let mut text_style = cx.editor_style.text.clone();
8268 if let Some(highlight_style) = old_highlight_id
8269 .and_then(|h| h.style(&cx.editor_style.syntax))
8270 {
8271 text_style = text_style.highlight(highlight_style);
8272 }
8273 div()
8274 .pl(cx.anchor_x)
8275 .child(EditorElement::new(
8276 &rename_editor,
8277 EditorStyle {
8278 background: cx.theme().system().transparent,
8279 local_player: cx.editor_style.local_player,
8280 text: text_style,
8281 scrollbar_width: cx.editor_style.scrollbar_width,
8282 syntax: cx.editor_style.syntax.clone(),
8283 status: cx.editor_style.status.clone(),
8284 inlay_hints_style: HighlightStyle {
8285 color: Some(cx.theme().status().hint),
8286 font_weight: Some(FontWeight::BOLD),
8287 ..HighlightStyle::default()
8288 },
8289 suggestions_style: HighlightStyle {
8290 color: Some(cx.theme().status().predictive),
8291 ..HighlightStyle::default()
8292 },
8293 },
8294 ))
8295 .into_any_element()
8296 }
8297 }),
8298 disposition: BlockDisposition::Below,
8299 }],
8300 Some(Autoscroll::fit()),
8301 cx,
8302 )[0];
8303 this.pending_rename = Some(RenameState {
8304 range,
8305 old_name,
8306 editor: rename_editor,
8307 block_id,
8308 });
8309 })?;
8310 }
8311
8312 Ok(())
8313 }))
8314 }
8315
8316 pub fn confirm_rename(
8317 &mut self,
8318 _: &ConfirmRename,
8319 cx: &mut ViewContext<Self>,
8320 ) -> Option<Task<Result<()>>> {
8321 let rename = self.take_rename(false, cx)?;
8322 let workspace = self.workspace()?;
8323 let (start_buffer, start) = self
8324 .buffer
8325 .read(cx)
8326 .text_anchor_for_position(rename.range.start, cx)?;
8327 let (end_buffer, end) = self
8328 .buffer
8329 .read(cx)
8330 .text_anchor_for_position(rename.range.end, cx)?;
8331 if start_buffer != end_buffer {
8332 return None;
8333 }
8334
8335 let buffer = start_buffer;
8336 let range = start..end;
8337 let old_name = rename.old_name;
8338 let new_name = rename.editor.read(cx).text(cx);
8339
8340 let rename = workspace
8341 .read(cx)
8342 .project()
8343 .clone()
8344 .update(cx, |project, cx| {
8345 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
8346 });
8347 let workspace = workspace.downgrade();
8348
8349 Some(cx.spawn(|editor, mut cx| async move {
8350 let project_transaction = rename.await?;
8351 Self::open_project_transaction(
8352 &editor,
8353 workspace,
8354 project_transaction,
8355 format!("Rename: {} → {}", old_name, new_name),
8356 cx.clone(),
8357 )
8358 .await?;
8359
8360 editor.update(&mut cx, |editor, cx| {
8361 editor.refresh_document_highlights(cx);
8362 })?;
8363 Ok(())
8364 }))
8365 }
8366
8367 fn take_rename(
8368 &mut self,
8369 moving_cursor: bool,
8370 cx: &mut ViewContext<Self>,
8371 ) -> Option<RenameState> {
8372 let rename = self.pending_rename.take()?;
8373 if rename.editor.focus_handle(cx).is_focused(cx) {
8374 cx.focus(&self.focus_handle);
8375 }
8376
8377 self.remove_blocks(
8378 [rename.block_id].into_iter().collect(),
8379 Some(Autoscroll::fit()),
8380 cx,
8381 );
8382 self.clear_highlights::<Rename>(cx);
8383 self.show_local_selections = true;
8384
8385 if moving_cursor {
8386 let rename_editor = rename.editor.read(cx);
8387 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
8388
8389 // Update the selection to match the position of the selection inside
8390 // the rename editor.
8391 let snapshot = self.buffer.read(cx).read(cx);
8392 let rename_range = rename.range.to_offset(&snapshot);
8393 let cursor_in_editor = snapshot
8394 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
8395 .min(rename_range.end);
8396 drop(snapshot);
8397
8398 self.change_selections(None, cx, |s| {
8399 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
8400 });
8401 } else {
8402 self.refresh_document_highlights(cx);
8403 }
8404
8405 Some(rename)
8406 }
8407
8408 pub fn pending_rename(&self) -> Option<&RenameState> {
8409 self.pending_rename.as_ref()
8410 }
8411
8412 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8413 let project = match &self.project {
8414 Some(project) => project.clone(),
8415 None => return None,
8416 };
8417
8418 Some(self.perform_format(project, FormatTrigger::Manual, cx))
8419 }
8420
8421 fn perform_format(
8422 &mut self,
8423 project: Model<Project>,
8424 trigger: FormatTrigger,
8425 cx: &mut ViewContext<Self>,
8426 ) -> Task<Result<()>> {
8427 let buffer = self.buffer().clone();
8428 let mut buffers = buffer.read(cx).all_buffers();
8429 if trigger == FormatTrigger::Save {
8430 buffers.retain(|buffer| buffer.read(cx).is_dirty());
8431 }
8432
8433 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
8434 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
8435
8436 cx.spawn(|_, mut cx| async move {
8437 let transaction = futures::select_biased! {
8438 () = timeout => {
8439 log::warn!("timed out waiting for formatting");
8440 None
8441 }
8442 transaction = format.log_err().fuse() => transaction,
8443 };
8444
8445 buffer
8446 .update(&mut cx, |buffer, cx| {
8447 if let Some(transaction) = transaction {
8448 if !buffer.is_singleton() {
8449 buffer.push_transaction(&transaction.0, cx);
8450 }
8451 }
8452
8453 cx.notify();
8454 })
8455 .ok();
8456
8457 Ok(())
8458 })
8459 }
8460
8461 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
8462 if let Some(project) = self.project.clone() {
8463 self.buffer.update(cx, |multi_buffer, cx| {
8464 project.update(cx, |project, cx| {
8465 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
8466 });
8467 })
8468 }
8469 }
8470
8471 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
8472 cx.show_character_palette();
8473 }
8474
8475 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
8476 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
8477 let buffer = self.buffer.read(cx).snapshot(cx);
8478 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
8479 let is_valid = buffer
8480 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
8481 .any(|entry| {
8482 entry.diagnostic.is_primary
8483 && !entry.range.is_empty()
8484 && entry.range.start == primary_range_start
8485 && entry.diagnostic.message == active_diagnostics.primary_message
8486 });
8487
8488 if is_valid != active_diagnostics.is_valid {
8489 active_diagnostics.is_valid = is_valid;
8490 let mut new_styles = HashMap::default();
8491 for (block_id, diagnostic) in &active_diagnostics.blocks {
8492 new_styles.insert(
8493 *block_id,
8494 diagnostic_block_renderer(diagnostic.clone(), is_valid),
8495 );
8496 }
8497 self.display_map
8498 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
8499 }
8500 }
8501 }
8502
8503 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
8504 self.dismiss_diagnostics(cx);
8505 let snapshot = self.snapshot(cx);
8506 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
8507 let buffer = self.buffer.read(cx).snapshot(cx);
8508
8509 let mut primary_range = None;
8510 let mut primary_message = None;
8511 let mut group_end = Point::zero();
8512 let diagnostic_group = buffer
8513 .diagnostic_group::<Point>(group_id)
8514 .filter_map(|entry| {
8515 if snapshot.is_line_folded(entry.range.start.row)
8516 && (entry.range.start.row == entry.range.end.row
8517 || snapshot.is_line_folded(entry.range.end.row))
8518 {
8519 return None;
8520 }
8521 if entry.range.end > group_end {
8522 group_end = entry.range.end;
8523 }
8524 if entry.diagnostic.is_primary {
8525 primary_range = Some(entry.range.clone());
8526 primary_message = Some(entry.diagnostic.message.clone());
8527 }
8528 Some(entry)
8529 })
8530 .collect::<Vec<_>>();
8531 let primary_range = primary_range?;
8532 let primary_message = primary_message?;
8533 let primary_range =
8534 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
8535
8536 let blocks = display_map
8537 .insert_blocks(
8538 diagnostic_group.iter().map(|entry| {
8539 let diagnostic = entry.diagnostic.clone();
8540 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
8541 BlockProperties {
8542 style: BlockStyle::Fixed,
8543 position: buffer.anchor_after(entry.range.start),
8544 height: message_height,
8545 render: diagnostic_block_renderer(diagnostic, true),
8546 disposition: BlockDisposition::Below,
8547 }
8548 }),
8549 cx,
8550 )
8551 .into_iter()
8552 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
8553 .collect();
8554
8555 Some(ActiveDiagnosticGroup {
8556 primary_range,
8557 primary_message,
8558 blocks,
8559 is_valid: true,
8560 })
8561 });
8562 self.active_diagnostics.is_some()
8563 }
8564
8565 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
8566 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
8567 self.display_map.update(cx, |display_map, cx| {
8568 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
8569 });
8570 cx.notify();
8571 }
8572 }
8573
8574 pub fn set_selections_from_remote(
8575 &mut self,
8576 selections: Vec<Selection<Anchor>>,
8577 pending_selection: Option<Selection<Anchor>>,
8578 cx: &mut ViewContext<Self>,
8579 ) {
8580 let old_cursor_position = self.selections.newest_anchor().head();
8581 self.selections.change_with(cx, |s| {
8582 s.select_anchors(selections);
8583 if let Some(pending_selection) = pending_selection {
8584 s.set_pending(pending_selection, SelectMode::Character);
8585 } else {
8586 s.clear_pending();
8587 }
8588 });
8589 self.selections_did_change(false, &old_cursor_position, cx);
8590 }
8591
8592 fn push_to_selection_history(&mut self) {
8593 self.selection_history.push(SelectionHistoryEntry {
8594 selections: self.selections.disjoint_anchors(),
8595 select_next_state: self.select_next_state.clone(),
8596 select_prev_state: self.select_prev_state.clone(),
8597 add_selections_state: self.add_selections_state.clone(),
8598 });
8599 }
8600
8601 pub fn transact(
8602 &mut self,
8603 cx: &mut ViewContext<Self>,
8604 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
8605 ) -> Option<TransactionId> {
8606 self.start_transaction_at(Instant::now(), cx);
8607 update(self, cx);
8608 self.end_transaction_at(Instant::now(), cx)
8609 }
8610
8611 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
8612 self.end_selection(cx);
8613 if let Some(tx_id) = self
8614 .buffer
8615 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
8616 {
8617 self.selection_history
8618 .insert_transaction(tx_id, self.selections.disjoint_anchors());
8619 cx.emit(EditorEvent::TransactionBegun {
8620 transaction_id: tx_id,
8621 })
8622 }
8623 }
8624
8625 fn end_transaction_at(
8626 &mut self,
8627 now: Instant,
8628 cx: &mut ViewContext<Self>,
8629 ) -> Option<TransactionId> {
8630 if let Some(tx_id) = self
8631 .buffer
8632 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
8633 {
8634 if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
8635 *end_selections = Some(self.selections.disjoint_anchors());
8636 } else {
8637 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
8638 }
8639
8640 cx.emit(EditorEvent::Edited);
8641 Some(tx_id)
8642 } else {
8643 None
8644 }
8645 }
8646
8647 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
8648 let mut fold_ranges = Vec::new();
8649
8650 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8651
8652 let selections = self.selections.all_adjusted(cx);
8653 for selection in selections {
8654 let range = selection.range().sorted();
8655 let buffer_start_row = range.start.row;
8656
8657 for row in (0..=range.end.row).rev() {
8658 let fold_range = display_map.foldable_range(row);
8659
8660 if let Some(fold_range) = fold_range {
8661 if fold_range.end.row >= buffer_start_row {
8662 fold_ranges.push(fold_range);
8663 if row <= range.start.row {
8664 break;
8665 }
8666 }
8667 }
8668 }
8669 }
8670
8671 self.fold_ranges(fold_ranges, true, cx);
8672 }
8673
8674 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
8675 let buffer_row = fold_at.buffer_row;
8676 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8677
8678 if let Some(fold_range) = display_map.foldable_range(buffer_row) {
8679 let autoscroll = self
8680 .selections
8681 .all::<Point>(cx)
8682 .iter()
8683 .any(|selection| fold_range.overlaps(&selection.range()));
8684
8685 self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
8686 }
8687 }
8688
8689 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
8690 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8691 let buffer = &display_map.buffer_snapshot;
8692 let selections = self.selections.all::<Point>(cx);
8693 let ranges = selections
8694 .iter()
8695 .map(|s| {
8696 let range = s.display_range(&display_map).sorted();
8697 let mut start = range.start.to_point(&display_map);
8698 let mut end = range.end.to_point(&display_map);
8699 start.column = 0;
8700 end.column = buffer.line_len(end.row);
8701 start..end
8702 })
8703 .collect::<Vec<_>>();
8704
8705 self.unfold_ranges(ranges, true, true, cx);
8706 }
8707
8708 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
8709 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8710
8711 let intersection_range = Point::new(unfold_at.buffer_row, 0)
8712 ..Point::new(
8713 unfold_at.buffer_row,
8714 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
8715 );
8716
8717 let autoscroll = self
8718 .selections
8719 .all::<Point>(cx)
8720 .iter()
8721 .any(|selection| selection.range().overlaps(&intersection_range));
8722
8723 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
8724 }
8725
8726 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
8727 let selections = self.selections.all::<Point>(cx);
8728 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8729 let line_mode = self.selections.line_mode;
8730 let ranges = selections.into_iter().map(|s| {
8731 if line_mode {
8732 let start = Point::new(s.start.row, 0);
8733 let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
8734 start..end
8735 } else {
8736 s.start..s.end
8737 }
8738 });
8739 self.fold_ranges(ranges, true, cx);
8740 }
8741
8742 pub fn fold_ranges<T: ToOffset + Clone>(
8743 &mut self,
8744 ranges: impl IntoIterator<Item = Range<T>>,
8745 auto_scroll: bool,
8746 cx: &mut ViewContext<Self>,
8747 ) {
8748 let mut fold_ranges = Vec::new();
8749 let mut buffers_affected = HashMap::default();
8750 let multi_buffer = self.buffer().read(cx);
8751 for range in ranges {
8752 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
8753 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
8754 };
8755 fold_ranges.push(range);
8756 }
8757
8758 let mut ranges = fold_ranges.into_iter().peekable();
8759 if ranges.peek().is_some() {
8760 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
8761
8762 if auto_scroll {
8763 self.request_autoscroll(Autoscroll::fit(), cx);
8764 }
8765
8766 for buffer in buffers_affected.into_values() {
8767 self.sync_expanded_diff_hunks(buffer, cx);
8768 }
8769
8770 cx.notify();
8771
8772 if let Some(active_diagnostics) = self.active_diagnostics.take() {
8773 // Clear diagnostics block when folding a range that contains it.
8774 let snapshot = self.snapshot(cx);
8775 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
8776 drop(snapshot);
8777 self.active_diagnostics = Some(active_diagnostics);
8778 self.dismiss_diagnostics(cx);
8779 } else {
8780 self.active_diagnostics = Some(active_diagnostics);
8781 }
8782 }
8783 }
8784 }
8785
8786 pub fn unfold_ranges<T: ToOffset + Clone>(
8787 &mut self,
8788 ranges: impl IntoIterator<Item = Range<T>>,
8789 inclusive: bool,
8790 auto_scroll: bool,
8791 cx: &mut ViewContext<Self>,
8792 ) {
8793 let mut unfold_ranges = Vec::new();
8794 let mut buffers_affected = HashMap::default();
8795 let multi_buffer = self.buffer().read(cx);
8796 for range in ranges {
8797 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
8798 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
8799 };
8800 unfold_ranges.push(range);
8801 }
8802
8803 let mut ranges = unfold_ranges.into_iter().peekable();
8804 if ranges.peek().is_some() {
8805 self.display_map
8806 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
8807 if auto_scroll {
8808 self.request_autoscroll(Autoscroll::fit(), cx);
8809 }
8810
8811 for buffer in buffers_affected.into_values() {
8812 self.sync_expanded_diff_hunks(buffer, cx);
8813 }
8814
8815 cx.notify();
8816 }
8817 }
8818
8819 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
8820 if hovered != self.gutter_hovered {
8821 self.gutter_hovered = hovered;
8822 cx.notify();
8823 }
8824 }
8825
8826 pub fn insert_blocks(
8827 &mut self,
8828 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
8829 autoscroll: Option<Autoscroll>,
8830 cx: &mut ViewContext<Self>,
8831 ) -> Vec<BlockId> {
8832 let blocks = self
8833 .display_map
8834 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
8835 if let Some(autoscroll) = autoscroll {
8836 self.request_autoscroll(autoscroll, cx);
8837 }
8838 blocks
8839 }
8840
8841 pub fn replace_blocks(
8842 &mut self,
8843 blocks: HashMap<BlockId, RenderBlock>,
8844 autoscroll: Option<Autoscroll>,
8845 cx: &mut ViewContext<Self>,
8846 ) {
8847 self.display_map
8848 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
8849 if let Some(autoscroll) = autoscroll {
8850 self.request_autoscroll(autoscroll, cx);
8851 }
8852 }
8853
8854 pub fn remove_blocks(
8855 &mut self,
8856 block_ids: HashSet<BlockId>,
8857 autoscroll: Option<Autoscroll>,
8858 cx: &mut ViewContext<Self>,
8859 ) {
8860 self.display_map.update(cx, |display_map, cx| {
8861 display_map.remove_blocks(block_ids, cx)
8862 });
8863 if let Some(autoscroll) = autoscroll {
8864 self.request_autoscroll(autoscroll, cx);
8865 }
8866 }
8867
8868 pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
8869 self.display_map
8870 .update(cx, |map, cx| map.snapshot(cx))
8871 .longest_row()
8872 }
8873
8874 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
8875 self.display_map
8876 .update(cx, |map, cx| map.snapshot(cx))
8877 .max_point()
8878 }
8879
8880 pub fn text(&self, cx: &AppContext) -> String {
8881 self.buffer.read(cx).read(cx).text()
8882 }
8883
8884 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
8885 let text = self.text(cx);
8886 let text = text.trim();
8887
8888 if text.is_empty() {
8889 return None;
8890 }
8891
8892 Some(text.to_string())
8893 }
8894
8895 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
8896 self.transact(cx, |this, cx| {
8897 this.buffer
8898 .read(cx)
8899 .as_singleton()
8900 .expect("you can only call set_text on editors for singleton buffers")
8901 .update(cx, |buffer, cx| buffer.set_text(text, cx));
8902 });
8903 }
8904
8905 pub fn display_text(&self, cx: &mut AppContext) -> String {
8906 self.display_map
8907 .update(cx, |map, cx| map.snapshot(cx))
8908 .text()
8909 }
8910
8911 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
8912 let mut wrap_guides = smallvec::smallvec![];
8913
8914 if self.show_wrap_guides == Some(false) {
8915 return wrap_guides;
8916 }
8917
8918 let settings = self.buffer.read(cx).settings_at(0, cx);
8919 if settings.show_wrap_guides {
8920 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
8921 wrap_guides.push((soft_wrap as usize, true));
8922 }
8923 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
8924 }
8925
8926 wrap_guides
8927 }
8928
8929 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
8930 let settings = self.buffer.read(cx).settings_at(0, cx);
8931 let mode = self
8932 .soft_wrap_mode_override
8933 .unwrap_or_else(|| settings.soft_wrap);
8934 match mode {
8935 language_settings::SoftWrap::None => SoftWrap::None,
8936 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
8937 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
8938 language_settings::SoftWrap::PreferredLineLength => {
8939 SoftWrap::Column(settings.preferred_line_length)
8940 }
8941 }
8942 }
8943
8944 pub fn set_soft_wrap_mode(
8945 &mut self,
8946 mode: language_settings::SoftWrap,
8947 cx: &mut ViewContext<Self>,
8948 ) {
8949 self.soft_wrap_mode_override = Some(mode);
8950 cx.notify();
8951 }
8952
8953 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
8954 let rem_size = cx.rem_size();
8955 self.display_map.update(cx, |map, cx| {
8956 map.set_font(
8957 style.text.font(),
8958 style.text.font_size.to_pixels(rem_size),
8959 cx,
8960 )
8961 });
8962 self.style = Some(style);
8963 }
8964
8965 pub fn style(&self) -> Option<&EditorStyle> {
8966 self.style.as_ref()
8967 }
8968
8969 // Called by the element. This method is not designed to be called outside of the editor
8970 // element's layout code because it does not notify when rewrapping is computed synchronously.
8971 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
8972 self.display_map
8973 .update(cx, |map, cx| map.set_wrap_width(width, cx))
8974 }
8975
8976 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
8977 if self.soft_wrap_mode_override.is_some() {
8978 self.soft_wrap_mode_override.take();
8979 } else {
8980 let soft_wrap = match self.soft_wrap_mode(cx) {
8981 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
8982 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
8983 language_settings::SoftWrap::PreferLine
8984 }
8985 };
8986 self.soft_wrap_mode_override = Some(soft_wrap);
8987 }
8988 cx.notify();
8989 }
8990
8991 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
8992 let mut editor_settings = EditorSettings::get_global(cx).clone();
8993 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
8994 EditorSettings::override_global(editor_settings, cx);
8995 }
8996
8997 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8998 self.show_gutter = show_gutter;
8999 cx.notify();
9000 }
9001
9002 pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
9003 self.show_wrap_guides = Some(show_gutter);
9004 cx.notify();
9005 }
9006
9007 pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
9008 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9009 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9010 cx.reveal_path(&file.abs_path(cx));
9011 }
9012 }
9013 }
9014
9015 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
9016 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9017 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9018 if let Some(path) = file.abs_path(cx).to_str() {
9019 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
9020 }
9021 }
9022 }
9023 }
9024
9025 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, 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 if let Some(path) = file.path().to_str() {
9029 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
9030 }
9031 }
9032 }
9033 }
9034
9035 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
9036 self.show_git_blame_gutter = !self.show_git_blame_gutter;
9037
9038 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
9039 self.start_git_blame(true, cx);
9040 }
9041
9042 cx.notify();
9043 }
9044
9045 pub fn toggle_git_blame_inline(
9046 &mut self,
9047 _: &ToggleGitBlameInline,
9048 cx: &mut ViewContext<Self>,
9049 ) {
9050 self.toggle_git_blame_inline_internal(true, cx);
9051 cx.notify();
9052 }
9053
9054 pub fn git_blame_inline_enabled(&self) -> bool {
9055 self.git_blame_inline_enabled
9056 }
9057
9058 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
9059 if let Some(project) = self.project.as_ref() {
9060 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
9061 return;
9062 };
9063
9064 if buffer.read(cx).file().is_none() {
9065 return;
9066 }
9067
9068 let focused = self.focus_handle(cx).contains_focused(cx);
9069
9070 let project = project.clone();
9071 let blame =
9072 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
9073 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
9074 self.blame = Some(blame);
9075 }
9076 }
9077
9078 fn toggle_git_blame_inline_internal(
9079 &mut self,
9080 user_triggered: bool,
9081 cx: &mut ViewContext<Self>,
9082 ) {
9083 if self.git_blame_inline_enabled {
9084 self.git_blame_inline_enabled = false;
9085 self.show_git_blame_inline = false;
9086 self.show_git_blame_inline_delay_task.take();
9087 } else {
9088 self.git_blame_inline_enabled = true;
9089 self.start_git_blame_inline(user_triggered, cx);
9090 }
9091
9092 cx.notify();
9093 }
9094
9095 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
9096 self.start_git_blame(user_triggered, cx);
9097
9098 if ProjectSettings::get_global(cx)
9099 .git
9100 .inline_blame_delay()
9101 .is_some()
9102 {
9103 self.start_inline_blame_timer(cx);
9104 } else {
9105 self.show_git_blame_inline = true
9106 }
9107 }
9108
9109 pub fn blame(&self) -> Option<&Model<GitBlame>> {
9110 self.blame.as_ref()
9111 }
9112
9113 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
9114 self.show_git_blame_gutter && self.has_blame_entries(cx)
9115 }
9116
9117 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
9118 self.show_git_blame_inline
9119 && self.focus_handle.is_focused(cx)
9120 && !self.newest_selection_head_on_empty_line(cx)
9121 && self.has_blame_entries(cx)
9122 }
9123
9124 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
9125 self.blame()
9126 .map_or(false, |blame| blame.read(cx).has_generated_entries())
9127 }
9128
9129 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
9130 let cursor_anchor = self.selections.newest_anchor().head();
9131
9132 let snapshot = self.buffer.read(cx).snapshot(cx);
9133 let buffer_row = cursor_anchor.to_point(&snapshot).row;
9134
9135 snapshot.line_len(buffer_row) == 0
9136 }
9137
9138 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
9139 let (path, repo) = maybe!({
9140 let project_handle = self.project.as_ref()?.clone();
9141 let project = project_handle.read(cx);
9142 let buffer = self.buffer().read(cx).as_singleton()?;
9143 let path = buffer
9144 .read(cx)
9145 .file()?
9146 .as_local()?
9147 .path()
9148 .to_str()?
9149 .to_string();
9150 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
9151 Some((path, repo))
9152 })
9153 .ok_or_else(|| anyhow!("unable to open git repository"))?;
9154
9155 const REMOTE_NAME: &str = "origin";
9156 let origin_url = repo
9157 .lock()
9158 .remote_url(REMOTE_NAME)
9159 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
9160 let sha = repo
9161 .lock()
9162 .head_sha()
9163 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
9164 let selections = self.selections.all::<Point>(cx);
9165 let selection = selections.iter().peekable().next();
9166
9167 build_permalink(BuildPermalinkParams {
9168 remote_url: &origin_url,
9169 sha: &sha,
9170 path: &path,
9171 selection: selection.map(|selection| {
9172 let range = selection.range();
9173 let start = range.start.row;
9174 let end = range.end.row;
9175 start..end
9176 }),
9177 })
9178 }
9179
9180 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
9181 let permalink = self.get_permalink_to_line(cx);
9182
9183 match permalink {
9184 Ok(permalink) => {
9185 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
9186 }
9187 Err(err) => {
9188 let message = format!("Failed to copy permalink: {err}");
9189
9190 Err::<(), anyhow::Error>(err).log_err();
9191
9192 if let Some(workspace) = self.workspace() {
9193 workspace.update(cx, |workspace, cx| {
9194 struct CopyPermalinkToLine;
9195
9196 workspace.show_toast(
9197 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
9198 cx,
9199 )
9200 })
9201 }
9202 }
9203 }
9204 }
9205
9206 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
9207 let permalink = self.get_permalink_to_line(cx);
9208
9209 match permalink {
9210 Ok(permalink) => {
9211 cx.open_url(permalink.as_ref());
9212 }
9213 Err(err) => {
9214 let message = format!("Failed to open permalink: {err}");
9215
9216 Err::<(), anyhow::Error>(err).log_err();
9217
9218 if let Some(workspace) = self.workspace() {
9219 workspace.update(cx, |workspace, cx| {
9220 struct OpenPermalinkToLine;
9221
9222 workspace.show_toast(
9223 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
9224 cx,
9225 )
9226 })
9227 }
9228 }
9229 }
9230 }
9231
9232 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
9233 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
9234 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
9235 pub fn highlight_rows<T: 'static>(
9236 &mut self,
9237 rows: Range<Anchor>,
9238 color: Option<Hsla>,
9239 cx: &mut ViewContext<Self>,
9240 ) {
9241 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
9242 match self.highlighted_rows.entry(TypeId::of::<T>()) {
9243 hash_map::Entry::Occupied(o) => {
9244 let row_highlights = o.into_mut();
9245 let existing_highlight_index =
9246 row_highlights.binary_search_by(|(_, highlight_range, _)| {
9247 highlight_range
9248 .start
9249 .cmp(&rows.start, &multi_buffer_snapshot)
9250 .then(highlight_range.end.cmp(&rows.end, &multi_buffer_snapshot))
9251 });
9252 match color {
9253 Some(color) => {
9254 let insert_index = match existing_highlight_index {
9255 Ok(i) => i,
9256 Err(i) => i,
9257 };
9258 row_highlights.insert(
9259 insert_index,
9260 (post_inc(&mut self.highlight_order), rows, color),
9261 );
9262 }
9263 None => {
9264 if let Ok(i) = existing_highlight_index {
9265 row_highlights.remove(i);
9266 }
9267 }
9268 }
9269 }
9270 hash_map::Entry::Vacant(v) => {
9271 if let Some(color) = color {
9272 v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
9273 }
9274 }
9275 }
9276 }
9277
9278 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
9279 pub fn clear_row_highlights<T: 'static>(&mut self) {
9280 self.highlighted_rows.remove(&TypeId::of::<T>());
9281 }
9282
9283 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
9284 pub fn highlighted_rows<T: 'static>(
9285 &self,
9286 ) -> Option<impl Iterator<Item = (&Range<Anchor>, &Hsla)>> {
9287 Some(
9288 self.highlighted_rows
9289 .get(&TypeId::of::<T>())?
9290 .iter()
9291 .map(|(_, range, color)| (range, color)),
9292 )
9293 }
9294
9295 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
9296 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
9297 /// Allows to ignore certain kinds of highlights.
9298 pub fn highlighted_display_rows(
9299 &mut self,
9300 exclude_highlights: HashSet<TypeId>,
9301 cx: &mut WindowContext,
9302 ) -> BTreeMap<u32, Hsla> {
9303 let snapshot = self.snapshot(cx);
9304 let mut used_highlight_orders = HashMap::default();
9305 self.highlighted_rows
9306 .iter()
9307 .filter(|(type_id, _)| !exclude_highlights.contains(type_id))
9308 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
9309 .fold(
9310 BTreeMap::<u32, Hsla>::new(),
9311 |mut unique_rows, (highlight_order, anchor_range, hsla)| {
9312 let start_row = anchor_range.start.to_display_point(&snapshot).row();
9313 let end_row = anchor_range.end.to_display_point(&snapshot).row();
9314 for row in start_row..=end_row {
9315 let used_index =
9316 used_highlight_orders.entry(row).or_insert(*highlight_order);
9317 if highlight_order >= used_index {
9318 *used_index = *highlight_order;
9319 unique_rows.insert(row, *hsla);
9320 }
9321 }
9322 unique_rows
9323 },
9324 )
9325 }
9326
9327 pub fn set_search_within_ranges(
9328 &mut self,
9329 ranges: &[Range<Anchor>],
9330 cx: &mut ViewContext<Self>,
9331 ) {
9332 self.highlight_background::<SearchWithinRange>(
9333 ranges,
9334 |colors| colors.editor_document_highlight_read_background,
9335 cx,
9336 )
9337 }
9338
9339 pub fn highlight_background<T: 'static>(
9340 &mut self,
9341 ranges: &[Range<Anchor>],
9342 color_fetcher: fn(&ThemeColors) -> Hsla,
9343 cx: &mut ViewContext<Self>,
9344 ) {
9345 let snapshot = self.snapshot(cx);
9346 // this is to try and catch a panic sooner
9347 for range in ranges {
9348 snapshot
9349 .buffer_snapshot
9350 .summary_for_anchor::<usize>(&range.start);
9351 snapshot
9352 .buffer_snapshot
9353 .summary_for_anchor::<usize>(&range.end);
9354 }
9355
9356 self.background_highlights
9357 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
9358 self.scrollbar_marker_state.dirty = true;
9359 cx.notify();
9360 }
9361
9362 pub fn clear_background_highlights<T: 'static>(
9363 &mut self,
9364 cx: &mut ViewContext<Self>,
9365 ) -> Option<BackgroundHighlight> {
9366 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
9367 if !text_highlights.1.is_empty() {
9368 self.scrollbar_marker_state.dirty = true;
9369 cx.notify();
9370 }
9371 Some(text_highlights)
9372 }
9373
9374 #[cfg(feature = "test-support")]
9375 pub fn all_text_background_highlights(
9376 &mut self,
9377 cx: &mut ViewContext<Self>,
9378 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
9379 let snapshot = self.snapshot(cx);
9380 let buffer = &snapshot.buffer_snapshot;
9381 let start = buffer.anchor_before(0);
9382 let end = buffer.anchor_after(buffer.len());
9383 let theme = cx.theme().colors();
9384 self.background_highlights_in_range(start..end, &snapshot, theme)
9385 }
9386
9387 fn document_highlights_for_position<'a>(
9388 &'a self,
9389 position: Anchor,
9390 buffer: &'a MultiBufferSnapshot,
9391 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
9392 let read_highlights = self
9393 .background_highlights
9394 .get(&TypeId::of::<DocumentHighlightRead>())
9395 .map(|h| &h.1);
9396 let write_highlights = self
9397 .background_highlights
9398 .get(&TypeId::of::<DocumentHighlightWrite>())
9399 .map(|h| &h.1);
9400 let left_position = position.bias_left(buffer);
9401 let right_position = position.bias_right(buffer);
9402 read_highlights
9403 .into_iter()
9404 .chain(write_highlights)
9405 .flat_map(move |ranges| {
9406 let start_ix = match ranges.binary_search_by(|probe| {
9407 let cmp = probe.end.cmp(&left_position, buffer);
9408 if cmp.is_ge() {
9409 Ordering::Greater
9410 } else {
9411 Ordering::Less
9412 }
9413 }) {
9414 Ok(i) | Err(i) => i,
9415 };
9416
9417 ranges[start_ix..]
9418 .iter()
9419 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
9420 })
9421 }
9422
9423 pub fn has_background_highlights<T: 'static>(&self) -> bool {
9424 self.background_highlights
9425 .get(&TypeId::of::<T>())
9426 .map_or(false, |(_, highlights)| !highlights.is_empty())
9427 }
9428
9429 pub fn background_highlights_in_range(
9430 &self,
9431 search_range: Range<Anchor>,
9432 display_snapshot: &DisplaySnapshot,
9433 theme: &ThemeColors,
9434 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
9435 let mut results = Vec::new();
9436 for (color_fetcher, ranges) in self.background_highlights.values() {
9437 let color = color_fetcher(theme);
9438 let start_ix = match ranges.binary_search_by(|probe| {
9439 let cmp = probe
9440 .end
9441 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
9442 if cmp.is_gt() {
9443 Ordering::Greater
9444 } else {
9445 Ordering::Less
9446 }
9447 }) {
9448 Ok(i) | Err(i) => i,
9449 };
9450 for range in &ranges[start_ix..] {
9451 if range
9452 .start
9453 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
9454 .is_ge()
9455 {
9456 break;
9457 }
9458
9459 let start = range.start.to_display_point(&display_snapshot);
9460 let end = range.end.to_display_point(&display_snapshot);
9461 results.push((start..end, color))
9462 }
9463 }
9464 results
9465 }
9466
9467 pub fn background_highlight_row_ranges<T: 'static>(
9468 &self,
9469 search_range: Range<Anchor>,
9470 display_snapshot: &DisplaySnapshot,
9471 count: usize,
9472 ) -> Vec<RangeInclusive<DisplayPoint>> {
9473 let mut results = Vec::new();
9474 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
9475 return vec![];
9476 };
9477
9478 let start_ix = match ranges.binary_search_by(|probe| {
9479 let cmp = probe
9480 .end
9481 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
9482 if cmp.is_gt() {
9483 Ordering::Greater
9484 } else {
9485 Ordering::Less
9486 }
9487 }) {
9488 Ok(i) | Err(i) => i,
9489 };
9490 let mut push_region = |start: Option<Point>, end: Option<Point>| {
9491 if let (Some(start_display), Some(end_display)) = (start, end) {
9492 results.push(
9493 start_display.to_display_point(display_snapshot)
9494 ..=end_display.to_display_point(display_snapshot),
9495 );
9496 }
9497 };
9498 let mut start_row: Option<Point> = None;
9499 let mut end_row: Option<Point> = None;
9500 if ranges.len() > count {
9501 return Vec::new();
9502 }
9503 for range in &ranges[start_ix..] {
9504 if range
9505 .start
9506 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
9507 .is_ge()
9508 {
9509 break;
9510 }
9511 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
9512 if let Some(current_row) = &end_row {
9513 if end.row == current_row.row {
9514 continue;
9515 }
9516 }
9517 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
9518 if start_row.is_none() {
9519 assert_eq!(end_row, None);
9520 start_row = Some(start);
9521 end_row = Some(end);
9522 continue;
9523 }
9524 if let Some(current_end) = end_row.as_mut() {
9525 if start.row > current_end.row + 1 {
9526 push_region(start_row, end_row);
9527 start_row = Some(start);
9528 end_row = Some(end);
9529 } else {
9530 // Merge two hunks.
9531 *current_end = end;
9532 }
9533 } else {
9534 unreachable!();
9535 }
9536 }
9537 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
9538 push_region(start_row, end_row);
9539 results
9540 }
9541
9542 /// Get the text ranges corresponding to the redaction query
9543 pub fn redacted_ranges(
9544 &self,
9545 search_range: Range<Anchor>,
9546 display_snapshot: &DisplaySnapshot,
9547 cx: &WindowContext,
9548 ) -> Vec<Range<DisplayPoint>> {
9549 display_snapshot
9550 .buffer_snapshot
9551 .redacted_ranges(search_range, |file| {
9552 if let Some(file) = file {
9553 file.is_private()
9554 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
9555 } else {
9556 false
9557 }
9558 })
9559 .map(|range| {
9560 range.start.to_display_point(display_snapshot)
9561 ..range.end.to_display_point(display_snapshot)
9562 })
9563 .collect()
9564 }
9565
9566 pub fn highlight_text<T: 'static>(
9567 &mut self,
9568 ranges: Vec<Range<Anchor>>,
9569 style: HighlightStyle,
9570 cx: &mut ViewContext<Self>,
9571 ) {
9572 self.display_map.update(cx, |map, _| {
9573 map.highlight_text(TypeId::of::<T>(), ranges, style)
9574 });
9575 cx.notify();
9576 }
9577
9578 pub(crate) fn highlight_inlays<T: 'static>(
9579 &mut self,
9580 highlights: Vec<InlayHighlight>,
9581 style: HighlightStyle,
9582 cx: &mut ViewContext<Self>,
9583 ) {
9584 self.display_map.update(cx, |map, _| {
9585 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
9586 });
9587 cx.notify();
9588 }
9589
9590 pub fn text_highlights<'a, T: 'static>(
9591 &'a self,
9592 cx: &'a AppContext,
9593 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
9594 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
9595 }
9596
9597 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
9598 let cleared = self
9599 .display_map
9600 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
9601 if cleared {
9602 cx.notify();
9603 }
9604 }
9605
9606 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
9607 (self.read_only(cx) || self.blink_manager.read(cx).visible())
9608 && self.focus_handle.is_focused(cx)
9609 }
9610
9611 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
9612 cx.notify();
9613 }
9614
9615 fn on_buffer_event(
9616 &mut self,
9617 multibuffer: Model<MultiBuffer>,
9618 event: &multi_buffer::Event,
9619 cx: &mut ViewContext<Self>,
9620 ) {
9621 match event {
9622 multi_buffer::Event::Edited {
9623 singleton_buffer_edited,
9624 } => {
9625 self.scrollbar_marker_state.dirty = true;
9626 self.refresh_active_diagnostics(cx);
9627 self.refresh_code_actions(cx);
9628 if self.has_active_inline_completion(cx) {
9629 self.update_visible_inline_completion(cx);
9630 }
9631 cx.emit(EditorEvent::BufferEdited);
9632 cx.emit(SearchEvent::MatchesInvalidated);
9633
9634 if *singleton_buffer_edited {
9635 if let Some(project) = &self.project {
9636 let project = project.read(cx);
9637 let languages_affected = multibuffer
9638 .read(cx)
9639 .all_buffers()
9640 .into_iter()
9641 .filter_map(|buffer| {
9642 let buffer = buffer.read(cx);
9643 let language = buffer.language()?;
9644 if project.is_local()
9645 && project.language_servers_for_buffer(buffer, cx).count() == 0
9646 {
9647 None
9648 } else {
9649 Some(language)
9650 }
9651 })
9652 .cloned()
9653 .collect::<HashSet<_>>();
9654 if !languages_affected.is_empty() {
9655 self.refresh_inlay_hints(
9656 InlayHintRefreshReason::BufferEdited(languages_affected),
9657 cx,
9658 );
9659 }
9660 }
9661 }
9662
9663 let Some(project) = &self.project else { return };
9664 let telemetry = project.read(cx).client().telemetry().clone();
9665 telemetry.log_edit_event("editor");
9666 }
9667 multi_buffer::Event::ExcerptsAdded {
9668 buffer,
9669 predecessor,
9670 excerpts,
9671 } => {
9672 cx.emit(EditorEvent::ExcerptsAdded {
9673 buffer: buffer.clone(),
9674 predecessor: *predecessor,
9675 excerpts: excerpts.clone(),
9676 });
9677 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
9678 }
9679 multi_buffer::Event::ExcerptsRemoved { ids } => {
9680 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
9681 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
9682 }
9683 multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
9684 multi_buffer::Event::LanguageChanged => {
9685 cx.emit(EditorEvent::Reparsed);
9686 cx.notify();
9687 }
9688 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
9689 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
9690 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
9691 cx.emit(EditorEvent::TitleChanged)
9692 }
9693 multi_buffer::Event::DiffBaseChanged => {
9694 self.scrollbar_marker_state.dirty = true;
9695 cx.emit(EditorEvent::DiffBaseChanged);
9696 cx.notify();
9697 }
9698 multi_buffer::Event::DiffUpdated { buffer } => {
9699 self.sync_expanded_diff_hunks(buffer.clone(), cx);
9700 cx.notify();
9701 }
9702 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
9703 multi_buffer::Event::DiagnosticsUpdated => {
9704 self.refresh_active_diagnostics(cx);
9705 self.scrollbar_marker_state.dirty = true;
9706 cx.notify();
9707 }
9708 _ => {}
9709 };
9710 }
9711
9712 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
9713 cx.notify();
9714 }
9715
9716 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
9717 self.refresh_inline_completion(true, cx);
9718 self.refresh_inlay_hints(
9719 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
9720 self.selections.newest_anchor().head(),
9721 &self.buffer.read(cx).snapshot(cx),
9722 cx,
9723 )),
9724 cx,
9725 );
9726 let editor_settings = EditorSettings::get_global(cx);
9727 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
9728 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
9729
9730 if self.mode == EditorMode::Full {
9731 let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
9732 if self.git_blame_inline_enabled != inline_blame_enabled {
9733 self.toggle_git_blame_inline_internal(false, cx);
9734 }
9735 }
9736
9737 cx.notify();
9738 }
9739
9740 pub fn set_searchable(&mut self, searchable: bool) {
9741 self.searchable = searchable;
9742 }
9743
9744 pub fn searchable(&self) -> bool {
9745 self.searchable
9746 }
9747
9748 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
9749 self.open_excerpts_common(true, cx)
9750 }
9751
9752 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
9753 self.open_excerpts_common(false, cx)
9754 }
9755
9756 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
9757 let buffer = self.buffer.read(cx);
9758 if buffer.is_singleton() {
9759 cx.propagate();
9760 return;
9761 }
9762
9763 let Some(workspace) = self.workspace() else {
9764 cx.propagate();
9765 return;
9766 };
9767
9768 let mut new_selections_by_buffer = HashMap::default();
9769 for selection in self.selections.all::<usize>(cx) {
9770 for (buffer, mut range, _) in
9771 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
9772 {
9773 if selection.reversed {
9774 mem::swap(&mut range.start, &mut range.end);
9775 }
9776 new_selections_by_buffer
9777 .entry(buffer)
9778 .or_insert(Vec::new())
9779 .push(range)
9780 }
9781 }
9782
9783 // We defer the pane interaction because we ourselves are a workspace item
9784 // and activating a new item causes the pane to call a method on us reentrantly,
9785 // which panics if we're on the stack.
9786 cx.window_context().defer(move |cx| {
9787 workspace.update(cx, |workspace, cx| {
9788 let pane = if split {
9789 workspace.adjacent_pane(cx)
9790 } else {
9791 workspace.active_pane().clone()
9792 };
9793
9794 for (buffer, ranges) in new_selections_by_buffer {
9795 let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
9796 editor.update(cx, |editor, cx| {
9797 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
9798 s.select_ranges(ranges);
9799 });
9800 });
9801 }
9802 })
9803 });
9804 }
9805
9806 fn jump(
9807 &mut self,
9808 path: ProjectPath,
9809 position: Point,
9810 anchor: language::Anchor,
9811 offset_from_top: u32,
9812 cx: &mut ViewContext<Self>,
9813 ) {
9814 let workspace = self.workspace();
9815 cx.spawn(|_, mut cx| async move {
9816 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
9817 let editor = workspace.update(&mut cx, |workspace, cx| {
9818 // Reset the preview item id before opening the new item
9819 workspace.active_pane().update(cx, |pane, cx| {
9820 pane.set_preview_item_id(None, cx);
9821 });
9822 workspace.open_path_preview(path, None, true, true, cx)
9823 })?;
9824 let editor = editor
9825 .await?
9826 .downcast::<Editor>()
9827 .ok_or_else(|| anyhow!("opened item was not an editor"))?
9828 .downgrade();
9829 editor.update(&mut cx, |editor, cx| {
9830 let buffer = editor
9831 .buffer()
9832 .read(cx)
9833 .as_singleton()
9834 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
9835 let buffer = buffer.read(cx);
9836 let cursor = if buffer.can_resolve(&anchor) {
9837 language::ToPoint::to_point(&anchor, buffer)
9838 } else {
9839 buffer.clip_point(position, Bias::Left)
9840 };
9841
9842 let nav_history = editor.nav_history.take();
9843 editor.change_selections(
9844 Some(Autoscroll::top_relative(offset_from_top as usize)),
9845 cx,
9846 |s| {
9847 s.select_ranges([cursor..cursor]);
9848 },
9849 );
9850 editor.nav_history = nav_history;
9851
9852 anyhow::Ok(())
9853 })??;
9854
9855 anyhow::Ok(())
9856 })
9857 .detach_and_log_err(cx);
9858 }
9859
9860 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
9861 let snapshot = self.buffer.read(cx).read(cx);
9862 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
9863 Some(
9864 ranges
9865 .iter()
9866 .map(move |range| {
9867 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
9868 })
9869 .collect(),
9870 )
9871 }
9872
9873 fn selection_replacement_ranges(
9874 &self,
9875 range: Range<OffsetUtf16>,
9876 cx: &AppContext,
9877 ) -> Vec<Range<OffsetUtf16>> {
9878 let selections = self.selections.all::<OffsetUtf16>(cx);
9879 let newest_selection = selections
9880 .iter()
9881 .max_by_key(|selection| selection.id)
9882 .unwrap();
9883 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
9884 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
9885 let snapshot = self.buffer.read(cx).read(cx);
9886 selections
9887 .into_iter()
9888 .map(|mut selection| {
9889 selection.start.0 =
9890 (selection.start.0 as isize).saturating_add(start_delta) as usize;
9891 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
9892 snapshot.clip_offset_utf16(selection.start, Bias::Left)
9893 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
9894 })
9895 .collect()
9896 }
9897
9898 fn report_editor_event(
9899 &self,
9900 operation: &'static str,
9901 file_extension: Option<String>,
9902 cx: &AppContext,
9903 ) {
9904 if cfg!(any(test, feature = "test-support")) {
9905 return;
9906 }
9907
9908 let Some(project) = &self.project else { return };
9909
9910 // If None, we are in a file without an extension
9911 let file = self
9912 .buffer
9913 .read(cx)
9914 .as_singleton()
9915 .and_then(|b| b.read(cx).file());
9916 let file_extension = file_extension.or(file
9917 .as_ref()
9918 .and_then(|file| Path::new(file.file_name(cx)).extension())
9919 .and_then(|e| e.to_str())
9920 .map(|a| a.to_string()));
9921
9922 let vim_mode = cx
9923 .global::<SettingsStore>()
9924 .raw_user_settings()
9925 .get("vim_mode")
9926 == Some(&serde_json::Value::Bool(true));
9927 let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
9928 let copilot_enabled_for_language = self
9929 .buffer
9930 .read(cx)
9931 .settings_at(0, cx)
9932 .show_copilot_suggestions;
9933
9934 let telemetry = project.read(cx).client().telemetry().clone();
9935 telemetry.report_editor_event(
9936 file_extension,
9937 vim_mode,
9938 operation,
9939 copilot_enabled,
9940 copilot_enabled_for_language,
9941 )
9942 }
9943
9944 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
9945 /// with each line being an array of {text, highlight} objects.
9946 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
9947 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
9948 return;
9949 };
9950
9951 #[derive(Serialize)]
9952 struct Chunk<'a> {
9953 text: String,
9954 highlight: Option<&'a str>,
9955 }
9956
9957 let snapshot = buffer.read(cx).snapshot();
9958 let range = self
9959 .selected_text_range(cx)
9960 .and_then(|selected_range| {
9961 if selected_range.is_empty() {
9962 None
9963 } else {
9964 Some(selected_range)
9965 }
9966 })
9967 .unwrap_or_else(|| 0..snapshot.len());
9968
9969 let chunks = snapshot.chunks(range, true);
9970 let mut lines = Vec::new();
9971 let mut line: VecDeque<Chunk> = VecDeque::new();
9972
9973 let Some(style) = self.style.as_ref() else {
9974 return;
9975 };
9976
9977 for chunk in chunks {
9978 let highlight = chunk
9979 .syntax_highlight_id
9980 .and_then(|id| id.name(&style.syntax));
9981 let mut chunk_lines = chunk.text.split('\n').peekable();
9982 while let Some(text) = chunk_lines.next() {
9983 let mut merged_with_last_token = false;
9984 if let Some(last_token) = line.back_mut() {
9985 if last_token.highlight == highlight {
9986 last_token.text.push_str(text);
9987 merged_with_last_token = true;
9988 }
9989 }
9990
9991 if !merged_with_last_token {
9992 line.push_back(Chunk {
9993 text: text.into(),
9994 highlight,
9995 });
9996 }
9997
9998 if chunk_lines.peek().is_some() {
9999 if line.len() > 1 && line.front().unwrap().text.is_empty() {
10000 line.pop_front();
10001 }
10002 if line.len() > 1 && line.back().unwrap().text.is_empty() {
10003 line.pop_back();
10004 }
10005
10006 lines.push(mem::take(&mut line));
10007 }
10008 }
10009 }
10010
10011 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
10012 return;
10013 };
10014 cx.write_to_clipboard(ClipboardItem::new(lines));
10015 }
10016
10017 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
10018 &self.inlay_hint_cache
10019 }
10020
10021 pub fn replay_insert_event(
10022 &mut self,
10023 text: &str,
10024 relative_utf16_range: Option<Range<isize>>,
10025 cx: &mut ViewContext<Self>,
10026 ) {
10027 if !self.input_enabled {
10028 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10029 return;
10030 }
10031 if let Some(relative_utf16_range) = relative_utf16_range {
10032 let selections = self.selections.all::<OffsetUtf16>(cx);
10033 self.change_selections(None, cx, |s| {
10034 let new_ranges = selections.into_iter().map(|range| {
10035 let start = OffsetUtf16(
10036 range
10037 .head()
10038 .0
10039 .saturating_add_signed(relative_utf16_range.start),
10040 );
10041 let end = OffsetUtf16(
10042 range
10043 .head()
10044 .0
10045 .saturating_add_signed(relative_utf16_range.end),
10046 );
10047 start..end
10048 });
10049 s.select_ranges(new_ranges);
10050 });
10051 }
10052
10053 self.handle_input(text, cx);
10054 }
10055
10056 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10057 let Some(project) = self.project.as_ref() else {
10058 return false;
10059 };
10060 let project = project.read(cx);
10061
10062 let mut supports = false;
10063 self.buffer().read(cx).for_each_buffer(|buffer| {
10064 if !supports {
10065 supports = project
10066 .language_servers_for_buffer(buffer.read(cx), cx)
10067 .any(
10068 |(_, server)| match server.capabilities().inlay_hint_provider {
10069 Some(lsp::OneOf::Left(enabled)) => enabled,
10070 Some(lsp::OneOf::Right(_)) => true,
10071 None => false,
10072 },
10073 )
10074 }
10075 });
10076 supports
10077 }
10078
10079 pub fn focus(&self, cx: &mut WindowContext) {
10080 cx.focus(&self.focus_handle)
10081 }
10082
10083 pub fn is_focused(&self, cx: &WindowContext) -> bool {
10084 self.focus_handle.is_focused(cx)
10085 }
10086
10087 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
10088 cx.emit(EditorEvent::Focused);
10089
10090 if let Some(rename) = self.pending_rename.as_ref() {
10091 let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
10092 cx.focus(&rename_editor_focus_handle);
10093 } else {
10094 if let Some(blame) = self.blame.as_ref() {
10095 blame.update(cx, GitBlame::focus)
10096 }
10097
10098 self.blink_manager.update(cx, BlinkManager::enable);
10099 self.show_cursor_names(cx);
10100 self.buffer.update(cx, |buffer, cx| {
10101 buffer.finalize_last_transaction(cx);
10102 if self.leader_peer_id.is_none() {
10103 buffer.set_active_selections(
10104 &self.selections.disjoint_anchors(),
10105 self.selections.line_mode,
10106 self.cursor_shape,
10107 cx,
10108 );
10109 }
10110 });
10111 }
10112 }
10113
10114 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
10115 self.blink_manager.update(cx, BlinkManager::disable);
10116 self.buffer
10117 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
10118
10119 if let Some(blame) = self.blame.as_ref() {
10120 blame.update(cx, GitBlame::blur)
10121 }
10122 self.hide_context_menu(cx);
10123 hide_hover(self, cx);
10124 cx.emit(EditorEvent::Blurred);
10125 cx.notify();
10126 }
10127
10128 pub fn register_action<A: Action>(
10129 &mut self,
10130 listener: impl Fn(&A, &mut WindowContext) + 'static,
10131 ) -> &mut Self {
10132 let listener = Arc::new(listener);
10133
10134 self.editor_actions.push(Box::new(move |cx| {
10135 let _view = cx.view().clone();
10136 let cx = cx.window_context();
10137 let listener = listener.clone();
10138 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
10139 let action = action.downcast_ref().unwrap();
10140 if phase == DispatchPhase::Bubble {
10141 listener(action, cx)
10142 }
10143 })
10144 }));
10145 self
10146 }
10147}
10148
10149fn hunks_for_selections(
10150 multi_buffer_snapshot: &MultiBufferSnapshot,
10151 selections: &[Selection<Anchor>],
10152) -> Vec<DiffHunk<u32>> {
10153 let mut hunks = Vec::with_capacity(selections.len());
10154 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
10155 HashMap::default();
10156 let display_rows_for_selections = selections.iter().map(|selection| {
10157 let head = selection.head();
10158 let tail = selection.tail();
10159 let start = tail.to_point(&multi_buffer_snapshot).row;
10160 let end = head.to_point(&multi_buffer_snapshot).row;
10161 if start > end {
10162 end..start
10163 } else {
10164 start..end
10165 }
10166 });
10167
10168 for selected_multi_buffer_rows in display_rows_for_selections {
10169 let query_rows = selected_multi_buffer_rows.start..selected_multi_buffer_rows.end + 1;
10170 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
10171 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
10172 // when the caret is just above or just below the deleted hunk.
10173 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
10174 let related_to_selection = if allow_adjacent {
10175 hunk.associated_range.overlaps(&query_rows)
10176 || hunk.associated_range.start == query_rows.end
10177 || hunk.associated_range.end == query_rows.start
10178 } else {
10179 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
10180 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
10181 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
10182 || selected_multi_buffer_rows.end == hunk.associated_range.start
10183 };
10184 if related_to_selection {
10185 if !processed_buffer_rows
10186 .entry(hunk.buffer_id)
10187 .or_default()
10188 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
10189 {
10190 continue;
10191 }
10192 hunks.push(hunk);
10193 }
10194 }
10195 }
10196
10197 hunks
10198}
10199
10200pub trait CollaborationHub {
10201 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
10202 fn user_participant_indices<'a>(
10203 &self,
10204 cx: &'a AppContext,
10205 ) -> &'a HashMap<u64, ParticipantIndex>;
10206 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
10207}
10208
10209impl CollaborationHub for Model<Project> {
10210 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
10211 self.read(cx).collaborators()
10212 }
10213
10214 fn user_participant_indices<'a>(
10215 &self,
10216 cx: &'a AppContext,
10217 ) -> &'a HashMap<u64, ParticipantIndex> {
10218 self.read(cx).user_store().read(cx).participant_indices()
10219 }
10220
10221 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
10222 let this = self.read(cx);
10223 let user_ids = this.collaborators().values().map(|c| c.user_id);
10224 this.user_store().read_with(cx, |user_store, cx| {
10225 user_store.participant_names(user_ids, cx)
10226 })
10227 }
10228}
10229
10230pub trait CompletionProvider {
10231 fn completions(
10232 &self,
10233 buffer: &Model<Buffer>,
10234 buffer_position: text::Anchor,
10235 cx: &mut ViewContext<Editor>,
10236 ) -> Task<Result<Vec<Completion>>>;
10237
10238 fn resolve_completions(
10239 &self,
10240 buffer: Model<Buffer>,
10241 completion_indices: Vec<usize>,
10242 completions: Arc<RwLock<Box<[Completion]>>>,
10243 cx: &mut ViewContext<Editor>,
10244 ) -> Task<Result<bool>>;
10245
10246 fn apply_additional_edits_for_completion(
10247 &self,
10248 buffer: Model<Buffer>,
10249 completion: Completion,
10250 push_to_history: bool,
10251 cx: &mut ViewContext<Editor>,
10252 ) -> Task<Result<Option<language::Transaction>>>;
10253}
10254
10255impl CompletionProvider for Model<Project> {
10256 fn completions(
10257 &self,
10258 buffer: &Model<Buffer>,
10259 buffer_position: text::Anchor,
10260 cx: &mut ViewContext<Editor>,
10261 ) -> Task<Result<Vec<Completion>>> {
10262 self.update(cx, |project, cx| {
10263 project.completions(&buffer, buffer_position, cx)
10264 })
10265 }
10266
10267 fn resolve_completions(
10268 &self,
10269 buffer: Model<Buffer>,
10270 completion_indices: Vec<usize>,
10271 completions: Arc<RwLock<Box<[Completion]>>>,
10272 cx: &mut ViewContext<Editor>,
10273 ) -> Task<Result<bool>> {
10274 self.update(cx, |project, cx| {
10275 project.resolve_completions(buffer, completion_indices, completions, cx)
10276 })
10277 }
10278
10279 fn apply_additional_edits_for_completion(
10280 &self,
10281 buffer: Model<Buffer>,
10282 completion: Completion,
10283 push_to_history: bool,
10284 cx: &mut ViewContext<Editor>,
10285 ) -> Task<Result<Option<language::Transaction>>> {
10286 self.update(cx, |project, cx| {
10287 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
10288 })
10289 }
10290}
10291
10292fn inlay_hint_settings(
10293 location: Anchor,
10294 snapshot: &MultiBufferSnapshot,
10295 cx: &mut ViewContext<'_, Editor>,
10296) -> InlayHintSettings {
10297 let file = snapshot.file_at(location);
10298 let language = snapshot.language_at(location);
10299 let settings = all_language_settings(file, cx);
10300 settings
10301 .language(language.map(|l| l.name()).as_deref())
10302 .inlay_hints
10303}
10304
10305fn consume_contiguous_rows(
10306 contiguous_row_selections: &mut Vec<Selection<Point>>,
10307 selection: &Selection<Point>,
10308 display_map: &DisplaySnapshot,
10309 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
10310) -> (u32, u32) {
10311 contiguous_row_selections.push(selection.clone());
10312 let start_row = selection.start.row;
10313 let mut end_row = ending_row(selection, display_map);
10314
10315 while let Some(next_selection) = selections.peek() {
10316 if next_selection.start.row <= end_row {
10317 end_row = ending_row(next_selection, display_map);
10318 contiguous_row_selections.push(selections.next().unwrap().clone());
10319 } else {
10320 break;
10321 }
10322 }
10323 (start_row, end_row)
10324}
10325
10326fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
10327 if next_selection.end.column > 0 || next_selection.is_empty() {
10328 display_map.next_line_boundary(next_selection.end).0.row + 1
10329 } else {
10330 next_selection.end.row
10331 }
10332}
10333
10334impl EditorSnapshot {
10335 pub fn remote_selections_in_range<'a>(
10336 &'a self,
10337 range: &'a Range<Anchor>,
10338 collaboration_hub: &dyn CollaborationHub,
10339 cx: &'a AppContext,
10340 ) -> impl 'a + Iterator<Item = RemoteSelection> {
10341 let participant_names = collaboration_hub.user_names(cx);
10342 let participant_indices = collaboration_hub.user_participant_indices(cx);
10343 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
10344 let collaborators_by_replica_id = collaborators_by_peer_id
10345 .iter()
10346 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
10347 .collect::<HashMap<_, _>>();
10348 self.buffer_snapshot
10349 .remote_selections_in_range(range)
10350 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10351 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10352 let participant_index = participant_indices.get(&collaborator.user_id).copied();
10353 let user_name = participant_names.get(&collaborator.user_id).cloned();
10354 Some(RemoteSelection {
10355 replica_id,
10356 selection,
10357 cursor_shape,
10358 line_mode,
10359 participant_index,
10360 peer_id: collaborator.peer_id,
10361 user_name,
10362 })
10363 })
10364 }
10365
10366 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10367 self.display_snapshot.buffer_snapshot.language_at(position)
10368 }
10369
10370 pub fn is_focused(&self) -> bool {
10371 self.is_focused
10372 }
10373
10374 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10375 self.placeholder_text.as_ref()
10376 }
10377
10378 pub fn scroll_position(&self) -> gpui::Point<f32> {
10379 self.scroll_anchor.scroll_position(&self.display_snapshot)
10380 }
10381
10382 pub fn gutter_dimensions(
10383 &self,
10384 font_id: FontId,
10385 font_size: Pixels,
10386 em_width: Pixels,
10387 max_line_number_width: Pixels,
10388 cx: &AppContext,
10389 ) -> GutterDimensions {
10390 if !self.show_gutter {
10391 return GutterDimensions::default();
10392 }
10393 let descent = cx.text_system().descent(font_id, font_size);
10394
10395 let show_git_gutter = matches!(
10396 ProjectSettings::get_global(cx).git.git_gutter,
10397 Some(GitGutterSetting::TrackedFiles)
10398 );
10399 let gutter_settings = EditorSettings::get_global(cx).gutter;
10400 let gutter_lines_enabled = gutter_settings.line_numbers;
10401 let line_gutter_width = if gutter_lines_enabled {
10402 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10403 let min_width_for_number_on_gutter = em_width * 4.0;
10404 max_line_number_width.max(min_width_for_number_on_gutter)
10405 } else {
10406 0.0.into()
10407 };
10408
10409 let git_blame_entries_width = self
10410 .render_git_blame_gutter
10411 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
10412
10413 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
10414 left_padding += if gutter_settings.code_actions {
10415 em_width * 3.0
10416 } else if show_git_gutter && gutter_lines_enabled {
10417 em_width * 2.0
10418 } else if show_git_gutter || gutter_lines_enabled {
10419 em_width
10420 } else {
10421 px(0.)
10422 };
10423
10424 let right_padding = if gutter_settings.folds && gutter_lines_enabled {
10425 em_width * 4.0
10426 } else if gutter_settings.folds {
10427 em_width * 3.0
10428 } else if gutter_lines_enabled {
10429 em_width
10430 } else {
10431 px(0.)
10432 };
10433
10434 GutterDimensions {
10435 left_padding,
10436 right_padding,
10437 width: line_gutter_width + left_padding + right_padding,
10438 margin: -descent,
10439 git_blame_entries_width,
10440 }
10441 }
10442}
10443
10444impl Deref for EditorSnapshot {
10445 type Target = DisplaySnapshot;
10446
10447 fn deref(&self) -> &Self::Target {
10448 &self.display_snapshot
10449 }
10450}
10451
10452#[derive(Clone, Debug, PartialEq, Eq)]
10453pub enum EditorEvent {
10454 InputIgnored {
10455 text: Arc<str>,
10456 },
10457 InputHandled {
10458 utf16_range_to_replace: Option<Range<isize>>,
10459 text: Arc<str>,
10460 },
10461 ExcerptsAdded {
10462 buffer: Model<Buffer>,
10463 predecessor: ExcerptId,
10464 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
10465 },
10466 ExcerptsRemoved {
10467 ids: Vec<ExcerptId>,
10468 },
10469 BufferEdited,
10470 Edited,
10471 Reparsed,
10472 Focused,
10473 Blurred,
10474 DirtyChanged,
10475 Saved,
10476 TitleChanged,
10477 DiffBaseChanged,
10478 SelectionsChanged {
10479 local: bool,
10480 },
10481 ScrollPositionChanged {
10482 local: bool,
10483 autoscroll: bool,
10484 },
10485 Closed,
10486 TransactionUndone {
10487 transaction_id: clock::Lamport,
10488 },
10489 TransactionBegun {
10490 transaction_id: clock::Lamport,
10491 },
10492}
10493
10494impl EventEmitter<EditorEvent> for Editor {}
10495
10496impl FocusableView for Editor {
10497 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
10498 self.focus_handle.clone()
10499 }
10500}
10501
10502impl Render for Editor {
10503 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
10504 let settings = ThemeSettings::get_global(cx);
10505
10506 let text_style = match self.mode {
10507 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
10508 color: cx.theme().colors().editor_foreground,
10509 font_family: settings.ui_font.family.clone(),
10510 font_features: settings.ui_font.features.clone(),
10511 font_size: rems(0.875).into(),
10512 font_weight: FontWeight::NORMAL,
10513 font_style: FontStyle::Normal,
10514 line_height: relative(settings.buffer_line_height.value()),
10515 background_color: None,
10516 underline: None,
10517 strikethrough: None,
10518 white_space: WhiteSpace::Normal,
10519 },
10520 EditorMode::Full => TextStyle {
10521 color: cx.theme().colors().editor_foreground,
10522 font_family: settings.buffer_font.family.clone(),
10523 font_features: settings.buffer_font.features.clone(),
10524 font_size: settings.buffer_font_size(cx).into(),
10525 font_weight: FontWeight::NORMAL,
10526 font_style: FontStyle::Normal,
10527 line_height: relative(settings.buffer_line_height.value()),
10528 background_color: None,
10529 underline: None,
10530 strikethrough: None,
10531 white_space: WhiteSpace::Normal,
10532 },
10533 };
10534
10535 let background = match self.mode {
10536 EditorMode::SingleLine => cx.theme().system().transparent,
10537 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
10538 EditorMode::Full => cx.theme().colors().editor_background,
10539 };
10540
10541 EditorElement::new(
10542 cx.view(),
10543 EditorStyle {
10544 background,
10545 local_player: cx.theme().players().local(),
10546 text: text_style,
10547 scrollbar_width: px(13.),
10548 syntax: cx.theme().syntax().clone(),
10549 status: cx.theme().status().clone(),
10550 inlay_hints_style: HighlightStyle {
10551 color: Some(cx.theme().status().hint),
10552 ..HighlightStyle::default()
10553 },
10554 suggestions_style: HighlightStyle {
10555 color: Some(cx.theme().status().predictive),
10556 ..HighlightStyle::default()
10557 },
10558 },
10559 )
10560 }
10561}
10562
10563impl ViewInputHandler for Editor {
10564 fn text_for_range(
10565 &mut self,
10566 range_utf16: Range<usize>,
10567 cx: &mut ViewContext<Self>,
10568 ) -> Option<String> {
10569 Some(
10570 self.buffer
10571 .read(cx)
10572 .read(cx)
10573 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
10574 .collect(),
10575 )
10576 }
10577
10578 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10579 // Prevent the IME menu from appearing when holding down an alphabetic key
10580 // while input is disabled.
10581 if !self.input_enabled {
10582 return None;
10583 }
10584
10585 let range = self.selections.newest::<OffsetUtf16>(cx).range();
10586 Some(range.start.0..range.end.0)
10587 }
10588
10589 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10590 let snapshot = self.buffer.read(cx).read(cx);
10591 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
10592 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
10593 }
10594
10595 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
10596 self.clear_highlights::<InputComposition>(cx);
10597 self.ime_transaction.take();
10598 }
10599
10600 fn replace_text_in_range(
10601 &mut self,
10602 range_utf16: Option<Range<usize>>,
10603 text: &str,
10604 cx: &mut ViewContext<Self>,
10605 ) {
10606 if !self.input_enabled {
10607 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10608 return;
10609 }
10610
10611 self.transact(cx, |this, cx| {
10612 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
10613 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10614 Some(this.selection_replacement_ranges(range_utf16, cx))
10615 } else {
10616 this.marked_text_ranges(cx)
10617 };
10618
10619 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
10620 let newest_selection_id = this.selections.newest_anchor().id;
10621 this.selections
10622 .all::<OffsetUtf16>(cx)
10623 .iter()
10624 .zip(ranges_to_replace.iter())
10625 .find_map(|(selection, range)| {
10626 if selection.id == newest_selection_id {
10627 Some(
10628 (range.start.0 as isize - selection.head().0 as isize)
10629 ..(range.end.0 as isize - selection.head().0 as isize),
10630 )
10631 } else {
10632 None
10633 }
10634 })
10635 });
10636
10637 cx.emit(EditorEvent::InputHandled {
10638 utf16_range_to_replace: range_to_replace,
10639 text: text.into(),
10640 });
10641
10642 if let Some(new_selected_ranges) = new_selected_ranges {
10643 this.change_selections(None, cx, |selections| {
10644 selections.select_ranges(new_selected_ranges)
10645 });
10646 this.backspace(&Default::default(), cx);
10647 }
10648
10649 this.handle_input(text, cx);
10650 });
10651
10652 if let Some(transaction) = self.ime_transaction {
10653 self.buffer.update(cx, |buffer, cx| {
10654 buffer.group_until_transaction(transaction, cx);
10655 });
10656 }
10657
10658 self.unmark_text(cx);
10659 }
10660
10661 fn replace_and_mark_text_in_range(
10662 &mut self,
10663 range_utf16: Option<Range<usize>>,
10664 text: &str,
10665 new_selected_range_utf16: Option<Range<usize>>,
10666 cx: &mut ViewContext<Self>,
10667 ) {
10668 if !self.input_enabled {
10669 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10670 return;
10671 }
10672
10673 let transaction = self.transact(cx, |this, cx| {
10674 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
10675 let snapshot = this.buffer.read(cx).read(cx);
10676 if let Some(relative_range_utf16) = range_utf16.as_ref() {
10677 for marked_range in &mut marked_ranges {
10678 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
10679 marked_range.start.0 += relative_range_utf16.start;
10680 marked_range.start =
10681 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
10682 marked_range.end =
10683 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
10684 }
10685 }
10686 Some(marked_ranges)
10687 } else if let Some(range_utf16) = range_utf16 {
10688 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10689 Some(this.selection_replacement_ranges(range_utf16, cx))
10690 } else {
10691 None
10692 };
10693
10694 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
10695 let newest_selection_id = this.selections.newest_anchor().id;
10696 this.selections
10697 .all::<OffsetUtf16>(cx)
10698 .iter()
10699 .zip(ranges_to_replace.iter())
10700 .find_map(|(selection, range)| {
10701 if selection.id == newest_selection_id {
10702 Some(
10703 (range.start.0 as isize - selection.head().0 as isize)
10704 ..(range.end.0 as isize - selection.head().0 as isize),
10705 )
10706 } else {
10707 None
10708 }
10709 })
10710 });
10711
10712 cx.emit(EditorEvent::InputHandled {
10713 utf16_range_to_replace: range_to_replace,
10714 text: text.into(),
10715 });
10716
10717 if let Some(ranges) = ranges_to_replace {
10718 this.change_selections(None, cx, |s| s.select_ranges(ranges));
10719 }
10720
10721 let marked_ranges = {
10722 let snapshot = this.buffer.read(cx).read(cx);
10723 this.selections
10724 .disjoint_anchors()
10725 .iter()
10726 .map(|selection| {
10727 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
10728 })
10729 .collect::<Vec<_>>()
10730 };
10731
10732 if text.is_empty() {
10733 this.unmark_text(cx);
10734 } else {
10735 this.highlight_text::<InputComposition>(
10736 marked_ranges.clone(),
10737 HighlightStyle {
10738 underline: Some(UnderlineStyle {
10739 thickness: px(1.),
10740 color: None,
10741 wavy: false,
10742 }),
10743 ..Default::default()
10744 },
10745 cx,
10746 );
10747 }
10748
10749 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
10750 let use_autoclose = this.use_autoclose;
10751 this.set_use_autoclose(false);
10752 this.handle_input(text, cx);
10753 this.set_use_autoclose(use_autoclose);
10754
10755 if let Some(new_selected_range) = new_selected_range_utf16 {
10756 let snapshot = this.buffer.read(cx).read(cx);
10757 let new_selected_ranges = marked_ranges
10758 .into_iter()
10759 .map(|marked_range| {
10760 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
10761 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
10762 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
10763 snapshot.clip_offset_utf16(new_start, Bias::Left)
10764 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
10765 })
10766 .collect::<Vec<_>>();
10767
10768 drop(snapshot);
10769 this.change_selections(None, cx, |selections| {
10770 selections.select_ranges(new_selected_ranges)
10771 });
10772 }
10773 });
10774
10775 self.ime_transaction = self.ime_transaction.or(transaction);
10776 if let Some(transaction) = self.ime_transaction {
10777 self.buffer.update(cx, |buffer, cx| {
10778 buffer.group_until_transaction(transaction, cx);
10779 });
10780 }
10781
10782 if self.text_highlights::<InputComposition>(cx).is_none() {
10783 self.ime_transaction.take();
10784 }
10785 }
10786
10787 fn bounds_for_range(
10788 &mut self,
10789 range_utf16: Range<usize>,
10790 element_bounds: gpui::Bounds<Pixels>,
10791 cx: &mut ViewContext<Self>,
10792 ) -> Option<gpui::Bounds<Pixels>> {
10793 let text_layout_details = self.text_layout_details(cx);
10794 let style = &text_layout_details.editor_style;
10795 let font_id = cx.text_system().resolve_font(&style.text.font());
10796 let font_size = style.text.font_size.to_pixels(cx.rem_size());
10797 let line_height = style.text.line_height_in_pixels(cx.rem_size());
10798 let em_width = cx
10799 .text_system()
10800 .typographic_bounds(font_id, font_size, 'm')
10801 .unwrap()
10802 .size
10803 .width;
10804
10805 let snapshot = self.snapshot(cx);
10806 let scroll_position = snapshot.scroll_position();
10807 let scroll_left = scroll_position.x * em_width;
10808
10809 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
10810 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
10811 + self.gutter_dimensions.width;
10812 let y = line_height * (start.row() as f32 - scroll_position.y);
10813
10814 Some(Bounds {
10815 origin: element_bounds.origin + point(x, y),
10816 size: size(em_width, line_height),
10817 })
10818 }
10819}
10820
10821trait SelectionExt {
10822 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
10823 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
10824 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
10825 fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
10826 -> Range<u32>;
10827}
10828
10829impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
10830 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
10831 let start = self.start.to_point(buffer);
10832 let end = self.end.to_point(buffer);
10833 if self.reversed {
10834 end..start
10835 } else {
10836 start..end
10837 }
10838 }
10839
10840 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
10841 let start = self.start.to_offset(buffer);
10842 let end = self.end.to_offset(buffer);
10843 if self.reversed {
10844 end..start
10845 } else {
10846 start..end
10847 }
10848 }
10849
10850 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
10851 let start = self
10852 .start
10853 .to_point(&map.buffer_snapshot)
10854 .to_display_point(map);
10855 let end = self
10856 .end
10857 .to_point(&map.buffer_snapshot)
10858 .to_display_point(map);
10859 if self.reversed {
10860 end..start
10861 } else {
10862 start..end
10863 }
10864 }
10865
10866 fn spanned_rows(
10867 &self,
10868 include_end_if_at_line_start: bool,
10869 map: &DisplaySnapshot,
10870 ) -> Range<u32> {
10871 let start = self.start.to_point(&map.buffer_snapshot);
10872 let mut end = self.end.to_point(&map.buffer_snapshot);
10873 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
10874 end.row -= 1;
10875 }
10876
10877 let buffer_start = map.prev_line_boundary(start).0;
10878 let buffer_end = map.next_line_boundary(end).0;
10879 buffer_start.row..buffer_end.row + 1
10880 }
10881}
10882
10883impl<T: InvalidationRegion> InvalidationStack<T> {
10884 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
10885 where
10886 S: Clone + ToOffset,
10887 {
10888 while let Some(region) = self.last() {
10889 let all_selections_inside_invalidation_ranges =
10890 if selections.len() == region.ranges().len() {
10891 selections
10892 .iter()
10893 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
10894 .all(|(selection, invalidation_range)| {
10895 let head = selection.head().to_offset(buffer);
10896 invalidation_range.start <= head && invalidation_range.end >= head
10897 })
10898 } else {
10899 false
10900 };
10901
10902 if all_selections_inside_invalidation_ranges {
10903 break;
10904 } else {
10905 self.pop();
10906 }
10907 }
10908 }
10909}
10910
10911impl<T> Default for InvalidationStack<T> {
10912 fn default() -> Self {
10913 Self(Default::default())
10914 }
10915}
10916
10917impl<T> Deref for InvalidationStack<T> {
10918 type Target = Vec<T>;
10919
10920 fn deref(&self) -> &Self::Target {
10921 &self.0
10922 }
10923}
10924
10925impl<T> DerefMut for InvalidationStack<T> {
10926 fn deref_mut(&mut self) -> &mut Self::Target {
10927 &mut self.0
10928 }
10929}
10930
10931impl InvalidationRegion for SnippetState {
10932 fn ranges(&self) -> &[Range<Anchor>] {
10933 &self.ranges[self.active_index]
10934 }
10935}
10936
10937pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
10938 let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
10939
10940 Box::new(move |cx: &mut BlockContext| {
10941 let group_id: SharedString = cx.block_id.to_string().into();
10942
10943 let mut text_style = cx.text_style().clone();
10944 text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
10945 let theme_settings = ThemeSettings::get_global(cx);
10946 text_style.font_family = theme_settings.buffer_font.family.clone();
10947 text_style.font_style = theme_settings.buffer_font.style;
10948 text_style.font_features = theme_settings.buffer_font.features.clone();
10949 text_style.font_weight = theme_settings.buffer_font.weight;
10950
10951 let multi_line_diagnostic = diagnostic.message.contains('\n');
10952
10953 let buttons = |diagnostic: &Diagnostic, block_id: usize| {
10954 if multi_line_diagnostic {
10955 v_flex()
10956 } else {
10957 h_flex()
10958 }
10959 .children(diagnostic.is_primary.then(|| {
10960 IconButton::new(("close-block", block_id), IconName::XCircle)
10961 .icon_color(Color::Muted)
10962 .size(ButtonSize::Compact)
10963 .style(ButtonStyle::Transparent)
10964 .visible_on_hover(group_id.clone())
10965 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
10966 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
10967 }))
10968 .child(
10969 IconButton::new(("copy-block", block_id), IconName::Copy)
10970 .icon_color(Color::Muted)
10971 .size(ButtonSize::Compact)
10972 .style(ButtonStyle::Transparent)
10973 .visible_on_hover(group_id.clone())
10974 .on_click({
10975 let message = diagnostic.message.clone();
10976 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
10977 })
10978 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
10979 )
10980 };
10981
10982 let icon_size = buttons(&diagnostic, cx.block_id)
10983 .into_any_element()
10984 .layout_as_root(AvailableSpace::min_size(), cx);
10985
10986 h_flex()
10987 .id(cx.block_id)
10988 .group(group_id.clone())
10989 .relative()
10990 .size_full()
10991 .pl(cx.gutter_dimensions.width)
10992 .w(cx.max_width + cx.gutter_dimensions.width)
10993 .child(
10994 div()
10995 .flex()
10996 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
10997 .flex_shrink(),
10998 )
10999 .child(buttons(&diagnostic, cx.block_id))
11000 .child(div().flex().flex_shrink_0().child(
11001 StyledText::new(text_without_backticks.clone()).with_highlights(
11002 &text_style,
11003 code_ranges.iter().map(|range| {
11004 (
11005 range.clone(),
11006 HighlightStyle {
11007 font_weight: Some(FontWeight::BOLD),
11008 ..Default::default()
11009 },
11010 )
11011 }),
11012 ),
11013 ))
11014 .into_any_element()
11015 })
11016}
11017
11018pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
11019 let mut text_without_backticks = String::new();
11020 let mut code_ranges = Vec::new();
11021
11022 if let Some(source) = &diagnostic.source {
11023 text_without_backticks.push_str(&source);
11024 code_ranges.push(0..source.len());
11025 text_without_backticks.push_str(": ");
11026 }
11027
11028 let mut prev_offset = 0;
11029 let mut in_code_block = false;
11030 for (ix, _) in diagnostic
11031 .message
11032 .match_indices('`')
11033 .chain([(diagnostic.message.len(), "")])
11034 {
11035 let prev_len = text_without_backticks.len();
11036 text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
11037 prev_offset = ix + 1;
11038 if in_code_block {
11039 code_ranges.push(prev_len..text_without_backticks.len());
11040 in_code_block = false;
11041 } else {
11042 in_code_block = true;
11043 }
11044 }
11045
11046 (text_without_backticks.into(), code_ranges)
11047}
11048
11049fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
11050 match (severity, valid) {
11051 (DiagnosticSeverity::ERROR, true) => colors.error,
11052 (DiagnosticSeverity::ERROR, false) => colors.error,
11053 (DiagnosticSeverity::WARNING, true) => colors.warning,
11054 (DiagnosticSeverity::WARNING, false) => colors.warning,
11055 (DiagnosticSeverity::INFORMATION, true) => colors.info,
11056 (DiagnosticSeverity::INFORMATION, false) => colors.info,
11057 (DiagnosticSeverity::HINT, true) => colors.info,
11058 (DiagnosticSeverity::HINT, false) => colors.info,
11059 _ => colors.ignored,
11060 }
11061}
11062
11063pub fn styled_runs_for_code_label<'a>(
11064 label: &'a CodeLabel,
11065 syntax_theme: &'a theme::SyntaxTheme,
11066) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
11067 let fade_out = HighlightStyle {
11068 fade_out: Some(0.35),
11069 ..Default::default()
11070 };
11071
11072 let mut prev_end = label.filter_range.end;
11073 label
11074 .runs
11075 .iter()
11076 .enumerate()
11077 .flat_map(move |(ix, (range, highlight_id))| {
11078 let style = if let Some(style) = highlight_id.style(syntax_theme) {
11079 style
11080 } else {
11081 return Default::default();
11082 };
11083 let mut muted_style = style;
11084 muted_style.highlight(fade_out);
11085
11086 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
11087 if range.start >= label.filter_range.end {
11088 if range.start > prev_end {
11089 runs.push((prev_end..range.start, fade_out));
11090 }
11091 runs.push((range.clone(), muted_style));
11092 } else if range.end <= label.filter_range.end {
11093 runs.push((range.clone(), style));
11094 } else {
11095 runs.push((range.start..label.filter_range.end, style));
11096 runs.push((label.filter_range.end..range.end, muted_style));
11097 }
11098 prev_end = cmp::max(prev_end, range.end);
11099
11100 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
11101 runs.push((prev_end..label.text.len(), fade_out));
11102 }
11103
11104 runs
11105 })
11106}
11107
11108pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
11109 let mut prev_index = 0;
11110 let mut prev_codepoint: Option<char> = None;
11111 text.char_indices()
11112 .chain([(text.len(), '\0')])
11113 .filter_map(move |(index, codepoint)| {
11114 let prev_codepoint = prev_codepoint.replace(codepoint)?;
11115 let is_boundary = index == text.len()
11116 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
11117 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
11118 if is_boundary {
11119 let chunk = &text[prev_index..index];
11120 prev_index = index;
11121 Some(chunk)
11122 } else {
11123 None
11124 }
11125 })
11126}
11127
11128trait RangeToAnchorExt {
11129 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
11130}
11131
11132impl<T: ToOffset> RangeToAnchorExt for Range<T> {
11133 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
11134 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
11135 }
11136}