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