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 do_paste(
6417 &mut self,
6418 text: &String,
6419 clipboard_selections: Option<Vec<ClipboardSelection>>,
6420 handle_entire_lines: bool,
6421 cx: &mut ViewContext<Self>,
6422 ) {
6423 if self.read_only(cx) {
6424 return;
6425 }
6426
6427 let clipboard_text = Cow::Borrowed(text);
6428
6429 self.transact(cx, |this, cx| {
6430 if let Some(mut clipboard_selections) = clipboard_selections {
6431 let old_selections = this.selections.all::<usize>(cx);
6432 let all_selections_were_entire_line =
6433 clipboard_selections.iter().all(|s| s.is_entire_line);
6434 let first_selection_indent_column =
6435 clipboard_selections.first().map(|s| s.first_line_indent);
6436 if clipboard_selections.len() != old_selections.len() {
6437 clipboard_selections.drain(..);
6438 }
6439
6440 this.buffer.update(cx, |buffer, cx| {
6441 let snapshot = buffer.read(cx);
6442 let mut start_offset = 0;
6443 let mut edits = Vec::new();
6444 let mut original_indent_columns = Vec::new();
6445 for (ix, selection) in old_selections.iter().enumerate() {
6446 let to_insert;
6447 let entire_line;
6448 let original_indent_column;
6449 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6450 let end_offset = start_offset + clipboard_selection.len;
6451 to_insert = &clipboard_text[start_offset..end_offset];
6452 entire_line = clipboard_selection.is_entire_line;
6453 start_offset = end_offset + 1;
6454 original_indent_column = Some(clipboard_selection.first_line_indent);
6455 } else {
6456 to_insert = clipboard_text.as_str();
6457 entire_line = all_selections_were_entire_line;
6458 original_indent_column = first_selection_indent_column
6459 }
6460
6461 // If the corresponding selection was empty when this slice of the
6462 // clipboard text was written, then the entire line containing the
6463 // selection was copied. If this selection is also currently empty,
6464 // then paste the line before the current line of the buffer.
6465 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6466 let column = selection.start.to_point(&snapshot).column as usize;
6467 let line_start = selection.start - column;
6468 line_start..line_start
6469 } else {
6470 selection.range()
6471 };
6472
6473 edits.push((range, to_insert));
6474 original_indent_columns.extend(original_indent_column);
6475 }
6476 drop(snapshot);
6477
6478 buffer.edit(
6479 edits,
6480 Some(AutoindentMode::Block {
6481 original_indent_columns,
6482 }),
6483 cx,
6484 );
6485 });
6486
6487 let selections = this.selections.all::<usize>(cx);
6488 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6489 } else {
6490 this.insert(&clipboard_text, cx);
6491 }
6492 });
6493 }
6494
6495 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6496 if let Some(item) = cx.read_from_clipboard() {
6497 self.do_paste(
6498 item.text(),
6499 item.metadata::<Vec<ClipboardSelection>>(),
6500 true,
6501 cx,
6502 )
6503 };
6504 }
6505
6506 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6507 if self.read_only(cx) {
6508 return;
6509 }
6510
6511 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6512 if let Some((selections, _)) =
6513 self.selection_history.transaction(transaction_id).cloned()
6514 {
6515 self.change_selections(None, cx, |s| {
6516 s.select_anchors(selections.to_vec());
6517 });
6518 }
6519 self.request_autoscroll(Autoscroll::fit(), cx);
6520 self.unmark_text(cx);
6521 self.refresh_inline_completion(true, cx);
6522 cx.emit(EditorEvent::Edited { transaction_id });
6523 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6524 }
6525 }
6526
6527 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6528 if self.read_only(cx) {
6529 return;
6530 }
6531
6532 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6533 if let Some((_, Some(selections))) =
6534 self.selection_history.transaction(transaction_id).cloned()
6535 {
6536 self.change_selections(None, cx, |s| {
6537 s.select_anchors(selections.to_vec());
6538 });
6539 }
6540 self.request_autoscroll(Autoscroll::fit(), cx);
6541 self.unmark_text(cx);
6542 self.refresh_inline_completion(true, cx);
6543 cx.emit(EditorEvent::Edited { transaction_id });
6544 }
6545 }
6546
6547 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6548 self.buffer
6549 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6550 }
6551
6552 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6553 self.buffer
6554 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6555 }
6556
6557 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6558 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6559 let line_mode = s.line_mode;
6560 s.move_with(|map, selection| {
6561 let cursor = if selection.is_empty() && !line_mode {
6562 movement::left(map, selection.start)
6563 } else {
6564 selection.start
6565 };
6566 selection.collapse_to(cursor, SelectionGoal::None);
6567 });
6568 })
6569 }
6570
6571 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6572 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6573 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6574 })
6575 }
6576
6577 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6578 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6579 let line_mode = s.line_mode;
6580 s.move_with(|map, selection| {
6581 let cursor = if selection.is_empty() && !line_mode {
6582 movement::right(map, selection.end)
6583 } else {
6584 selection.end
6585 };
6586 selection.collapse_to(cursor, SelectionGoal::None)
6587 });
6588 })
6589 }
6590
6591 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6592 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6593 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6594 })
6595 }
6596
6597 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6598 if self.take_rename(true, cx).is_some() {
6599 return;
6600 }
6601
6602 if matches!(self.mode, EditorMode::SingleLine) {
6603 cx.propagate();
6604 return;
6605 }
6606
6607 let text_layout_details = &self.text_layout_details(cx);
6608 let selection_count = self.selections.count();
6609 let first_selection = self.selections.first_anchor();
6610
6611 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6612 let line_mode = s.line_mode;
6613 s.move_with(|map, selection| {
6614 if !selection.is_empty() && !line_mode {
6615 selection.goal = SelectionGoal::None;
6616 }
6617 let (cursor, goal) = movement::up(
6618 map,
6619 selection.start,
6620 selection.goal,
6621 false,
6622 &text_layout_details,
6623 );
6624 selection.collapse_to(cursor, goal);
6625 });
6626 });
6627
6628 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6629 {
6630 cx.propagate();
6631 }
6632 }
6633
6634 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6635 if self.take_rename(true, cx).is_some() {
6636 return;
6637 }
6638
6639 if matches!(self.mode, EditorMode::SingleLine) {
6640 cx.propagate();
6641 return;
6642 }
6643
6644 let text_layout_details = &self.text_layout_details(cx);
6645
6646 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6647 let line_mode = s.line_mode;
6648 s.move_with(|map, selection| {
6649 if !selection.is_empty() && !line_mode {
6650 selection.goal = SelectionGoal::None;
6651 }
6652 let (cursor, goal) = movement::up_by_rows(
6653 map,
6654 selection.start,
6655 action.lines,
6656 selection.goal,
6657 false,
6658 &text_layout_details,
6659 );
6660 selection.collapse_to(cursor, goal);
6661 });
6662 })
6663 }
6664
6665 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6666 if self.take_rename(true, cx).is_some() {
6667 return;
6668 }
6669
6670 if matches!(self.mode, EditorMode::SingleLine) {
6671 cx.propagate();
6672 return;
6673 }
6674
6675 let text_layout_details = &self.text_layout_details(cx);
6676
6677 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6678 let line_mode = s.line_mode;
6679 s.move_with(|map, selection| {
6680 if !selection.is_empty() && !line_mode {
6681 selection.goal = SelectionGoal::None;
6682 }
6683 let (cursor, goal) = movement::down_by_rows(
6684 map,
6685 selection.start,
6686 action.lines,
6687 selection.goal,
6688 false,
6689 &text_layout_details,
6690 );
6691 selection.collapse_to(cursor, goal);
6692 });
6693 })
6694 }
6695
6696 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6697 let text_layout_details = &self.text_layout_details(cx);
6698 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6699 s.move_heads_with(|map, head, goal| {
6700 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6701 })
6702 })
6703 }
6704
6705 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6706 let text_layout_details = &self.text_layout_details(cx);
6707 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6708 s.move_heads_with(|map, head, goal| {
6709 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6710 })
6711 })
6712 }
6713
6714 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6715 if self.take_rename(true, cx).is_some() {
6716 return;
6717 }
6718
6719 if matches!(self.mode, EditorMode::SingleLine) {
6720 cx.propagate();
6721 return;
6722 }
6723
6724 let row_count = if let Some(row_count) = self.visible_line_count() {
6725 row_count as u32 - 1
6726 } else {
6727 return;
6728 };
6729
6730 let autoscroll = if action.center_cursor {
6731 Autoscroll::center()
6732 } else {
6733 Autoscroll::fit()
6734 };
6735
6736 let text_layout_details = &self.text_layout_details(cx);
6737
6738 self.change_selections(Some(autoscroll), cx, |s| {
6739 let line_mode = s.line_mode;
6740 s.move_with(|map, selection| {
6741 if !selection.is_empty() && !line_mode {
6742 selection.goal = SelectionGoal::None;
6743 }
6744 let (cursor, goal) = movement::up_by_rows(
6745 map,
6746 selection.end,
6747 row_count,
6748 selection.goal,
6749 false,
6750 &text_layout_details,
6751 );
6752 selection.collapse_to(cursor, goal);
6753 });
6754 });
6755 }
6756
6757 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
6758 let text_layout_details = &self.text_layout_details(cx);
6759 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6760 s.move_heads_with(|map, head, goal| {
6761 movement::up(map, head, goal, false, &text_layout_details)
6762 })
6763 })
6764 }
6765
6766 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
6767 self.take_rename(true, cx);
6768
6769 if self.mode == EditorMode::SingleLine {
6770 cx.propagate();
6771 return;
6772 }
6773
6774 let text_layout_details = &self.text_layout_details(cx);
6775 let selection_count = self.selections.count();
6776 let first_selection = self.selections.first_anchor();
6777
6778 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6779 let line_mode = s.line_mode;
6780 s.move_with(|map, selection| {
6781 if !selection.is_empty() && !line_mode {
6782 selection.goal = SelectionGoal::None;
6783 }
6784 let (cursor, goal) = movement::down(
6785 map,
6786 selection.end,
6787 selection.goal,
6788 false,
6789 &text_layout_details,
6790 );
6791 selection.collapse_to(cursor, goal);
6792 });
6793 });
6794
6795 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6796 {
6797 cx.propagate();
6798 }
6799 }
6800
6801 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
6802 if self.take_rename(true, cx).is_some() {
6803 return;
6804 }
6805
6806 if self
6807 .context_menu
6808 .write()
6809 .as_mut()
6810 .map(|menu| menu.select_last(self.project.as_ref(), cx))
6811 .unwrap_or(false)
6812 {
6813 return;
6814 }
6815
6816 if matches!(self.mode, EditorMode::SingleLine) {
6817 cx.propagate();
6818 return;
6819 }
6820
6821 let row_count = if let Some(row_count) = self.visible_line_count() {
6822 row_count as u32 - 1
6823 } else {
6824 return;
6825 };
6826
6827 let autoscroll = if action.center_cursor {
6828 Autoscroll::center()
6829 } else {
6830 Autoscroll::fit()
6831 };
6832
6833 let text_layout_details = &self.text_layout_details(cx);
6834 self.change_selections(Some(autoscroll), cx, |s| {
6835 let line_mode = s.line_mode;
6836 s.move_with(|map, selection| {
6837 if !selection.is_empty() && !line_mode {
6838 selection.goal = SelectionGoal::None;
6839 }
6840 let (cursor, goal) = movement::down_by_rows(
6841 map,
6842 selection.end,
6843 row_count,
6844 selection.goal,
6845 false,
6846 &text_layout_details,
6847 );
6848 selection.collapse_to(cursor, goal);
6849 });
6850 });
6851 }
6852
6853 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
6854 let text_layout_details = &self.text_layout_details(cx);
6855 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6856 s.move_heads_with(|map, head, goal| {
6857 movement::down(map, head, goal, false, &text_layout_details)
6858 })
6859 });
6860 }
6861
6862 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
6863 if let Some(context_menu) = self.context_menu.write().as_mut() {
6864 context_menu.select_first(self.project.as_ref(), cx);
6865 }
6866 }
6867
6868 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
6869 if let Some(context_menu) = self.context_menu.write().as_mut() {
6870 context_menu.select_prev(self.project.as_ref(), cx);
6871 }
6872 }
6873
6874 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
6875 if let Some(context_menu) = self.context_menu.write().as_mut() {
6876 context_menu.select_next(self.project.as_ref(), cx);
6877 }
6878 }
6879
6880 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
6881 if let Some(context_menu) = self.context_menu.write().as_mut() {
6882 context_menu.select_last(self.project.as_ref(), cx);
6883 }
6884 }
6885
6886 pub fn move_to_previous_word_start(
6887 &mut self,
6888 _: &MoveToPreviousWordStart,
6889 cx: &mut ViewContext<Self>,
6890 ) {
6891 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6892 s.move_cursors_with(|map, head, _| {
6893 (
6894 movement::previous_word_start(map, head),
6895 SelectionGoal::None,
6896 )
6897 });
6898 })
6899 }
6900
6901 pub fn move_to_previous_subword_start(
6902 &mut self,
6903 _: &MoveToPreviousSubwordStart,
6904 cx: &mut ViewContext<Self>,
6905 ) {
6906 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6907 s.move_cursors_with(|map, head, _| {
6908 (
6909 movement::previous_subword_start(map, head),
6910 SelectionGoal::None,
6911 )
6912 });
6913 })
6914 }
6915
6916 pub fn select_to_previous_word_start(
6917 &mut self,
6918 _: &SelectToPreviousWordStart,
6919 cx: &mut ViewContext<Self>,
6920 ) {
6921 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6922 s.move_heads_with(|map, head, _| {
6923 (
6924 movement::previous_word_start(map, head),
6925 SelectionGoal::None,
6926 )
6927 });
6928 })
6929 }
6930
6931 pub fn select_to_previous_subword_start(
6932 &mut self,
6933 _: &SelectToPreviousSubwordStart,
6934 cx: &mut ViewContext<Self>,
6935 ) {
6936 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6937 s.move_heads_with(|map, head, _| {
6938 (
6939 movement::previous_subword_start(map, head),
6940 SelectionGoal::None,
6941 )
6942 });
6943 })
6944 }
6945
6946 pub fn delete_to_previous_word_start(
6947 &mut self,
6948 _: &DeleteToPreviousWordStart,
6949 cx: &mut ViewContext<Self>,
6950 ) {
6951 self.transact(cx, |this, cx| {
6952 this.select_autoclose_pair(cx);
6953 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6954 let line_mode = s.line_mode;
6955 s.move_with(|map, selection| {
6956 if selection.is_empty() && !line_mode {
6957 let cursor = movement::previous_word_start(map, selection.head());
6958 selection.set_head(cursor, SelectionGoal::None);
6959 }
6960 });
6961 });
6962 this.insert("", cx);
6963 });
6964 }
6965
6966 pub fn delete_to_previous_subword_start(
6967 &mut self,
6968 _: &DeleteToPreviousSubwordStart,
6969 cx: &mut ViewContext<Self>,
6970 ) {
6971 self.transact(cx, |this, cx| {
6972 this.select_autoclose_pair(cx);
6973 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6974 let line_mode = s.line_mode;
6975 s.move_with(|map, selection| {
6976 if selection.is_empty() && !line_mode {
6977 let cursor = movement::previous_subword_start(map, selection.head());
6978 selection.set_head(cursor, SelectionGoal::None);
6979 }
6980 });
6981 });
6982 this.insert("", cx);
6983 });
6984 }
6985
6986 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
6987 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6988 s.move_cursors_with(|map, head, _| {
6989 (movement::next_word_end(map, head), SelectionGoal::None)
6990 });
6991 })
6992 }
6993
6994 pub fn move_to_next_subword_end(
6995 &mut self,
6996 _: &MoveToNextSubwordEnd,
6997 cx: &mut ViewContext<Self>,
6998 ) {
6999 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7000 s.move_cursors_with(|map, head, _| {
7001 (movement::next_subword_end(map, head), SelectionGoal::None)
7002 });
7003 })
7004 }
7005
7006 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7007 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7008 s.move_heads_with(|map, head, _| {
7009 (movement::next_word_end(map, head), SelectionGoal::None)
7010 });
7011 })
7012 }
7013
7014 pub fn select_to_next_subword_end(
7015 &mut self,
7016 _: &SelectToNextSubwordEnd,
7017 cx: &mut ViewContext<Self>,
7018 ) {
7019 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7020 s.move_heads_with(|map, head, _| {
7021 (movement::next_subword_end(map, head), SelectionGoal::None)
7022 });
7023 })
7024 }
7025
7026 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7027 self.transact(cx, |this, cx| {
7028 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7029 let line_mode = s.line_mode;
7030 s.move_with(|map, selection| {
7031 if selection.is_empty() && !line_mode {
7032 let cursor = movement::next_word_end(map, selection.head());
7033 selection.set_head(cursor, SelectionGoal::None);
7034 }
7035 });
7036 });
7037 this.insert("", cx);
7038 });
7039 }
7040
7041 pub fn delete_to_next_subword_end(
7042 &mut self,
7043 _: &DeleteToNextSubwordEnd,
7044 cx: &mut ViewContext<Self>,
7045 ) {
7046 self.transact(cx, |this, cx| {
7047 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7048 s.move_with(|map, selection| {
7049 if selection.is_empty() {
7050 let cursor = movement::next_subword_end(map, selection.head());
7051 selection.set_head(cursor, SelectionGoal::None);
7052 }
7053 });
7054 });
7055 this.insert("", cx);
7056 });
7057 }
7058
7059 pub fn move_to_beginning_of_line(
7060 &mut self,
7061 action: &MoveToBeginningOfLine,
7062 cx: &mut ViewContext<Self>,
7063 ) {
7064 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7065 s.move_cursors_with(|map, head, _| {
7066 (
7067 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7068 SelectionGoal::None,
7069 )
7070 });
7071 })
7072 }
7073
7074 pub fn select_to_beginning_of_line(
7075 &mut self,
7076 action: &SelectToBeginningOfLine,
7077 cx: &mut ViewContext<Self>,
7078 ) {
7079 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7080 s.move_heads_with(|map, head, _| {
7081 (
7082 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7083 SelectionGoal::None,
7084 )
7085 });
7086 });
7087 }
7088
7089 pub fn delete_to_beginning_of_line(
7090 &mut self,
7091 _: &DeleteToBeginningOfLine,
7092 cx: &mut ViewContext<Self>,
7093 ) {
7094 self.transact(cx, |this, cx| {
7095 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7096 s.move_with(|_, selection| {
7097 selection.reversed = true;
7098 });
7099 });
7100
7101 this.select_to_beginning_of_line(
7102 &SelectToBeginningOfLine {
7103 stop_at_soft_wraps: false,
7104 },
7105 cx,
7106 );
7107 this.backspace(&Backspace, cx);
7108 });
7109 }
7110
7111 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7112 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7113 s.move_cursors_with(|map, head, _| {
7114 (
7115 movement::line_end(map, head, action.stop_at_soft_wraps),
7116 SelectionGoal::None,
7117 )
7118 });
7119 })
7120 }
7121
7122 pub fn select_to_end_of_line(
7123 &mut self,
7124 action: &SelectToEndOfLine,
7125 cx: &mut ViewContext<Self>,
7126 ) {
7127 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7128 s.move_heads_with(|map, head, _| {
7129 (
7130 movement::line_end(map, head, action.stop_at_soft_wraps),
7131 SelectionGoal::None,
7132 )
7133 });
7134 })
7135 }
7136
7137 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7138 self.transact(cx, |this, cx| {
7139 this.select_to_end_of_line(
7140 &SelectToEndOfLine {
7141 stop_at_soft_wraps: false,
7142 },
7143 cx,
7144 );
7145 this.delete(&Delete, cx);
7146 });
7147 }
7148
7149 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7150 self.transact(cx, |this, cx| {
7151 this.select_to_end_of_line(
7152 &SelectToEndOfLine {
7153 stop_at_soft_wraps: false,
7154 },
7155 cx,
7156 );
7157 this.cut(&Cut, cx);
7158 });
7159 }
7160
7161 pub fn move_to_start_of_paragraph(
7162 &mut self,
7163 _: &MoveToStartOfParagraph,
7164 cx: &mut ViewContext<Self>,
7165 ) {
7166 if matches!(self.mode, EditorMode::SingleLine) {
7167 cx.propagate();
7168 return;
7169 }
7170
7171 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7172 s.move_with(|map, selection| {
7173 selection.collapse_to(
7174 movement::start_of_paragraph(map, selection.head(), 1),
7175 SelectionGoal::None,
7176 )
7177 });
7178 })
7179 }
7180
7181 pub fn move_to_end_of_paragraph(
7182 &mut self,
7183 _: &MoveToEndOfParagraph,
7184 cx: &mut ViewContext<Self>,
7185 ) {
7186 if matches!(self.mode, EditorMode::SingleLine) {
7187 cx.propagate();
7188 return;
7189 }
7190
7191 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7192 s.move_with(|map, selection| {
7193 selection.collapse_to(
7194 movement::end_of_paragraph(map, selection.head(), 1),
7195 SelectionGoal::None,
7196 )
7197 });
7198 })
7199 }
7200
7201 pub fn select_to_start_of_paragraph(
7202 &mut self,
7203 _: &SelectToStartOfParagraph,
7204 cx: &mut ViewContext<Self>,
7205 ) {
7206 if matches!(self.mode, EditorMode::SingleLine) {
7207 cx.propagate();
7208 return;
7209 }
7210
7211 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7212 s.move_heads_with(|map, head, _| {
7213 (
7214 movement::start_of_paragraph(map, head, 1),
7215 SelectionGoal::None,
7216 )
7217 });
7218 })
7219 }
7220
7221 pub fn select_to_end_of_paragraph(
7222 &mut self,
7223 _: &SelectToEndOfParagraph,
7224 cx: &mut ViewContext<Self>,
7225 ) {
7226 if matches!(self.mode, EditorMode::SingleLine) {
7227 cx.propagate();
7228 return;
7229 }
7230
7231 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7232 s.move_heads_with(|map, head, _| {
7233 (
7234 movement::end_of_paragraph(map, head, 1),
7235 SelectionGoal::None,
7236 )
7237 });
7238 })
7239 }
7240
7241 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7242 if matches!(self.mode, EditorMode::SingleLine) {
7243 cx.propagate();
7244 return;
7245 }
7246
7247 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7248 s.select_ranges(vec![0..0]);
7249 });
7250 }
7251
7252 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7253 let mut selection = self.selections.last::<Point>(cx);
7254 selection.set_head(Point::zero(), SelectionGoal::None);
7255
7256 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7257 s.select(vec![selection]);
7258 });
7259 }
7260
7261 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7262 if matches!(self.mode, EditorMode::SingleLine) {
7263 cx.propagate();
7264 return;
7265 }
7266
7267 let cursor = self.buffer.read(cx).read(cx).len();
7268 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7269 s.select_ranges(vec![cursor..cursor])
7270 });
7271 }
7272
7273 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7274 self.nav_history = nav_history;
7275 }
7276
7277 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7278 self.nav_history.as_ref()
7279 }
7280
7281 fn push_to_nav_history(
7282 &mut self,
7283 cursor_anchor: Anchor,
7284 new_position: Option<Point>,
7285 cx: &mut ViewContext<Self>,
7286 ) {
7287 if let Some(nav_history) = self.nav_history.as_mut() {
7288 let buffer = self.buffer.read(cx).read(cx);
7289 let cursor_position = cursor_anchor.to_point(&buffer);
7290 let scroll_state = self.scroll_manager.anchor();
7291 let scroll_top_row = scroll_state.top_row(&buffer);
7292 drop(buffer);
7293
7294 if let Some(new_position) = new_position {
7295 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7296 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7297 return;
7298 }
7299 }
7300
7301 nav_history.push(
7302 Some(NavigationData {
7303 cursor_anchor,
7304 cursor_position,
7305 scroll_anchor: scroll_state,
7306 scroll_top_row,
7307 }),
7308 cx,
7309 );
7310 }
7311 }
7312
7313 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7314 let buffer = self.buffer.read(cx).snapshot(cx);
7315 let mut selection = self.selections.first::<usize>(cx);
7316 selection.set_head(buffer.len(), SelectionGoal::None);
7317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7318 s.select(vec![selection]);
7319 });
7320 }
7321
7322 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7323 let end = self.buffer.read(cx).read(cx).len();
7324 self.change_selections(None, cx, |s| {
7325 s.select_ranges(vec![0..end]);
7326 });
7327 }
7328
7329 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7330 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7331 let mut selections = self.selections.all::<Point>(cx);
7332 let max_point = display_map.buffer_snapshot.max_point();
7333 for selection in &mut selections {
7334 let rows = selection.spanned_rows(true, &display_map);
7335 selection.start = Point::new(rows.start.0, 0);
7336 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7337 selection.reversed = false;
7338 }
7339 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7340 s.select(selections);
7341 });
7342 }
7343
7344 pub fn split_selection_into_lines(
7345 &mut self,
7346 _: &SplitSelectionIntoLines,
7347 cx: &mut ViewContext<Self>,
7348 ) {
7349 let mut to_unfold = Vec::new();
7350 let mut new_selection_ranges = Vec::new();
7351 {
7352 let selections = self.selections.all::<Point>(cx);
7353 let buffer = self.buffer.read(cx).read(cx);
7354 for selection in selections {
7355 for row in selection.start.row..selection.end.row {
7356 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7357 new_selection_ranges.push(cursor..cursor);
7358 }
7359 new_selection_ranges.push(selection.end..selection.end);
7360 to_unfold.push(selection.start..selection.end);
7361 }
7362 }
7363 self.unfold_ranges(to_unfold, true, true, cx);
7364 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7365 s.select_ranges(new_selection_ranges);
7366 });
7367 }
7368
7369 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7370 self.add_selection(true, cx);
7371 }
7372
7373 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7374 self.add_selection(false, cx);
7375 }
7376
7377 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7378 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7379 let mut selections = self.selections.all::<Point>(cx);
7380 let text_layout_details = self.text_layout_details(cx);
7381 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7382 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7383 let range = oldest_selection.display_range(&display_map).sorted();
7384
7385 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7386 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7387 let positions = start_x.min(end_x)..start_x.max(end_x);
7388
7389 selections.clear();
7390 let mut stack = Vec::new();
7391 for row in range.start.row().0..=range.end.row().0 {
7392 if let Some(selection) = self.selections.build_columnar_selection(
7393 &display_map,
7394 DisplayRow(row),
7395 &positions,
7396 oldest_selection.reversed,
7397 &text_layout_details,
7398 ) {
7399 stack.push(selection.id);
7400 selections.push(selection);
7401 }
7402 }
7403
7404 if above {
7405 stack.reverse();
7406 }
7407
7408 AddSelectionsState { above, stack }
7409 });
7410
7411 let last_added_selection = *state.stack.last().unwrap();
7412 let mut new_selections = Vec::new();
7413 if above == state.above {
7414 let end_row = if above {
7415 DisplayRow(0)
7416 } else {
7417 display_map.max_point().row()
7418 };
7419
7420 'outer: for selection in selections {
7421 if selection.id == last_added_selection {
7422 let range = selection.display_range(&display_map).sorted();
7423 debug_assert_eq!(range.start.row(), range.end.row());
7424 let mut row = range.start.row();
7425 let positions =
7426 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7427 px(start)..px(end)
7428 } else {
7429 let start_x =
7430 display_map.x_for_display_point(range.start, &text_layout_details);
7431 let end_x =
7432 display_map.x_for_display_point(range.end, &text_layout_details);
7433 start_x.min(end_x)..start_x.max(end_x)
7434 };
7435
7436 while row != end_row {
7437 if above {
7438 row.0 -= 1;
7439 } else {
7440 row.0 += 1;
7441 }
7442
7443 if let Some(new_selection) = self.selections.build_columnar_selection(
7444 &display_map,
7445 row,
7446 &positions,
7447 selection.reversed,
7448 &text_layout_details,
7449 ) {
7450 state.stack.push(new_selection.id);
7451 if above {
7452 new_selections.push(new_selection);
7453 new_selections.push(selection);
7454 } else {
7455 new_selections.push(selection);
7456 new_selections.push(new_selection);
7457 }
7458
7459 continue 'outer;
7460 }
7461 }
7462 }
7463
7464 new_selections.push(selection);
7465 }
7466 } else {
7467 new_selections = selections;
7468 new_selections.retain(|s| s.id != last_added_selection);
7469 state.stack.pop();
7470 }
7471
7472 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7473 s.select(new_selections);
7474 });
7475 if state.stack.len() > 1 {
7476 self.add_selections_state = Some(state);
7477 }
7478 }
7479
7480 pub fn select_next_match_internal(
7481 &mut self,
7482 display_map: &DisplaySnapshot,
7483 replace_newest: bool,
7484 autoscroll: Option<Autoscroll>,
7485 cx: &mut ViewContext<Self>,
7486 ) -> Result<()> {
7487 fn select_next_match_ranges(
7488 this: &mut Editor,
7489 range: Range<usize>,
7490 replace_newest: bool,
7491 auto_scroll: Option<Autoscroll>,
7492 cx: &mut ViewContext<Editor>,
7493 ) {
7494 this.unfold_ranges([range.clone()], false, true, cx);
7495 this.change_selections(auto_scroll, cx, |s| {
7496 if replace_newest {
7497 s.delete(s.newest_anchor().id);
7498 }
7499 s.insert_range(range.clone());
7500 });
7501 }
7502
7503 let buffer = &display_map.buffer_snapshot;
7504 let mut selections = self.selections.all::<usize>(cx);
7505 if let Some(mut select_next_state) = self.select_next_state.take() {
7506 let query = &select_next_state.query;
7507 if !select_next_state.done {
7508 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7509 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7510 let mut next_selected_range = None;
7511
7512 let bytes_after_last_selection =
7513 buffer.bytes_in_range(last_selection.end..buffer.len());
7514 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7515 let query_matches = query
7516 .stream_find_iter(bytes_after_last_selection)
7517 .map(|result| (last_selection.end, result))
7518 .chain(
7519 query
7520 .stream_find_iter(bytes_before_first_selection)
7521 .map(|result| (0, result)),
7522 );
7523
7524 for (start_offset, query_match) in query_matches {
7525 let query_match = query_match.unwrap(); // can only fail due to I/O
7526 let offset_range =
7527 start_offset + query_match.start()..start_offset + query_match.end();
7528 let display_range = offset_range.start.to_display_point(&display_map)
7529 ..offset_range.end.to_display_point(&display_map);
7530
7531 if !select_next_state.wordwise
7532 || (!movement::is_inside_word(&display_map, display_range.start)
7533 && !movement::is_inside_word(&display_map, display_range.end))
7534 {
7535 // TODO: This is n^2, because we might check all the selections
7536 if !selections
7537 .iter()
7538 .any(|selection| selection.range().overlaps(&offset_range))
7539 {
7540 next_selected_range = Some(offset_range);
7541 break;
7542 }
7543 }
7544 }
7545
7546 if let Some(next_selected_range) = next_selected_range {
7547 select_next_match_ranges(
7548 self,
7549 next_selected_range,
7550 replace_newest,
7551 autoscroll,
7552 cx,
7553 );
7554 } else {
7555 select_next_state.done = true;
7556 }
7557 }
7558
7559 self.select_next_state = Some(select_next_state);
7560 } else {
7561 let mut only_carets = true;
7562 let mut same_text_selected = true;
7563 let mut selected_text = None;
7564
7565 let mut selections_iter = selections.iter().peekable();
7566 while let Some(selection) = selections_iter.next() {
7567 if selection.start != selection.end {
7568 only_carets = false;
7569 }
7570
7571 if same_text_selected {
7572 if selected_text.is_none() {
7573 selected_text =
7574 Some(buffer.text_for_range(selection.range()).collect::<String>());
7575 }
7576
7577 if let Some(next_selection) = selections_iter.peek() {
7578 if next_selection.range().len() == selection.range().len() {
7579 let next_selected_text = buffer
7580 .text_for_range(next_selection.range())
7581 .collect::<String>();
7582 if Some(next_selected_text) != selected_text {
7583 same_text_selected = false;
7584 selected_text = None;
7585 }
7586 } else {
7587 same_text_selected = false;
7588 selected_text = None;
7589 }
7590 }
7591 }
7592 }
7593
7594 if only_carets {
7595 for selection in &mut selections {
7596 let word_range = movement::surrounding_word(
7597 &display_map,
7598 selection.start.to_display_point(&display_map),
7599 );
7600 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7601 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7602 selection.goal = SelectionGoal::None;
7603 selection.reversed = false;
7604 select_next_match_ranges(
7605 self,
7606 selection.start..selection.end,
7607 replace_newest,
7608 autoscroll,
7609 cx,
7610 );
7611 }
7612
7613 if selections.len() == 1 {
7614 let selection = selections
7615 .last()
7616 .expect("ensured that there's only one selection");
7617 let query = buffer
7618 .text_for_range(selection.start..selection.end)
7619 .collect::<String>();
7620 let is_empty = query.is_empty();
7621 let select_state = SelectNextState {
7622 query: AhoCorasick::new(&[query])?,
7623 wordwise: true,
7624 done: is_empty,
7625 };
7626 self.select_next_state = Some(select_state);
7627 } else {
7628 self.select_next_state = None;
7629 }
7630 } else if let Some(selected_text) = selected_text {
7631 self.select_next_state = Some(SelectNextState {
7632 query: AhoCorasick::new(&[selected_text])?,
7633 wordwise: false,
7634 done: false,
7635 });
7636 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7637 }
7638 }
7639 Ok(())
7640 }
7641
7642 pub fn select_all_matches(
7643 &mut self,
7644 _action: &SelectAllMatches,
7645 cx: &mut ViewContext<Self>,
7646 ) -> Result<()> {
7647 self.push_to_selection_history();
7648 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7649
7650 self.select_next_match_internal(&display_map, false, None, cx)?;
7651 let Some(select_next_state) = self.select_next_state.as_mut() else {
7652 return Ok(());
7653 };
7654 if select_next_state.done {
7655 return Ok(());
7656 }
7657
7658 let mut new_selections = self.selections.all::<usize>(cx);
7659
7660 let buffer = &display_map.buffer_snapshot;
7661 let query_matches = select_next_state
7662 .query
7663 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7664
7665 for query_match in query_matches {
7666 let query_match = query_match.unwrap(); // can only fail due to I/O
7667 let offset_range = query_match.start()..query_match.end();
7668 let display_range = offset_range.start.to_display_point(&display_map)
7669 ..offset_range.end.to_display_point(&display_map);
7670
7671 if !select_next_state.wordwise
7672 || (!movement::is_inside_word(&display_map, display_range.start)
7673 && !movement::is_inside_word(&display_map, display_range.end))
7674 {
7675 self.selections.change_with(cx, |selections| {
7676 new_selections.push(Selection {
7677 id: selections.new_selection_id(),
7678 start: offset_range.start,
7679 end: offset_range.end,
7680 reversed: false,
7681 goal: SelectionGoal::None,
7682 });
7683 });
7684 }
7685 }
7686
7687 new_selections.sort_by_key(|selection| selection.start);
7688 let mut ix = 0;
7689 while ix + 1 < new_selections.len() {
7690 let current_selection = &new_selections[ix];
7691 let next_selection = &new_selections[ix + 1];
7692 if current_selection.range().overlaps(&next_selection.range()) {
7693 if current_selection.id < next_selection.id {
7694 new_selections.remove(ix + 1);
7695 } else {
7696 new_selections.remove(ix);
7697 }
7698 } else {
7699 ix += 1;
7700 }
7701 }
7702
7703 select_next_state.done = true;
7704 self.unfold_ranges(
7705 new_selections.iter().map(|selection| selection.range()),
7706 false,
7707 false,
7708 cx,
7709 );
7710 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
7711 selections.select(new_selections)
7712 });
7713
7714 Ok(())
7715 }
7716
7717 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
7718 self.push_to_selection_history();
7719 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7720 self.select_next_match_internal(
7721 &display_map,
7722 action.replace_newest,
7723 Some(Autoscroll::newest()),
7724 cx,
7725 )?;
7726 Ok(())
7727 }
7728
7729 pub fn select_previous(
7730 &mut self,
7731 action: &SelectPrevious,
7732 cx: &mut ViewContext<Self>,
7733 ) -> Result<()> {
7734 self.push_to_selection_history();
7735 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7736 let buffer = &display_map.buffer_snapshot;
7737 let mut selections = self.selections.all::<usize>(cx);
7738 if let Some(mut select_prev_state) = self.select_prev_state.take() {
7739 let query = &select_prev_state.query;
7740 if !select_prev_state.done {
7741 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7742 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7743 let mut next_selected_range = None;
7744 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
7745 let bytes_before_last_selection =
7746 buffer.reversed_bytes_in_range(0..last_selection.start);
7747 let bytes_after_first_selection =
7748 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
7749 let query_matches = query
7750 .stream_find_iter(bytes_before_last_selection)
7751 .map(|result| (last_selection.start, result))
7752 .chain(
7753 query
7754 .stream_find_iter(bytes_after_first_selection)
7755 .map(|result| (buffer.len(), result)),
7756 );
7757 for (end_offset, query_match) in query_matches {
7758 let query_match = query_match.unwrap(); // can only fail due to I/O
7759 let offset_range =
7760 end_offset - query_match.end()..end_offset - query_match.start();
7761 let display_range = offset_range.start.to_display_point(&display_map)
7762 ..offset_range.end.to_display_point(&display_map);
7763
7764 if !select_prev_state.wordwise
7765 || (!movement::is_inside_word(&display_map, display_range.start)
7766 && !movement::is_inside_word(&display_map, display_range.end))
7767 {
7768 next_selected_range = Some(offset_range);
7769 break;
7770 }
7771 }
7772
7773 if let Some(next_selected_range) = next_selected_range {
7774 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
7775 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7776 if action.replace_newest {
7777 s.delete(s.newest_anchor().id);
7778 }
7779 s.insert_range(next_selected_range);
7780 });
7781 } else {
7782 select_prev_state.done = true;
7783 }
7784 }
7785
7786 self.select_prev_state = Some(select_prev_state);
7787 } else {
7788 let mut only_carets = true;
7789 let mut same_text_selected = true;
7790 let mut selected_text = None;
7791
7792 let mut selections_iter = selections.iter().peekable();
7793 while let Some(selection) = selections_iter.next() {
7794 if selection.start != selection.end {
7795 only_carets = false;
7796 }
7797
7798 if same_text_selected {
7799 if selected_text.is_none() {
7800 selected_text =
7801 Some(buffer.text_for_range(selection.range()).collect::<String>());
7802 }
7803
7804 if let Some(next_selection) = selections_iter.peek() {
7805 if next_selection.range().len() == selection.range().len() {
7806 let next_selected_text = buffer
7807 .text_for_range(next_selection.range())
7808 .collect::<String>();
7809 if Some(next_selected_text) != selected_text {
7810 same_text_selected = false;
7811 selected_text = None;
7812 }
7813 } else {
7814 same_text_selected = false;
7815 selected_text = None;
7816 }
7817 }
7818 }
7819 }
7820
7821 if only_carets {
7822 for selection in &mut selections {
7823 let word_range = movement::surrounding_word(
7824 &display_map,
7825 selection.start.to_display_point(&display_map),
7826 );
7827 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7828 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7829 selection.goal = SelectionGoal::None;
7830 selection.reversed = false;
7831 }
7832 if selections.len() == 1 {
7833 let selection = selections
7834 .last()
7835 .expect("ensured that there's only one selection");
7836 let query = buffer
7837 .text_for_range(selection.start..selection.end)
7838 .collect::<String>();
7839 let is_empty = query.is_empty();
7840 let select_state = SelectNextState {
7841 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
7842 wordwise: true,
7843 done: is_empty,
7844 };
7845 self.select_prev_state = Some(select_state);
7846 } else {
7847 self.select_prev_state = None;
7848 }
7849
7850 self.unfold_ranges(
7851 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
7852 false,
7853 true,
7854 cx,
7855 );
7856 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7857 s.select(selections);
7858 });
7859 } else if let Some(selected_text) = selected_text {
7860 self.select_prev_state = Some(SelectNextState {
7861 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
7862 wordwise: false,
7863 done: false,
7864 });
7865 self.select_previous(action, cx)?;
7866 }
7867 }
7868 Ok(())
7869 }
7870
7871 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
7872 let text_layout_details = &self.text_layout_details(cx);
7873 self.transact(cx, |this, cx| {
7874 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7875 let mut edits = Vec::new();
7876 let mut selection_edit_ranges = Vec::new();
7877 let mut last_toggled_row = None;
7878 let snapshot = this.buffer.read(cx).read(cx);
7879 let empty_str: Arc<str> = "".into();
7880 let mut suffixes_inserted = Vec::new();
7881
7882 fn comment_prefix_range(
7883 snapshot: &MultiBufferSnapshot,
7884 row: MultiBufferRow,
7885 comment_prefix: &str,
7886 comment_prefix_whitespace: &str,
7887 ) -> Range<Point> {
7888 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
7889
7890 let mut line_bytes = snapshot
7891 .bytes_in_range(start..snapshot.max_point())
7892 .flatten()
7893 .copied();
7894
7895 // If this line currently begins with the line comment prefix, then record
7896 // the range containing the prefix.
7897 if line_bytes
7898 .by_ref()
7899 .take(comment_prefix.len())
7900 .eq(comment_prefix.bytes())
7901 {
7902 // Include any whitespace that matches the comment prefix.
7903 let matching_whitespace_len = line_bytes
7904 .zip(comment_prefix_whitespace.bytes())
7905 .take_while(|(a, b)| a == b)
7906 .count() as u32;
7907 let end = Point::new(
7908 start.row,
7909 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
7910 );
7911 start..end
7912 } else {
7913 start..start
7914 }
7915 }
7916
7917 fn comment_suffix_range(
7918 snapshot: &MultiBufferSnapshot,
7919 row: MultiBufferRow,
7920 comment_suffix: &str,
7921 comment_suffix_has_leading_space: bool,
7922 ) -> Range<Point> {
7923 let end = Point::new(row.0, snapshot.line_len(row));
7924 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
7925
7926 let mut line_end_bytes = snapshot
7927 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
7928 .flatten()
7929 .copied();
7930
7931 let leading_space_len = if suffix_start_column > 0
7932 && line_end_bytes.next() == Some(b' ')
7933 && comment_suffix_has_leading_space
7934 {
7935 1
7936 } else {
7937 0
7938 };
7939
7940 // If this line currently begins with the line comment prefix, then record
7941 // the range containing the prefix.
7942 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
7943 let start = Point::new(end.row, suffix_start_column - leading_space_len);
7944 start..end
7945 } else {
7946 end..end
7947 }
7948 }
7949
7950 // TODO: Handle selections that cross excerpts
7951 for selection in &mut selections {
7952 let start_column = snapshot
7953 .indent_size_for_line(MultiBufferRow(selection.start.row))
7954 .len;
7955 let language = if let Some(language) =
7956 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
7957 {
7958 language
7959 } else {
7960 continue;
7961 };
7962
7963 selection_edit_ranges.clear();
7964
7965 // If multiple selections contain a given row, avoid processing that
7966 // row more than once.
7967 let mut start_row = MultiBufferRow(selection.start.row);
7968 if last_toggled_row == Some(start_row) {
7969 start_row = start_row.next_row();
7970 }
7971 let end_row =
7972 if selection.end.row > selection.start.row && selection.end.column == 0 {
7973 MultiBufferRow(selection.end.row - 1)
7974 } else {
7975 MultiBufferRow(selection.end.row)
7976 };
7977 last_toggled_row = Some(end_row);
7978
7979 if start_row > end_row {
7980 continue;
7981 }
7982
7983 // If the language has line comments, toggle those.
7984 let full_comment_prefixes = language.line_comment_prefixes();
7985 if !full_comment_prefixes.is_empty() {
7986 let first_prefix = full_comment_prefixes
7987 .first()
7988 .expect("prefixes is non-empty");
7989 let prefix_trimmed_lengths = full_comment_prefixes
7990 .iter()
7991 .map(|p| p.trim_end_matches(' ').len())
7992 .collect::<SmallVec<[usize; 4]>>();
7993
7994 let mut all_selection_lines_are_comments = true;
7995
7996 for row in start_row.0..=end_row.0 {
7997 let row = MultiBufferRow(row);
7998 if start_row < end_row && snapshot.is_line_blank(row) {
7999 continue;
8000 }
8001
8002 let prefix_range = full_comment_prefixes
8003 .iter()
8004 .zip(prefix_trimmed_lengths.iter().copied())
8005 .map(|(prefix, trimmed_prefix_len)| {
8006 comment_prefix_range(
8007 snapshot.deref(),
8008 row,
8009 &prefix[..trimmed_prefix_len],
8010 &prefix[trimmed_prefix_len..],
8011 )
8012 })
8013 .max_by_key(|range| range.end.column - range.start.column)
8014 .expect("prefixes is non-empty");
8015
8016 if prefix_range.is_empty() {
8017 all_selection_lines_are_comments = false;
8018 }
8019
8020 selection_edit_ranges.push(prefix_range);
8021 }
8022
8023 if all_selection_lines_are_comments {
8024 edits.extend(
8025 selection_edit_ranges
8026 .iter()
8027 .cloned()
8028 .map(|range| (range, empty_str.clone())),
8029 );
8030 } else {
8031 let min_column = selection_edit_ranges
8032 .iter()
8033 .map(|range| range.start.column)
8034 .min()
8035 .unwrap_or(0);
8036 edits.extend(selection_edit_ranges.iter().map(|range| {
8037 let position = Point::new(range.start.row, min_column);
8038 (position..position, first_prefix.clone())
8039 }));
8040 }
8041 } else if let Some((full_comment_prefix, comment_suffix)) =
8042 language.block_comment_delimiters()
8043 {
8044 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8045 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8046 let prefix_range = comment_prefix_range(
8047 snapshot.deref(),
8048 start_row,
8049 comment_prefix,
8050 comment_prefix_whitespace,
8051 );
8052 let suffix_range = comment_suffix_range(
8053 snapshot.deref(),
8054 end_row,
8055 comment_suffix.trim_start_matches(' '),
8056 comment_suffix.starts_with(' '),
8057 );
8058
8059 if prefix_range.is_empty() || suffix_range.is_empty() {
8060 edits.push((
8061 prefix_range.start..prefix_range.start,
8062 full_comment_prefix.clone(),
8063 ));
8064 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8065 suffixes_inserted.push((end_row, comment_suffix.len()));
8066 } else {
8067 edits.push((prefix_range, empty_str.clone()));
8068 edits.push((suffix_range, empty_str.clone()));
8069 }
8070 } else {
8071 continue;
8072 }
8073 }
8074
8075 drop(snapshot);
8076 this.buffer.update(cx, |buffer, cx| {
8077 buffer.edit(edits, None, cx);
8078 });
8079
8080 // Adjust selections so that they end before any comment suffixes that
8081 // were inserted.
8082 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8083 let mut selections = this.selections.all::<Point>(cx);
8084 let snapshot = this.buffer.read(cx).read(cx);
8085 for selection in &mut selections {
8086 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8087 match row.cmp(&MultiBufferRow(selection.end.row)) {
8088 Ordering::Less => {
8089 suffixes_inserted.next();
8090 continue;
8091 }
8092 Ordering::Greater => break,
8093 Ordering::Equal => {
8094 if selection.end.column == snapshot.line_len(row) {
8095 if selection.is_empty() {
8096 selection.start.column -= suffix_len as u32;
8097 }
8098 selection.end.column -= suffix_len as u32;
8099 }
8100 break;
8101 }
8102 }
8103 }
8104 }
8105
8106 drop(snapshot);
8107 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8108
8109 let selections = this.selections.all::<Point>(cx);
8110 let selections_on_single_row = selections.windows(2).all(|selections| {
8111 selections[0].start.row == selections[1].start.row
8112 && selections[0].end.row == selections[1].end.row
8113 && selections[0].start.row == selections[0].end.row
8114 });
8115 let selections_selecting = selections
8116 .iter()
8117 .any(|selection| selection.start != selection.end);
8118 let advance_downwards = action.advance_downwards
8119 && selections_on_single_row
8120 && !selections_selecting
8121 && this.mode != EditorMode::SingleLine;
8122
8123 if advance_downwards {
8124 let snapshot = this.buffer.read(cx).snapshot(cx);
8125
8126 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8127 s.move_cursors_with(|display_snapshot, display_point, _| {
8128 let mut point = display_point.to_point(display_snapshot);
8129 point.row += 1;
8130 point = snapshot.clip_point(point, Bias::Left);
8131 let display_point = point.to_display_point(display_snapshot);
8132 let goal = SelectionGoal::HorizontalPosition(
8133 display_snapshot
8134 .x_for_display_point(display_point, &text_layout_details)
8135 .into(),
8136 );
8137 (display_point, goal)
8138 })
8139 });
8140 }
8141 });
8142 }
8143
8144 pub fn select_larger_syntax_node(
8145 &mut self,
8146 _: &SelectLargerSyntaxNode,
8147 cx: &mut ViewContext<Self>,
8148 ) {
8149 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8150 let buffer = self.buffer.read(cx).snapshot(cx);
8151 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8152
8153 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8154 let mut selected_larger_node = false;
8155 let new_selections = old_selections
8156 .iter()
8157 .map(|selection| {
8158 let old_range = selection.start..selection.end;
8159 let mut new_range = old_range.clone();
8160 while let Some(containing_range) =
8161 buffer.range_for_syntax_ancestor(new_range.clone())
8162 {
8163 new_range = containing_range;
8164 if !display_map.intersects_fold(new_range.start)
8165 && !display_map.intersects_fold(new_range.end)
8166 {
8167 break;
8168 }
8169 }
8170
8171 selected_larger_node |= new_range != old_range;
8172 Selection {
8173 id: selection.id,
8174 start: new_range.start,
8175 end: new_range.end,
8176 goal: SelectionGoal::None,
8177 reversed: selection.reversed,
8178 }
8179 })
8180 .collect::<Vec<_>>();
8181
8182 if selected_larger_node {
8183 stack.push(old_selections);
8184 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8185 s.select(new_selections);
8186 });
8187 }
8188 self.select_larger_syntax_node_stack = stack;
8189 }
8190
8191 pub fn select_smaller_syntax_node(
8192 &mut self,
8193 _: &SelectSmallerSyntaxNode,
8194 cx: &mut ViewContext<Self>,
8195 ) {
8196 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8197 if let Some(selections) = stack.pop() {
8198 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8199 s.select(selections.to_vec());
8200 });
8201 }
8202 self.select_larger_syntax_node_stack = stack;
8203 }
8204
8205 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8206 let project = self.project.clone();
8207 cx.spawn(|this, mut cx| async move {
8208 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8209 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8210 }) else {
8211 return;
8212 };
8213
8214 let Some(project) = project else {
8215 return;
8216 };
8217
8218 let hide_runnables = project
8219 .update(&mut cx, |project, cx| {
8220 // Do not display any test indicators in non-dev server remote projects.
8221 project.is_remote() && project.ssh_connection_string(cx).is_none()
8222 })
8223 .unwrap_or(true);
8224 if hide_runnables {
8225 return;
8226 }
8227 let new_rows =
8228 cx.background_executor()
8229 .spawn({
8230 let snapshot = display_snapshot.clone();
8231 async move {
8232 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8233 }
8234 })
8235 .await;
8236 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8237
8238 this.update(&mut cx, |this, _| {
8239 this.clear_tasks();
8240 for (key, value) in rows {
8241 this.insert_tasks(key, value);
8242 }
8243 })
8244 .ok();
8245 })
8246 }
8247 fn fetch_runnable_ranges(
8248 snapshot: &DisplaySnapshot,
8249 range: Range<Anchor>,
8250 ) -> Vec<language::RunnableRange> {
8251 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8252 }
8253
8254 fn runnable_rows(
8255 project: Model<Project>,
8256 snapshot: DisplaySnapshot,
8257 runnable_ranges: Vec<RunnableRange>,
8258 mut cx: AsyncWindowContext,
8259 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8260 runnable_ranges
8261 .into_iter()
8262 .filter_map(|mut runnable| {
8263 let tasks = cx
8264 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8265 .ok()?;
8266 if tasks.is_empty() {
8267 return None;
8268 }
8269
8270 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8271
8272 let row = snapshot
8273 .buffer_snapshot
8274 .buffer_line_for_row(MultiBufferRow(point.row))?
8275 .1
8276 .start
8277 .row;
8278
8279 let context_range =
8280 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8281 Some((
8282 (runnable.buffer_id, row),
8283 RunnableTasks {
8284 templates: tasks,
8285 offset: MultiBufferOffset(runnable.run_range.start),
8286 context_range,
8287 column: point.column,
8288 extra_variables: runnable.extra_captures,
8289 },
8290 ))
8291 })
8292 .collect()
8293 }
8294
8295 fn templates_with_tags(
8296 project: &Model<Project>,
8297 runnable: &mut Runnable,
8298 cx: &WindowContext<'_>,
8299 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8300 let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
8301 let worktree_id = project
8302 .buffer_for_id(runnable.buffer)
8303 .and_then(|buffer| buffer.read(cx).file())
8304 .map(|file| WorktreeId::from_usize(file.worktree_id()));
8305
8306 (project.task_inventory().clone(), worktree_id)
8307 });
8308
8309 let inventory = inventory.read(cx);
8310 let tags = mem::take(&mut runnable.tags);
8311 let mut tags: Vec<_> = tags
8312 .into_iter()
8313 .flat_map(|tag| {
8314 let tag = tag.0.clone();
8315 inventory
8316 .list_tasks(Some(runnable.language.clone()), worktree_id)
8317 .into_iter()
8318 .filter(move |(_, template)| {
8319 template.tags.iter().any(|source_tag| source_tag == &tag)
8320 })
8321 })
8322 .sorted_by_key(|(kind, _)| kind.to_owned())
8323 .collect();
8324 if let Some((leading_tag_source, _)) = tags.first() {
8325 // Strongest source wins; if we have worktree tag binding, prefer that to
8326 // global and language bindings;
8327 // if we have a global binding, prefer that to language binding.
8328 let first_mismatch = tags
8329 .iter()
8330 .position(|(tag_source, _)| tag_source != leading_tag_source);
8331 if let Some(index) = first_mismatch {
8332 tags.truncate(index);
8333 }
8334 }
8335
8336 tags
8337 }
8338
8339 pub fn move_to_enclosing_bracket(
8340 &mut self,
8341 _: &MoveToEnclosingBracket,
8342 cx: &mut ViewContext<Self>,
8343 ) {
8344 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8345 s.move_offsets_with(|snapshot, selection| {
8346 let Some(enclosing_bracket_ranges) =
8347 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8348 else {
8349 return;
8350 };
8351
8352 let mut best_length = usize::MAX;
8353 let mut best_inside = false;
8354 let mut best_in_bracket_range = false;
8355 let mut best_destination = None;
8356 for (open, close) in enclosing_bracket_ranges {
8357 let close = close.to_inclusive();
8358 let length = close.end() - open.start;
8359 let inside = selection.start >= open.end && selection.end <= *close.start();
8360 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8361 || close.contains(&selection.head());
8362
8363 // If best is next to a bracket and current isn't, skip
8364 if !in_bracket_range && best_in_bracket_range {
8365 continue;
8366 }
8367
8368 // Prefer smaller lengths unless best is inside and current isn't
8369 if length > best_length && (best_inside || !inside) {
8370 continue;
8371 }
8372
8373 best_length = length;
8374 best_inside = inside;
8375 best_in_bracket_range = in_bracket_range;
8376 best_destination = Some(
8377 if close.contains(&selection.start) && close.contains(&selection.end) {
8378 if inside {
8379 open.end
8380 } else {
8381 open.start
8382 }
8383 } else {
8384 if inside {
8385 *close.start()
8386 } else {
8387 *close.end()
8388 }
8389 },
8390 );
8391 }
8392
8393 if let Some(destination) = best_destination {
8394 selection.collapse_to(destination, SelectionGoal::None);
8395 }
8396 })
8397 });
8398 }
8399
8400 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8401 self.end_selection(cx);
8402 self.selection_history.mode = SelectionHistoryMode::Undoing;
8403 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8404 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8405 self.select_next_state = entry.select_next_state;
8406 self.select_prev_state = entry.select_prev_state;
8407 self.add_selections_state = entry.add_selections_state;
8408 self.request_autoscroll(Autoscroll::newest(), cx);
8409 }
8410 self.selection_history.mode = SelectionHistoryMode::Normal;
8411 }
8412
8413 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8414 self.end_selection(cx);
8415 self.selection_history.mode = SelectionHistoryMode::Redoing;
8416 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8417 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8418 self.select_next_state = entry.select_next_state;
8419 self.select_prev_state = entry.select_prev_state;
8420 self.add_selections_state = entry.add_selections_state;
8421 self.request_autoscroll(Autoscroll::newest(), cx);
8422 }
8423 self.selection_history.mode = SelectionHistoryMode::Normal;
8424 }
8425
8426 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8427 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8428 }
8429
8430 pub fn expand_excerpts_down(
8431 &mut self,
8432 action: &ExpandExcerptsDown,
8433 cx: &mut ViewContext<Self>,
8434 ) {
8435 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8436 }
8437
8438 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8439 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8440 }
8441
8442 pub fn expand_excerpts_for_direction(
8443 &mut self,
8444 lines: u32,
8445 direction: ExpandExcerptDirection,
8446 cx: &mut ViewContext<Self>,
8447 ) {
8448 let selections = self.selections.disjoint_anchors();
8449
8450 let lines = if lines == 0 {
8451 EditorSettings::get_global(cx).expand_excerpt_lines
8452 } else {
8453 lines
8454 };
8455
8456 self.buffer.update(cx, |buffer, cx| {
8457 buffer.expand_excerpts(
8458 selections
8459 .into_iter()
8460 .map(|selection| selection.head().excerpt_id)
8461 .dedup(),
8462 lines,
8463 direction,
8464 cx,
8465 )
8466 })
8467 }
8468
8469 pub fn expand_excerpt(
8470 &mut self,
8471 excerpt: ExcerptId,
8472 direction: ExpandExcerptDirection,
8473 cx: &mut ViewContext<Self>,
8474 ) {
8475 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8476 self.buffer.update(cx, |buffer, cx| {
8477 buffer.expand_excerpts([excerpt], lines, direction, cx)
8478 })
8479 }
8480
8481 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8482 self.go_to_diagnostic_impl(Direction::Next, cx)
8483 }
8484
8485 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8486 self.go_to_diagnostic_impl(Direction::Prev, cx)
8487 }
8488
8489 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8490 let buffer = self.buffer.read(cx).snapshot(cx);
8491 let selection = self.selections.newest::<usize>(cx);
8492
8493 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8494 if direction == Direction::Next {
8495 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8496 let (group_id, jump_to) = popover.activation_info();
8497 if self.activate_diagnostics(group_id, cx) {
8498 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8499 let mut new_selection = s.newest_anchor().clone();
8500 new_selection.collapse_to(jump_to, SelectionGoal::None);
8501 s.select_anchors(vec![new_selection.clone()]);
8502 });
8503 }
8504 return;
8505 }
8506 }
8507
8508 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8509 active_diagnostics
8510 .primary_range
8511 .to_offset(&buffer)
8512 .to_inclusive()
8513 });
8514 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8515 if active_primary_range.contains(&selection.head()) {
8516 *active_primary_range.start()
8517 } else {
8518 selection.head()
8519 }
8520 } else {
8521 selection.head()
8522 };
8523 let snapshot = self.snapshot(cx);
8524 loop {
8525 let diagnostics = if direction == Direction::Prev {
8526 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8527 } else {
8528 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8529 }
8530 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8531 let group = diagnostics
8532 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8533 // be sorted in a stable way
8534 // skip until we are at current active diagnostic, if it exists
8535 .skip_while(|entry| {
8536 (match direction {
8537 Direction::Prev => entry.range.start >= search_start,
8538 Direction::Next => entry.range.start <= search_start,
8539 }) && self
8540 .active_diagnostics
8541 .as_ref()
8542 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8543 })
8544 .find_map(|entry| {
8545 if entry.diagnostic.is_primary
8546 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8547 && !entry.range.is_empty()
8548 // if we match with the active diagnostic, skip it
8549 && Some(entry.diagnostic.group_id)
8550 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8551 {
8552 Some((entry.range, entry.diagnostic.group_id))
8553 } else {
8554 None
8555 }
8556 });
8557
8558 if let Some((primary_range, group_id)) = group {
8559 if self.activate_diagnostics(group_id, cx) {
8560 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8561 s.select(vec![Selection {
8562 id: selection.id,
8563 start: primary_range.start,
8564 end: primary_range.start,
8565 reversed: false,
8566 goal: SelectionGoal::None,
8567 }]);
8568 });
8569 }
8570 break;
8571 } else {
8572 // Cycle around to the start of the buffer, potentially moving back to the start of
8573 // the currently active diagnostic.
8574 active_primary_range.take();
8575 if direction == Direction::Prev {
8576 if search_start == buffer.len() {
8577 break;
8578 } else {
8579 search_start = buffer.len();
8580 }
8581 } else if search_start == 0 {
8582 break;
8583 } else {
8584 search_start = 0;
8585 }
8586 }
8587 }
8588 }
8589
8590 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8591 let snapshot = self
8592 .display_map
8593 .update(cx, |display_map, cx| display_map.snapshot(cx));
8594 let selection = self.selections.newest::<Point>(cx);
8595
8596 if !self.seek_in_direction(
8597 &snapshot,
8598 selection.head(),
8599 false,
8600 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8601 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8602 ),
8603 cx,
8604 ) {
8605 let wrapped_point = Point::zero();
8606 self.seek_in_direction(
8607 &snapshot,
8608 wrapped_point,
8609 true,
8610 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8611 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8612 ),
8613 cx,
8614 );
8615 }
8616 }
8617
8618 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8619 let snapshot = self
8620 .display_map
8621 .update(cx, |display_map, cx| display_map.snapshot(cx));
8622 let selection = self.selections.newest::<Point>(cx);
8623
8624 if !self.seek_in_direction(
8625 &snapshot,
8626 selection.head(),
8627 false,
8628 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8629 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8630 ),
8631 cx,
8632 ) {
8633 let wrapped_point = snapshot.buffer_snapshot.max_point();
8634 self.seek_in_direction(
8635 &snapshot,
8636 wrapped_point,
8637 true,
8638 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8639 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8640 ),
8641 cx,
8642 );
8643 }
8644 }
8645
8646 fn seek_in_direction(
8647 &mut self,
8648 snapshot: &DisplaySnapshot,
8649 initial_point: Point,
8650 is_wrapped: bool,
8651 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8652 cx: &mut ViewContext<Editor>,
8653 ) -> bool {
8654 let display_point = initial_point.to_display_point(snapshot);
8655 let mut hunks = hunks
8656 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8657 .filter(|hunk| {
8658 if is_wrapped {
8659 true
8660 } else {
8661 !hunk.contains_display_row(display_point.row())
8662 }
8663 })
8664 .dedup();
8665
8666 if let Some(hunk) = hunks.next() {
8667 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8668 let row = hunk.start_display_row();
8669 let point = DisplayPoint::new(row, 0);
8670 s.select_display_ranges([point..point]);
8671 });
8672
8673 true
8674 } else {
8675 false
8676 }
8677 }
8678
8679 pub fn go_to_definition(
8680 &mut self,
8681 _: &GoToDefinition,
8682 cx: &mut ViewContext<Self>,
8683 ) -> Task<Result<bool>> {
8684 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8685 }
8686
8687 pub fn go_to_implementation(
8688 &mut self,
8689 _: &GoToImplementation,
8690 cx: &mut ViewContext<Self>,
8691 ) -> Task<Result<bool>> {
8692 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8693 }
8694
8695 pub fn go_to_implementation_split(
8696 &mut self,
8697 _: &GoToImplementationSplit,
8698 cx: &mut ViewContext<Self>,
8699 ) -> Task<Result<bool>> {
8700 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8701 }
8702
8703 pub fn go_to_type_definition(
8704 &mut self,
8705 _: &GoToTypeDefinition,
8706 cx: &mut ViewContext<Self>,
8707 ) -> Task<Result<bool>> {
8708 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8709 }
8710
8711 pub fn go_to_definition_split(
8712 &mut self,
8713 _: &GoToDefinitionSplit,
8714 cx: &mut ViewContext<Self>,
8715 ) -> Task<Result<bool>> {
8716 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
8717 }
8718
8719 pub fn go_to_type_definition_split(
8720 &mut self,
8721 _: &GoToTypeDefinitionSplit,
8722 cx: &mut ViewContext<Self>,
8723 ) -> Task<Result<bool>> {
8724 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
8725 }
8726
8727 fn go_to_definition_of_kind(
8728 &mut self,
8729 kind: GotoDefinitionKind,
8730 split: bool,
8731 cx: &mut ViewContext<Self>,
8732 ) -> Task<Result<bool>> {
8733 let Some(workspace) = self.workspace() else {
8734 return Task::ready(Ok(false));
8735 };
8736 let buffer = self.buffer.read(cx);
8737 let head = self.selections.newest::<usize>(cx).head();
8738 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
8739 text_anchor
8740 } else {
8741 return Task::ready(Ok(false));
8742 };
8743
8744 let project = workspace.read(cx).project().clone();
8745 let definitions = project.update(cx, |project, cx| match kind {
8746 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
8747 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
8748 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
8749 });
8750
8751 cx.spawn(|editor, mut cx| async move {
8752 let definitions = definitions.await?;
8753 let navigated = editor
8754 .update(&mut cx, |editor, cx| {
8755 editor.navigate_to_hover_links(
8756 Some(kind),
8757 definitions
8758 .into_iter()
8759 .filter(|location| {
8760 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
8761 })
8762 .map(HoverLink::Text)
8763 .collect::<Vec<_>>(),
8764 split,
8765 cx,
8766 )
8767 })?
8768 .await?;
8769 anyhow::Ok(navigated)
8770 })
8771 }
8772
8773 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
8774 let position = self.selections.newest_anchor().head();
8775 let Some((buffer, buffer_position)) =
8776 self.buffer.read(cx).text_anchor_for_position(position, cx)
8777 else {
8778 return;
8779 };
8780
8781 cx.spawn(|editor, mut cx| async move {
8782 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
8783 editor.update(&mut cx, |_, cx| {
8784 cx.open_url(&url);
8785 })
8786 } else {
8787 Ok(())
8788 }
8789 })
8790 .detach();
8791 }
8792
8793 pub(crate) fn navigate_to_hover_links(
8794 &mut self,
8795 kind: Option<GotoDefinitionKind>,
8796 mut definitions: Vec<HoverLink>,
8797 split: bool,
8798 cx: &mut ViewContext<Editor>,
8799 ) -> Task<Result<bool>> {
8800 // If there is one definition, just open it directly
8801 if definitions.len() == 1 {
8802 let definition = definitions.pop().unwrap();
8803 let target_task = match definition {
8804 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8805 HoverLink::InlayHint(lsp_location, server_id) => {
8806 self.compute_target_location(lsp_location, server_id, cx)
8807 }
8808 HoverLink::Url(url) => {
8809 cx.open_url(&url);
8810 Task::ready(Ok(None))
8811 }
8812 };
8813 cx.spawn(|editor, mut cx| async move {
8814 let target = target_task.await.context("target resolution task")?;
8815 if let Some(target) = target {
8816 editor.update(&mut cx, |editor, cx| {
8817 let Some(workspace) = editor.workspace() else {
8818 return false;
8819 };
8820 let pane = workspace.read(cx).active_pane().clone();
8821
8822 let range = target.range.to_offset(target.buffer.read(cx));
8823 let range = editor.range_for_match(&range);
8824
8825 /// If select range has more than one line, we
8826 /// just point the cursor to range.start.
8827 fn check_multiline_range(
8828 buffer: &Buffer,
8829 range: Range<usize>,
8830 ) -> Range<usize> {
8831 if buffer.offset_to_point(range.start).row
8832 == buffer.offset_to_point(range.end).row
8833 {
8834 range
8835 } else {
8836 range.start..range.start
8837 }
8838 }
8839
8840 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
8841 let buffer = target.buffer.read(cx);
8842 let range = check_multiline_range(buffer, range);
8843 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
8844 s.select_ranges([range]);
8845 });
8846 } else {
8847 cx.window_context().defer(move |cx| {
8848 let target_editor: View<Self> =
8849 workspace.update(cx, |workspace, cx| {
8850 let pane = if split {
8851 workspace.adjacent_pane(cx)
8852 } else {
8853 workspace.active_pane().clone()
8854 };
8855
8856 workspace.open_project_item(pane, target.buffer.clone(), cx)
8857 });
8858 target_editor.update(cx, |target_editor, cx| {
8859 // When selecting a definition in a different buffer, disable the nav history
8860 // to avoid creating a history entry at the previous cursor location.
8861 pane.update(cx, |pane, _| pane.disable_history());
8862 let buffer = target.buffer.read(cx);
8863 let range = check_multiline_range(buffer, range);
8864 target_editor.change_selections(
8865 Some(Autoscroll::focused()),
8866 cx,
8867 |s| {
8868 s.select_ranges([range]);
8869 },
8870 );
8871 pane.update(cx, |pane, _| pane.enable_history());
8872 });
8873 });
8874 }
8875 true
8876 })
8877 } else {
8878 Ok(false)
8879 }
8880 })
8881 } else if !definitions.is_empty() {
8882 let replica_id = self.replica_id(cx);
8883 cx.spawn(|editor, mut cx| async move {
8884 let (title, location_tasks, workspace) = editor
8885 .update(&mut cx, |editor, cx| {
8886 let tab_kind = match kind {
8887 Some(GotoDefinitionKind::Implementation) => "Implementations",
8888 _ => "Definitions",
8889 };
8890 let title = definitions
8891 .iter()
8892 .find_map(|definition| match definition {
8893 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
8894 let buffer = origin.buffer.read(cx);
8895 format!(
8896 "{} for {}",
8897 tab_kind,
8898 buffer
8899 .text_for_range(origin.range.clone())
8900 .collect::<String>()
8901 )
8902 }),
8903 HoverLink::InlayHint(_, _) => None,
8904 HoverLink::Url(_) => None,
8905 })
8906 .unwrap_or(tab_kind.to_string());
8907 let location_tasks = definitions
8908 .into_iter()
8909 .map(|definition| match definition {
8910 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8911 HoverLink::InlayHint(lsp_location, server_id) => {
8912 editor.compute_target_location(lsp_location, server_id, cx)
8913 }
8914 HoverLink::Url(_) => Task::ready(Ok(None)),
8915 })
8916 .collect::<Vec<_>>();
8917 (title, location_tasks, editor.workspace().clone())
8918 })
8919 .context("location tasks preparation")?;
8920
8921 let locations = futures::future::join_all(location_tasks)
8922 .await
8923 .into_iter()
8924 .filter_map(|location| location.transpose())
8925 .collect::<Result<_>>()
8926 .context("location tasks")?;
8927
8928 let Some(workspace) = workspace else {
8929 return Ok(false);
8930 };
8931 let opened = workspace
8932 .update(&mut cx, |workspace, cx| {
8933 Self::open_locations_in_multibuffer(
8934 workspace, locations, replica_id, title, split, cx,
8935 )
8936 })
8937 .ok();
8938
8939 anyhow::Ok(opened.is_some())
8940 })
8941 } else {
8942 Task::ready(Ok(false))
8943 }
8944 }
8945
8946 fn compute_target_location(
8947 &self,
8948 lsp_location: lsp::Location,
8949 server_id: LanguageServerId,
8950 cx: &mut ViewContext<Editor>,
8951 ) -> Task<anyhow::Result<Option<Location>>> {
8952 let Some(project) = self.project.clone() else {
8953 return Task::Ready(Some(Ok(None)));
8954 };
8955
8956 cx.spawn(move |editor, mut cx| async move {
8957 let location_task = editor.update(&mut cx, |editor, cx| {
8958 project.update(cx, |project, cx| {
8959 let language_server_name =
8960 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
8961 project
8962 .language_server_for_buffer(buffer.read(cx), server_id, cx)
8963 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
8964 });
8965 language_server_name.map(|language_server_name| {
8966 project.open_local_buffer_via_lsp(
8967 lsp::Uri::from(lsp_location.uri.clone()),
8968 server_id,
8969 language_server_name,
8970 cx,
8971 )
8972 })
8973 })
8974 })?;
8975 let location = match location_task {
8976 Some(task) => Some({
8977 let target_buffer_handle = task.await.context("open local buffer")?;
8978 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
8979 let target_start = target_buffer
8980 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
8981 let target_end = target_buffer
8982 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
8983 target_buffer.anchor_after(target_start)
8984 ..target_buffer.anchor_before(target_end)
8985 })?;
8986 Location {
8987 buffer: target_buffer_handle,
8988 range,
8989 }
8990 }),
8991 None => None,
8992 };
8993 Ok(location)
8994 })
8995 }
8996
8997 pub fn find_all_references(
8998 &mut self,
8999 _: &FindAllReferences,
9000 cx: &mut ViewContext<Self>,
9001 ) -> Option<Task<Result<()>>> {
9002 let multi_buffer = self.buffer.read(cx);
9003 let selection = self.selections.newest::<usize>(cx);
9004 let head = selection.head();
9005
9006 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9007 let head_anchor = multi_buffer_snapshot.anchor_at(
9008 head,
9009 if head < selection.tail() {
9010 Bias::Right
9011 } else {
9012 Bias::Left
9013 },
9014 );
9015
9016 match self
9017 .find_all_references_task_sources
9018 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9019 {
9020 Ok(_) => {
9021 log::info!(
9022 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9023 );
9024 return None;
9025 }
9026 Err(i) => {
9027 self.find_all_references_task_sources.insert(i, head_anchor);
9028 }
9029 }
9030
9031 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9032 let replica_id = self.replica_id(cx);
9033 let workspace = self.workspace()?;
9034 let project = workspace.read(cx).project().clone();
9035 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9036 Some(cx.spawn(|editor, mut cx| async move {
9037 let _cleanup = defer({
9038 let mut cx = cx.clone();
9039 move || {
9040 let _ = editor.update(&mut cx, |editor, _| {
9041 if let Ok(i) =
9042 editor
9043 .find_all_references_task_sources
9044 .binary_search_by(|anchor| {
9045 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9046 })
9047 {
9048 editor.find_all_references_task_sources.remove(i);
9049 }
9050 });
9051 }
9052 });
9053
9054 let locations = references.await?;
9055 if locations.is_empty() {
9056 return anyhow::Ok(());
9057 }
9058
9059 workspace.update(&mut cx, |workspace, cx| {
9060 let title = locations
9061 .first()
9062 .as_ref()
9063 .map(|location| {
9064 let buffer = location.buffer.read(cx);
9065 format!(
9066 "References to `{}`",
9067 buffer
9068 .text_for_range(location.range.clone())
9069 .collect::<String>()
9070 )
9071 })
9072 .unwrap();
9073 Self::open_locations_in_multibuffer(
9074 workspace, locations, replica_id, title, false, cx,
9075 );
9076 })
9077 }))
9078 }
9079
9080 /// Opens a multibuffer with the given project locations in it
9081 pub fn open_locations_in_multibuffer(
9082 workspace: &mut Workspace,
9083 mut locations: Vec<Location>,
9084 replica_id: ReplicaId,
9085 title: String,
9086 split: bool,
9087 cx: &mut ViewContext<Workspace>,
9088 ) {
9089 // If there are multiple definitions, open them in a multibuffer
9090 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9091 let mut locations = locations.into_iter().peekable();
9092 let mut ranges_to_highlight = Vec::new();
9093 let capability = workspace.project().read(cx).capability();
9094
9095 let excerpt_buffer = cx.new_model(|cx| {
9096 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9097 while let Some(location) = locations.next() {
9098 let buffer = location.buffer.read(cx);
9099 let mut ranges_for_buffer = Vec::new();
9100 let range = location.range.to_offset(buffer);
9101 ranges_for_buffer.push(range.clone());
9102
9103 while let Some(next_location) = locations.peek() {
9104 if next_location.buffer == location.buffer {
9105 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9106 locations.next();
9107 } else {
9108 break;
9109 }
9110 }
9111
9112 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9113 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9114 location.buffer.clone(),
9115 ranges_for_buffer,
9116 DEFAULT_MULTIBUFFER_CONTEXT,
9117 cx,
9118 ))
9119 }
9120
9121 multibuffer.with_title(title)
9122 });
9123
9124 let editor = cx.new_view(|cx| {
9125 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9126 });
9127 editor.update(cx, |editor, cx| {
9128 editor.highlight_background::<Self>(
9129 &ranges_to_highlight,
9130 |theme| theme.editor_highlighted_line_background,
9131 cx,
9132 );
9133 });
9134
9135 let item = Box::new(editor);
9136 let item_id = item.item_id();
9137
9138 if split {
9139 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9140 } else {
9141 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9142 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9143 pane.close_current_preview_item(cx)
9144 } else {
9145 None
9146 }
9147 });
9148 workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
9149 }
9150 workspace.active_pane().update(cx, |pane, cx| {
9151 pane.set_preview_item_id(Some(item_id), cx);
9152 });
9153 }
9154
9155 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9156 use language::ToOffset as _;
9157
9158 let project = self.project.clone()?;
9159 let selection = self.selections.newest_anchor().clone();
9160 let (cursor_buffer, cursor_buffer_position) = self
9161 .buffer
9162 .read(cx)
9163 .text_anchor_for_position(selection.head(), cx)?;
9164 let (tail_buffer, cursor_buffer_position_end) = self
9165 .buffer
9166 .read(cx)
9167 .text_anchor_for_position(selection.tail(), cx)?;
9168 if tail_buffer != cursor_buffer {
9169 return None;
9170 }
9171
9172 let snapshot = cursor_buffer.read(cx).snapshot();
9173 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9174 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9175 let prepare_rename = project.update(cx, |project, cx| {
9176 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9177 });
9178 drop(snapshot);
9179
9180 Some(cx.spawn(|this, mut cx| async move {
9181 let rename_range = if let Some(range) = prepare_rename.await? {
9182 Some(range)
9183 } else {
9184 this.update(&mut cx, |this, cx| {
9185 let buffer = this.buffer.read(cx).snapshot(cx);
9186 let mut buffer_highlights = this
9187 .document_highlights_for_position(selection.head(), &buffer)
9188 .filter(|highlight| {
9189 highlight.start.excerpt_id == selection.head().excerpt_id
9190 && highlight.end.excerpt_id == selection.head().excerpt_id
9191 });
9192 buffer_highlights
9193 .next()
9194 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9195 })?
9196 };
9197 if let Some(rename_range) = rename_range {
9198 this.update(&mut cx, |this, cx| {
9199 let snapshot = cursor_buffer.read(cx).snapshot();
9200 let rename_buffer_range = rename_range.to_offset(&snapshot);
9201 let cursor_offset_in_rename_range =
9202 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9203 let cursor_offset_in_rename_range_end =
9204 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9205
9206 this.take_rename(false, cx);
9207 let buffer = this.buffer.read(cx).read(cx);
9208 let cursor_offset = selection.head().to_offset(&buffer);
9209 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9210 let rename_end = rename_start + rename_buffer_range.len();
9211 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9212 let mut old_highlight_id = None;
9213 let old_name: Arc<str> = buffer
9214 .chunks(rename_start..rename_end, true)
9215 .map(|chunk| {
9216 if old_highlight_id.is_none() {
9217 old_highlight_id = chunk.syntax_highlight_id;
9218 }
9219 chunk.text
9220 })
9221 .collect::<String>()
9222 .into();
9223
9224 drop(buffer);
9225
9226 // Position the selection in the rename editor so that it matches the current selection.
9227 this.show_local_selections = false;
9228 let rename_editor = cx.new_view(|cx| {
9229 let mut editor = Editor::single_line(cx);
9230 editor.buffer.update(cx, |buffer, cx| {
9231 buffer.edit([(0..0, old_name.clone())], None, cx)
9232 });
9233 let rename_selection_range = match cursor_offset_in_rename_range
9234 .cmp(&cursor_offset_in_rename_range_end)
9235 {
9236 Ordering::Equal => {
9237 editor.select_all(&SelectAll, cx);
9238 return editor;
9239 }
9240 Ordering::Less => {
9241 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9242 }
9243 Ordering::Greater => {
9244 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9245 }
9246 };
9247 if rename_selection_range.end > old_name.len() {
9248 editor.select_all(&SelectAll, cx);
9249 } else {
9250 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9251 s.select_ranges([rename_selection_range]);
9252 });
9253 }
9254 editor
9255 });
9256
9257 let write_highlights =
9258 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9259 let read_highlights =
9260 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9261 let ranges = write_highlights
9262 .iter()
9263 .flat_map(|(_, ranges)| ranges.iter())
9264 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9265 .cloned()
9266 .collect();
9267
9268 this.highlight_text::<Rename>(
9269 ranges,
9270 HighlightStyle {
9271 fade_out: Some(0.6),
9272 ..Default::default()
9273 },
9274 cx,
9275 );
9276 let rename_focus_handle = rename_editor.focus_handle(cx);
9277 cx.focus(&rename_focus_handle);
9278 let block_id = this.insert_blocks(
9279 [BlockProperties {
9280 style: BlockStyle::Flex,
9281 position: range.start,
9282 height: 1,
9283 render: Box::new({
9284 let rename_editor = rename_editor.clone();
9285 move |cx: &mut BlockContext| {
9286 let mut text_style = cx.editor_style.text.clone();
9287 if let Some(highlight_style) = old_highlight_id
9288 .and_then(|h| h.style(&cx.editor_style.syntax))
9289 {
9290 text_style = text_style.highlight(highlight_style);
9291 }
9292 div()
9293 .pl(cx.anchor_x)
9294 .child(EditorElement::new(
9295 &rename_editor,
9296 EditorStyle {
9297 background: cx.theme().system().transparent,
9298 local_player: cx.editor_style.local_player,
9299 text: text_style,
9300 scrollbar_width: cx.editor_style.scrollbar_width,
9301 syntax: cx.editor_style.syntax.clone(),
9302 status: cx.editor_style.status.clone(),
9303 inlay_hints_style: HighlightStyle {
9304 color: Some(cx.theme().status().hint),
9305 font_weight: Some(FontWeight::BOLD),
9306 ..HighlightStyle::default()
9307 },
9308 suggestions_style: HighlightStyle {
9309 color: Some(cx.theme().status().predictive),
9310 ..HighlightStyle::default()
9311 },
9312 },
9313 ))
9314 .into_any_element()
9315 }
9316 }),
9317 disposition: BlockDisposition::Below,
9318 }],
9319 Some(Autoscroll::fit()),
9320 cx,
9321 )[0];
9322 this.pending_rename = Some(RenameState {
9323 range,
9324 old_name,
9325 editor: rename_editor,
9326 block_id,
9327 });
9328 })?;
9329 }
9330
9331 Ok(())
9332 }))
9333 }
9334
9335 pub fn confirm_rename(
9336 &mut self,
9337 _: &ConfirmRename,
9338 cx: &mut ViewContext<Self>,
9339 ) -> Option<Task<Result<()>>> {
9340 let rename = self.take_rename(false, cx)?;
9341 let workspace = self.workspace()?;
9342 let (start_buffer, start) = self
9343 .buffer
9344 .read(cx)
9345 .text_anchor_for_position(rename.range.start, cx)?;
9346 let (end_buffer, end) = self
9347 .buffer
9348 .read(cx)
9349 .text_anchor_for_position(rename.range.end, cx)?;
9350 if start_buffer != end_buffer {
9351 return None;
9352 }
9353
9354 let buffer = start_buffer;
9355 let range = start..end;
9356 let old_name = rename.old_name;
9357 let new_name = rename.editor.read(cx).text(cx);
9358
9359 let rename = workspace
9360 .read(cx)
9361 .project()
9362 .clone()
9363 .update(cx, |project, cx| {
9364 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9365 });
9366 let workspace = workspace.downgrade();
9367
9368 Some(cx.spawn(|editor, mut cx| async move {
9369 let project_transaction = rename.await?;
9370 Self::open_project_transaction(
9371 &editor,
9372 workspace,
9373 project_transaction,
9374 format!("Rename: {} → {}", old_name, new_name),
9375 cx.clone(),
9376 )
9377 .await?;
9378
9379 editor.update(&mut cx, |editor, cx| {
9380 editor.refresh_document_highlights(cx);
9381 })?;
9382 Ok(())
9383 }))
9384 }
9385
9386 fn take_rename(
9387 &mut self,
9388 moving_cursor: bool,
9389 cx: &mut ViewContext<Self>,
9390 ) -> Option<RenameState> {
9391 let rename = self.pending_rename.take()?;
9392 if rename.editor.focus_handle(cx).is_focused(cx) {
9393 cx.focus(&self.focus_handle);
9394 }
9395
9396 self.remove_blocks(
9397 [rename.block_id].into_iter().collect(),
9398 Some(Autoscroll::fit()),
9399 cx,
9400 );
9401 self.clear_highlights::<Rename>(cx);
9402 self.show_local_selections = true;
9403
9404 if moving_cursor {
9405 let rename_editor = rename.editor.read(cx);
9406 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9407
9408 // Update the selection to match the position of the selection inside
9409 // the rename editor.
9410 let snapshot = self.buffer.read(cx).read(cx);
9411 let rename_range = rename.range.to_offset(&snapshot);
9412 let cursor_in_editor = snapshot
9413 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9414 .min(rename_range.end);
9415 drop(snapshot);
9416
9417 self.change_selections(None, cx, |s| {
9418 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9419 });
9420 } else {
9421 self.refresh_document_highlights(cx);
9422 }
9423
9424 Some(rename)
9425 }
9426
9427 pub fn pending_rename(&self) -> Option<&RenameState> {
9428 self.pending_rename.as_ref()
9429 }
9430
9431 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9432 let project = match &self.project {
9433 Some(project) => project.clone(),
9434 None => return None,
9435 };
9436
9437 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9438 }
9439
9440 fn perform_format(
9441 &mut self,
9442 project: Model<Project>,
9443 trigger: FormatTrigger,
9444 cx: &mut ViewContext<Self>,
9445 ) -> Task<Result<()>> {
9446 let buffer = self.buffer().clone();
9447 let mut buffers = buffer.read(cx).all_buffers();
9448 if trigger == FormatTrigger::Save {
9449 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9450 }
9451
9452 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9453 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9454
9455 cx.spawn(|_, mut cx| async move {
9456 let transaction = futures::select_biased! {
9457 () = timeout => {
9458 log::warn!("timed out waiting for formatting");
9459 None
9460 }
9461 transaction = format.log_err().fuse() => transaction,
9462 };
9463
9464 buffer
9465 .update(&mut cx, |buffer, cx| {
9466 if let Some(transaction) = transaction {
9467 if !buffer.is_singleton() {
9468 buffer.push_transaction(&transaction.0, cx);
9469 }
9470 }
9471
9472 cx.notify();
9473 })
9474 .ok();
9475
9476 Ok(())
9477 })
9478 }
9479
9480 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9481 if let Some(project) = self.project.clone() {
9482 self.buffer.update(cx, |multi_buffer, cx| {
9483 project.update(cx, |project, cx| {
9484 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9485 });
9486 })
9487 }
9488 }
9489
9490 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9491 cx.show_character_palette();
9492 }
9493
9494 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9495 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9496 let buffer = self.buffer.read(cx).snapshot(cx);
9497 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9498 let is_valid = buffer
9499 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9500 .any(|entry| {
9501 entry.diagnostic.is_primary
9502 && !entry.range.is_empty()
9503 && entry.range.start == primary_range_start
9504 && entry.diagnostic.message == active_diagnostics.primary_message
9505 });
9506
9507 if is_valid != active_diagnostics.is_valid {
9508 active_diagnostics.is_valid = is_valid;
9509 let mut new_styles = HashMap::default();
9510 for (block_id, diagnostic) in &active_diagnostics.blocks {
9511 new_styles.insert(
9512 *block_id,
9513 (
9514 None,
9515 diagnostic_block_renderer(diagnostic.clone(), is_valid),
9516 ),
9517 );
9518 }
9519 self.display_map.update(cx, |display_map, cx| {
9520 display_map.replace_blocks(new_styles, cx)
9521 });
9522 }
9523 }
9524 }
9525
9526 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9527 self.dismiss_diagnostics(cx);
9528 let snapshot = self.snapshot(cx);
9529 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9530 let buffer = self.buffer.read(cx).snapshot(cx);
9531
9532 let mut primary_range = None;
9533 let mut primary_message = None;
9534 let mut group_end = Point::zero();
9535 let diagnostic_group = buffer
9536 .diagnostic_group::<MultiBufferPoint>(group_id)
9537 .filter_map(|entry| {
9538 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9539 && (entry.range.start.row == entry.range.end.row
9540 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9541 {
9542 return None;
9543 }
9544 if entry.range.end > group_end {
9545 group_end = entry.range.end;
9546 }
9547 if entry.diagnostic.is_primary {
9548 primary_range = Some(entry.range.clone());
9549 primary_message = Some(entry.diagnostic.message.clone());
9550 }
9551 Some(entry)
9552 })
9553 .collect::<Vec<_>>();
9554 let primary_range = primary_range?;
9555 let primary_message = primary_message?;
9556 let primary_range =
9557 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9558
9559 let blocks = display_map
9560 .insert_blocks(
9561 diagnostic_group.iter().map(|entry| {
9562 let diagnostic = entry.diagnostic.clone();
9563 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
9564 BlockProperties {
9565 style: BlockStyle::Fixed,
9566 position: buffer.anchor_after(entry.range.start),
9567 height: message_height,
9568 render: diagnostic_block_renderer(diagnostic, true),
9569 disposition: BlockDisposition::Below,
9570 }
9571 }),
9572 cx,
9573 )
9574 .into_iter()
9575 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9576 .collect();
9577
9578 Some(ActiveDiagnosticGroup {
9579 primary_range,
9580 primary_message,
9581 group_id,
9582 blocks,
9583 is_valid: true,
9584 })
9585 });
9586 self.active_diagnostics.is_some()
9587 }
9588
9589 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9590 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9591 self.display_map.update(cx, |display_map, cx| {
9592 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9593 });
9594 cx.notify();
9595 }
9596 }
9597
9598 pub fn set_selections_from_remote(
9599 &mut self,
9600 selections: Vec<Selection<Anchor>>,
9601 pending_selection: Option<Selection<Anchor>>,
9602 cx: &mut ViewContext<Self>,
9603 ) {
9604 let old_cursor_position = self.selections.newest_anchor().head();
9605 self.selections.change_with(cx, |s| {
9606 s.select_anchors(selections);
9607 if let Some(pending_selection) = pending_selection {
9608 s.set_pending(pending_selection, SelectMode::Character);
9609 } else {
9610 s.clear_pending();
9611 }
9612 });
9613 self.selections_did_change(false, &old_cursor_position, true, cx);
9614 }
9615
9616 fn push_to_selection_history(&mut self) {
9617 self.selection_history.push(SelectionHistoryEntry {
9618 selections: self.selections.disjoint_anchors(),
9619 select_next_state: self.select_next_state.clone(),
9620 select_prev_state: self.select_prev_state.clone(),
9621 add_selections_state: self.add_selections_state.clone(),
9622 });
9623 }
9624
9625 pub fn transact(
9626 &mut self,
9627 cx: &mut ViewContext<Self>,
9628 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
9629 ) -> Option<TransactionId> {
9630 self.start_transaction_at(Instant::now(), cx);
9631 update(self, cx);
9632 self.end_transaction_at(Instant::now(), cx)
9633 }
9634
9635 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
9636 self.end_selection(cx);
9637 if let Some(tx_id) = self
9638 .buffer
9639 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9640 {
9641 self.selection_history
9642 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9643 cx.emit(EditorEvent::TransactionBegun {
9644 transaction_id: tx_id,
9645 })
9646 }
9647 }
9648
9649 fn end_transaction_at(
9650 &mut self,
9651 now: Instant,
9652 cx: &mut ViewContext<Self>,
9653 ) -> Option<TransactionId> {
9654 if let Some(transaction_id) = self
9655 .buffer
9656 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9657 {
9658 if let Some((_, end_selections)) =
9659 self.selection_history.transaction_mut(transaction_id)
9660 {
9661 *end_selections = Some(self.selections.disjoint_anchors());
9662 } else {
9663 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9664 }
9665
9666 cx.emit(EditorEvent::Edited { transaction_id });
9667 Some(transaction_id)
9668 } else {
9669 None
9670 }
9671 }
9672
9673 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9674 let mut fold_ranges = Vec::new();
9675
9676 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9677
9678 let selections = self.selections.all_adjusted(cx);
9679 for selection in selections {
9680 let range = selection.range().sorted();
9681 let buffer_start_row = range.start.row;
9682
9683 for row in (0..=range.end.row).rev() {
9684 if let Some((foldable_range, fold_text)) =
9685 display_map.foldable_range(MultiBufferRow(row))
9686 {
9687 if foldable_range.end.row >= buffer_start_row {
9688 fold_ranges.push((foldable_range, fold_text));
9689 if row <= range.start.row {
9690 break;
9691 }
9692 }
9693 }
9694 }
9695 }
9696
9697 self.fold_ranges(fold_ranges, true, cx);
9698 }
9699
9700 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
9701 let buffer_row = fold_at.buffer_row;
9702 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9703
9704 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
9705 let autoscroll = self
9706 .selections
9707 .all::<Point>(cx)
9708 .iter()
9709 .any(|selection| fold_range.overlaps(&selection.range()));
9710
9711 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
9712 }
9713 }
9714
9715 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
9716 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9717 let buffer = &display_map.buffer_snapshot;
9718 let selections = self.selections.all::<Point>(cx);
9719 let ranges = selections
9720 .iter()
9721 .map(|s| {
9722 let range = s.display_range(&display_map).sorted();
9723 let mut start = range.start.to_point(&display_map);
9724 let mut end = range.end.to_point(&display_map);
9725 start.column = 0;
9726 end.column = buffer.line_len(MultiBufferRow(end.row));
9727 start..end
9728 })
9729 .collect::<Vec<_>>();
9730
9731 self.unfold_ranges(ranges, true, true, cx);
9732 }
9733
9734 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
9735 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9736
9737 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
9738 ..Point::new(
9739 unfold_at.buffer_row.0,
9740 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
9741 );
9742
9743 let autoscroll = self
9744 .selections
9745 .all::<Point>(cx)
9746 .iter()
9747 .any(|selection| selection.range().overlaps(&intersection_range));
9748
9749 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
9750 }
9751
9752 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
9753 let selections = self.selections.all::<Point>(cx);
9754 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9755 let line_mode = self.selections.line_mode;
9756 let ranges = selections.into_iter().map(|s| {
9757 if line_mode {
9758 let start = Point::new(s.start.row, 0);
9759 let end = Point::new(
9760 s.end.row,
9761 display_map
9762 .buffer_snapshot
9763 .line_len(MultiBufferRow(s.end.row)),
9764 );
9765 (start..end, display_map.fold_placeholder.clone())
9766 } else {
9767 (s.start..s.end, display_map.fold_placeholder.clone())
9768 }
9769 });
9770 self.fold_ranges(ranges, true, cx);
9771 }
9772
9773 pub fn fold_ranges<T: ToOffset + Clone>(
9774 &mut self,
9775 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
9776 auto_scroll: bool,
9777 cx: &mut ViewContext<Self>,
9778 ) {
9779 let mut fold_ranges = Vec::new();
9780 let mut buffers_affected = HashMap::default();
9781 let multi_buffer = self.buffer().read(cx);
9782 for (fold_range, fold_text) in ranges {
9783 if let Some((_, buffer, _)) =
9784 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
9785 {
9786 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9787 };
9788 fold_ranges.push((fold_range, fold_text));
9789 }
9790
9791 let mut ranges = fold_ranges.into_iter().peekable();
9792 if ranges.peek().is_some() {
9793 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
9794
9795 if auto_scroll {
9796 self.request_autoscroll(Autoscroll::fit(), cx);
9797 }
9798
9799 for buffer in buffers_affected.into_values() {
9800 self.sync_expanded_diff_hunks(buffer, cx);
9801 }
9802
9803 cx.notify();
9804
9805 if let Some(active_diagnostics) = self.active_diagnostics.take() {
9806 // Clear diagnostics block when folding a range that contains it.
9807 let snapshot = self.snapshot(cx);
9808 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
9809 drop(snapshot);
9810 self.active_diagnostics = Some(active_diagnostics);
9811 self.dismiss_diagnostics(cx);
9812 } else {
9813 self.active_diagnostics = Some(active_diagnostics);
9814 }
9815 }
9816
9817 self.scrollbar_marker_state.dirty = true;
9818 }
9819 }
9820
9821 pub fn unfold_ranges<T: ToOffset + Clone>(
9822 &mut self,
9823 ranges: impl IntoIterator<Item = Range<T>>,
9824 inclusive: bool,
9825 auto_scroll: bool,
9826 cx: &mut ViewContext<Self>,
9827 ) {
9828 let mut unfold_ranges = Vec::new();
9829 let mut buffers_affected = HashMap::default();
9830 let multi_buffer = self.buffer().read(cx);
9831 for range in ranges {
9832 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
9833 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9834 };
9835 unfold_ranges.push(range);
9836 }
9837
9838 let mut ranges = unfold_ranges.into_iter().peekable();
9839 if ranges.peek().is_some() {
9840 self.display_map
9841 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
9842 if auto_scroll {
9843 self.request_autoscroll(Autoscroll::fit(), cx);
9844 }
9845
9846 for buffer in buffers_affected.into_values() {
9847 self.sync_expanded_diff_hunks(buffer, cx);
9848 }
9849
9850 cx.notify();
9851 self.scrollbar_marker_state.dirty = true;
9852 self.active_indent_guides_state.dirty = true;
9853 }
9854 }
9855
9856 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
9857 if hovered != self.gutter_hovered {
9858 self.gutter_hovered = hovered;
9859 cx.notify();
9860 }
9861 }
9862
9863 pub fn insert_blocks(
9864 &mut self,
9865 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
9866 autoscroll: Option<Autoscroll>,
9867 cx: &mut ViewContext<Self>,
9868 ) -> Vec<BlockId> {
9869 let blocks = self
9870 .display_map
9871 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
9872 if let Some(autoscroll) = autoscroll {
9873 self.request_autoscroll(autoscroll, cx);
9874 }
9875 blocks
9876 }
9877
9878 pub fn replace_blocks(
9879 &mut self,
9880 blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
9881 autoscroll: Option<Autoscroll>,
9882 cx: &mut ViewContext<Self>,
9883 ) {
9884 self.display_map
9885 .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
9886 if let Some(autoscroll) = autoscroll {
9887 self.request_autoscroll(autoscroll, cx);
9888 }
9889 }
9890
9891 pub fn remove_blocks(
9892 &mut self,
9893 block_ids: HashSet<BlockId>,
9894 autoscroll: Option<Autoscroll>,
9895 cx: &mut ViewContext<Self>,
9896 ) {
9897 self.display_map.update(cx, |display_map, cx| {
9898 display_map.remove_blocks(block_ids, cx)
9899 });
9900 if let Some(autoscroll) = autoscroll {
9901 self.request_autoscroll(autoscroll, cx);
9902 }
9903 }
9904
9905 pub fn insert_flaps(
9906 &mut self,
9907 flaps: impl IntoIterator<Item = Flap>,
9908 cx: &mut ViewContext<Self>,
9909 ) -> Vec<FlapId> {
9910 self.display_map
9911 .update(cx, |map, cx| map.insert_flaps(flaps, cx))
9912 }
9913
9914 pub fn remove_flaps(
9915 &mut self,
9916 ids: impl IntoIterator<Item = FlapId>,
9917 cx: &mut ViewContext<Self>,
9918 ) {
9919 self.display_map
9920 .update(cx, |map, cx| map.remove_flaps(ids, cx));
9921 }
9922
9923 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
9924 self.display_map
9925 .update(cx, |map, cx| map.snapshot(cx))
9926 .longest_row()
9927 }
9928
9929 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
9930 self.display_map
9931 .update(cx, |map, cx| map.snapshot(cx))
9932 .max_point()
9933 }
9934
9935 pub fn text(&self, cx: &AppContext) -> String {
9936 self.buffer.read(cx).read(cx).text()
9937 }
9938
9939 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
9940 let text = self.text(cx);
9941 let text = text.trim();
9942
9943 if text.is_empty() {
9944 return None;
9945 }
9946
9947 Some(text.to_string())
9948 }
9949
9950 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
9951 self.transact(cx, |this, cx| {
9952 this.buffer
9953 .read(cx)
9954 .as_singleton()
9955 .expect("you can only call set_text on editors for singleton buffers")
9956 .update(cx, |buffer, cx| buffer.set_text(text, cx));
9957 });
9958 }
9959
9960 pub fn display_text(&self, cx: &mut AppContext) -> String {
9961 self.display_map
9962 .update(cx, |map, cx| map.snapshot(cx))
9963 .text()
9964 }
9965
9966 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
9967 let mut wrap_guides = smallvec::smallvec![];
9968
9969 if self.show_wrap_guides == Some(false) {
9970 return wrap_guides;
9971 }
9972
9973 let settings = self.buffer.read(cx).settings_at(0, cx);
9974 if settings.show_wrap_guides {
9975 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
9976 wrap_guides.push((soft_wrap as usize, true));
9977 }
9978 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
9979 }
9980
9981 wrap_guides
9982 }
9983
9984 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
9985 let settings = self.buffer.read(cx).settings_at(0, cx);
9986 let mode = self
9987 .soft_wrap_mode_override
9988 .unwrap_or_else(|| settings.soft_wrap);
9989 match mode {
9990 language_settings::SoftWrap::None => SoftWrap::None,
9991 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
9992 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
9993 language_settings::SoftWrap::PreferredLineLength => {
9994 SoftWrap::Column(settings.preferred_line_length)
9995 }
9996 }
9997 }
9998
9999 pub fn set_soft_wrap_mode(
10000 &mut self,
10001 mode: language_settings::SoftWrap,
10002 cx: &mut ViewContext<Self>,
10003 ) {
10004 self.soft_wrap_mode_override = Some(mode);
10005 cx.notify();
10006 }
10007
10008 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10009 let rem_size = cx.rem_size();
10010 self.display_map.update(cx, |map, cx| {
10011 map.set_font(
10012 style.text.font(),
10013 style.text.font_size.to_pixels(rem_size),
10014 cx,
10015 )
10016 });
10017 self.style = Some(style);
10018 }
10019
10020 pub fn style(&self) -> Option<&EditorStyle> {
10021 self.style.as_ref()
10022 }
10023
10024 // Called by the element. This method is not designed to be called outside of the editor
10025 // element's layout code because it does not notify when rewrapping is computed synchronously.
10026 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10027 self.display_map
10028 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10029 }
10030
10031 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10032 if self.soft_wrap_mode_override.is_some() {
10033 self.soft_wrap_mode_override.take();
10034 } else {
10035 let soft_wrap = match self.soft_wrap_mode(cx) {
10036 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10037 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10038 language_settings::SoftWrap::PreferLine
10039 }
10040 };
10041 self.soft_wrap_mode_override = Some(soft_wrap);
10042 }
10043 cx.notify();
10044 }
10045
10046 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10047 let Some(workspace) = self.workspace() else {
10048 return;
10049 };
10050 let fs = workspace.read(cx).app_state().fs.clone();
10051 let current_show = TabBarSettings::get_global(cx).show;
10052 update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10053 setting.show = Some(!current_show);
10054 });
10055 }
10056
10057 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10058 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10059 self.buffer
10060 .read(cx)
10061 .settings_at(0, cx)
10062 .indent_guides
10063 .enabled
10064 });
10065 self.show_indent_guides = Some(!currently_enabled);
10066 cx.notify();
10067 }
10068
10069 fn should_show_indent_guides(&self) -> Option<bool> {
10070 self.show_indent_guides
10071 }
10072
10073 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10074 let mut editor_settings = EditorSettings::get_global(cx).clone();
10075 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10076 EditorSettings::override_global(editor_settings, cx);
10077 }
10078
10079 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10080 self.show_gutter = show_gutter;
10081 cx.notify();
10082 }
10083
10084 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10085 self.show_line_numbers = Some(show_line_numbers);
10086 cx.notify();
10087 }
10088
10089 pub fn set_show_git_diff_gutter(
10090 &mut self,
10091 show_git_diff_gutter: bool,
10092 cx: &mut ViewContext<Self>,
10093 ) {
10094 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10095 cx.notify();
10096 }
10097
10098 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10099 self.show_code_actions = Some(show_code_actions);
10100 cx.notify();
10101 }
10102
10103 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10104 self.show_wrap_guides = Some(show_wrap_guides);
10105 cx.notify();
10106 }
10107
10108 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10109 self.show_indent_guides = Some(show_indent_guides);
10110 cx.notify();
10111 }
10112
10113 pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
10114 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10115 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10116 cx.reveal_path(&file.abs_path(cx));
10117 }
10118 }
10119 }
10120
10121 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10122 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10123 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10124 if let Some(path) = file.abs_path(cx).to_str() {
10125 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10126 }
10127 }
10128 }
10129 }
10130
10131 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10132 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10133 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10134 if let Some(path) = file.path().to_str() {
10135 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10136 }
10137 }
10138 }
10139 }
10140
10141 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10142 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10143
10144 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10145 self.start_git_blame(true, cx);
10146 }
10147
10148 cx.notify();
10149 }
10150
10151 pub fn toggle_git_blame_inline(
10152 &mut self,
10153 _: &ToggleGitBlameInline,
10154 cx: &mut ViewContext<Self>,
10155 ) {
10156 self.toggle_git_blame_inline_internal(true, cx);
10157 cx.notify();
10158 }
10159
10160 pub fn git_blame_inline_enabled(&self) -> bool {
10161 self.git_blame_inline_enabled
10162 }
10163
10164 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10165 if let Some(project) = self.project.as_ref() {
10166 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10167 return;
10168 };
10169
10170 if buffer.read(cx).file().is_none() {
10171 return;
10172 }
10173
10174 let focused = self.focus_handle(cx).contains_focused(cx);
10175
10176 let project = project.clone();
10177 let blame =
10178 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10179 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10180 self.blame = Some(blame);
10181 }
10182 }
10183
10184 fn toggle_git_blame_inline_internal(
10185 &mut self,
10186 user_triggered: bool,
10187 cx: &mut ViewContext<Self>,
10188 ) {
10189 if self.git_blame_inline_enabled {
10190 self.git_blame_inline_enabled = false;
10191 self.show_git_blame_inline = false;
10192 self.show_git_blame_inline_delay_task.take();
10193 } else {
10194 self.git_blame_inline_enabled = true;
10195 self.start_git_blame_inline(user_triggered, cx);
10196 }
10197
10198 cx.notify();
10199 }
10200
10201 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10202 self.start_git_blame(user_triggered, cx);
10203
10204 if ProjectSettings::get_global(cx)
10205 .git
10206 .inline_blame_delay()
10207 .is_some()
10208 {
10209 self.start_inline_blame_timer(cx);
10210 } else {
10211 self.show_git_blame_inline = true
10212 }
10213 }
10214
10215 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10216 self.blame.as_ref()
10217 }
10218
10219 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10220 self.show_git_blame_gutter && self.has_blame_entries(cx)
10221 }
10222
10223 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10224 self.show_git_blame_inline
10225 && self.focus_handle.is_focused(cx)
10226 && !self.newest_selection_head_on_empty_line(cx)
10227 && self.has_blame_entries(cx)
10228 }
10229
10230 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10231 self.blame()
10232 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10233 }
10234
10235 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10236 let cursor_anchor = self.selections.newest_anchor().head();
10237
10238 let snapshot = self.buffer.read(cx).snapshot(cx);
10239 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10240
10241 snapshot.line_len(buffer_row) == 0
10242 }
10243
10244 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10245 let (path, selection, repo) = maybe!({
10246 let project_handle = self.project.as_ref()?.clone();
10247 let project = project_handle.read(cx);
10248
10249 let selection = self.selections.newest::<Point>(cx);
10250 let selection_range = selection.range();
10251
10252 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10253 (buffer, selection_range.start.row..selection_range.end.row)
10254 } else {
10255 let buffer_ranges = self
10256 .buffer()
10257 .read(cx)
10258 .range_to_buffer_ranges(selection_range, cx);
10259
10260 let (buffer, range, _) = if selection.reversed {
10261 buffer_ranges.first()
10262 } else {
10263 buffer_ranges.last()
10264 }?;
10265
10266 let snapshot = buffer.read(cx).snapshot();
10267 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10268 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10269 (buffer.clone(), selection)
10270 };
10271
10272 let path = buffer
10273 .read(cx)
10274 .file()?
10275 .as_local()?
10276 .path()
10277 .to_str()?
10278 .to_string();
10279 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10280 Some((path, selection, repo))
10281 })
10282 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10283
10284 const REMOTE_NAME: &str = "origin";
10285 let origin_url = repo
10286 .remote_url(REMOTE_NAME)
10287 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10288 let sha = repo
10289 .head_sha()
10290 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10291
10292 let (provider, remote) =
10293 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10294 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10295
10296 Ok(provider.build_permalink(
10297 remote,
10298 BuildPermalinkParams {
10299 sha: &sha,
10300 path: &path,
10301 selection: Some(selection),
10302 },
10303 ))
10304 }
10305
10306 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10307 let permalink = self.get_permalink_to_line(cx);
10308
10309 match permalink {
10310 Ok(permalink) => {
10311 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10312 }
10313 Err(err) => {
10314 let message = format!("Failed to copy permalink: {err}");
10315
10316 Err::<(), anyhow::Error>(err).log_err();
10317
10318 if let Some(workspace) = self.workspace() {
10319 workspace.update(cx, |workspace, cx| {
10320 struct CopyPermalinkToLine;
10321
10322 workspace.show_toast(
10323 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10324 cx,
10325 )
10326 })
10327 }
10328 }
10329 }
10330 }
10331
10332 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10333 let permalink = self.get_permalink_to_line(cx);
10334
10335 match permalink {
10336 Ok(permalink) => {
10337 cx.open_url(permalink.as_ref());
10338 }
10339 Err(err) => {
10340 let message = format!("Failed to open permalink: {err}");
10341
10342 Err::<(), anyhow::Error>(err).log_err();
10343
10344 if let Some(workspace) = self.workspace() {
10345 workspace.update(cx, |workspace, cx| {
10346 struct OpenPermalinkToLine;
10347
10348 workspace.show_toast(
10349 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10350 cx,
10351 )
10352 })
10353 }
10354 }
10355 }
10356 }
10357
10358 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10359 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10360 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10361 pub fn highlight_rows<T: 'static>(
10362 &mut self,
10363 rows: RangeInclusive<Anchor>,
10364 color: Option<Hsla>,
10365 should_autoscroll: bool,
10366 cx: &mut ViewContext<Self>,
10367 ) {
10368 let snapshot = self.buffer().read(cx).snapshot(cx);
10369 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10370 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10371 highlight
10372 .range
10373 .start()
10374 .cmp(&rows.start(), &snapshot)
10375 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10376 });
10377 match (color, existing_highlight_index) {
10378 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10379 ix,
10380 RowHighlight {
10381 index: post_inc(&mut self.highlight_order),
10382 range: rows,
10383 should_autoscroll,
10384 color,
10385 },
10386 ),
10387 (None, Ok(i)) => {
10388 row_highlights.remove(i);
10389 }
10390 }
10391 }
10392
10393 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10394 pub fn clear_row_highlights<T: 'static>(&mut self) {
10395 self.highlighted_rows.remove(&TypeId::of::<T>());
10396 }
10397
10398 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10399 pub fn highlighted_rows<T: 'static>(
10400 &self,
10401 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10402 Some(
10403 self.highlighted_rows
10404 .get(&TypeId::of::<T>())?
10405 .iter()
10406 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10407 )
10408 }
10409
10410 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10411 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10412 /// Allows to ignore certain kinds of highlights.
10413 pub fn highlighted_display_rows(
10414 &mut self,
10415 cx: &mut WindowContext,
10416 ) -> BTreeMap<DisplayRow, Hsla> {
10417 let snapshot = self.snapshot(cx);
10418 let mut used_highlight_orders = HashMap::default();
10419 self.highlighted_rows
10420 .iter()
10421 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10422 .fold(
10423 BTreeMap::<DisplayRow, Hsla>::new(),
10424 |mut unique_rows, highlight| {
10425 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10426 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10427 for row in start_row.0..=end_row.0 {
10428 let used_index =
10429 used_highlight_orders.entry(row).or_insert(highlight.index);
10430 if highlight.index >= *used_index {
10431 *used_index = highlight.index;
10432 match highlight.color {
10433 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10434 None => unique_rows.remove(&DisplayRow(row)),
10435 };
10436 }
10437 }
10438 unique_rows
10439 },
10440 )
10441 }
10442
10443 pub fn highlighted_display_row_for_autoscroll(
10444 &self,
10445 snapshot: &DisplaySnapshot,
10446 ) -> Option<DisplayRow> {
10447 self.highlighted_rows
10448 .values()
10449 .flat_map(|highlighted_rows| highlighted_rows.iter())
10450 .filter_map(|highlight| {
10451 if highlight.color.is_none() || !highlight.should_autoscroll {
10452 return None;
10453 }
10454 Some(highlight.range.start().to_display_point(&snapshot).row())
10455 })
10456 .min()
10457 }
10458
10459 pub fn set_search_within_ranges(
10460 &mut self,
10461 ranges: &[Range<Anchor>],
10462 cx: &mut ViewContext<Self>,
10463 ) {
10464 self.highlight_background::<SearchWithinRange>(
10465 ranges,
10466 |colors| colors.editor_document_highlight_read_background,
10467 cx,
10468 )
10469 }
10470
10471 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10472 self.clear_background_highlights::<SearchWithinRange>(cx);
10473 }
10474
10475 pub fn highlight_background<T: 'static>(
10476 &mut self,
10477 ranges: &[Range<Anchor>],
10478 color_fetcher: fn(&ThemeColors) -> Hsla,
10479 cx: &mut ViewContext<Self>,
10480 ) {
10481 let snapshot = self.snapshot(cx);
10482 // this is to try and catch a panic sooner
10483 for range in ranges {
10484 snapshot
10485 .buffer_snapshot
10486 .summary_for_anchor::<usize>(&range.start);
10487 snapshot
10488 .buffer_snapshot
10489 .summary_for_anchor::<usize>(&range.end);
10490 }
10491
10492 self.background_highlights
10493 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10494 self.scrollbar_marker_state.dirty = true;
10495 cx.notify();
10496 }
10497
10498 pub fn clear_background_highlights<T: 'static>(
10499 &mut self,
10500 cx: &mut ViewContext<Self>,
10501 ) -> Option<BackgroundHighlight> {
10502 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10503 if !text_highlights.1.is_empty() {
10504 self.scrollbar_marker_state.dirty = true;
10505 cx.notify();
10506 }
10507 Some(text_highlights)
10508 }
10509
10510 pub fn highlight_gutter<T: 'static>(
10511 &mut self,
10512 ranges: &[Range<Anchor>],
10513 color_fetcher: fn(&AppContext) -> Hsla,
10514 cx: &mut ViewContext<Self>,
10515 ) {
10516 self.gutter_highlights
10517 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10518 cx.notify();
10519 }
10520
10521 pub fn clear_gutter_highlights<T: 'static>(
10522 &mut self,
10523 cx: &mut ViewContext<Self>,
10524 ) -> Option<GutterHighlight> {
10525 cx.notify();
10526 self.gutter_highlights.remove(&TypeId::of::<T>())
10527 }
10528
10529 #[cfg(feature = "test-support")]
10530 pub fn all_text_background_highlights(
10531 &mut self,
10532 cx: &mut ViewContext<Self>,
10533 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10534 let snapshot = self.snapshot(cx);
10535 let buffer = &snapshot.buffer_snapshot;
10536 let start = buffer.anchor_before(0);
10537 let end = buffer.anchor_after(buffer.len());
10538 let theme = cx.theme().colors();
10539 self.background_highlights_in_range(start..end, &snapshot, theme)
10540 }
10541
10542 #[cfg(feature = "test-support")]
10543 pub fn search_background_highlights(
10544 &mut self,
10545 cx: &mut ViewContext<Self>,
10546 ) -> Vec<Range<Point>> {
10547 let snapshot = self.buffer().read(cx).snapshot(cx);
10548
10549 let highlights = self
10550 .background_highlights
10551 .get(&TypeId::of::<items::BufferSearchHighlights>());
10552
10553 if let Some((_color, ranges)) = highlights {
10554 ranges
10555 .iter()
10556 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10557 .collect_vec()
10558 } else {
10559 vec![]
10560 }
10561 }
10562
10563 fn document_highlights_for_position<'a>(
10564 &'a self,
10565 position: Anchor,
10566 buffer: &'a MultiBufferSnapshot,
10567 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10568 let read_highlights = self
10569 .background_highlights
10570 .get(&TypeId::of::<DocumentHighlightRead>())
10571 .map(|h| &h.1);
10572 let write_highlights = self
10573 .background_highlights
10574 .get(&TypeId::of::<DocumentHighlightWrite>())
10575 .map(|h| &h.1);
10576 let left_position = position.bias_left(buffer);
10577 let right_position = position.bias_right(buffer);
10578 read_highlights
10579 .into_iter()
10580 .chain(write_highlights)
10581 .flat_map(move |ranges| {
10582 let start_ix = match ranges.binary_search_by(|probe| {
10583 let cmp = probe.end.cmp(&left_position, buffer);
10584 if cmp.is_ge() {
10585 Ordering::Greater
10586 } else {
10587 Ordering::Less
10588 }
10589 }) {
10590 Ok(i) | Err(i) => i,
10591 };
10592
10593 ranges[start_ix..]
10594 .iter()
10595 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10596 })
10597 }
10598
10599 pub fn has_background_highlights<T: 'static>(&self) -> bool {
10600 self.background_highlights
10601 .get(&TypeId::of::<T>())
10602 .map_or(false, |(_, highlights)| !highlights.is_empty())
10603 }
10604
10605 pub fn background_highlights_in_range(
10606 &self,
10607 search_range: Range<Anchor>,
10608 display_snapshot: &DisplaySnapshot,
10609 theme: &ThemeColors,
10610 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10611 let mut results = Vec::new();
10612 for (color_fetcher, ranges) in self.background_highlights.values() {
10613 let color = color_fetcher(theme);
10614 let start_ix = match ranges.binary_search_by(|probe| {
10615 let cmp = probe
10616 .end
10617 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10618 if cmp.is_gt() {
10619 Ordering::Greater
10620 } else {
10621 Ordering::Less
10622 }
10623 }) {
10624 Ok(i) | Err(i) => i,
10625 };
10626 for range in &ranges[start_ix..] {
10627 if range
10628 .start
10629 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10630 .is_ge()
10631 {
10632 break;
10633 }
10634
10635 let start = range.start.to_display_point(&display_snapshot);
10636 let end = range.end.to_display_point(&display_snapshot);
10637 results.push((start..end, color))
10638 }
10639 }
10640 results
10641 }
10642
10643 pub fn background_highlight_row_ranges<T: 'static>(
10644 &self,
10645 search_range: Range<Anchor>,
10646 display_snapshot: &DisplaySnapshot,
10647 count: usize,
10648 ) -> Vec<RangeInclusive<DisplayPoint>> {
10649 let mut results = Vec::new();
10650 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10651 return vec![];
10652 };
10653
10654 let start_ix = match ranges.binary_search_by(|probe| {
10655 let cmp = probe
10656 .end
10657 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10658 if cmp.is_gt() {
10659 Ordering::Greater
10660 } else {
10661 Ordering::Less
10662 }
10663 }) {
10664 Ok(i) | Err(i) => i,
10665 };
10666 let mut push_region = |start: Option<Point>, end: Option<Point>| {
10667 if let (Some(start_display), Some(end_display)) = (start, end) {
10668 results.push(
10669 start_display.to_display_point(display_snapshot)
10670 ..=end_display.to_display_point(display_snapshot),
10671 );
10672 }
10673 };
10674 let mut start_row: Option<Point> = None;
10675 let mut end_row: Option<Point> = None;
10676 if ranges.len() > count {
10677 return Vec::new();
10678 }
10679 for range in &ranges[start_ix..] {
10680 if range
10681 .start
10682 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10683 .is_ge()
10684 {
10685 break;
10686 }
10687 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10688 if let Some(current_row) = &end_row {
10689 if end.row == current_row.row {
10690 continue;
10691 }
10692 }
10693 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10694 if start_row.is_none() {
10695 assert_eq!(end_row, None);
10696 start_row = Some(start);
10697 end_row = Some(end);
10698 continue;
10699 }
10700 if let Some(current_end) = end_row.as_mut() {
10701 if start.row > current_end.row + 1 {
10702 push_region(start_row, end_row);
10703 start_row = Some(start);
10704 end_row = Some(end);
10705 } else {
10706 // Merge two hunks.
10707 *current_end = end;
10708 }
10709 } else {
10710 unreachable!();
10711 }
10712 }
10713 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10714 push_region(start_row, end_row);
10715 results
10716 }
10717
10718 pub fn gutter_highlights_in_range(
10719 &self,
10720 search_range: Range<Anchor>,
10721 display_snapshot: &DisplaySnapshot,
10722 cx: &AppContext,
10723 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10724 let mut results = Vec::new();
10725 for (color_fetcher, ranges) in self.gutter_highlights.values() {
10726 let color = color_fetcher(cx);
10727 let start_ix = match ranges.binary_search_by(|probe| {
10728 let cmp = probe
10729 .end
10730 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10731 if cmp.is_gt() {
10732 Ordering::Greater
10733 } else {
10734 Ordering::Less
10735 }
10736 }) {
10737 Ok(i) | Err(i) => i,
10738 };
10739 for range in &ranges[start_ix..] {
10740 if range
10741 .start
10742 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10743 .is_ge()
10744 {
10745 break;
10746 }
10747
10748 let start = range.start.to_display_point(&display_snapshot);
10749 let end = range.end.to_display_point(&display_snapshot);
10750 results.push((start..end, color))
10751 }
10752 }
10753 results
10754 }
10755
10756 /// Get the text ranges corresponding to the redaction query
10757 pub fn redacted_ranges(
10758 &self,
10759 search_range: Range<Anchor>,
10760 display_snapshot: &DisplaySnapshot,
10761 cx: &WindowContext,
10762 ) -> Vec<Range<DisplayPoint>> {
10763 display_snapshot
10764 .buffer_snapshot
10765 .redacted_ranges(search_range, |file| {
10766 if let Some(file) = file {
10767 file.is_private()
10768 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10769 } else {
10770 false
10771 }
10772 })
10773 .map(|range| {
10774 range.start.to_display_point(display_snapshot)
10775 ..range.end.to_display_point(display_snapshot)
10776 })
10777 .collect()
10778 }
10779
10780 pub fn highlight_text<T: 'static>(
10781 &mut self,
10782 ranges: Vec<Range<Anchor>>,
10783 style: HighlightStyle,
10784 cx: &mut ViewContext<Self>,
10785 ) {
10786 self.display_map.update(cx, |map, _| {
10787 map.highlight_text(TypeId::of::<T>(), ranges, style)
10788 });
10789 cx.notify();
10790 }
10791
10792 pub(crate) fn highlight_inlays<T: 'static>(
10793 &mut self,
10794 highlights: Vec<InlayHighlight>,
10795 style: HighlightStyle,
10796 cx: &mut ViewContext<Self>,
10797 ) {
10798 self.display_map.update(cx, |map, _| {
10799 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
10800 });
10801 cx.notify();
10802 }
10803
10804 pub fn text_highlights<'a, T: 'static>(
10805 &'a self,
10806 cx: &'a AppContext,
10807 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
10808 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
10809 }
10810
10811 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
10812 let cleared = self
10813 .display_map
10814 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
10815 if cleared {
10816 cx.notify();
10817 }
10818 }
10819
10820 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
10821 (self.read_only(cx) || self.blink_manager.read(cx).visible())
10822 && self.focus_handle.is_focused(cx)
10823 }
10824
10825 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
10826 cx.notify();
10827 }
10828
10829 fn on_buffer_event(
10830 &mut self,
10831 multibuffer: Model<MultiBuffer>,
10832 event: &multi_buffer::Event,
10833 cx: &mut ViewContext<Self>,
10834 ) {
10835 match event {
10836 multi_buffer::Event::Edited {
10837 singleton_buffer_edited,
10838 } => {
10839 self.scrollbar_marker_state.dirty = true;
10840 self.active_indent_guides_state.dirty = true;
10841 self.refresh_active_diagnostics(cx);
10842 self.refresh_code_actions(cx);
10843 if self.has_active_inline_completion(cx) {
10844 self.update_visible_inline_completion(cx);
10845 }
10846 cx.emit(EditorEvent::BufferEdited);
10847 cx.emit(SearchEvent::MatchesInvalidated);
10848 if *singleton_buffer_edited {
10849 if let Some(project) = &self.project {
10850 let project = project.read(cx);
10851 let languages_affected = multibuffer
10852 .read(cx)
10853 .all_buffers()
10854 .into_iter()
10855 .filter_map(|buffer| {
10856 let buffer = buffer.read(cx);
10857 let language = buffer.language()?;
10858 if project.is_local()
10859 && project.language_servers_for_buffer(buffer, cx).count() == 0
10860 {
10861 None
10862 } else {
10863 Some(language)
10864 }
10865 })
10866 .cloned()
10867 .collect::<HashSet<_>>();
10868 if !languages_affected.is_empty() {
10869 self.refresh_inlay_hints(
10870 InlayHintRefreshReason::BufferEdited(languages_affected),
10871 cx,
10872 );
10873 }
10874 }
10875 }
10876
10877 let Some(project) = &self.project else { return };
10878 let telemetry = project.read(cx).client().telemetry().clone();
10879 refresh_linked_ranges(self, cx);
10880 telemetry.log_edit_event("editor");
10881 }
10882 multi_buffer::Event::ExcerptsAdded {
10883 buffer,
10884 predecessor,
10885 excerpts,
10886 } => {
10887 self.tasks_update_task = Some(self.refresh_runnables(cx));
10888 cx.emit(EditorEvent::ExcerptsAdded {
10889 buffer: buffer.clone(),
10890 predecessor: *predecessor,
10891 excerpts: excerpts.clone(),
10892 });
10893 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
10894 }
10895 multi_buffer::Event::ExcerptsRemoved { ids } => {
10896 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
10897 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
10898 }
10899 multi_buffer::Event::ExcerptsEdited { ids } => {
10900 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
10901 }
10902 multi_buffer::Event::ExcerptsExpanded { ids } => {
10903 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
10904 }
10905 multi_buffer::Event::Reparsed(buffer_id) => {
10906 self.tasks_update_task = Some(self.refresh_runnables(cx));
10907
10908 cx.emit(EditorEvent::Reparsed(*buffer_id));
10909 }
10910 multi_buffer::Event::LanguageChanged(buffer_id) => {
10911 linked_editing_ranges::refresh_linked_ranges(self, cx);
10912 cx.emit(EditorEvent::Reparsed(*buffer_id));
10913 cx.notify();
10914 }
10915 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
10916 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
10917 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
10918 cx.emit(EditorEvent::TitleChanged)
10919 }
10920 multi_buffer::Event::DiffBaseChanged => {
10921 self.scrollbar_marker_state.dirty = true;
10922 cx.emit(EditorEvent::DiffBaseChanged);
10923 cx.notify();
10924 }
10925 multi_buffer::Event::DiffUpdated { buffer } => {
10926 self.sync_expanded_diff_hunks(buffer.clone(), cx);
10927 cx.notify();
10928 }
10929 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
10930 multi_buffer::Event::DiagnosticsUpdated => {
10931 self.refresh_active_diagnostics(cx);
10932 self.scrollbar_marker_state.dirty = true;
10933 cx.notify();
10934 }
10935 _ => {}
10936 };
10937 }
10938
10939 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
10940 cx.notify();
10941 }
10942
10943 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
10944 self.refresh_inline_completion(true, cx);
10945 self.refresh_inlay_hints(
10946 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
10947 self.selections.newest_anchor().head(),
10948 &self.buffer.read(cx).snapshot(cx),
10949 cx,
10950 )),
10951 cx,
10952 );
10953 let editor_settings = EditorSettings::get_global(cx);
10954 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
10955 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
10956
10957 if self.mode == EditorMode::Full {
10958 let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
10959 if self.git_blame_inline_enabled != inline_blame_enabled {
10960 self.toggle_git_blame_inline_internal(false, cx);
10961 }
10962 }
10963
10964 cx.notify();
10965 }
10966
10967 pub fn set_searchable(&mut self, searchable: bool) {
10968 self.searchable = searchable;
10969 }
10970
10971 pub fn searchable(&self) -> bool {
10972 self.searchable
10973 }
10974
10975 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
10976 self.open_excerpts_common(true, cx)
10977 }
10978
10979 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
10980 self.open_excerpts_common(false, cx)
10981 }
10982
10983 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
10984 let buffer = self.buffer.read(cx);
10985 if buffer.is_singleton() {
10986 cx.propagate();
10987 return;
10988 }
10989
10990 let Some(workspace) = self.workspace() else {
10991 cx.propagate();
10992 return;
10993 };
10994
10995 let mut new_selections_by_buffer = HashMap::default();
10996 for selection in self.selections.all::<usize>(cx) {
10997 for (buffer, mut range, _) in
10998 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
10999 {
11000 if selection.reversed {
11001 mem::swap(&mut range.start, &mut range.end);
11002 }
11003 new_selections_by_buffer
11004 .entry(buffer)
11005 .or_insert(Vec::new())
11006 .push(range)
11007 }
11008 }
11009
11010 // We defer the pane interaction because we ourselves are a workspace item
11011 // and activating a new item causes the pane to call a method on us reentrantly,
11012 // which panics if we're on the stack.
11013 cx.window_context().defer(move |cx| {
11014 workspace.update(cx, |workspace, cx| {
11015 let pane = if split {
11016 workspace.adjacent_pane(cx)
11017 } else {
11018 workspace.active_pane().clone()
11019 };
11020
11021 for (buffer, ranges) in new_selections_by_buffer {
11022 let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11023 editor.update(cx, |editor, cx| {
11024 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11025 s.select_ranges(ranges);
11026 });
11027 });
11028 }
11029 })
11030 });
11031 }
11032
11033 fn jump(
11034 &mut self,
11035 path: ProjectPath,
11036 position: Point,
11037 anchor: language::Anchor,
11038 offset_from_top: u32,
11039 cx: &mut ViewContext<Self>,
11040 ) {
11041 let workspace = self.workspace();
11042 cx.spawn(|_, mut cx| async move {
11043 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11044 let editor = workspace.update(&mut cx, |workspace, cx| {
11045 // Reset the preview item id before opening the new item
11046 workspace.active_pane().update(cx, |pane, cx| {
11047 pane.set_preview_item_id(None, cx);
11048 });
11049 workspace.open_path_preview(path, None, true, true, cx)
11050 })?;
11051 let editor = editor
11052 .await?
11053 .downcast::<Editor>()
11054 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11055 .downgrade();
11056 editor.update(&mut cx, |editor, cx| {
11057 let buffer = editor
11058 .buffer()
11059 .read(cx)
11060 .as_singleton()
11061 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11062 let buffer = buffer.read(cx);
11063 let cursor = if buffer.can_resolve(&anchor) {
11064 language::ToPoint::to_point(&anchor, buffer)
11065 } else {
11066 buffer.clip_point(position, Bias::Left)
11067 };
11068
11069 let nav_history = editor.nav_history.take();
11070 editor.change_selections(
11071 Some(Autoscroll::top_relative(offset_from_top as usize)),
11072 cx,
11073 |s| {
11074 s.select_ranges([cursor..cursor]);
11075 },
11076 );
11077 editor.nav_history = nav_history;
11078
11079 anyhow::Ok(())
11080 })??;
11081
11082 anyhow::Ok(())
11083 })
11084 .detach_and_log_err(cx);
11085 }
11086
11087 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11088 let snapshot = self.buffer.read(cx).read(cx);
11089 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11090 Some(
11091 ranges
11092 .iter()
11093 .map(move |range| {
11094 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11095 })
11096 .collect(),
11097 )
11098 }
11099
11100 fn selection_replacement_ranges(
11101 &self,
11102 range: Range<OffsetUtf16>,
11103 cx: &AppContext,
11104 ) -> Vec<Range<OffsetUtf16>> {
11105 let selections = self.selections.all::<OffsetUtf16>(cx);
11106 let newest_selection = selections
11107 .iter()
11108 .max_by_key(|selection| selection.id)
11109 .unwrap();
11110 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11111 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11112 let snapshot = self.buffer.read(cx).read(cx);
11113 selections
11114 .into_iter()
11115 .map(|mut selection| {
11116 selection.start.0 =
11117 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11118 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11119 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11120 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11121 })
11122 .collect()
11123 }
11124
11125 fn report_editor_event(
11126 &self,
11127 operation: &'static str,
11128 file_extension: Option<String>,
11129 cx: &AppContext,
11130 ) {
11131 if cfg!(any(test, feature = "test-support")) {
11132 return;
11133 }
11134
11135 let Some(project) = &self.project else { return };
11136
11137 // If None, we are in a file without an extension
11138 let file = self
11139 .buffer
11140 .read(cx)
11141 .as_singleton()
11142 .and_then(|b| b.read(cx).file());
11143 let file_extension = file_extension.or(file
11144 .as_ref()
11145 .and_then(|file| Path::new(file.file_name(cx)).extension())
11146 .and_then(|e| e.to_str())
11147 .map(|a| a.to_string()));
11148
11149 let vim_mode = cx
11150 .global::<SettingsStore>()
11151 .raw_user_settings()
11152 .get("vim_mode")
11153 == Some(&serde_json::Value::Bool(true));
11154
11155 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11156 == language::language_settings::InlineCompletionProvider::Copilot;
11157 let copilot_enabled_for_language = self
11158 .buffer
11159 .read(cx)
11160 .settings_at(0, cx)
11161 .show_inline_completions;
11162
11163 let telemetry = project.read(cx).client().telemetry().clone();
11164 telemetry.report_editor_event(
11165 file_extension,
11166 vim_mode,
11167 operation,
11168 copilot_enabled,
11169 copilot_enabled_for_language,
11170 )
11171 }
11172
11173 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11174 /// with each line being an array of {text, highlight} objects.
11175 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11176 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11177 return;
11178 };
11179
11180 #[derive(Serialize)]
11181 struct Chunk<'a> {
11182 text: String,
11183 highlight: Option<&'a str>,
11184 }
11185
11186 let snapshot = buffer.read(cx).snapshot();
11187 let range = self
11188 .selected_text_range(cx)
11189 .and_then(|selected_range| {
11190 if selected_range.is_empty() {
11191 None
11192 } else {
11193 Some(selected_range)
11194 }
11195 })
11196 .unwrap_or_else(|| 0..snapshot.len());
11197
11198 let chunks = snapshot.chunks(range, true);
11199 let mut lines = Vec::new();
11200 let mut line: VecDeque<Chunk> = VecDeque::new();
11201
11202 let Some(style) = self.style.as_ref() else {
11203 return;
11204 };
11205
11206 for chunk in chunks {
11207 let highlight = chunk
11208 .syntax_highlight_id
11209 .and_then(|id| id.name(&style.syntax));
11210 let mut chunk_lines = chunk.text.split('\n').peekable();
11211 while let Some(text) = chunk_lines.next() {
11212 let mut merged_with_last_token = false;
11213 if let Some(last_token) = line.back_mut() {
11214 if last_token.highlight == highlight {
11215 last_token.text.push_str(text);
11216 merged_with_last_token = true;
11217 }
11218 }
11219
11220 if !merged_with_last_token {
11221 line.push_back(Chunk {
11222 text: text.into(),
11223 highlight,
11224 });
11225 }
11226
11227 if chunk_lines.peek().is_some() {
11228 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11229 line.pop_front();
11230 }
11231 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11232 line.pop_back();
11233 }
11234
11235 lines.push(mem::take(&mut line));
11236 }
11237 }
11238 }
11239
11240 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11241 return;
11242 };
11243 cx.write_to_clipboard(ClipboardItem::new(lines));
11244 }
11245
11246 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11247 &self.inlay_hint_cache
11248 }
11249
11250 pub fn replay_insert_event(
11251 &mut self,
11252 text: &str,
11253 relative_utf16_range: Option<Range<isize>>,
11254 cx: &mut ViewContext<Self>,
11255 ) {
11256 if !self.input_enabled {
11257 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11258 return;
11259 }
11260 if let Some(relative_utf16_range) = relative_utf16_range {
11261 let selections = self.selections.all::<OffsetUtf16>(cx);
11262 self.change_selections(None, cx, |s| {
11263 let new_ranges = selections.into_iter().map(|range| {
11264 let start = OffsetUtf16(
11265 range
11266 .head()
11267 .0
11268 .saturating_add_signed(relative_utf16_range.start),
11269 );
11270 let end = OffsetUtf16(
11271 range
11272 .head()
11273 .0
11274 .saturating_add_signed(relative_utf16_range.end),
11275 );
11276 start..end
11277 });
11278 s.select_ranges(new_ranges);
11279 });
11280 }
11281
11282 self.handle_input(text, cx);
11283 }
11284
11285 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11286 let Some(project) = self.project.as_ref() else {
11287 return false;
11288 };
11289 let project = project.read(cx);
11290
11291 let mut supports = false;
11292 self.buffer().read(cx).for_each_buffer(|buffer| {
11293 if !supports {
11294 supports = project
11295 .language_servers_for_buffer(buffer.read(cx), cx)
11296 .any(
11297 |(_, server)| match server.capabilities().inlay_hint_provider {
11298 Some(lsp::OneOf::Left(enabled)) => enabled,
11299 Some(lsp::OneOf::Right(_)) => true,
11300 None => false,
11301 },
11302 )
11303 }
11304 });
11305 supports
11306 }
11307
11308 pub fn focus(&self, cx: &mut WindowContext) {
11309 cx.focus(&self.focus_handle)
11310 }
11311
11312 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11313 self.focus_handle.is_focused(cx)
11314 }
11315
11316 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11317 cx.emit(EditorEvent::Focused);
11318 if let Some(rename) = self.pending_rename.as_ref() {
11319 let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
11320 cx.focus(&rename_editor_focus_handle);
11321 } else {
11322 if let Some(blame) = self.blame.as_ref() {
11323 blame.update(cx, GitBlame::focus)
11324 }
11325
11326 self.blink_manager.update(cx, BlinkManager::enable);
11327 self.show_cursor_names(cx);
11328 self.buffer.update(cx, |buffer, cx| {
11329 buffer.finalize_last_transaction(cx);
11330 if self.leader_peer_id.is_none() {
11331 buffer.set_active_selections(
11332 &self.selections.disjoint_anchors(),
11333 self.selections.line_mode,
11334 self.cursor_shape,
11335 cx,
11336 );
11337 }
11338 });
11339 }
11340 }
11341
11342 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11343 self.blink_manager.update(cx, BlinkManager::disable);
11344 self.buffer
11345 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11346
11347 if let Some(blame) = self.blame.as_ref() {
11348 blame.update(cx, GitBlame::blur)
11349 }
11350 self.hide_context_menu(cx);
11351 hide_hover(self, cx);
11352 cx.emit(EditorEvent::Blurred);
11353 cx.notify();
11354 }
11355
11356 pub fn register_action<A: Action>(
11357 &mut self,
11358 listener: impl Fn(&A, &mut WindowContext) + 'static,
11359 ) -> Subscription {
11360 let id = self.next_editor_action_id.post_inc();
11361 let listener = Arc::new(listener);
11362 self.editor_actions.borrow_mut().insert(
11363 id,
11364 Box::new(move |cx| {
11365 let _view = cx.view().clone();
11366 let cx = cx.window_context();
11367 let listener = listener.clone();
11368 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11369 let action = action.downcast_ref().unwrap();
11370 if phase == DispatchPhase::Bubble {
11371 listener(action, cx)
11372 }
11373 })
11374 }),
11375 );
11376
11377 let editor_actions = self.editor_actions.clone();
11378 Subscription::new(move || {
11379 editor_actions.borrow_mut().remove(&id);
11380 })
11381 }
11382
11383 pub fn file_header_size(&self) -> u8 {
11384 self.file_header_size
11385 }
11386}
11387
11388fn hunks_for_selections(
11389 multi_buffer_snapshot: &MultiBufferSnapshot,
11390 selections: &[Selection<Anchor>],
11391) -> Vec<DiffHunk<MultiBufferRow>> {
11392 let mut hunks = Vec::with_capacity(selections.len());
11393 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11394 HashMap::default();
11395 let buffer_rows_for_selections = selections.iter().map(|selection| {
11396 let head = selection.head();
11397 let tail = selection.tail();
11398 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11399 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11400 if start > end {
11401 end..start
11402 } else {
11403 start..end
11404 }
11405 });
11406
11407 for selected_multi_buffer_rows in buffer_rows_for_selections {
11408 let query_rows =
11409 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11410 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11411 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11412 // when the caret is just above or just below the deleted hunk.
11413 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11414 let related_to_selection = if allow_adjacent {
11415 hunk.associated_range.overlaps(&query_rows)
11416 || hunk.associated_range.start == query_rows.end
11417 || hunk.associated_range.end == query_rows.start
11418 } else {
11419 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11420 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11421 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11422 || selected_multi_buffer_rows.end == hunk.associated_range.start
11423 };
11424 if related_to_selection {
11425 if !processed_buffer_rows
11426 .entry(hunk.buffer_id)
11427 .or_default()
11428 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11429 {
11430 continue;
11431 }
11432 hunks.push(hunk);
11433 }
11434 }
11435 }
11436
11437 hunks
11438}
11439
11440pub trait CollaborationHub {
11441 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11442 fn user_participant_indices<'a>(
11443 &self,
11444 cx: &'a AppContext,
11445 ) -> &'a HashMap<u64, ParticipantIndex>;
11446 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11447}
11448
11449impl CollaborationHub for Model<Project> {
11450 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11451 self.read(cx).collaborators()
11452 }
11453
11454 fn user_participant_indices<'a>(
11455 &self,
11456 cx: &'a AppContext,
11457 ) -> &'a HashMap<u64, ParticipantIndex> {
11458 self.read(cx).user_store().read(cx).participant_indices()
11459 }
11460
11461 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11462 let this = self.read(cx);
11463 let user_ids = this.collaborators().values().map(|c| c.user_id);
11464 this.user_store().read_with(cx, |user_store, cx| {
11465 user_store.participant_names(user_ids, cx)
11466 })
11467 }
11468}
11469
11470pub trait CompletionProvider {
11471 fn completions(
11472 &self,
11473 buffer: &Model<Buffer>,
11474 buffer_position: text::Anchor,
11475 trigger: CompletionContext,
11476 cx: &mut ViewContext<Editor>,
11477 ) -> Task<Result<Vec<Completion>>>;
11478
11479 fn resolve_completions(
11480 &self,
11481 buffer: Model<Buffer>,
11482 completion_indices: Vec<usize>,
11483 completions: Arc<RwLock<Box<[Completion]>>>,
11484 cx: &mut ViewContext<Editor>,
11485 ) -> Task<Result<bool>>;
11486
11487 fn apply_additional_edits_for_completion(
11488 &self,
11489 buffer: Model<Buffer>,
11490 completion: Completion,
11491 push_to_history: bool,
11492 cx: &mut ViewContext<Editor>,
11493 ) -> Task<Result<Option<language::Transaction>>>;
11494
11495 fn is_completion_trigger(
11496 &self,
11497 buffer: &Model<Buffer>,
11498 position: language::Anchor,
11499 text: &str,
11500 trigger_in_words: bool,
11501 cx: &mut ViewContext<Editor>,
11502 ) -> bool;
11503}
11504
11505impl CompletionProvider for Model<Project> {
11506 fn completions(
11507 &self,
11508 buffer: &Model<Buffer>,
11509 buffer_position: text::Anchor,
11510 options: CompletionContext,
11511 cx: &mut ViewContext<Editor>,
11512 ) -> Task<Result<Vec<Completion>>> {
11513 self.update(cx, |project, cx| {
11514 project.completions(&buffer, buffer_position, options, cx)
11515 })
11516 }
11517
11518 fn resolve_completions(
11519 &self,
11520 buffer: Model<Buffer>,
11521 completion_indices: Vec<usize>,
11522 completions: Arc<RwLock<Box<[Completion]>>>,
11523 cx: &mut ViewContext<Editor>,
11524 ) -> Task<Result<bool>> {
11525 self.update(cx, |project, cx| {
11526 project.resolve_completions(buffer, completion_indices, completions, cx)
11527 })
11528 }
11529
11530 fn apply_additional_edits_for_completion(
11531 &self,
11532 buffer: Model<Buffer>,
11533 completion: Completion,
11534 push_to_history: bool,
11535 cx: &mut ViewContext<Editor>,
11536 ) -> Task<Result<Option<language::Transaction>>> {
11537 self.update(cx, |project, cx| {
11538 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11539 })
11540 }
11541
11542 fn is_completion_trigger(
11543 &self,
11544 buffer: &Model<Buffer>,
11545 position: language::Anchor,
11546 text: &str,
11547 trigger_in_words: bool,
11548 cx: &mut ViewContext<Editor>,
11549 ) -> bool {
11550 if !EditorSettings::get_global(cx).show_completions_on_input {
11551 return false;
11552 }
11553
11554 let mut chars = text.chars();
11555 let char = if let Some(char) = chars.next() {
11556 char
11557 } else {
11558 return false;
11559 };
11560 if chars.next().is_some() {
11561 return false;
11562 }
11563
11564 let buffer = buffer.read(cx);
11565 let scope = buffer.snapshot().language_scope_at(position);
11566 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11567 return true;
11568 }
11569
11570 buffer
11571 .completion_triggers()
11572 .iter()
11573 .any(|string| string == text)
11574 }
11575}
11576
11577fn inlay_hint_settings(
11578 location: Anchor,
11579 snapshot: &MultiBufferSnapshot,
11580 cx: &mut ViewContext<'_, Editor>,
11581) -> InlayHintSettings {
11582 let file = snapshot.file_at(location);
11583 let language = snapshot.language_at(location);
11584 let settings = all_language_settings(file, cx);
11585 settings
11586 .language(language.map(|l| l.name()).as_deref())
11587 .inlay_hints
11588}
11589
11590fn consume_contiguous_rows(
11591 contiguous_row_selections: &mut Vec<Selection<Point>>,
11592 selection: &Selection<Point>,
11593 display_map: &DisplaySnapshot,
11594 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11595) -> (MultiBufferRow, MultiBufferRow) {
11596 contiguous_row_selections.push(selection.clone());
11597 let start_row = MultiBufferRow(selection.start.row);
11598 let mut end_row = ending_row(selection, display_map);
11599
11600 while let Some(next_selection) = selections.peek() {
11601 if next_selection.start.row <= end_row.0 {
11602 end_row = ending_row(next_selection, display_map);
11603 contiguous_row_selections.push(selections.next().unwrap().clone());
11604 } else {
11605 break;
11606 }
11607 }
11608 (start_row, end_row)
11609}
11610
11611fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11612 if next_selection.end.column > 0 || next_selection.is_empty() {
11613 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11614 } else {
11615 MultiBufferRow(next_selection.end.row)
11616 }
11617}
11618
11619impl EditorSnapshot {
11620 pub fn remote_selections_in_range<'a>(
11621 &'a self,
11622 range: &'a Range<Anchor>,
11623 collaboration_hub: &dyn CollaborationHub,
11624 cx: &'a AppContext,
11625 ) -> impl 'a + Iterator<Item = RemoteSelection> {
11626 let participant_names = collaboration_hub.user_names(cx);
11627 let participant_indices = collaboration_hub.user_participant_indices(cx);
11628 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11629 let collaborators_by_replica_id = collaborators_by_peer_id
11630 .iter()
11631 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11632 .collect::<HashMap<_, _>>();
11633 self.buffer_snapshot
11634 .remote_selections_in_range(range)
11635 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11636 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11637 let participant_index = participant_indices.get(&collaborator.user_id).copied();
11638 let user_name = participant_names.get(&collaborator.user_id).cloned();
11639 Some(RemoteSelection {
11640 replica_id,
11641 selection,
11642 cursor_shape,
11643 line_mode,
11644 participant_index,
11645 peer_id: collaborator.peer_id,
11646 user_name,
11647 })
11648 })
11649 }
11650
11651 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11652 self.display_snapshot.buffer_snapshot.language_at(position)
11653 }
11654
11655 pub fn is_focused(&self) -> bool {
11656 self.is_focused
11657 }
11658
11659 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11660 self.placeholder_text.as_ref()
11661 }
11662
11663 pub fn scroll_position(&self) -> gpui::Point<f32> {
11664 self.scroll_anchor.scroll_position(&self.display_snapshot)
11665 }
11666
11667 pub fn gutter_dimensions(
11668 &self,
11669 font_id: FontId,
11670 font_size: Pixels,
11671 em_width: Pixels,
11672 max_line_number_width: Pixels,
11673 cx: &AppContext,
11674 ) -> GutterDimensions {
11675 if !self.show_gutter {
11676 return GutterDimensions::default();
11677 }
11678 let descent = cx.text_system().descent(font_id, font_size);
11679
11680 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11681 matches!(
11682 ProjectSettings::get_global(cx).git.git_gutter,
11683 Some(GitGutterSetting::TrackedFiles)
11684 )
11685 });
11686 let gutter_settings = EditorSettings::get_global(cx).gutter;
11687 let show_line_numbers = self
11688 .show_line_numbers
11689 .unwrap_or_else(|| gutter_settings.line_numbers);
11690 let line_gutter_width = if show_line_numbers {
11691 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11692 let min_width_for_number_on_gutter = em_width * 4.0;
11693 max_line_number_width.max(min_width_for_number_on_gutter)
11694 } else {
11695 0.0.into()
11696 };
11697
11698 let show_code_actions = self
11699 .show_code_actions
11700 .unwrap_or_else(|| gutter_settings.code_actions);
11701
11702 let git_blame_entries_width = self
11703 .render_git_blame_gutter
11704 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11705
11706 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11707 left_padding += if show_code_actions {
11708 em_width * 3.0
11709 } else if show_git_gutter && show_line_numbers {
11710 em_width * 2.0
11711 } else if show_git_gutter || show_line_numbers {
11712 em_width
11713 } else {
11714 px(0.)
11715 };
11716
11717 let right_padding = if gutter_settings.folds && show_line_numbers {
11718 em_width * 4.0
11719 } else if gutter_settings.folds {
11720 em_width * 3.0
11721 } else if show_line_numbers {
11722 em_width
11723 } else {
11724 px(0.)
11725 };
11726
11727 GutterDimensions {
11728 left_padding,
11729 right_padding,
11730 width: line_gutter_width + left_padding + right_padding,
11731 margin: -descent,
11732 git_blame_entries_width,
11733 }
11734 }
11735
11736 pub fn render_fold_toggle(
11737 &self,
11738 buffer_row: MultiBufferRow,
11739 row_contains_cursor: bool,
11740 editor: View<Editor>,
11741 cx: &mut WindowContext,
11742 ) -> Option<AnyElement> {
11743 let folded = self.is_line_folded(buffer_row);
11744
11745 if let Some(flap) = self
11746 .flap_snapshot
11747 .query_row(buffer_row, &self.buffer_snapshot)
11748 {
11749 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11750 if folded {
11751 editor.update(cx, |editor, cx| {
11752 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11753 });
11754 } else {
11755 editor.update(cx, |editor, cx| {
11756 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11757 });
11758 }
11759 });
11760
11761 Some((flap.render_toggle)(
11762 buffer_row,
11763 folded,
11764 toggle_callback,
11765 cx,
11766 ))
11767 } else if folded
11768 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
11769 {
11770 Some(
11771 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
11772 .selected(folded)
11773 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
11774 if folded {
11775 this.unfold_at(&UnfoldAt { buffer_row }, cx);
11776 } else {
11777 this.fold_at(&FoldAt { buffer_row }, cx);
11778 }
11779 }))
11780 .into_any_element(),
11781 )
11782 } else {
11783 None
11784 }
11785 }
11786
11787 pub fn render_flap_trailer(
11788 &self,
11789 buffer_row: MultiBufferRow,
11790 cx: &mut WindowContext,
11791 ) -> Option<AnyElement> {
11792 let folded = self.is_line_folded(buffer_row);
11793 let flap = self
11794 .flap_snapshot
11795 .query_row(buffer_row, &self.buffer_snapshot)?;
11796 Some((flap.render_trailer)(buffer_row, folded, cx))
11797 }
11798}
11799
11800impl Deref for EditorSnapshot {
11801 type Target = DisplaySnapshot;
11802
11803 fn deref(&self) -> &Self::Target {
11804 &self.display_snapshot
11805 }
11806}
11807
11808#[derive(Clone, Debug, PartialEq, Eq)]
11809pub enum EditorEvent {
11810 InputIgnored {
11811 text: Arc<str>,
11812 },
11813 InputHandled {
11814 utf16_range_to_replace: Option<Range<isize>>,
11815 text: Arc<str>,
11816 },
11817 ExcerptsAdded {
11818 buffer: Model<Buffer>,
11819 predecessor: ExcerptId,
11820 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
11821 },
11822 ExcerptsRemoved {
11823 ids: Vec<ExcerptId>,
11824 },
11825 ExcerptsEdited {
11826 ids: Vec<ExcerptId>,
11827 },
11828 ExcerptsExpanded {
11829 ids: Vec<ExcerptId>,
11830 },
11831 BufferEdited,
11832 Edited {
11833 transaction_id: clock::Lamport,
11834 },
11835 Reparsed(BufferId),
11836 Focused,
11837 Blurred,
11838 DirtyChanged,
11839 Saved,
11840 TitleChanged,
11841 DiffBaseChanged,
11842 SelectionsChanged {
11843 local: bool,
11844 },
11845 ScrollPositionChanged {
11846 local: bool,
11847 autoscroll: bool,
11848 },
11849 Closed,
11850 TransactionUndone {
11851 transaction_id: clock::Lamport,
11852 },
11853 TransactionBegun {
11854 transaction_id: clock::Lamport,
11855 },
11856}
11857
11858impl EventEmitter<EditorEvent> for Editor {}
11859
11860impl FocusableView for Editor {
11861 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
11862 self.focus_handle.clone()
11863 }
11864}
11865
11866impl Render for Editor {
11867 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
11868 let settings = ThemeSettings::get_global(cx);
11869
11870 let text_style = match self.mode {
11871 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
11872 color: cx.theme().colors().editor_foreground,
11873 font_family: settings.ui_font.family.clone(),
11874 font_features: settings.ui_font.features.clone(),
11875 font_size: rems(0.875).into(),
11876 font_weight: settings.ui_font.weight,
11877 font_style: FontStyle::Normal,
11878 line_height: relative(settings.buffer_line_height.value()),
11879 background_color: None,
11880 underline: None,
11881 strikethrough: None,
11882 white_space: WhiteSpace::Normal,
11883 },
11884 EditorMode::Full => TextStyle {
11885 color: cx.theme().colors().editor_foreground,
11886 font_family: settings.buffer_font.family.clone(),
11887 font_features: settings.buffer_font.features.clone(),
11888 font_size: settings.buffer_font_size(cx).into(),
11889 font_weight: settings.buffer_font.weight,
11890 font_style: FontStyle::Normal,
11891 line_height: relative(settings.buffer_line_height.value()),
11892 background_color: None,
11893 underline: None,
11894 strikethrough: None,
11895 white_space: WhiteSpace::Normal,
11896 },
11897 };
11898
11899 let background = match self.mode {
11900 EditorMode::SingleLine => cx.theme().system().transparent,
11901 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
11902 EditorMode::Full => cx.theme().colors().editor_background,
11903 };
11904
11905 EditorElement::new(
11906 cx.view(),
11907 EditorStyle {
11908 background,
11909 local_player: cx.theme().players().local(),
11910 text: text_style,
11911 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
11912 syntax: cx.theme().syntax().clone(),
11913 status: cx.theme().status().clone(),
11914 inlay_hints_style: HighlightStyle {
11915 color: Some(cx.theme().status().hint),
11916 ..HighlightStyle::default()
11917 },
11918 suggestions_style: HighlightStyle {
11919 color: Some(cx.theme().status().predictive),
11920 ..HighlightStyle::default()
11921 },
11922 },
11923 )
11924 }
11925}
11926
11927impl ViewInputHandler for Editor {
11928 fn text_for_range(
11929 &mut self,
11930 range_utf16: Range<usize>,
11931 cx: &mut ViewContext<Self>,
11932 ) -> Option<String> {
11933 Some(
11934 self.buffer
11935 .read(cx)
11936 .read(cx)
11937 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
11938 .collect(),
11939 )
11940 }
11941
11942 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11943 // Prevent the IME menu from appearing when holding down an alphabetic key
11944 // while input is disabled.
11945 if !self.input_enabled {
11946 return None;
11947 }
11948
11949 let range = self.selections.newest::<OffsetUtf16>(cx).range();
11950 Some(range.start.0..range.end.0)
11951 }
11952
11953 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11954 let snapshot = self.buffer.read(cx).read(cx);
11955 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
11956 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
11957 }
11958
11959 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
11960 self.clear_highlights::<InputComposition>(cx);
11961 self.ime_transaction.take();
11962 }
11963
11964 fn replace_text_in_range(
11965 &mut self,
11966 range_utf16: Option<Range<usize>>,
11967 text: &str,
11968 cx: &mut ViewContext<Self>,
11969 ) {
11970 if !self.input_enabled {
11971 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11972 return;
11973 }
11974
11975 self.transact(cx, |this, cx| {
11976 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
11977 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11978 Some(this.selection_replacement_ranges(range_utf16, cx))
11979 } else {
11980 this.marked_text_ranges(cx)
11981 };
11982
11983 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
11984 let newest_selection_id = this.selections.newest_anchor().id;
11985 this.selections
11986 .all::<OffsetUtf16>(cx)
11987 .iter()
11988 .zip(ranges_to_replace.iter())
11989 .find_map(|(selection, range)| {
11990 if selection.id == newest_selection_id {
11991 Some(
11992 (range.start.0 as isize - selection.head().0 as isize)
11993 ..(range.end.0 as isize - selection.head().0 as isize),
11994 )
11995 } else {
11996 None
11997 }
11998 })
11999 });
12000
12001 cx.emit(EditorEvent::InputHandled {
12002 utf16_range_to_replace: range_to_replace,
12003 text: text.into(),
12004 });
12005
12006 if let Some(new_selected_ranges) = new_selected_ranges {
12007 this.change_selections(None, cx, |selections| {
12008 selections.select_ranges(new_selected_ranges)
12009 });
12010 this.backspace(&Default::default(), cx);
12011 }
12012
12013 this.handle_input(text, cx);
12014 });
12015
12016 if let Some(transaction) = self.ime_transaction {
12017 self.buffer.update(cx, |buffer, cx| {
12018 buffer.group_until_transaction(transaction, cx);
12019 });
12020 }
12021
12022 self.unmark_text(cx);
12023 }
12024
12025 fn replace_and_mark_text_in_range(
12026 &mut self,
12027 range_utf16: Option<Range<usize>>,
12028 text: &str,
12029 new_selected_range_utf16: Option<Range<usize>>,
12030 cx: &mut ViewContext<Self>,
12031 ) {
12032 if !self.input_enabled {
12033 return;
12034 }
12035
12036 let transaction = self.transact(cx, |this, cx| {
12037 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12038 let snapshot = this.buffer.read(cx).read(cx);
12039 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12040 for marked_range in &mut marked_ranges {
12041 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12042 marked_range.start.0 += relative_range_utf16.start;
12043 marked_range.start =
12044 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12045 marked_range.end =
12046 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12047 }
12048 }
12049 Some(marked_ranges)
12050 } else if let Some(range_utf16) = range_utf16 {
12051 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12052 Some(this.selection_replacement_ranges(range_utf16, cx))
12053 } else {
12054 None
12055 };
12056
12057 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12058 let newest_selection_id = this.selections.newest_anchor().id;
12059 this.selections
12060 .all::<OffsetUtf16>(cx)
12061 .iter()
12062 .zip(ranges_to_replace.iter())
12063 .find_map(|(selection, range)| {
12064 if selection.id == newest_selection_id {
12065 Some(
12066 (range.start.0 as isize - selection.head().0 as isize)
12067 ..(range.end.0 as isize - selection.head().0 as isize),
12068 )
12069 } else {
12070 None
12071 }
12072 })
12073 });
12074
12075 cx.emit(EditorEvent::InputHandled {
12076 utf16_range_to_replace: range_to_replace,
12077 text: text.into(),
12078 });
12079
12080 if let Some(ranges) = ranges_to_replace {
12081 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12082 }
12083
12084 let marked_ranges = {
12085 let snapshot = this.buffer.read(cx).read(cx);
12086 this.selections
12087 .disjoint_anchors()
12088 .iter()
12089 .map(|selection| {
12090 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12091 })
12092 .collect::<Vec<_>>()
12093 };
12094
12095 if text.is_empty() {
12096 this.unmark_text(cx);
12097 } else {
12098 this.highlight_text::<InputComposition>(
12099 marked_ranges.clone(),
12100 HighlightStyle {
12101 underline: Some(UnderlineStyle {
12102 thickness: px(1.),
12103 color: None,
12104 wavy: false,
12105 }),
12106 ..Default::default()
12107 },
12108 cx,
12109 );
12110 }
12111
12112 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12113 let use_autoclose = this.use_autoclose;
12114 this.set_use_autoclose(false);
12115 this.handle_input(text, cx);
12116 this.set_use_autoclose(use_autoclose);
12117
12118 if let Some(new_selected_range) = new_selected_range_utf16 {
12119 let snapshot = this.buffer.read(cx).read(cx);
12120 let new_selected_ranges = marked_ranges
12121 .into_iter()
12122 .map(|marked_range| {
12123 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12124 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12125 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12126 snapshot.clip_offset_utf16(new_start, Bias::Left)
12127 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12128 })
12129 .collect::<Vec<_>>();
12130
12131 drop(snapshot);
12132 this.change_selections(None, cx, |selections| {
12133 selections.select_ranges(new_selected_ranges)
12134 });
12135 }
12136 });
12137
12138 self.ime_transaction = self.ime_transaction.or(transaction);
12139 if let Some(transaction) = self.ime_transaction {
12140 self.buffer.update(cx, |buffer, cx| {
12141 buffer.group_until_transaction(transaction, cx);
12142 });
12143 }
12144
12145 if self.text_highlights::<InputComposition>(cx).is_none() {
12146 self.ime_transaction.take();
12147 }
12148 }
12149
12150 fn bounds_for_range(
12151 &mut self,
12152 range_utf16: Range<usize>,
12153 element_bounds: gpui::Bounds<Pixels>,
12154 cx: &mut ViewContext<Self>,
12155 ) -> Option<gpui::Bounds<Pixels>> {
12156 let text_layout_details = self.text_layout_details(cx);
12157 let style = &text_layout_details.editor_style;
12158 let font_id = cx.text_system().resolve_font(&style.text.font());
12159 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12160 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12161 let em_width = cx
12162 .text_system()
12163 .typographic_bounds(font_id, font_size, 'm')
12164 .unwrap()
12165 .size
12166 .width;
12167
12168 let snapshot = self.snapshot(cx);
12169 let scroll_position = snapshot.scroll_position();
12170 let scroll_left = scroll_position.x * em_width;
12171
12172 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12173 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12174 + self.gutter_dimensions.width;
12175 let y = line_height * (start.row().as_f32() - scroll_position.y);
12176
12177 Some(Bounds {
12178 origin: element_bounds.origin + point(x, y),
12179 size: size(em_width, line_height),
12180 })
12181 }
12182}
12183
12184trait SelectionExt {
12185 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12186 fn spanned_rows(
12187 &self,
12188 include_end_if_at_line_start: bool,
12189 map: &DisplaySnapshot,
12190 ) -> Range<MultiBufferRow>;
12191}
12192
12193impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12194 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12195 let start = self
12196 .start
12197 .to_point(&map.buffer_snapshot)
12198 .to_display_point(map);
12199 let end = self
12200 .end
12201 .to_point(&map.buffer_snapshot)
12202 .to_display_point(map);
12203 if self.reversed {
12204 end..start
12205 } else {
12206 start..end
12207 }
12208 }
12209
12210 fn spanned_rows(
12211 &self,
12212 include_end_if_at_line_start: bool,
12213 map: &DisplaySnapshot,
12214 ) -> Range<MultiBufferRow> {
12215 let start = self.start.to_point(&map.buffer_snapshot);
12216 let mut end = self.end.to_point(&map.buffer_snapshot);
12217 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12218 end.row -= 1;
12219 }
12220
12221 let buffer_start = map.prev_line_boundary(start).0;
12222 let buffer_end = map.next_line_boundary(end).0;
12223 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12224 }
12225}
12226
12227impl<T: InvalidationRegion> InvalidationStack<T> {
12228 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12229 where
12230 S: Clone + ToOffset,
12231 {
12232 while let Some(region) = self.last() {
12233 let all_selections_inside_invalidation_ranges =
12234 if selections.len() == region.ranges().len() {
12235 selections
12236 .iter()
12237 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12238 .all(|(selection, invalidation_range)| {
12239 let head = selection.head().to_offset(buffer);
12240 invalidation_range.start <= head && invalidation_range.end >= head
12241 })
12242 } else {
12243 false
12244 };
12245
12246 if all_selections_inside_invalidation_ranges {
12247 break;
12248 } else {
12249 self.pop();
12250 }
12251 }
12252 }
12253}
12254
12255impl<T> Default for InvalidationStack<T> {
12256 fn default() -> Self {
12257 Self(Default::default())
12258 }
12259}
12260
12261impl<T> Deref for InvalidationStack<T> {
12262 type Target = Vec<T>;
12263
12264 fn deref(&self) -> &Self::Target {
12265 &self.0
12266 }
12267}
12268
12269impl<T> DerefMut for InvalidationStack<T> {
12270 fn deref_mut(&mut self) -> &mut Self::Target {
12271 &mut self.0
12272 }
12273}
12274
12275impl InvalidationRegion for SnippetState {
12276 fn ranges(&self) -> &[Range<Anchor>] {
12277 &self.ranges[self.active_index]
12278 }
12279}
12280
12281pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12282 let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12283
12284 Box::new(move |cx: &mut BlockContext| {
12285 let group_id: SharedString = cx.block_id.to_string().into();
12286
12287 let mut text_style = cx.text_style().clone();
12288 text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
12289 let theme_settings = ThemeSettings::get_global(cx);
12290 text_style.font_family = theme_settings.buffer_font.family.clone();
12291 text_style.font_style = theme_settings.buffer_font.style;
12292 text_style.font_features = theme_settings.buffer_font.features.clone();
12293 text_style.font_weight = theme_settings.buffer_font.weight;
12294
12295 let multi_line_diagnostic = diagnostic.message.contains('\n');
12296
12297 let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12298 if multi_line_diagnostic {
12299 v_flex()
12300 } else {
12301 h_flex()
12302 }
12303 .children(diagnostic.is_primary.then(|| {
12304 IconButton::new(("close-block", block_id), IconName::XCircle)
12305 .icon_color(Color::Muted)
12306 .size(ButtonSize::Compact)
12307 .style(ButtonStyle::Transparent)
12308 .visible_on_hover(group_id.clone())
12309 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12310 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12311 }))
12312 .child(
12313 IconButton::new(("copy-block", block_id), IconName::Copy)
12314 .icon_color(Color::Muted)
12315 .size(ButtonSize::Compact)
12316 .style(ButtonStyle::Transparent)
12317 .visible_on_hover(group_id.clone())
12318 .on_click({
12319 let message = diagnostic.message.clone();
12320 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12321 })
12322 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12323 )
12324 };
12325
12326 let icon_size = buttons(&diagnostic, cx.block_id)
12327 .into_any_element()
12328 .layout_as_root(AvailableSpace::min_size(), cx);
12329
12330 h_flex()
12331 .id(cx.block_id)
12332 .group(group_id.clone())
12333 .relative()
12334 .size_full()
12335 .pl(cx.gutter_dimensions.width)
12336 .w(cx.max_width + cx.gutter_dimensions.width)
12337 .child(
12338 div()
12339 .flex()
12340 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12341 .flex_shrink(),
12342 )
12343 .child(buttons(&diagnostic, cx.block_id))
12344 .child(div().flex().flex_shrink_0().child(
12345 StyledText::new(text_without_backticks.clone()).with_highlights(
12346 &text_style,
12347 code_ranges.iter().map(|range| {
12348 (
12349 range.clone(),
12350 HighlightStyle {
12351 font_weight: Some(FontWeight::BOLD),
12352 ..Default::default()
12353 },
12354 )
12355 }),
12356 ),
12357 ))
12358 .into_any_element()
12359 })
12360}
12361
12362pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12363 let mut text_without_backticks = String::new();
12364 let mut code_ranges = Vec::new();
12365
12366 if let Some(source) = &diagnostic.source {
12367 text_without_backticks.push_str(&source);
12368 code_ranges.push(0..source.len());
12369 text_without_backticks.push_str(": ");
12370 }
12371
12372 let mut prev_offset = 0;
12373 let mut in_code_block = false;
12374 for (ix, _) in diagnostic
12375 .message
12376 .match_indices('`')
12377 .chain([(diagnostic.message.len(), "")])
12378 {
12379 let prev_len = text_without_backticks.len();
12380 text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12381 prev_offset = ix + 1;
12382 if in_code_block {
12383 code_ranges.push(prev_len..text_without_backticks.len());
12384 in_code_block = false;
12385 } else {
12386 in_code_block = true;
12387 }
12388 }
12389
12390 (text_without_backticks.into(), code_ranges)
12391}
12392
12393fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
12394 match (severity, valid) {
12395 (DiagnosticSeverity::ERROR, true) => colors.error,
12396 (DiagnosticSeverity::ERROR, false) => colors.error,
12397 (DiagnosticSeverity::WARNING, true) => colors.warning,
12398 (DiagnosticSeverity::WARNING, false) => colors.warning,
12399 (DiagnosticSeverity::INFORMATION, true) => colors.info,
12400 (DiagnosticSeverity::INFORMATION, false) => colors.info,
12401 (DiagnosticSeverity::HINT, true) => colors.info,
12402 (DiagnosticSeverity::HINT, false) => colors.info,
12403 _ => colors.ignored,
12404 }
12405}
12406
12407pub fn styled_runs_for_code_label<'a>(
12408 label: &'a CodeLabel,
12409 syntax_theme: &'a theme::SyntaxTheme,
12410) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12411 let fade_out = HighlightStyle {
12412 fade_out: Some(0.35),
12413 ..Default::default()
12414 };
12415
12416 let mut prev_end = label.filter_range.end;
12417 label
12418 .runs
12419 .iter()
12420 .enumerate()
12421 .flat_map(move |(ix, (range, highlight_id))| {
12422 let style = if let Some(style) = highlight_id.style(syntax_theme) {
12423 style
12424 } else {
12425 return Default::default();
12426 };
12427 let mut muted_style = style;
12428 muted_style.highlight(fade_out);
12429
12430 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12431 if range.start >= label.filter_range.end {
12432 if range.start > prev_end {
12433 runs.push((prev_end..range.start, fade_out));
12434 }
12435 runs.push((range.clone(), muted_style));
12436 } else if range.end <= label.filter_range.end {
12437 runs.push((range.clone(), style));
12438 } else {
12439 runs.push((range.start..label.filter_range.end, style));
12440 runs.push((label.filter_range.end..range.end, muted_style));
12441 }
12442 prev_end = cmp::max(prev_end, range.end);
12443
12444 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12445 runs.push((prev_end..label.text.len(), fade_out));
12446 }
12447
12448 runs
12449 })
12450}
12451
12452pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12453 let mut prev_index = 0;
12454 let mut prev_codepoint: Option<char> = None;
12455 text.char_indices()
12456 .chain([(text.len(), '\0')])
12457 .filter_map(move |(index, codepoint)| {
12458 let prev_codepoint = prev_codepoint.replace(codepoint)?;
12459 let is_boundary = index == text.len()
12460 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12461 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12462 if is_boundary {
12463 let chunk = &text[prev_index..index];
12464 prev_index = index;
12465 Some(chunk)
12466 } else {
12467 None
12468 }
12469 })
12470}
12471
12472trait RangeToAnchorExt {
12473 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12474}
12475
12476impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12477 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12478 let start_offset = self.start.to_offset(snapshot);
12479 let end_offset = self.end.to_offset(snapshot);
12480 if start_offset == end_offset {
12481 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12482 } else {
12483 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12484 }
12485 }
12486}
12487
12488pub trait RowExt {
12489 fn as_f32(&self) -> f32;
12490
12491 fn next_row(&self) -> Self;
12492
12493 fn previous_row(&self) -> Self;
12494
12495 fn minus(&self, other: Self) -> u32;
12496}
12497
12498impl RowExt for DisplayRow {
12499 fn as_f32(&self) -> f32 {
12500 self.0 as f32
12501 }
12502
12503 fn next_row(&self) -> Self {
12504 Self(self.0 + 1)
12505 }
12506
12507 fn previous_row(&self) -> Self {
12508 Self(self.0.saturating_sub(1))
12509 }
12510
12511 fn minus(&self, other: Self) -> u32 {
12512 self.0 - other.0
12513 }
12514}
12515
12516impl RowExt for MultiBufferRow {
12517 fn as_f32(&self) -> f32 {
12518 self.0 as f32
12519 }
12520
12521 fn next_row(&self) -> Self {
12522 Self(self.0 + 1)
12523 }
12524
12525 fn previous_row(&self) -> Self {
12526 Self(self.0.saturating_sub(1))
12527 }
12528
12529 fn minus(&self, other: Self) -> u32 {
12530 self.0 - other.0
12531 }
12532}
12533
12534trait RowRangeExt {
12535 type Row;
12536
12537 fn len(&self) -> usize;
12538
12539 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12540}
12541
12542impl RowRangeExt for Range<MultiBufferRow> {
12543 type Row = MultiBufferRow;
12544
12545 fn len(&self) -> usize {
12546 (self.end.0 - self.start.0) as usize
12547 }
12548
12549 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12550 (self.start.0..self.end.0).map(MultiBufferRow)
12551 }
12552}
12553
12554impl RowRangeExt for Range<DisplayRow> {
12555 type Row = DisplayRow;
12556
12557 fn len(&self) -> usize {
12558 (self.end.0 - self.start.0) as usize
12559 }
12560
12561 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12562 (self.start.0..self.end.0).map(DisplayRow)
12563 }
12564}
12565
12566fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12567 if hunk.diff_base_byte_range.is_empty() {
12568 DiffHunkStatus::Added
12569 } else if hunk.associated_range.is_empty() {
12570 DiffHunkStatus::Removed
12571 } else {
12572 DiffHunkStatus::Modified
12573 }
12574}