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