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