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