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