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