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