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