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