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