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;
42mod signature_help;
43#[cfg(any(test, feature = "test-support"))]
44pub mod test;
45
46use ::git::diff::{DiffHunk, DiffHunkStatus};
47use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
48pub(crate) use actions::*;
49use aho_corasick::AhoCorasick;
50use anyhow::{anyhow, Context as _, Result};
51use blink_manager::BlinkManager;
52use client::{Collaborator, ParticipantIndex};
53use clock::ReplicaId;
54use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
55use convert_case::{Case, Casing};
56use debounced_delay::DebouncedDelay;
57use display_map::*;
58pub use display_map::{DisplayPoint, FoldPlaceholder};
59pub use editor_settings::{CurrentLineHighlight, EditorSettings};
60use element::LineWithInvisibles;
61pub use element::{
62 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
63};
64use futures::FutureExt;
65use fuzzy::{StringMatch, StringMatchCandidate};
66use git::blame::GitBlame;
67use git::diff_hunk_to_display;
68use gpui::{
69 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
70 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
71 Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
72 FocusableView, FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText,
73 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
74 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
75 UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
76 WeakFocusHandle, WeakView, WhiteSpace, WindowContext,
77};
78use highlight_matching_bracket::refresh_matching_bracket_highlights;
79use hover_popover::{hide_hover, HoverState};
80use hunk_diff::ExpandedHunks;
81pub(crate) use hunk_diff::HunkToExpand;
82use indent_guides::ActiveIndentGuidesState;
83use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
84pub use inline_completion_provider::*;
85pub use items::MAX_TAB_TITLE_LEN;
86use itertools::Itertools;
87use language::{
88 char_kind,
89 language_settings::{self, all_language_settings, InlayHintSettings},
90 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
91 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
92 Point, Selection, SelectionGoal, TransactionId,
93};
94use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
95use linked_editing_ranges::refresh_linked_ranges;
96use task::{ResolvedTask, TaskTemplate, TaskVariables};
97
98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
99pub use lsp::CompletionContext;
100use lsp::{
101 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
102 LanguageServerId,
103};
104use mouse_context_menu::MouseContextMenu;
105use movement::TextLayoutDetails;
106pub use multi_buffer::{
107 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
108 ToPoint,
109};
110use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
111use ordered_float::OrderedFloat;
112use parking_lot::{Mutex, RwLock};
113use project::project_settings::{GitGutterSetting, ProjectSettings};
114use project::{
115 CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
116 ProjectTransaction, TaskSourceKind, WorktreeId,
117};
118use rand::prelude::*;
119use rpc::{proto::*, ErrorExt};
120use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
121use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
122use serde::{Deserialize, Serialize};
123use settings::{update_settings_file, Settings, SettingsStore};
124use smallvec::SmallVec;
125use snippet::Snippet;
126use std::{
127 any::TypeId,
128 borrow::Cow,
129 cell::RefCell,
130 cmp::{self, Ordering, Reverse},
131 mem,
132 num::NonZeroU32,
133 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
134 path::Path,
135 rc::Rc,
136 sync::Arc,
137 time::{Duration, Instant},
138};
139pub use sum_tree::Bias;
140use sum_tree::TreeMap;
141use text::{BufferId, OffsetUtf16, Rope};
142use theme::{
143 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
144 ThemeColors, ThemeSettings,
145};
146use ui::{
147 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
148 ListItem, Popover, Tooltip,
149};
150use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
151use workspace::item::{ItemHandle, PreviewTabsSettings};
152use workspace::notifications::{DetachAndPromptErr, NotificationId};
153use workspace::{
154 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
155};
156use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
157
158use crate::hover_links::find_url;
159use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
160
161pub const FILE_HEADER_HEIGHT: u8 = 1;
162pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
163pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
164pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
165const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
166const MAX_LINE_LEN: usize = 1024;
167const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
168const MAX_SELECTION_HISTORY_LEN: usize = 1024;
169pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
170#[doc(hidden)]
171pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
172#[doc(hidden)]
173pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
174
175pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
176
177pub fn render_parsed_markdown(
178 element_id: impl Into<ElementId>,
179 parsed: &language::ParsedMarkdown,
180 editor_style: &EditorStyle,
181 workspace: Option<WeakView<Workspace>>,
182 cx: &mut WindowContext,
183) -> InteractiveText {
184 let code_span_background_color = cx
185 .theme()
186 .colors()
187 .editor_document_highlight_read_background;
188
189 let highlights = gpui::combine_highlights(
190 parsed.highlights.iter().filter_map(|(range, highlight)| {
191 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
192 Some((range.clone(), highlight))
193 }),
194 parsed
195 .regions
196 .iter()
197 .zip(&parsed.region_ranges)
198 .filter_map(|(region, range)| {
199 if region.code {
200 Some((
201 range.clone(),
202 HighlightStyle {
203 background_color: Some(code_span_background_color),
204 ..Default::default()
205 },
206 ))
207 } else {
208 None
209 }
210 }),
211 );
212
213 let mut links = Vec::new();
214 let mut link_ranges = Vec::new();
215 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
216 if let Some(link) = region.link.clone() {
217 links.push(link);
218 link_ranges.push(range.clone());
219 }
220 }
221
222 InteractiveText::new(
223 element_id,
224 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
225 )
226 .on_click(link_ranges, move |clicked_range_ix, cx| {
227 match &links[clicked_range_ix] {
228 markdown::Link::Web { url } => cx.open_url(url),
229 markdown::Link::Path { path } => {
230 if let Some(workspace) = &workspace {
231 _ = workspace.update(cx, |workspace, cx| {
232 workspace.open_abs_path(path.clone(), false, cx).detach();
233 });
234 }
235 }
236 }
237 })
238}
239
240#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
241pub(crate) enum InlayId {
242 Suggestion(usize),
243 Hint(usize),
244}
245
246impl InlayId {
247 fn id(&self) -> usize {
248 match self {
249 Self::Suggestion(id) => *id,
250 Self::Hint(id) => *id,
251 }
252 }
253}
254
255enum DiffRowHighlight {}
256enum DocumentHighlightRead {}
257enum DocumentHighlightWrite {}
258enum InputComposition {}
259
260#[derive(Copy, Clone, PartialEq, Eq)]
261pub enum Direction {
262 Prev,
263 Next,
264}
265
266pub fn init_settings(cx: &mut AppContext) {
267 EditorSettings::register(cx);
268}
269
270pub fn init(cx: &mut AppContext) {
271 init_settings(cx);
272
273 workspace::register_project_item::<Editor>(cx);
274 workspace::FollowableViewRegistry::register::<Editor>(cx);
275 workspace::register_deserializable_item::<Editor>(cx);
276 cx.observe_new_views(
277 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
278 workspace.register_action(Editor::new_file);
279 workspace.register_action(Editor::new_file_in_direction);
280 },
281 )
282 .detach();
283
284 cx.on_action(move |_: &workspace::NewFile, cx| {
285 let app_state = workspace::AppState::global(cx);
286 if let Some(app_state) = app_state.upgrade() {
287 workspace::open_new(app_state, cx, |workspace, cx| {
288 Editor::new_file(workspace, &Default::default(), cx)
289 })
290 .detach();
291 }
292 });
293 cx.on_action(move |_: &workspace::NewWindow, cx| {
294 let app_state = workspace::AppState::global(cx);
295 if let Some(app_state) = app_state.upgrade() {
296 workspace::open_new(app_state, cx, |workspace, cx| {
297 Editor::new_file(workspace, &Default::default(), cx)
298 })
299 .detach();
300 }
301 });
302}
303
304pub struct SearchWithinRange;
305
306trait InvalidationRegion {
307 fn ranges(&self) -> &[Range<Anchor>];
308}
309
310#[derive(Clone, Debug, PartialEq)]
311pub enum SelectPhase {
312 Begin {
313 position: DisplayPoint,
314 add: bool,
315 click_count: usize,
316 },
317 BeginColumnar {
318 position: DisplayPoint,
319 reset: bool,
320 goal_column: u32,
321 },
322 Extend {
323 position: DisplayPoint,
324 click_count: usize,
325 },
326 Update {
327 position: DisplayPoint,
328 goal_column: u32,
329 scroll_delta: gpui::Point<f32>,
330 },
331 End,
332}
333
334#[derive(Clone, Debug)]
335pub enum SelectMode {
336 Character,
337 Word(Range<Anchor>),
338 Line(Range<Anchor>),
339 All,
340}
341
342#[derive(Copy, Clone, PartialEq, Eq, Debug)]
343pub enum EditorMode {
344 SingleLine { auto_width: bool },
345 AutoHeight { max_lines: usize },
346 Full,
347}
348
349#[derive(Clone, Debug)]
350pub enum SoftWrap {
351 None,
352 PreferLine,
353 EditorWidth,
354 Column(u32),
355}
356
357#[derive(Clone)]
358pub struct EditorStyle {
359 pub background: Hsla,
360 pub local_player: PlayerColor,
361 pub text: TextStyle,
362 pub scrollbar_width: Pixels,
363 pub syntax: Arc<SyntaxTheme>,
364 pub status: StatusColors,
365 pub inlay_hints_style: HighlightStyle,
366 pub suggestions_style: HighlightStyle,
367}
368
369impl Default for EditorStyle {
370 fn default() -> Self {
371 Self {
372 background: Hsla::default(),
373 local_player: PlayerColor::default(),
374 text: TextStyle::default(),
375 scrollbar_width: Pixels::default(),
376 syntax: Default::default(),
377 // HACK: Status colors don't have a real default.
378 // We should look into removing the status colors from the editor
379 // style and retrieve them directly from the theme.
380 status: StatusColors::dark(),
381 inlay_hints_style: HighlightStyle::default(),
382 suggestions_style: HighlightStyle::default(),
383 }
384 }
385}
386
387type CompletionId = usize;
388
389#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
390struct EditorActionId(usize);
391
392impl EditorActionId {
393 pub fn post_inc(&mut self) -> Self {
394 let answer = self.0;
395
396 *self = Self(answer + 1);
397
398 Self(answer)
399 }
400}
401
402// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
403// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
404
405type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
406type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
407
408struct ScrollbarMarkerState {
409 scrollbar_size: Size<Pixels>,
410 dirty: bool,
411 markers: Arc<[PaintQuad]>,
412 pending_refresh: Option<Task<Result<()>>>,
413}
414
415impl ScrollbarMarkerState {
416 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
417 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
418 }
419}
420
421impl Default for ScrollbarMarkerState {
422 fn default() -> Self {
423 Self {
424 scrollbar_size: Size::default(),
425 dirty: false,
426 markers: Arc::from([]),
427 pending_refresh: None,
428 }
429 }
430}
431
432#[derive(Clone, Debug)]
433struct RunnableTasks {
434 templates: Vec<(TaskSourceKind, TaskTemplate)>,
435 offset: MultiBufferOffset,
436 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
437 column: u32,
438 // Values of all named captures, including those starting with '_'
439 extra_variables: HashMap<String, String>,
440 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
441 context_range: Range<BufferOffset>,
442}
443
444#[derive(Clone)]
445struct ResolvedTasks {
446 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
447 position: Anchor,
448}
449#[derive(Copy, Clone, Debug)]
450struct MultiBufferOffset(usize);
451#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
452struct BufferOffset(usize);
453/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
454///
455/// See the [module level documentation](self) for more information.
456pub struct Editor {
457 focus_handle: FocusHandle,
458 last_focused_descendant: Option<WeakFocusHandle>,
459 /// The text buffer being edited
460 buffer: Model<MultiBuffer>,
461 /// Map of how text in the buffer should be displayed.
462 /// Handles soft wraps, folds, fake inlay text insertions, etc.
463 pub display_map: Model<DisplayMap>,
464 pub selections: SelectionsCollection,
465 pub scroll_manager: ScrollManager,
466 /// When inline assist editors are linked, they all render cursors because
467 /// typing enters text into each of them, even the ones that aren't focused.
468 pub(crate) show_cursor_when_unfocused: bool,
469 columnar_selection_tail: Option<Anchor>,
470 add_selections_state: Option<AddSelectionsState>,
471 select_next_state: Option<SelectNextState>,
472 select_prev_state: Option<SelectNextState>,
473 selection_history: SelectionHistory,
474 autoclose_regions: Vec<AutocloseRegion>,
475 snippet_stack: InvalidationStack<SnippetState>,
476 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
477 ime_transaction: Option<TransactionId>,
478 active_diagnostics: Option<ActiveDiagnosticGroup>,
479 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
480 project: Option<Model<Project>>,
481 completion_provider: Option<Box<dyn CompletionProvider>>,
482 collaboration_hub: Option<Box<dyn CollaborationHub>>,
483 blink_manager: Model<BlinkManager>,
484 show_cursor_names: bool,
485 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
486 pub show_local_selections: bool,
487 mode: EditorMode,
488 show_breadcrumbs: bool,
489 show_gutter: bool,
490 show_line_numbers: Option<bool>,
491 show_git_diff_gutter: Option<bool>,
492 show_code_actions: Option<bool>,
493 show_runnables: Option<bool>,
494 show_wrap_guides: Option<bool>,
495 show_indent_guides: Option<bool>,
496 placeholder_text: Option<Arc<str>>,
497 highlight_order: usize,
498 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
499 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
500 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
501 scrollbar_marker_state: ScrollbarMarkerState,
502 active_indent_guides_state: ActiveIndentGuidesState,
503 nav_history: Option<ItemNavHistory>,
504 context_menu: RwLock<Option<ContextMenu>>,
505 mouse_context_menu: Option<MouseContextMenu>,
506 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
507 signature_help_state: SignatureHelpState,
508 auto_signature_help: Option<bool>,
509 find_all_references_task_sources: Vec<Anchor>,
510 next_completion_id: CompletionId,
511 completion_documentation_pre_resolve_debounce: DebouncedDelay,
512 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
513 code_actions_task: Option<Task<()>>,
514 document_highlights_task: Option<Task<()>>,
515 linked_editing_range_task: Option<Task<Option<()>>>,
516 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
517 pending_rename: Option<RenameState>,
518 searchable: bool,
519 cursor_shape: CursorShape,
520 current_line_highlight: Option<CurrentLineHighlight>,
521 collapse_matches: bool,
522 autoindent_mode: Option<AutoindentMode>,
523 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
524 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
525 input_enabled: bool,
526 use_modal_editing: bool,
527 read_only: bool,
528 leader_peer_id: Option<PeerId>,
529 remote_id: Option<ViewId>,
530 hover_state: HoverState,
531 gutter_hovered: bool,
532 hovered_link_state: Option<HoveredLinkState>,
533 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
534 active_inline_completion: Option<Inlay>,
535 show_inline_completions: bool,
536 inlay_hint_cache: InlayHintCache,
537 expanded_hunks: ExpandedHunks,
538 next_inlay_id: usize,
539 _subscriptions: Vec<Subscription>,
540 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
541 gutter_dimensions: GutterDimensions,
542 pub vim_replace_map: HashMap<Range<usize>, String>,
543 style: Option<EditorStyle>,
544 next_editor_action_id: EditorActionId,
545 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
546 use_autoclose: bool,
547 use_auto_surround: bool,
548 auto_replace_emoji_shortcode: bool,
549 show_git_blame_gutter: bool,
550 show_git_blame_inline: bool,
551 show_git_blame_inline_delay_task: Option<Task<()>>,
552 git_blame_inline_enabled: bool,
553 show_selection_menu: Option<bool>,
554 blame: Option<Model<GitBlame>>,
555 blame_subscription: Option<Subscription>,
556 custom_context_menu: Option<
557 Box<
558 dyn 'static
559 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
560 >,
561 >,
562 last_bounds: Option<Bounds<Pixels>>,
563 expect_bounds_change: Option<Bounds<Pixels>>,
564 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
565 tasks_update_task: Option<Task<()>>,
566 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
567 file_header_size: u8,
568 breadcrumb_header: Option<String>,
569}
570
571#[derive(Clone)]
572pub struct EditorSnapshot {
573 pub mode: EditorMode,
574 show_gutter: bool,
575 show_line_numbers: Option<bool>,
576 show_git_diff_gutter: Option<bool>,
577 show_code_actions: Option<bool>,
578 show_runnables: Option<bool>,
579 render_git_blame_gutter: bool,
580 pub display_snapshot: DisplaySnapshot,
581 pub placeholder_text: Option<Arc<str>>,
582 is_focused: bool,
583 scroll_anchor: ScrollAnchor,
584 ongoing_scroll: OngoingScroll,
585 current_line_highlight: CurrentLineHighlight,
586 gutter_hovered: bool,
587}
588
589const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
590
591#[derive(Debug, Clone, Copy)]
592pub struct GutterDimensions {
593 pub left_padding: Pixels,
594 pub right_padding: Pixels,
595 pub width: Pixels,
596 pub margin: Pixels,
597 pub git_blame_entries_width: Option<Pixels>,
598}
599
600impl GutterDimensions {
601 /// The full width of the space taken up by the gutter.
602 pub fn full_width(&self) -> Pixels {
603 self.margin + self.width
604 }
605
606 /// The width of the space reserved for the fold indicators,
607 /// use alongside 'justify_end' and `gutter_width` to
608 /// right align content with the line numbers
609 pub fn fold_area_width(&self) -> Pixels {
610 self.margin + self.right_padding
611 }
612}
613
614impl Default for GutterDimensions {
615 fn default() -> Self {
616 Self {
617 left_padding: Pixels::ZERO,
618 right_padding: Pixels::ZERO,
619 width: Pixels::ZERO,
620 margin: Pixels::ZERO,
621 git_blame_entries_width: None,
622 }
623 }
624}
625
626#[derive(Debug)]
627pub struct RemoteSelection {
628 pub replica_id: ReplicaId,
629 pub selection: Selection<Anchor>,
630 pub cursor_shape: CursorShape,
631 pub peer_id: PeerId,
632 pub line_mode: bool,
633 pub participant_index: Option<ParticipantIndex>,
634 pub user_name: Option<SharedString>,
635}
636
637#[derive(Clone, Debug)]
638struct SelectionHistoryEntry {
639 selections: Arc<[Selection<Anchor>]>,
640 select_next_state: Option<SelectNextState>,
641 select_prev_state: Option<SelectNextState>,
642 add_selections_state: Option<AddSelectionsState>,
643}
644
645enum SelectionHistoryMode {
646 Normal,
647 Undoing,
648 Redoing,
649}
650
651#[derive(Clone, PartialEq, Eq, Hash)]
652struct HoveredCursor {
653 replica_id: u16,
654 selection_id: usize,
655}
656
657impl Default for SelectionHistoryMode {
658 fn default() -> Self {
659 Self::Normal
660 }
661}
662
663#[derive(Default)]
664struct SelectionHistory {
665 #[allow(clippy::type_complexity)]
666 selections_by_transaction:
667 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
668 mode: SelectionHistoryMode,
669 undo_stack: VecDeque<SelectionHistoryEntry>,
670 redo_stack: VecDeque<SelectionHistoryEntry>,
671}
672
673impl SelectionHistory {
674 fn insert_transaction(
675 &mut self,
676 transaction_id: TransactionId,
677 selections: Arc<[Selection<Anchor>]>,
678 ) {
679 self.selections_by_transaction
680 .insert(transaction_id, (selections, None));
681 }
682
683 #[allow(clippy::type_complexity)]
684 fn transaction(
685 &self,
686 transaction_id: TransactionId,
687 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
688 self.selections_by_transaction.get(&transaction_id)
689 }
690
691 #[allow(clippy::type_complexity)]
692 fn transaction_mut(
693 &mut self,
694 transaction_id: TransactionId,
695 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
696 self.selections_by_transaction.get_mut(&transaction_id)
697 }
698
699 fn push(&mut self, entry: SelectionHistoryEntry) {
700 if !entry.selections.is_empty() {
701 match self.mode {
702 SelectionHistoryMode::Normal => {
703 self.push_undo(entry);
704 self.redo_stack.clear();
705 }
706 SelectionHistoryMode::Undoing => self.push_redo(entry),
707 SelectionHistoryMode::Redoing => self.push_undo(entry),
708 }
709 }
710 }
711
712 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
713 if self
714 .undo_stack
715 .back()
716 .map_or(true, |e| e.selections != entry.selections)
717 {
718 self.undo_stack.push_back(entry);
719 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
720 self.undo_stack.pop_front();
721 }
722 }
723 }
724
725 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
726 if self
727 .redo_stack
728 .back()
729 .map_or(true, |e| e.selections != entry.selections)
730 {
731 self.redo_stack.push_back(entry);
732 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
733 self.redo_stack.pop_front();
734 }
735 }
736 }
737}
738
739struct RowHighlight {
740 index: usize,
741 range: RangeInclusive<Anchor>,
742 color: Option<Hsla>,
743 should_autoscroll: bool,
744}
745
746#[derive(Clone, Debug)]
747struct AddSelectionsState {
748 above: bool,
749 stack: Vec<usize>,
750}
751
752#[derive(Clone)]
753struct SelectNextState {
754 query: AhoCorasick,
755 wordwise: bool,
756 done: bool,
757}
758
759impl std::fmt::Debug for SelectNextState {
760 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
761 f.debug_struct(std::any::type_name::<Self>())
762 .field("wordwise", &self.wordwise)
763 .field("done", &self.done)
764 .finish()
765 }
766}
767
768#[derive(Debug)]
769struct AutocloseRegion {
770 selection_id: usize,
771 range: Range<Anchor>,
772 pair: BracketPair,
773}
774
775#[derive(Debug)]
776struct SnippetState {
777 ranges: Vec<Vec<Range<Anchor>>>,
778 active_index: usize,
779}
780
781#[doc(hidden)]
782pub struct RenameState {
783 pub range: Range<Anchor>,
784 pub old_name: Arc<str>,
785 pub editor: View<Editor>,
786 block_id: BlockId,
787}
788
789struct InvalidationStack<T>(Vec<T>);
790
791struct RegisteredInlineCompletionProvider {
792 provider: Arc<dyn InlineCompletionProviderHandle>,
793 _subscription: Subscription,
794}
795
796enum ContextMenu {
797 Completions(CompletionsMenu),
798 CodeActions(CodeActionsMenu),
799}
800
801impl ContextMenu {
802 fn select_first(
803 &mut self,
804 project: Option<&Model<Project>>,
805 cx: &mut ViewContext<Editor>,
806 ) -> bool {
807 if self.visible() {
808 match self {
809 ContextMenu::Completions(menu) => menu.select_first(project, cx),
810 ContextMenu::CodeActions(menu) => menu.select_first(cx),
811 }
812 true
813 } else {
814 false
815 }
816 }
817
818 fn select_prev(
819 &mut self,
820 project: Option<&Model<Project>>,
821 cx: &mut ViewContext<Editor>,
822 ) -> bool {
823 if self.visible() {
824 match self {
825 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
826 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
827 }
828 true
829 } else {
830 false
831 }
832 }
833
834 fn select_next(
835 &mut self,
836 project: Option<&Model<Project>>,
837 cx: &mut ViewContext<Editor>,
838 ) -> bool {
839 if self.visible() {
840 match self {
841 ContextMenu::Completions(menu) => menu.select_next(project, cx),
842 ContextMenu::CodeActions(menu) => menu.select_next(cx),
843 }
844 true
845 } else {
846 false
847 }
848 }
849
850 fn select_last(
851 &mut self,
852 project: Option<&Model<Project>>,
853 cx: &mut ViewContext<Editor>,
854 ) -> bool {
855 if self.visible() {
856 match self {
857 ContextMenu::Completions(menu) => menu.select_last(project, cx),
858 ContextMenu::CodeActions(menu) => menu.select_last(cx),
859 }
860 true
861 } else {
862 false
863 }
864 }
865
866 fn visible(&self) -> bool {
867 match self {
868 ContextMenu::Completions(menu) => menu.visible(),
869 ContextMenu::CodeActions(menu) => menu.visible(),
870 }
871 }
872
873 fn render(
874 &self,
875 cursor_position: DisplayPoint,
876 style: &EditorStyle,
877 max_height: Pixels,
878 workspace: Option<WeakView<Workspace>>,
879 cx: &mut ViewContext<Editor>,
880 ) -> (ContextMenuOrigin, AnyElement) {
881 match self {
882 ContextMenu::Completions(menu) => (
883 ContextMenuOrigin::EditorPoint(cursor_position),
884 menu.render(style, max_height, workspace, cx),
885 ),
886 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
887 }
888 }
889}
890
891enum ContextMenuOrigin {
892 EditorPoint(DisplayPoint),
893 GutterIndicator(DisplayRow),
894}
895
896#[derive(Clone)]
897struct CompletionsMenu {
898 id: CompletionId,
899 initial_position: Anchor,
900 buffer: Model<Buffer>,
901 completions: Arc<RwLock<Box<[Completion]>>>,
902 match_candidates: Arc<[StringMatchCandidate]>,
903 matches: Arc<[StringMatch]>,
904 selected_item: usize,
905 scroll_handle: UniformListScrollHandle,
906 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
907}
908
909impl CompletionsMenu {
910 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
911 self.selected_item = 0;
912 self.scroll_handle.scroll_to_item(self.selected_item);
913 self.attempt_resolve_selected_completion_documentation(project, cx);
914 cx.notify();
915 }
916
917 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
918 if self.selected_item > 0 {
919 self.selected_item -= 1;
920 } else {
921 self.selected_item = self.matches.len() - 1;
922 }
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 select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
929 if self.selected_item + 1 < self.matches.len() {
930 self.selected_item += 1;
931 } else {
932 self.selected_item = 0;
933 }
934 self.scroll_handle.scroll_to_item(self.selected_item);
935 self.attempt_resolve_selected_completion_documentation(project, cx);
936 cx.notify();
937 }
938
939 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
940 self.selected_item = self.matches.len() - 1;
941 self.scroll_handle.scroll_to_item(self.selected_item);
942 self.attempt_resolve_selected_completion_documentation(project, cx);
943 cx.notify();
944 }
945
946 fn pre_resolve_completion_documentation(
947 buffer: Model<Buffer>,
948 completions: Arc<RwLock<Box<[Completion]>>>,
949 matches: Arc<[StringMatch]>,
950 editor: &Editor,
951 cx: &mut ViewContext<Editor>,
952 ) -> Task<()> {
953 let settings = EditorSettings::get_global(cx);
954 if !settings.show_completion_documentation {
955 return Task::ready(());
956 }
957
958 let Some(provider) = editor.completion_provider.as_ref() else {
959 return Task::ready(());
960 };
961
962 let resolve_task = provider.resolve_completions(
963 buffer,
964 matches.iter().map(|m| m.candidate_id).collect(),
965 completions.clone(),
966 cx,
967 );
968
969 return cx.spawn(move |this, mut cx| async move {
970 if let Some(true) = resolve_task.await.log_err() {
971 this.update(&mut cx, |_, cx| cx.notify()).ok();
972 }
973 });
974 }
975
976 fn attempt_resolve_selected_completion_documentation(
977 &mut self,
978 project: Option<&Model<Project>>,
979 cx: &mut ViewContext<Editor>,
980 ) {
981 let settings = EditorSettings::get_global(cx);
982 if !settings.show_completion_documentation {
983 return;
984 }
985
986 let completion_index = self.matches[self.selected_item].candidate_id;
987 let Some(project) = project else {
988 return;
989 };
990
991 let resolve_task = project.update(cx, |project, cx| {
992 project.resolve_completions(
993 self.buffer.clone(),
994 vec![completion_index],
995 self.completions.clone(),
996 cx,
997 )
998 });
999
1000 let delay_ms =
1001 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1002 let delay = Duration::from_millis(delay_ms);
1003
1004 self.selected_completion_documentation_resolve_debounce
1005 .lock()
1006 .fire_new(delay, cx, |_, cx| {
1007 cx.spawn(move |this, mut cx| async move {
1008 if let Some(true) = resolve_task.await.log_err() {
1009 this.update(&mut cx, |_, cx| cx.notify()).ok();
1010 }
1011 })
1012 });
1013 }
1014
1015 fn visible(&self) -> bool {
1016 !self.matches.is_empty()
1017 }
1018
1019 fn render(
1020 &self,
1021 style: &EditorStyle,
1022 max_height: Pixels,
1023 workspace: Option<WeakView<Workspace>>,
1024 cx: &mut ViewContext<Editor>,
1025 ) -> AnyElement {
1026 let settings = EditorSettings::get_global(cx);
1027 let show_completion_documentation = settings.show_completion_documentation;
1028
1029 let widest_completion_ix = self
1030 .matches
1031 .iter()
1032 .enumerate()
1033 .max_by_key(|(_, mat)| {
1034 let completions = self.completions.read();
1035 let completion = &completions[mat.candidate_id];
1036 let documentation = &completion.documentation;
1037
1038 let mut len = completion.label.text.chars().count();
1039 if let Some(Documentation::SingleLine(text)) = documentation {
1040 if show_completion_documentation {
1041 len += text.chars().count();
1042 }
1043 }
1044
1045 len
1046 })
1047 .map(|(ix, _)| ix);
1048
1049 let completions = self.completions.clone();
1050 let matches = self.matches.clone();
1051 let selected_item = self.selected_item;
1052 let style = style.clone();
1053
1054 let multiline_docs = if show_completion_documentation {
1055 let mat = &self.matches[selected_item];
1056 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1057 Some(Documentation::MultiLinePlainText(text)) => {
1058 Some(div().child(SharedString::from(text.clone())))
1059 }
1060 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1061 Some(div().child(render_parsed_markdown(
1062 "completions_markdown",
1063 parsed,
1064 &style,
1065 workspace,
1066 cx,
1067 )))
1068 }
1069 _ => None,
1070 };
1071 multiline_docs.map(|div| {
1072 div.id("multiline_docs")
1073 .max_h(max_height)
1074 .flex_1()
1075 .px_1p5()
1076 .py_1()
1077 .min_w(px(260.))
1078 .max_w(px(640.))
1079 .w(px(500.))
1080 .overflow_y_scroll()
1081 .occlude()
1082 })
1083 } else {
1084 None
1085 };
1086
1087 let list = uniform_list(
1088 cx.view().clone(),
1089 "completions",
1090 matches.len(),
1091 move |_editor, range, cx| {
1092 let start_ix = range.start;
1093 let completions_guard = completions.read();
1094
1095 matches[range]
1096 .iter()
1097 .enumerate()
1098 .map(|(ix, mat)| {
1099 let item_ix = start_ix + ix;
1100 let candidate_id = mat.candidate_id;
1101 let completion = &completions_guard[candidate_id];
1102
1103 let documentation = if show_completion_documentation {
1104 &completion.documentation
1105 } else {
1106 &None
1107 };
1108
1109 let highlights = gpui::combine_highlights(
1110 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1111 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1112 |(range, mut highlight)| {
1113 // Ignore font weight for syntax highlighting, as we'll use it
1114 // for fuzzy matches.
1115 highlight.font_weight = None;
1116
1117 if completion.lsp_completion.deprecated.unwrap_or(false) {
1118 highlight.strikethrough = Some(StrikethroughStyle {
1119 thickness: 1.0.into(),
1120 ..Default::default()
1121 });
1122 highlight.color = Some(cx.theme().colors().text_muted);
1123 }
1124
1125 (range, highlight)
1126 },
1127 ),
1128 );
1129 let completion_label = StyledText::new(completion.label.text.clone())
1130 .with_highlights(&style.text, highlights);
1131 let documentation_label =
1132 if let Some(Documentation::SingleLine(text)) = documentation {
1133 if text.trim().is_empty() {
1134 None
1135 } else {
1136 Some(
1137 Label::new(text.clone())
1138 .ml_4()
1139 .size(LabelSize::Small)
1140 .color(Color::Muted),
1141 )
1142 }
1143 } else {
1144 None
1145 };
1146
1147 div().min_w(px(220.)).max_w(px(540.)).child(
1148 ListItem::new(mat.candidate_id)
1149 .inset(true)
1150 .selected(item_ix == selected_item)
1151 .on_click(cx.listener(move |editor, _event, cx| {
1152 cx.stop_propagation();
1153 if let Some(task) = editor.confirm_completion(
1154 &ConfirmCompletion {
1155 item_ix: Some(item_ix),
1156 },
1157 cx,
1158 ) {
1159 task.detach_and_log_err(cx)
1160 }
1161 }))
1162 .child(h_flex().overflow_hidden().child(completion_label))
1163 .end_slot::<Label>(documentation_label),
1164 )
1165 })
1166 .collect()
1167 },
1168 )
1169 .occlude()
1170 .max_h(max_height)
1171 .track_scroll(self.scroll_handle.clone())
1172 .with_width_from_item(widest_completion_ix)
1173 .with_sizing_behavior(ListSizingBehavior::Infer);
1174
1175 Popover::new()
1176 .child(list)
1177 .when_some(multiline_docs, |popover, multiline_docs| {
1178 popover.aside(multiline_docs)
1179 })
1180 .into_any_element()
1181 }
1182
1183 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1184 let mut matches = if let Some(query) = query {
1185 fuzzy::match_strings(
1186 &self.match_candidates,
1187 query,
1188 query.chars().any(|c| c.is_uppercase()),
1189 100,
1190 &Default::default(),
1191 executor,
1192 )
1193 .await
1194 } else {
1195 self.match_candidates
1196 .iter()
1197 .enumerate()
1198 .map(|(candidate_id, candidate)| StringMatch {
1199 candidate_id,
1200 score: Default::default(),
1201 positions: Default::default(),
1202 string: candidate.string.clone(),
1203 })
1204 .collect()
1205 };
1206
1207 // Remove all candidates where the query's start does not match the start of any word in the candidate
1208 if let Some(query) = query {
1209 if let Some(query_start) = query.chars().next() {
1210 matches.retain(|string_match| {
1211 split_words(&string_match.string).any(|word| {
1212 // Check that the first codepoint of the word as lowercase matches the first
1213 // codepoint of the query as lowercase
1214 word.chars()
1215 .flat_map(|codepoint| codepoint.to_lowercase())
1216 .zip(query_start.to_lowercase())
1217 .all(|(word_cp, query_cp)| word_cp == query_cp)
1218 })
1219 });
1220 }
1221 }
1222
1223 let completions = self.completions.read();
1224 matches.sort_unstable_by_key(|mat| {
1225 // We do want to strike a balance here between what the language server tells us
1226 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1227 // `Creat` and there is a local variable called `CreateComponent`).
1228 // So what we do is: we bucket all matches into two buckets
1229 // - Strong matches
1230 // - Weak matches
1231 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1232 // and the Weak matches are the rest.
1233 //
1234 // For the strong matches, we sort by the language-servers score first and for the weak
1235 // matches, we prefer our fuzzy finder first.
1236 //
1237 // The thinking behind that: it's useless to take the sort_text the language-server gives
1238 // us into account when it's obviously a bad match.
1239
1240 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1241 enum MatchScore<'a> {
1242 Strong {
1243 sort_text: Option<&'a str>,
1244 score: Reverse<OrderedFloat<f64>>,
1245 sort_key: (usize, &'a str),
1246 },
1247 Weak {
1248 score: Reverse<OrderedFloat<f64>>,
1249 sort_text: Option<&'a str>,
1250 sort_key: (usize, &'a str),
1251 },
1252 }
1253
1254 let completion = &completions[mat.candidate_id];
1255 let sort_key = completion.sort_key();
1256 let sort_text = completion.lsp_completion.sort_text.as_deref();
1257 let score = Reverse(OrderedFloat(mat.score));
1258
1259 if mat.score >= 0.2 {
1260 MatchScore::Strong {
1261 sort_text,
1262 score,
1263 sort_key,
1264 }
1265 } else {
1266 MatchScore::Weak {
1267 score,
1268 sort_text,
1269 sort_key,
1270 }
1271 }
1272 });
1273
1274 for mat in &mut matches {
1275 let completion = &completions[mat.candidate_id];
1276 mat.string.clone_from(&completion.label.text);
1277 for position in &mut mat.positions {
1278 *position += completion.label.filter_range.start;
1279 }
1280 }
1281 drop(completions);
1282
1283 self.matches = matches.into();
1284 self.selected_item = 0;
1285 }
1286}
1287
1288#[derive(Clone)]
1289struct CodeActionContents {
1290 tasks: Option<Arc<ResolvedTasks>>,
1291 actions: Option<Arc<[CodeAction]>>,
1292}
1293
1294impl CodeActionContents {
1295 fn len(&self) -> usize {
1296 match (&self.tasks, &self.actions) {
1297 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1298 (Some(tasks), None) => tasks.templates.len(),
1299 (None, Some(actions)) => actions.len(),
1300 (None, None) => 0,
1301 }
1302 }
1303
1304 fn is_empty(&self) -> bool {
1305 match (&self.tasks, &self.actions) {
1306 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1307 (Some(tasks), None) => tasks.templates.is_empty(),
1308 (None, Some(actions)) => actions.is_empty(),
1309 (None, None) => true,
1310 }
1311 }
1312
1313 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1314 self.tasks
1315 .iter()
1316 .flat_map(|tasks| {
1317 tasks
1318 .templates
1319 .iter()
1320 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1321 })
1322 .chain(self.actions.iter().flat_map(|actions| {
1323 actions
1324 .iter()
1325 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1326 }))
1327 }
1328 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1329 match (&self.tasks, &self.actions) {
1330 (Some(tasks), Some(actions)) => {
1331 if index < tasks.templates.len() {
1332 tasks
1333 .templates
1334 .get(index)
1335 .cloned()
1336 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1337 } else {
1338 actions
1339 .get(index - tasks.templates.len())
1340 .cloned()
1341 .map(CodeActionsItem::CodeAction)
1342 }
1343 }
1344 (Some(tasks), None) => tasks
1345 .templates
1346 .get(index)
1347 .cloned()
1348 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1349 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1350 (None, None) => None,
1351 }
1352 }
1353}
1354
1355#[allow(clippy::large_enum_variant)]
1356#[derive(Clone)]
1357enum CodeActionsItem {
1358 Task(TaskSourceKind, ResolvedTask),
1359 CodeAction(CodeAction),
1360}
1361
1362impl CodeActionsItem {
1363 fn as_task(&self) -> Option<&ResolvedTask> {
1364 let Self::Task(_, task) = self else {
1365 return None;
1366 };
1367 Some(task)
1368 }
1369 fn as_code_action(&self) -> Option<&CodeAction> {
1370 let Self::CodeAction(action) = self else {
1371 return None;
1372 };
1373 Some(action)
1374 }
1375 fn label(&self) -> String {
1376 match self {
1377 Self::CodeAction(action) => action.lsp_action.title.clone(),
1378 Self::Task(_, task) => task.resolved_label.clone(),
1379 }
1380 }
1381}
1382
1383struct CodeActionsMenu {
1384 actions: CodeActionContents,
1385 buffer: Model<Buffer>,
1386 selected_item: usize,
1387 scroll_handle: UniformListScrollHandle,
1388 deployed_from_indicator: Option<DisplayRow>,
1389}
1390
1391impl CodeActionsMenu {
1392 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1393 self.selected_item = 0;
1394 self.scroll_handle.scroll_to_item(self.selected_item);
1395 cx.notify()
1396 }
1397
1398 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1399 if self.selected_item > 0 {
1400 self.selected_item -= 1;
1401 } else {
1402 self.selected_item = self.actions.len() - 1;
1403 }
1404 self.scroll_handle.scroll_to_item(self.selected_item);
1405 cx.notify();
1406 }
1407
1408 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1409 if self.selected_item + 1 < self.actions.len() {
1410 self.selected_item += 1;
1411 } else {
1412 self.selected_item = 0;
1413 }
1414 self.scroll_handle.scroll_to_item(self.selected_item);
1415 cx.notify();
1416 }
1417
1418 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1419 self.selected_item = self.actions.len() - 1;
1420 self.scroll_handle.scroll_to_item(self.selected_item);
1421 cx.notify()
1422 }
1423
1424 fn visible(&self) -> bool {
1425 !self.actions.is_empty()
1426 }
1427
1428 fn render(
1429 &self,
1430 cursor_position: DisplayPoint,
1431 _style: &EditorStyle,
1432 max_height: Pixels,
1433 cx: &mut ViewContext<Editor>,
1434 ) -> (ContextMenuOrigin, AnyElement) {
1435 let actions = self.actions.clone();
1436 let selected_item = self.selected_item;
1437 let element = uniform_list(
1438 cx.view().clone(),
1439 "code_actions_menu",
1440 self.actions.len(),
1441 move |_this, range, cx| {
1442 actions
1443 .iter()
1444 .skip(range.start)
1445 .take(range.end - range.start)
1446 .enumerate()
1447 .map(|(ix, action)| {
1448 let item_ix = range.start + ix;
1449 let selected = selected_item == item_ix;
1450 let colors = cx.theme().colors();
1451 div()
1452 .px_2()
1453 .text_color(colors.text)
1454 .when(selected, |style| {
1455 style
1456 .bg(colors.element_active)
1457 .text_color(colors.text_accent)
1458 })
1459 .hover(|style| {
1460 style
1461 .bg(colors.element_hover)
1462 .text_color(colors.text_accent)
1463 })
1464 .whitespace_nowrap()
1465 .when_some(action.as_code_action(), |this, action| {
1466 this.on_mouse_down(
1467 MouseButton::Left,
1468 cx.listener(move |editor, _, cx| {
1469 cx.stop_propagation();
1470 if let Some(task) = editor.confirm_code_action(
1471 &ConfirmCodeAction {
1472 item_ix: Some(item_ix),
1473 },
1474 cx,
1475 ) {
1476 task.detach_and_log_err(cx)
1477 }
1478 }),
1479 )
1480 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1481 .child(SharedString::from(action.lsp_action.title.clone()))
1482 })
1483 .when_some(action.as_task(), |this, task| {
1484 this.on_mouse_down(
1485 MouseButton::Left,
1486 cx.listener(move |editor, _, cx| {
1487 cx.stop_propagation();
1488 if let Some(task) = editor.confirm_code_action(
1489 &ConfirmCodeAction {
1490 item_ix: Some(item_ix),
1491 },
1492 cx,
1493 ) {
1494 task.detach_and_log_err(cx)
1495 }
1496 }),
1497 )
1498 .child(SharedString::from(task.resolved_label.clone()))
1499 })
1500 })
1501 .collect()
1502 },
1503 )
1504 .elevation_1(cx)
1505 .px_2()
1506 .py_1()
1507 .max_h(max_height)
1508 .occlude()
1509 .track_scroll(self.scroll_handle.clone())
1510 .with_width_from_item(
1511 self.actions
1512 .iter()
1513 .enumerate()
1514 .max_by_key(|(_, action)| match action {
1515 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1516 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1517 })
1518 .map(|(ix, _)| ix),
1519 )
1520 .with_sizing_behavior(ListSizingBehavior::Infer)
1521 .into_any_element();
1522
1523 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1524 ContextMenuOrigin::GutterIndicator(row)
1525 } else {
1526 ContextMenuOrigin::EditorPoint(cursor_position)
1527 };
1528
1529 (cursor_position, element)
1530 }
1531}
1532
1533#[derive(Debug)]
1534struct ActiveDiagnosticGroup {
1535 primary_range: Range<Anchor>,
1536 primary_message: String,
1537 group_id: usize,
1538 blocks: HashMap<BlockId, Diagnostic>,
1539 is_valid: bool,
1540}
1541
1542#[derive(Serialize, Deserialize, Clone, Debug)]
1543pub struct ClipboardSelection {
1544 pub len: usize,
1545 pub is_entire_line: bool,
1546 pub first_line_indent: u32,
1547}
1548
1549#[derive(Debug)]
1550pub(crate) struct NavigationData {
1551 cursor_anchor: Anchor,
1552 cursor_position: Point,
1553 scroll_anchor: ScrollAnchor,
1554 scroll_top_row: u32,
1555}
1556
1557enum GotoDefinitionKind {
1558 Symbol,
1559 Type,
1560 Implementation,
1561}
1562
1563#[derive(Debug, Clone)]
1564enum InlayHintRefreshReason {
1565 Toggle(bool),
1566 SettingsChange(InlayHintSettings),
1567 NewLinesShown,
1568 BufferEdited(HashSet<Arc<Language>>),
1569 RefreshRequested,
1570 ExcerptsRemoved(Vec<ExcerptId>),
1571}
1572
1573impl InlayHintRefreshReason {
1574 fn description(&self) -> &'static str {
1575 match self {
1576 Self::Toggle(_) => "toggle",
1577 Self::SettingsChange(_) => "settings change",
1578 Self::NewLinesShown => "new lines shown",
1579 Self::BufferEdited(_) => "buffer edited",
1580 Self::RefreshRequested => "refresh requested",
1581 Self::ExcerptsRemoved(_) => "excerpts removed",
1582 }
1583 }
1584}
1585
1586impl Editor {
1587 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1588 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1589 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1590 Self::new(
1591 EditorMode::SingleLine { auto_width: false },
1592 buffer,
1593 None,
1594 false,
1595 cx,
1596 )
1597 }
1598
1599 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1600 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1601 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1602 Self::new(EditorMode::Full, buffer, None, false, cx)
1603 }
1604
1605 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1606 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1607 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1608 Self::new(
1609 EditorMode::SingleLine { auto_width: true },
1610 buffer,
1611 None,
1612 false,
1613 cx,
1614 )
1615 }
1616
1617 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1618 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1619 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1620 Self::new(
1621 EditorMode::AutoHeight { max_lines },
1622 buffer,
1623 None,
1624 false,
1625 cx,
1626 )
1627 }
1628
1629 pub fn for_buffer(
1630 buffer: Model<Buffer>,
1631 project: Option<Model<Project>>,
1632 cx: &mut ViewContext<Self>,
1633 ) -> Self {
1634 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1635 Self::new(EditorMode::Full, buffer, project, false, cx)
1636 }
1637
1638 pub fn for_multibuffer(
1639 buffer: Model<MultiBuffer>,
1640 project: Option<Model<Project>>,
1641 show_excerpt_controls: bool,
1642 cx: &mut ViewContext<Self>,
1643 ) -> Self {
1644 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1645 }
1646
1647 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1648 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1649 let mut clone = Self::new(
1650 self.mode,
1651 self.buffer.clone(),
1652 self.project.clone(),
1653 show_excerpt_controls,
1654 cx,
1655 );
1656 self.display_map.update(cx, |display_map, cx| {
1657 let snapshot = display_map.snapshot(cx);
1658 clone.display_map.update(cx, |display_map, cx| {
1659 display_map.set_state(&snapshot, cx);
1660 });
1661 });
1662 clone.selections.clone_state(&self.selections);
1663 clone.scroll_manager.clone_state(&self.scroll_manager);
1664 clone.searchable = self.searchable;
1665 clone
1666 }
1667
1668 pub fn new(
1669 mode: EditorMode,
1670 buffer: Model<MultiBuffer>,
1671 project: Option<Model<Project>>,
1672 show_excerpt_controls: bool,
1673 cx: &mut ViewContext<Self>,
1674 ) -> Self {
1675 let style = cx.text_style();
1676 let font_size = style.font_size.to_pixels(cx.rem_size());
1677 let editor = cx.view().downgrade();
1678 let fold_placeholder = FoldPlaceholder {
1679 constrain_width: true,
1680 render: Arc::new(move |fold_id, fold_range, cx| {
1681 let editor = editor.clone();
1682 div()
1683 .id(fold_id)
1684 .bg(cx.theme().colors().ghost_element_background)
1685 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1686 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1687 .rounded_sm()
1688 .size_full()
1689 .cursor_pointer()
1690 .child("⋯")
1691 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1692 .on_click(move |_, cx| {
1693 editor
1694 .update(cx, |editor, cx| {
1695 editor.unfold_ranges(
1696 [fold_range.start..fold_range.end],
1697 true,
1698 false,
1699 cx,
1700 );
1701 cx.stop_propagation();
1702 })
1703 .ok();
1704 })
1705 .into_any()
1706 }),
1707 merge_adjacent: true,
1708 };
1709 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1710 let display_map = cx.new_model(|cx| {
1711 DisplayMap::new(
1712 buffer.clone(),
1713 style.font(),
1714 font_size,
1715 None,
1716 show_excerpt_controls,
1717 file_header_size,
1718 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1719 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1720 fold_placeholder,
1721 cx,
1722 )
1723 });
1724
1725 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1726
1727 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1728
1729 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1730 .then(|| language_settings::SoftWrap::PreferLine);
1731
1732 let mut project_subscriptions = Vec::new();
1733 if mode == EditorMode::Full {
1734 if let Some(project) = project.as_ref() {
1735 if buffer.read(cx).is_singleton() {
1736 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1737 cx.emit(EditorEvent::TitleChanged);
1738 }));
1739 }
1740 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1741 if let project::Event::RefreshInlayHints = event {
1742 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1743 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1744 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1745 let focus_handle = editor.focus_handle(cx);
1746 if focus_handle.is_focused(cx) {
1747 let snapshot = buffer.read(cx).snapshot();
1748 for (range, snippet) in snippet_edits {
1749 let editor_range =
1750 language::range_from_lsp(*range).to_offset(&snapshot);
1751 editor
1752 .insert_snippet(&[editor_range], snippet.clone(), cx)
1753 .ok();
1754 }
1755 }
1756 }
1757 }
1758 }));
1759 let task_inventory = project.read(cx).task_inventory().clone();
1760 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1761 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1762 }));
1763 }
1764 }
1765
1766 let inlay_hint_settings = inlay_hint_settings(
1767 selections.newest_anchor().head(),
1768 &buffer.read(cx).snapshot(cx),
1769 cx,
1770 );
1771 let focus_handle = cx.focus_handle();
1772 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1773 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1774 .detach();
1775 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1776 .detach();
1777 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1778
1779 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1780 Some(false)
1781 } else {
1782 None
1783 };
1784
1785 let mut this = Self {
1786 focus_handle,
1787 show_cursor_when_unfocused: false,
1788 last_focused_descendant: None,
1789 buffer: buffer.clone(),
1790 display_map: display_map.clone(),
1791 selections,
1792 scroll_manager: ScrollManager::new(cx),
1793 columnar_selection_tail: None,
1794 add_selections_state: None,
1795 select_next_state: None,
1796 select_prev_state: None,
1797 selection_history: Default::default(),
1798 autoclose_regions: Default::default(),
1799 snippet_stack: Default::default(),
1800 select_larger_syntax_node_stack: Vec::new(),
1801 ime_transaction: Default::default(),
1802 active_diagnostics: None,
1803 soft_wrap_mode_override,
1804 completion_provider: project.clone().map(|project| Box::new(project) as _),
1805 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1806 project,
1807 blink_manager: blink_manager.clone(),
1808 show_local_selections: true,
1809 mode,
1810 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1811 show_gutter: mode == EditorMode::Full,
1812 show_line_numbers: None,
1813 show_git_diff_gutter: None,
1814 show_code_actions: None,
1815 show_runnables: None,
1816 show_wrap_guides: None,
1817 show_indent_guides,
1818 placeholder_text: None,
1819 highlight_order: 0,
1820 highlighted_rows: HashMap::default(),
1821 background_highlights: Default::default(),
1822 gutter_highlights: TreeMap::default(),
1823 scrollbar_marker_state: ScrollbarMarkerState::default(),
1824 active_indent_guides_state: ActiveIndentGuidesState::default(),
1825 nav_history: None,
1826 context_menu: RwLock::new(None),
1827 mouse_context_menu: None,
1828 completion_tasks: Default::default(),
1829 signature_help_state: SignatureHelpState::default(),
1830 auto_signature_help: None,
1831 find_all_references_task_sources: Vec::new(),
1832 next_completion_id: 0,
1833 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1834 next_inlay_id: 0,
1835 available_code_actions: Default::default(),
1836 code_actions_task: Default::default(),
1837 document_highlights_task: Default::default(),
1838 linked_editing_range_task: Default::default(),
1839 pending_rename: Default::default(),
1840 searchable: true,
1841 cursor_shape: Default::default(),
1842 current_line_highlight: None,
1843 autoindent_mode: Some(AutoindentMode::EachLine),
1844 collapse_matches: false,
1845 workspace: None,
1846 keymap_context_layers: Default::default(),
1847 input_enabled: true,
1848 use_modal_editing: mode == EditorMode::Full,
1849 read_only: false,
1850 use_autoclose: true,
1851 use_auto_surround: true,
1852 auto_replace_emoji_shortcode: false,
1853 leader_peer_id: None,
1854 remote_id: None,
1855 hover_state: Default::default(),
1856 hovered_link_state: Default::default(),
1857 inline_completion_provider: None,
1858 active_inline_completion: None,
1859 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1860 expanded_hunks: ExpandedHunks::default(),
1861 gutter_hovered: false,
1862 pixel_position_of_newest_cursor: None,
1863 last_bounds: None,
1864 expect_bounds_change: None,
1865 gutter_dimensions: GutterDimensions::default(),
1866 style: None,
1867 show_cursor_names: false,
1868 hovered_cursors: Default::default(),
1869 next_editor_action_id: EditorActionId::default(),
1870 editor_actions: Rc::default(),
1871 vim_replace_map: Default::default(),
1872 show_inline_completions: mode == EditorMode::Full,
1873 custom_context_menu: None,
1874 show_git_blame_gutter: false,
1875 show_git_blame_inline: false,
1876 show_selection_menu: None,
1877 show_git_blame_inline_delay_task: None,
1878 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1879 blame: None,
1880 blame_subscription: None,
1881 file_header_size,
1882 tasks: Default::default(),
1883 _subscriptions: vec![
1884 cx.observe(&buffer, Self::on_buffer_changed),
1885 cx.subscribe(&buffer, Self::on_buffer_event),
1886 cx.observe(&display_map, Self::on_display_map_changed),
1887 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1888 cx.observe_global::<SettingsStore>(Self::settings_changed),
1889 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1890 cx.observe_window_activation(|editor, cx| {
1891 let active = cx.is_window_active();
1892 editor.blink_manager.update(cx, |blink_manager, cx| {
1893 if active {
1894 blink_manager.enable(cx);
1895 } else {
1896 blink_manager.show_cursor(cx);
1897 blink_manager.disable(cx);
1898 }
1899 });
1900 }),
1901 ],
1902 tasks_update_task: None,
1903 linked_edit_ranges: Default::default(),
1904 previous_search_ranges: None,
1905 breadcrumb_header: None,
1906 };
1907 this.tasks_update_task = Some(this.refresh_runnables(cx));
1908 this._subscriptions.extend(project_subscriptions);
1909
1910 this.end_selection(cx);
1911 this.scroll_manager.show_scrollbar(cx);
1912
1913 if mode == EditorMode::Full {
1914 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1915 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1916
1917 if this.git_blame_inline_enabled {
1918 this.git_blame_inline_enabled = true;
1919 this.start_git_blame_inline(false, cx);
1920 }
1921 }
1922
1923 this.report_editor_event("open", None, cx);
1924 this
1925 }
1926
1927 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1928 self.mouse_context_menu
1929 .as_ref()
1930 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1931 }
1932
1933 fn key_context(&self, cx: &AppContext) -> KeyContext {
1934 let mut key_context = KeyContext::new_with_defaults();
1935 key_context.add("Editor");
1936 let mode = match self.mode {
1937 EditorMode::SingleLine { .. } => "single_line",
1938 EditorMode::AutoHeight { .. } => "auto_height",
1939 EditorMode::Full => "full",
1940 };
1941
1942 if EditorSettings::get_global(cx).jupyter.enabled {
1943 key_context.add("jupyter");
1944 }
1945
1946 key_context.set("mode", mode);
1947 if self.pending_rename.is_some() {
1948 key_context.add("renaming");
1949 }
1950 if self.context_menu_visible() {
1951 match self.context_menu.read().as_ref() {
1952 Some(ContextMenu::Completions(_)) => {
1953 key_context.add("menu");
1954 key_context.add("showing_completions")
1955 }
1956 Some(ContextMenu::CodeActions(_)) => {
1957 key_context.add("menu");
1958 key_context.add("showing_code_actions")
1959 }
1960 None => {}
1961 }
1962 }
1963
1964 for layer in self.keymap_context_layers.values() {
1965 key_context.extend(layer);
1966 }
1967
1968 if let Some(extension) = self
1969 .buffer
1970 .read(cx)
1971 .as_singleton()
1972 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1973 {
1974 key_context.set("extension", extension.to_string());
1975 }
1976
1977 if self.has_active_inline_completion(cx) {
1978 key_context.add("copilot_suggestion");
1979 key_context.add("inline_completion");
1980 }
1981
1982 key_context
1983 }
1984
1985 pub fn new_file(
1986 workspace: &mut Workspace,
1987 _: &workspace::NewFile,
1988 cx: &mut ViewContext<Workspace>,
1989 ) {
1990 let project = workspace.project().clone();
1991 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1992
1993 cx.spawn(|workspace, mut cx| async move {
1994 let buffer = create.await?;
1995 workspace.update(&mut cx, |workspace, cx| {
1996 workspace.add_item_to_active_pane(
1997 Box::new(
1998 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1999 ),
2000 None,
2001 cx,
2002 )
2003 })
2004 })
2005 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2006 ErrorCode::RemoteUpgradeRequired => Some(format!(
2007 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2008 e.error_tag("required").unwrap_or("the latest version")
2009 )),
2010 _ => None,
2011 });
2012 }
2013
2014 pub fn new_file_in_direction(
2015 workspace: &mut Workspace,
2016 action: &workspace::NewFileInDirection,
2017 cx: &mut ViewContext<Workspace>,
2018 ) {
2019 let project = workspace.project().clone();
2020 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2021 let direction = action.0;
2022
2023 cx.spawn(|workspace, mut cx| async move {
2024 let buffer = create.await?;
2025 workspace.update(&mut cx, move |workspace, cx| {
2026 workspace.split_item(
2027 direction,
2028 Box::new(
2029 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2030 ),
2031 cx,
2032 )
2033 })?;
2034 anyhow::Ok(())
2035 })
2036 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2037 ErrorCode::RemoteUpgradeRequired => Some(format!(
2038 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2039 e.error_tag("required").unwrap_or("the latest version")
2040 )),
2041 _ => None,
2042 });
2043 }
2044
2045 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2046 self.buffer.read(cx).replica_id()
2047 }
2048
2049 pub fn leader_peer_id(&self) -> Option<PeerId> {
2050 self.leader_peer_id
2051 }
2052
2053 pub fn buffer(&self) -> &Model<MultiBuffer> {
2054 &self.buffer
2055 }
2056
2057 pub fn workspace(&self) -> Option<View<Workspace>> {
2058 self.workspace.as_ref()?.0.upgrade()
2059 }
2060
2061 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2062 self.buffer().read(cx).title(cx)
2063 }
2064
2065 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2066 EditorSnapshot {
2067 mode: self.mode,
2068 show_gutter: self.show_gutter,
2069 show_line_numbers: self.show_line_numbers,
2070 show_git_diff_gutter: self.show_git_diff_gutter,
2071 show_code_actions: self.show_code_actions,
2072 show_runnables: self.show_runnables,
2073 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2074 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2075 scroll_anchor: self.scroll_manager.anchor(),
2076 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2077 placeholder_text: self.placeholder_text.clone(),
2078 is_focused: self.focus_handle.is_focused(cx),
2079 current_line_highlight: self
2080 .current_line_highlight
2081 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2082 gutter_hovered: self.gutter_hovered,
2083 }
2084 }
2085
2086 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2087 self.buffer.read(cx).language_at(point, cx)
2088 }
2089
2090 pub fn file_at<T: ToOffset>(
2091 &self,
2092 point: T,
2093 cx: &AppContext,
2094 ) -> Option<Arc<dyn language::File>> {
2095 self.buffer.read(cx).read(cx).file_at(point).cloned()
2096 }
2097
2098 pub fn active_excerpt(
2099 &self,
2100 cx: &AppContext,
2101 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2102 self.buffer
2103 .read(cx)
2104 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2105 }
2106
2107 pub fn mode(&self) -> EditorMode {
2108 self.mode
2109 }
2110
2111 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2112 self.collaboration_hub.as_deref()
2113 }
2114
2115 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2116 self.collaboration_hub = Some(hub);
2117 }
2118
2119 pub fn set_custom_context_menu(
2120 &mut self,
2121 f: impl 'static
2122 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2123 ) {
2124 self.custom_context_menu = Some(Box::new(f))
2125 }
2126
2127 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2128 self.completion_provider = Some(provider);
2129 }
2130
2131 pub fn set_inline_completion_provider<T>(
2132 &mut self,
2133 provider: Option<Model<T>>,
2134 cx: &mut ViewContext<Self>,
2135 ) where
2136 T: InlineCompletionProvider,
2137 {
2138 self.inline_completion_provider =
2139 provider.map(|provider| RegisteredInlineCompletionProvider {
2140 _subscription: cx.observe(&provider, |this, _, cx| {
2141 if this.focus_handle.is_focused(cx) {
2142 this.update_visible_inline_completion(cx);
2143 }
2144 }),
2145 provider: Arc::new(provider),
2146 });
2147 self.refresh_inline_completion(false, cx);
2148 }
2149
2150 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2151 self.placeholder_text.as_deref()
2152 }
2153
2154 pub fn set_placeholder_text(
2155 &mut self,
2156 placeholder_text: impl Into<Arc<str>>,
2157 cx: &mut ViewContext<Self>,
2158 ) {
2159 let placeholder_text = Some(placeholder_text.into());
2160 if self.placeholder_text != placeholder_text {
2161 self.placeholder_text = placeholder_text;
2162 cx.notify();
2163 }
2164 }
2165
2166 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2167 self.cursor_shape = cursor_shape;
2168
2169 // Disrupt blink for immediate user feedback that the cursor shape has changed
2170 self.blink_manager.update(cx, BlinkManager::show_cursor);
2171
2172 cx.notify();
2173 }
2174
2175 pub fn set_current_line_highlight(
2176 &mut self,
2177 current_line_highlight: Option<CurrentLineHighlight>,
2178 ) {
2179 self.current_line_highlight = current_line_highlight;
2180 }
2181
2182 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2183 self.collapse_matches = collapse_matches;
2184 }
2185
2186 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2187 if self.collapse_matches {
2188 return range.start..range.start;
2189 }
2190 range.clone()
2191 }
2192
2193 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2194 if self.display_map.read(cx).clip_at_line_ends != clip {
2195 self.display_map
2196 .update(cx, |map, _| map.clip_at_line_ends = clip);
2197 }
2198 }
2199
2200 pub fn set_keymap_context_layer<Tag: 'static>(
2201 &mut self,
2202 context: KeyContext,
2203 cx: &mut ViewContext<Self>,
2204 ) {
2205 self.keymap_context_layers
2206 .insert(TypeId::of::<Tag>(), context);
2207 cx.notify();
2208 }
2209
2210 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2211 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2212 cx.notify();
2213 }
2214
2215 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2216 self.input_enabled = input_enabled;
2217 }
2218
2219 pub fn set_autoindent(&mut self, autoindent: bool) {
2220 if autoindent {
2221 self.autoindent_mode = Some(AutoindentMode::EachLine);
2222 } else {
2223 self.autoindent_mode = None;
2224 }
2225 }
2226
2227 pub fn read_only(&self, cx: &AppContext) -> bool {
2228 self.read_only || self.buffer.read(cx).read_only()
2229 }
2230
2231 pub fn set_read_only(&mut self, read_only: bool) {
2232 self.read_only = read_only;
2233 }
2234
2235 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2236 self.use_autoclose = autoclose;
2237 }
2238
2239 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2240 self.use_auto_surround = auto_surround;
2241 }
2242
2243 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2244 self.auto_replace_emoji_shortcode = auto_replace;
2245 }
2246
2247 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2248 self.show_inline_completions = show_inline_completions;
2249 }
2250
2251 pub fn set_use_modal_editing(&mut self, to: bool) {
2252 self.use_modal_editing = to;
2253 }
2254
2255 pub fn use_modal_editing(&self) -> bool {
2256 self.use_modal_editing
2257 }
2258
2259 fn selections_did_change(
2260 &mut self,
2261 local: bool,
2262 old_cursor_position: &Anchor,
2263 show_completions: bool,
2264 cx: &mut ViewContext<Self>,
2265 ) {
2266 // Copy selections to primary selection buffer
2267 #[cfg(target_os = "linux")]
2268 if local {
2269 let selections = self.selections.all::<usize>(cx);
2270 let buffer_handle = self.buffer.read(cx).read(cx);
2271
2272 let mut text = String::new();
2273 for (index, selection) in selections.iter().enumerate() {
2274 let text_for_selection = buffer_handle
2275 .text_for_range(selection.start..selection.end)
2276 .collect::<String>();
2277
2278 text.push_str(&text_for_selection);
2279 if index != selections.len() - 1 {
2280 text.push('\n');
2281 }
2282 }
2283
2284 if !text.is_empty() {
2285 cx.write_to_primary(ClipboardItem::new(text));
2286 }
2287 }
2288
2289 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2290 self.buffer.update(cx, |buffer, cx| {
2291 buffer.set_active_selections(
2292 &self.selections.disjoint_anchors(),
2293 self.selections.line_mode,
2294 self.cursor_shape,
2295 cx,
2296 )
2297 });
2298 }
2299 let display_map = self
2300 .display_map
2301 .update(cx, |display_map, cx| display_map.snapshot(cx));
2302 let buffer = &display_map.buffer_snapshot;
2303 self.add_selections_state = None;
2304 self.select_next_state = None;
2305 self.select_prev_state = None;
2306 self.select_larger_syntax_node_stack.clear();
2307 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2308 self.snippet_stack
2309 .invalidate(&self.selections.disjoint_anchors(), buffer);
2310 self.take_rename(false, cx);
2311
2312 let new_cursor_position = self.selections.newest_anchor().head();
2313
2314 self.push_to_nav_history(
2315 *old_cursor_position,
2316 Some(new_cursor_position.to_point(buffer)),
2317 cx,
2318 );
2319
2320 if local {
2321 let new_cursor_position = self.selections.newest_anchor().head();
2322 let mut context_menu = self.context_menu.write();
2323 let completion_menu = match context_menu.as_ref() {
2324 Some(ContextMenu::Completions(menu)) => Some(menu),
2325
2326 _ => {
2327 *context_menu = None;
2328 None
2329 }
2330 };
2331
2332 if let Some(completion_menu) = completion_menu {
2333 let cursor_position = new_cursor_position.to_offset(buffer);
2334 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2335 if kind == Some(CharKind::Word)
2336 && word_range.to_inclusive().contains(&cursor_position)
2337 {
2338 let mut completion_menu = completion_menu.clone();
2339 drop(context_menu);
2340
2341 let query = Self::completion_query(buffer, cursor_position);
2342 cx.spawn(move |this, mut cx| async move {
2343 completion_menu
2344 .filter(query.as_deref(), cx.background_executor().clone())
2345 .await;
2346
2347 this.update(&mut cx, |this, cx| {
2348 let mut context_menu = this.context_menu.write();
2349 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2350 return;
2351 };
2352
2353 if menu.id > completion_menu.id {
2354 return;
2355 }
2356
2357 *context_menu = Some(ContextMenu::Completions(completion_menu));
2358 drop(context_menu);
2359 cx.notify();
2360 })
2361 })
2362 .detach();
2363
2364 if show_completions {
2365 self.show_completions(&ShowCompletions { trigger: None }, cx);
2366 }
2367 } else {
2368 drop(context_menu);
2369 self.hide_context_menu(cx);
2370 }
2371 } else {
2372 drop(context_menu);
2373 }
2374
2375 hide_hover(self, cx);
2376
2377 if old_cursor_position.to_display_point(&display_map).row()
2378 != new_cursor_position.to_display_point(&display_map).row()
2379 {
2380 self.available_code_actions.take();
2381 }
2382 self.refresh_code_actions(cx);
2383 self.refresh_document_highlights(cx);
2384 refresh_matching_bracket_highlights(self, cx);
2385 self.discard_inline_completion(false, cx);
2386 linked_editing_ranges::refresh_linked_ranges(self, cx);
2387 if self.git_blame_inline_enabled {
2388 self.start_inline_blame_timer(cx);
2389 }
2390 }
2391
2392 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2393 cx.emit(EditorEvent::SelectionsChanged { local });
2394
2395 if self.selections.disjoint_anchors().len() == 1 {
2396 cx.emit(SearchEvent::ActiveMatchChanged)
2397 }
2398 cx.notify();
2399 }
2400
2401 pub fn change_selections<R>(
2402 &mut self,
2403 autoscroll: Option<Autoscroll>,
2404 cx: &mut ViewContext<Self>,
2405 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2406 ) -> R {
2407 self.change_selections_inner(autoscroll, true, cx, change)
2408 }
2409
2410 pub fn change_selections_inner<R>(
2411 &mut self,
2412 autoscroll: Option<Autoscroll>,
2413 request_completions: bool,
2414 cx: &mut ViewContext<Self>,
2415 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2416 ) -> R {
2417 let old_cursor_position = self.selections.newest_anchor().head();
2418 self.push_to_selection_history();
2419
2420 let (changed, result) = self.selections.change_with(cx, change);
2421
2422 if changed {
2423 if let Some(autoscroll) = autoscroll {
2424 self.request_autoscroll(autoscroll, cx);
2425 }
2426 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2427
2428 if self.should_open_signature_help_automatically(
2429 &old_cursor_position,
2430 self.signature_help_state.backspace_pressed(),
2431 cx,
2432 ) {
2433 self.show_signature_help(&ShowSignatureHelp, cx);
2434 }
2435 self.signature_help_state.set_backspace_pressed(false);
2436 }
2437
2438 result
2439 }
2440
2441 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2442 where
2443 I: IntoIterator<Item = (Range<S>, T)>,
2444 S: ToOffset,
2445 T: Into<Arc<str>>,
2446 {
2447 if self.read_only(cx) {
2448 return;
2449 }
2450
2451 self.buffer
2452 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2453 }
2454
2455 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2456 where
2457 I: IntoIterator<Item = (Range<S>, T)>,
2458 S: ToOffset,
2459 T: Into<Arc<str>>,
2460 {
2461 if self.read_only(cx) {
2462 return;
2463 }
2464
2465 self.buffer.update(cx, |buffer, cx| {
2466 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2467 });
2468 }
2469
2470 pub fn edit_with_block_indent<I, S, T>(
2471 &mut self,
2472 edits: I,
2473 original_indent_columns: Vec<u32>,
2474 cx: &mut ViewContext<Self>,
2475 ) where
2476 I: IntoIterator<Item = (Range<S>, T)>,
2477 S: ToOffset,
2478 T: Into<Arc<str>>,
2479 {
2480 if self.read_only(cx) {
2481 return;
2482 }
2483
2484 self.buffer.update(cx, |buffer, cx| {
2485 buffer.edit(
2486 edits,
2487 Some(AutoindentMode::Block {
2488 original_indent_columns,
2489 }),
2490 cx,
2491 )
2492 });
2493 }
2494
2495 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2496 self.hide_context_menu(cx);
2497
2498 match phase {
2499 SelectPhase::Begin {
2500 position,
2501 add,
2502 click_count,
2503 } => self.begin_selection(position, add, click_count, cx),
2504 SelectPhase::BeginColumnar {
2505 position,
2506 goal_column,
2507 reset,
2508 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2509 SelectPhase::Extend {
2510 position,
2511 click_count,
2512 } => self.extend_selection(position, click_count, cx),
2513 SelectPhase::Update {
2514 position,
2515 goal_column,
2516 scroll_delta,
2517 } => self.update_selection(position, goal_column, scroll_delta, cx),
2518 SelectPhase::End => self.end_selection(cx),
2519 }
2520 }
2521
2522 fn extend_selection(
2523 &mut self,
2524 position: DisplayPoint,
2525 click_count: usize,
2526 cx: &mut ViewContext<Self>,
2527 ) {
2528 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2529 let tail = self.selections.newest::<usize>(cx).tail();
2530 self.begin_selection(position, false, click_count, cx);
2531
2532 let position = position.to_offset(&display_map, Bias::Left);
2533 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2534
2535 let mut pending_selection = self
2536 .selections
2537 .pending_anchor()
2538 .expect("extend_selection not called with pending selection");
2539 if position >= tail {
2540 pending_selection.start = tail_anchor;
2541 } else {
2542 pending_selection.end = tail_anchor;
2543 pending_selection.reversed = true;
2544 }
2545
2546 let mut pending_mode = self.selections.pending_mode().unwrap();
2547 match &mut pending_mode {
2548 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2549 _ => {}
2550 }
2551
2552 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2553 s.set_pending(pending_selection, pending_mode)
2554 });
2555 }
2556
2557 fn begin_selection(
2558 &mut self,
2559 position: DisplayPoint,
2560 add: bool,
2561 click_count: usize,
2562 cx: &mut ViewContext<Self>,
2563 ) {
2564 if !self.focus_handle.is_focused(cx) {
2565 self.last_focused_descendant = None;
2566 cx.focus(&self.focus_handle);
2567 }
2568
2569 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2570 let buffer = &display_map.buffer_snapshot;
2571 let newest_selection = self.selections.newest_anchor().clone();
2572 let position = display_map.clip_point(position, Bias::Left);
2573
2574 let start;
2575 let end;
2576 let mode;
2577 let auto_scroll;
2578 match click_count {
2579 1 => {
2580 start = buffer.anchor_before(position.to_point(&display_map));
2581 end = start;
2582 mode = SelectMode::Character;
2583 auto_scroll = true;
2584 }
2585 2 => {
2586 let range = movement::surrounding_word(&display_map, position);
2587 start = buffer.anchor_before(range.start.to_point(&display_map));
2588 end = buffer.anchor_before(range.end.to_point(&display_map));
2589 mode = SelectMode::Word(start..end);
2590 auto_scroll = true;
2591 }
2592 3 => {
2593 let position = display_map
2594 .clip_point(position, Bias::Left)
2595 .to_point(&display_map);
2596 let line_start = display_map.prev_line_boundary(position).0;
2597 let next_line_start = buffer.clip_point(
2598 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2599 Bias::Left,
2600 );
2601 start = buffer.anchor_before(line_start);
2602 end = buffer.anchor_before(next_line_start);
2603 mode = SelectMode::Line(start..end);
2604 auto_scroll = true;
2605 }
2606 _ => {
2607 start = buffer.anchor_before(0);
2608 end = buffer.anchor_before(buffer.len());
2609 mode = SelectMode::All;
2610 auto_scroll = false;
2611 }
2612 }
2613
2614 let point_to_delete: Option<usize> = {
2615 let selected_points: Vec<Selection<Point>> =
2616 self.selections.disjoint_in_range(start..end, cx);
2617
2618 if !add || click_count > 1 {
2619 None
2620 } else if selected_points.len() > 0 {
2621 Some(selected_points[0].id)
2622 } else {
2623 let clicked_point_already_selected =
2624 self.selections.disjoint.iter().find(|selection| {
2625 selection.start.to_point(buffer) == start.to_point(buffer)
2626 || selection.end.to_point(buffer) == end.to_point(buffer)
2627 });
2628
2629 if let Some(selection) = clicked_point_already_selected {
2630 Some(selection.id)
2631 } else {
2632 None
2633 }
2634 }
2635 };
2636
2637 let selections_count = self.selections.count();
2638
2639 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2640 if let Some(point_to_delete) = point_to_delete {
2641 s.delete(point_to_delete);
2642
2643 if selections_count == 1 {
2644 s.set_pending_anchor_range(start..end, mode);
2645 }
2646 } else {
2647 if !add {
2648 s.clear_disjoint();
2649 } else if click_count > 1 {
2650 s.delete(newest_selection.id)
2651 }
2652
2653 s.set_pending_anchor_range(start..end, mode);
2654 }
2655 });
2656 }
2657
2658 fn begin_columnar_selection(
2659 &mut self,
2660 position: DisplayPoint,
2661 goal_column: u32,
2662 reset: bool,
2663 cx: &mut ViewContext<Self>,
2664 ) {
2665 if !self.focus_handle.is_focused(cx) {
2666 self.last_focused_descendant = None;
2667 cx.focus(&self.focus_handle);
2668 }
2669
2670 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2671
2672 if reset {
2673 let pointer_position = display_map
2674 .buffer_snapshot
2675 .anchor_before(position.to_point(&display_map));
2676
2677 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2678 s.clear_disjoint();
2679 s.set_pending_anchor_range(
2680 pointer_position..pointer_position,
2681 SelectMode::Character,
2682 );
2683 });
2684 }
2685
2686 let tail = self.selections.newest::<Point>(cx).tail();
2687 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2688
2689 if !reset {
2690 self.select_columns(
2691 tail.to_display_point(&display_map),
2692 position,
2693 goal_column,
2694 &display_map,
2695 cx,
2696 );
2697 }
2698 }
2699
2700 fn update_selection(
2701 &mut self,
2702 position: DisplayPoint,
2703 goal_column: u32,
2704 scroll_delta: gpui::Point<f32>,
2705 cx: &mut ViewContext<Self>,
2706 ) {
2707 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2708
2709 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2710 let tail = tail.to_display_point(&display_map);
2711 self.select_columns(tail, position, goal_column, &display_map, cx);
2712 } else if let Some(mut pending) = self.selections.pending_anchor() {
2713 let buffer = self.buffer.read(cx).snapshot(cx);
2714 let head;
2715 let tail;
2716 let mode = self.selections.pending_mode().unwrap();
2717 match &mode {
2718 SelectMode::Character => {
2719 head = position.to_point(&display_map);
2720 tail = pending.tail().to_point(&buffer);
2721 }
2722 SelectMode::Word(original_range) => {
2723 let original_display_range = original_range.start.to_display_point(&display_map)
2724 ..original_range.end.to_display_point(&display_map);
2725 let original_buffer_range = original_display_range.start.to_point(&display_map)
2726 ..original_display_range.end.to_point(&display_map);
2727 if movement::is_inside_word(&display_map, position)
2728 || original_display_range.contains(&position)
2729 {
2730 let word_range = movement::surrounding_word(&display_map, position);
2731 if word_range.start < original_display_range.start {
2732 head = word_range.start.to_point(&display_map);
2733 } else {
2734 head = word_range.end.to_point(&display_map);
2735 }
2736 } else {
2737 head = position.to_point(&display_map);
2738 }
2739
2740 if head <= original_buffer_range.start {
2741 tail = original_buffer_range.end;
2742 } else {
2743 tail = original_buffer_range.start;
2744 }
2745 }
2746 SelectMode::Line(original_range) => {
2747 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2748
2749 let position = display_map
2750 .clip_point(position, Bias::Left)
2751 .to_point(&display_map);
2752 let line_start = display_map.prev_line_boundary(position).0;
2753 let next_line_start = buffer.clip_point(
2754 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2755 Bias::Left,
2756 );
2757
2758 if line_start < original_range.start {
2759 head = line_start
2760 } else {
2761 head = next_line_start
2762 }
2763
2764 if head <= original_range.start {
2765 tail = original_range.end;
2766 } else {
2767 tail = original_range.start;
2768 }
2769 }
2770 SelectMode::All => {
2771 return;
2772 }
2773 };
2774
2775 if head < tail {
2776 pending.start = buffer.anchor_before(head);
2777 pending.end = buffer.anchor_before(tail);
2778 pending.reversed = true;
2779 } else {
2780 pending.start = buffer.anchor_before(tail);
2781 pending.end = buffer.anchor_before(head);
2782 pending.reversed = false;
2783 }
2784
2785 self.change_selections(None, cx, |s| {
2786 s.set_pending(pending, mode);
2787 });
2788 } else {
2789 log::error!("update_selection dispatched with no pending selection");
2790 return;
2791 }
2792
2793 self.apply_scroll_delta(scroll_delta, cx);
2794 cx.notify();
2795 }
2796
2797 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2798 self.columnar_selection_tail.take();
2799 if self.selections.pending_anchor().is_some() {
2800 let selections = self.selections.all::<usize>(cx);
2801 self.change_selections(None, cx, |s| {
2802 s.select(selections);
2803 s.clear_pending();
2804 });
2805 }
2806 }
2807
2808 fn select_columns(
2809 &mut self,
2810 tail: DisplayPoint,
2811 head: DisplayPoint,
2812 goal_column: u32,
2813 display_map: &DisplaySnapshot,
2814 cx: &mut ViewContext<Self>,
2815 ) {
2816 let start_row = cmp::min(tail.row(), head.row());
2817 let end_row = cmp::max(tail.row(), head.row());
2818 let start_column = cmp::min(tail.column(), goal_column);
2819 let end_column = cmp::max(tail.column(), goal_column);
2820 let reversed = start_column < tail.column();
2821
2822 let selection_ranges = (start_row.0..=end_row.0)
2823 .map(DisplayRow)
2824 .filter_map(|row| {
2825 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2826 let start = display_map
2827 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2828 .to_point(display_map);
2829 let end = display_map
2830 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2831 .to_point(display_map);
2832 if reversed {
2833 Some(end..start)
2834 } else {
2835 Some(start..end)
2836 }
2837 } else {
2838 None
2839 }
2840 })
2841 .collect::<Vec<_>>();
2842
2843 self.change_selections(None, cx, |s| {
2844 s.select_ranges(selection_ranges);
2845 });
2846 cx.notify();
2847 }
2848
2849 pub fn has_pending_nonempty_selection(&self) -> bool {
2850 let pending_nonempty_selection = match self.selections.pending_anchor() {
2851 Some(Selection { start, end, .. }) => start != end,
2852 None => false,
2853 };
2854
2855 pending_nonempty_selection
2856 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2857 }
2858
2859 pub fn has_pending_selection(&self) -> bool {
2860 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2861 }
2862
2863 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2864 self.clear_expanded_diff_hunks(cx);
2865 if self.dismiss_menus_and_popups(true, cx) {
2866 return;
2867 }
2868
2869 if self.mode == EditorMode::Full {
2870 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2871 return;
2872 }
2873 }
2874
2875 cx.propagate();
2876 }
2877
2878 pub fn dismiss_menus_and_popups(
2879 &mut self,
2880 should_report_inline_completion_event: bool,
2881 cx: &mut ViewContext<Self>,
2882 ) -> bool {
2883 if self.take_rename(false, cx).is_some() {
2884 return true;
2885 }
2886
2887 if hide_hover(self, cx) {
2888 return true;
2889 }
2890
2891 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2892 return true;
2893 }
2894
2895 if self.hide_context_menu(cx).is_some() {
2896 return true;
2897 }
2898
2899 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2900 return true;
2901 }
2902
2903 if self.snippet_stack.pop().is_some() {
2904 return true;
2905 }
2906
2907 if self.mode == EditorMode::Full {
2908 if self.active_diagnostics.is_some() {
2909 self.dismiss_diagnostics(cx);
2910 return true;
2911 }
2912 }
2913
2914 false
2915 }
2916
2917 fn linked_editing_ranges_for(
2918 &self,
2919 selection: Range<text::Anchor>,
2920 cx: &AppContext,
2921 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2922 if self.linked_edit_ranges.is_empty() {
2923 return None;
2924 }
2925 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2926 selection.end.buffer_id.and_then(|end_buffer_id| {
2927 if selection.start.buffer_id != Some(end_buffer_id) {
2928 return None;
2929 }
2930 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2931 let snapshot = buffer.read(cx).snapshot();
2932 self.linked_edit_ranges
2933 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2934 .map(|ranges| (ranges, snapshot, buffer))
2935 })?;
2936 use text::ToOffset as TO;
2937 // find offset from the start of current range to current cursor position
2938 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2939
2940 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2941 let start_difference = start_offset - start_byte_offset;
2942 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2943 let end_difference = end_offset - start_byte_offset;
2944 // Current range has associated linked ranges.
2945 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2946 for range in linked_ranges.iter() {
2947 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2948 let end_offset = start_offset + end_difference;
2949 let start_offset = start_offset + start_difference;
2950 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2951 continue;
2952 }
2953 let start = buffer_snapshot.anchor_after(start_offset);
2954 let end = buffer_snapshot.anchor_after(end_offset);
2955 linked_edits
2956 .entry(buffer.clone())
2957 .or_default()
2958 .push(start..end);
2959 }
2960 Some(linked_edits)
2961 }
2962
2963 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2964 let text: Arc<str> = text.into();
2965
2966 if self.read_only(cx) {
2967 return;
2968 }
2969
2970 let selections = self.selections.all_adjusted(cx);
2971 let mut bracket_inserted = false;
2972 let mut edits = Vec::new();
2973 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2974 let mut new_selections = Vec::with_capacity(selections.len());
2975 let mut new_autoclose_regions = Vec::new();
2976 let snapshot = self.buffer.read(cx).read(cx);
2977
2978 for (selection, autoclose_region) in
2979 self.selections_with_autoclose_regions(selections, &snapshot)
2980 {
2981 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2982 // Determine if the inserted text matches the opening or closing
2983 // bracket of any of this language's bracket pairs.
2984 let mut bracket_pair = None;
2985 let mut is_bracket_pair_start = false;
2986 let mut is_bracket_pair_end = false;
2987 if !text.is_empty() {
2988 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2989 // and they are removing the character that triggered IME popup.
2990 for (pair, enabled) in scope.brackets() {
2991 if !pair.close && !pair.surround {
2992 continue;
2993 }
2994
2995 if enabled && pair.start.ends_with(text.as_ref()) {
2996 bracket_pair = Some(pair.clone());
2997 is_bracket_pair_start = true;
2998 break;
2999 }
3000 if pair.end.as_str() == text.as_ref() {
3001 bracket_pair = Some(pair.clone());
3002 is_bracket_pair_end = true;
3003 break;
3004 }
3005 }
3006 }
3007
3008 if let Some(bracket_pair) = bracket_pair {
3009 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3010 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3011 let auto_surround =
3012 self.use_auto_surround && snapshot_settings.use_auto_surround;
3013 if selection.is_empty() {
3014 if is_bracket_pair_start {
3015 let prefix_len = bracket_pair.start.len() - text.len();
3016
3017 // If the inserted text is a suffix of an opening bracket and the
3018 // selection is preceded by the rest of the opening bracket, then
3019 // insert the closing bracket.
3020 let following_text_allows_autoclose = snapshot
3021 .chars_at(selection.start)
3022 .next()
3023 .map_or(true, |c| scope.should_autoclose_before(c));
3024 let preceding_text_matches_prefix = prefix_len == 0
3025 || (selection.start.column >= (prefix_len as u32)
3026 && snapshot.contains_str_at(
3027 Point::new(
3028 selection.start.row,
3029 selection.start.column - (prefix_len as u32),
3030 ),
3031 &bracket_pair.start[..prefix_len],
3032 ));
3033
3034 if autoclose
3035 && bracket_pair.close
3036 && following_text_allows_autoclose
3037 && preceding_text_matches_prefix
3038 {
3039 let anchor = snapshot.anchor_before(selection.end);
3040 new_selections.push((selection.map(|_| anchor), text.len()));
3041 new_autoclose_regions.push((
3042 anchor,
3043 text.len(),
3044 selection.id,
3045 bracket_pair.clone(),
3046 ));
3047 edits.push((
3048 selection.range(),
3049 format!("{}{}", text, bracket_pair.end).into(),
3050 ));
3051 bracket_inserted = true;
3052 continue;
3053 }
3054 }
3055
3056 if let Some(region) = autoclose_region {
3057 // If the selection is followed by an auto-inserted closing bracket,
3058 // then don't insert that closing bracket again; just move the selection
3059 // past the closing bracket.
3060 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3061 && text.as_ref() == region.pair.end.as_str();
3062 if should_skip {
3063 let anchor = snapshot.anchor_after(selection.end);
3064 new_selections
3065 .push((selection.map(|_| anchor), region.pair.end.len()));
3066 continue;
3067 }
3068 }
3069
3070 let always_treat_brackets_as_autoclosed = snapshot
3071 .settings_at(selection.start, cx)
3072 .always_treat_brackets_as_autoclosed;
3073 if always_treat_brackets_as_autoclosed
3074 && is_bracket_pair_end
3075 && snapshot.contains_str_at(selection.end, text.as_ref())
3076 {
3077 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3078 // and the inserted text is a closing bracket and the selection is followed
3079 // by the closing bracket then move the selection past the closing bracket.
3080 let anchor = snapshot.anchor_after(selection.end);
3081 new_selections.push((selection.map(|_| anchor), text.len()));
3082 continue;
3083 }
3084 }
3085 // If an opening bracket is 1 character long and is typed while
3086 // text is selected, then surround that text with the bracket pair.
3087 else if auto_surround
3088 && bracket_pair.surround
3089 && is_bracket_pair_start
3090 && bracket_pair.start.chars().count() == 1
3091 {
3092 edits.push((selection.start..selection.start, text.clone()));
3093 edits.push((
3094 selection.end..selection.end,
3095 bracket_pair.end.as_str().into(),
3096 ));
3097 bracket_inserted = true;
3098 new_selections.push((
3099 Selection {
3100 id: selection.id,
3101 start: snapshot.anchor_after(selection.start),
3102 end: snapshot.anchor_before(selection.end),
3103 reversed: selection.reversed,
3104 goal: selection.goal,
3105 },
3106 0,
3107 ));
3108 continue;
3109 }
3110 }
3111 }
3112
3113 if self.auto_replace_emoji_shortcode
3114 && selection.is_empty()
3115 && text.as_ref().ends_with(':')
3116 {
3117 if let Some(possible_emoji_short_code) =
3118 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3119 {
3120 if !possible_emoji_short_code.is_empty() {
3121 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3122 let emoji_shortcode_start = Point::new(
3123 selection.start.row,
3124 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3125 );
3126
3127 // Remove shortcode from buffer
3128 edits.push((
3129 emoji_shortcode_start..selection.start,
3130 "".to_string().into(),
3131 ));
3132 new_selections.push((
3133 Selection {
3134 id: selection.id,
3135 start: snapshot.anchor_after(emoji_shortcode_start),
3136 end: snapshot.anchor_before(selection.start),
3137 reversed: selection.reversed,
3138 goal: selection.goal,
3139 },
3140 0,
3141 ));
3142
3143 // Insert emoji
3144 let selection_start_anchor = snapshot.anchor_after(selection.start);
3145 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3146 edits.push((selection.start..selection.end, emoji.to_string().into()));
3147
3148 continue;
3149 }
3150 }
3151 }
3152 }
3153
3154 // If not handling any auto-close operation, then just replace the selected
3155 // text with the given input and move the selection to the end of the
3156 // newly inserted text.
3157 let anchor = snapshot.anchor_after(selection.end);
3158 if !self.linked_edit_ranges.is_empty() {
3159 let start_anchor = snapshot.anchor_before(selection.start);
3160
3161 let is_word_char = text.chars().next().map_or(true, |char| {
3162 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3163 let kind = char_kind(&scope, char);
3164
3165 kind == CharKind::Word
3166 });
3167
3168 if is_word_char {
3169 if let Some(ranges) = self
3170 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3171 {
3172 for (buffer, edits) in ranges {
3173 linked_edits
3174 .entry(buffer.clone())
3175 .or_default()
3176 .extend(edits.into_iter().map(|range| (range, text.clone())));
3177 }
3178 }
3179 }
3180 }
3181
3182 new_selections.push((selection.map(|_| anchor), 0));
3183 edits.push((selection.start..selection.end, text.clone()));
3184 }
3185
3186 drop(snapshot);
3187
3188 self.transact(cx, |this, cx| {
3189 this.buffer.update(cx, |buffer, cx| {
3190 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3191 });
3192 for (buffer, edits) in linked_edits {
3193 buffer.update(cx, |buffer, cx| {
3194 let snapshot = buffer.snapshot();
3195 let edits = edits
3196 .into_iter()
3197 .map(|(range, text)| {
3198 use text::ToPoint as TP;
3199 let end_point = TP::to_point(&range.end, &snapshot);
3200 let start_point = TP::to_point(&range.start, &snapshot);
3201 (start_point..end_point, text)
3202 })
3203 .sorted_by_key(|(range, _)| range.start)
3204 .collect::<Vec<_>>();
3205 buffer.edit(edits, None, cx);
3206 })
3207 }
3208 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3209 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3210 let snapshot = this.buffer.read(cx).read(cx);
3211 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3212 .zip(new_selection_deltas)
3213 .map(|(selection, delta)| Selection {
3214 id: selection.id,
3215 start: selection.start + delta,
3216 end: selection.end + delta,
3217 reversed: selection.reversed,
3218 goal: SelectionGoal::None,
3219 })
3220 .collect::<Vec<_>>();
3221
3222 let mut i = 0;
3223 for (position, delta, selection_id, pair) in new_autoclose_regions {
3224 let position = position.to_offset(&snapshot) + delta;
3225 let start = snapshot.anchor_before(position);
3226 let end = snapshot.anchor_after(position);
3227 while let Some(existing_state) = this.autoclose_regions.get(i) {
3228 match existing_state.range.start.cmp(&start, &snapshot) {
3229 Ordering::Less => i += 1,
3230 Ordering::Greater => break,
3231 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3232 Ordering::Less => i += 1,
3233 Ordering::Equal => break,
3234 Ordering::Greater => break,
3235 },
3236 }
3237 }
3238 this.autoclose_regions.insert(
3239 i,
3240 AutocloseRegion {
3241 selection_id,
3242 range: start..end,
3243 pair,
3244 },
3245 );
3246 }
3247
3248 drop(snapshot);
3249 let had_active_inline_completion = this.has_active_inline_completion(cx);
3250 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3251 s.select(new_selections)
3252 });
3253
3254 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3255 if let Some(on_type_format_task) =
3256 this.trigger_on_type_formatting(text.to_string(), cx)
3257 {
3258 on_type_format_task.detach_and_log_err(cx);
3259 }
3260 }
3261
3262 let editor_settings = EditorSettings::get_global(cx);
3263 if bracket_inserted
3264 && (editor_settings.auto_signature_help
3265 || editor_settings.show_signature_help_after_edits)
3266 {
3267 this.show_signature_help(&ShowSignatureHelp, cx);
3268 }
3269
3270 let trigger_in_words = !had_active_inline_completion;
3271 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3272 linked_editing_ranges::refresh_linked_ranges(this, cx);
3273 this.refresh_inline_completion(true, cx);
3274 });
3275 }
3276
3277 fn find_possible_emoji_shortcode_at_position(
3278 snapshot: &MultiBufferSnapshot,
3279 position: Point,
3280 ) -> Option<String> {
3281 let mut chars = Vec::new();
3282 let mut found_colon = false;
3283 for char in snapshot.reversed_chars_at(position).take(100) {
3284 // Found a possible emoji shortcode in the middle of the buffer
3285 if found_colon {
3286 if char.is_whitespace() {
3287 chars.reverse();
3288 return Some(chars.iter().collect());
3289 }
3290 // If the previous character is not a whitespace, we are in the middle of a word
3291 // and we only want to complete the shortcode if the word is made up of other emojis
3292 let mut containing_word = String::new();
3293 for ch in snapshot
3294 .reversed_chars_at(position)
3295 .skip(chars.len() + 1)
3296 .take(100)
3297 {
3298 if ch.is_whitespace() {
3299 break;
3300 }
3301 containing_word.push(ch);
3302 }
3303 let containing_word = containing_word.chars().rev().collect::<String>();
3304 if util::word_consists_of_emojis(containing_word.as_str()) {
3305 chars.reverse();
3306 return Some(chars.iter().collect());
3307 }
3308 }
3309
3310 if char.is_whitespace() || !char.is_ascii() {
3311 return None;
3312 }
3313 if char == ':' {
3314 found_colon = true;
3315 } else {
3316 chars.push(char);
3317 }
3318 }
3319 // Found a possible emoji shortcode at the beginning of the buffer
3320 chars.reverse();
3321 Some(chars.iter().collect())
3322 }
3323
3324 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3325 self.transact(cx, |this, cx| {
3326 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3327 let selections = this.selections.all::<usize>(cx);
3328 let multi_buffer = this.buffer.read(cx);
3329 let buffer = multi_buffer.snapshot(cx);
3330 selections
3331 .iter()
3332 .map(|selection| {
3333 let start_point = selection.start.to_point(&buffer);
3334 let mut indent =
3335 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3336 indent.len = cmp::min(indent.len, start_point.column);
3337 let start = selection.start;
3338 let end = selection.end;
3339 let selection_is_empty = start == end;
3340 let language_scope = buffer.language_scope_at(start);
3341 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3342 &language_scope
3343 {
3344 let leading_whitespace_len = buffer
3345 .reversed_chars_at(start)
3346 .take_while(|c| c.is_whitespace() && *c != '\n')
3347 .map(|c| c.len_utf8())
3348 .sum::<usize>();
3349
3350 let trailing_whitespace_len = buffer
3351 .chars_at(end)
3352 .take_while(|c| c.is_whitespace() && *c != '\n')
3353 .map(|c| c.len_utf8())
3354 .sum::<usize>();
3355
3356 let insert_extra_newline =
3357 language.brackets().any(|(pair, enabled)| {
3358 let pair_start = pair.start.trim_end();
3359 let pair_end = pair.end.trim_start();
3360
3361 enabled
3362 && pair.newline
3363 && buffer.contains_str_at(
3364 end + trailing_whitespace_len,
3365 pair_end,
3366 )
3367 && buffer.contains_str_at(
3368 (start - leading_whitespace_len)
3369 .saturating_sub(pair_start.len()),
3370 pair_start,
3371 )
3372 });
3373
3374 // Comment extension on newline is allowed only for cursor selections
3375 let comment_delimiter = maybe!({
3376 if !selection_is_empty {
3377 return None;
3378 }
3379
3380 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3381 return None;
3382 }
3383
3384 let delimiters = language.line_comment_prefixes();
3385 let max_len_of_delimiter =
3386 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3387 let (snapshot, range) =
3388 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3389
3390 let mut index_of_first_non_whitespace = 0;
3391 let comment_candidate = snapshot
3392 .chars_for_range(range)
3393 .skip_while(|c| {
3394 let should_skip = c.is_whitespace();
3395 if should_skip {
3396 index_of_first_non_whitespace += 1;
3397 }
3398 should_skip
3399 })
3400 .take(max_len_of_delimiter)
3401 .collect::<String>();
3402 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3403 comment_candidate.starts_with(comment_prefix.as_ref())
3404 })?;
3405 let cursor_is_placed_after_comment_marker =
3406 index_of_first_non_whitespace + comment_prefix.len()
3407 <= start_point.column as usize;
3408 if cursor_is_placed_after_comment_marker {
3409 Some(comment_prefix.clone())
3410 } else {
3411 None
3412 }
3413 });
3414 (comment_delimiter, insert_extra_newline)
3415 } else {
3416 (None, false)
3417 };
3418
3419 let capacity_for_delimiter = comment_delimiter
3420 .as_deref()
3421 .map(str::len)
3422 .unwrap_or_default();
3423 let mut new_text =
3424 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3425 new_text.push_str("\n");
3426 new_text.extend(indent.chars());
3427 if let Some(delimiter) = &comment_delimiter {
3428 new_text.push_str(&delimiter);
3429 }
3430 if insert_extra_newline {
3431 new_text = new_text.repeat(2);
3432 }
3433
3434 let anchor = buffer.anchor_after(end);
3435 let new_selection = selection.map(|_| anchor);
3436 (
3437 (start..end, new_text),
3438 (insert_extra_newline, new_selection),
3439 )
3440 })
3441 .unzip()
3442 };
3443
3444 this.edit_with_autoindent(edits, cx);
3445 let buffer = this.buffer.read(cx).snapshot(cx);
3446 let new_selections = selection_fixup_info
3447 .into_iter()
3448 .map(|(extra_newline_inserted, new_selection)| {
3449 let mut cursor = new_selection.end.to_point(&buffer);
3450 if extra_newline_inserted {
3451 cursor.row -= 1;
3452 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3453 }
3454 new_selection.map(|_| cursor)
3455 })
3456 .collect();
3457
3458 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3459 this.refresh_inline_completion(true, cx);
3460 });
3461 }
3462
3463 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3464 let buffer = self.buffer.read(cx);
3465 let snapshot = buffer.snapshot(cx);
3466
3467 let mut edits = Vec::new();
3468 let mut rows = Vec::new();
3469
3470 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3471 let cursor = selection.head();
3472 let row = cursor.row;
3473
3474 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3475
3476 let newline = "\n".to_string();
3477 edits.push((start_of_line..start_of_line, newline));
3478
3479 rows.push(row + rows_inserted as u32);
3480 }
3481
3482 self.transact(cx, |editor, cx| {
3483 editor.edit(edits, cx);
3484
3485 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3486 let mut index = 0;
3487 s.move_cursors_with(|map, _, _| {
3488 let row = rows[index];
3489 index += 1;
3490
3491 let point = Point::new(row, 0);
3492 let boundary = map.next_line_boundary(point).1;
3493 let clipped = map.clip_point(boundary, Bias::Left);
3494
3495 (clipped, SelectionGoal::None)
3496 });
3497 });
3498
3499 let mut indent_edits = Vec::new();
3500 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3501 for row in rows {
3502 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3503 for (row, indent) in indents {
3504 if indent.len == 0 {
3505 continue;
3506 }
3507
3508 let text = match indent.kind {
3509 IndentKind::Space => " ".repeat(indent.len as usize),
3510 IndentKind::Tab => "\t".repeat(indent.len as usize),
3511 };
3512 let point = Point::new(row.0, 0);
3513 indent_edits.push((point..point, text));
3514 }
3515 }
3516 editor.edit(indent_edits, cx);
3517 });
3518 }
3519
3520 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3521 let buffer = self.buffer.read(cx);
3522 let snapshot = buffer.snapshot(cx);
3523
3524 let mut edits = Vec::new();
3525 let mut rows = Vec::new();
3526 let mut rows_inserted = 0;
3527
3528 for selection in self.selections.all_adjusted(cx) {
3529 let cursor = selection.head();
3530 let row = cursor.row;
3531
3532 let point = Point::new(row + 1, 0);
3533 let start_of_line = snapshot.clip_point(point, Bias::Left);
3534
3535 let newline = "\n".to_string();
3536 edits.push((start_of_line..start_of_line, newline));
3537
3538 rows_inserted += 1;
3539 rows.push(row + rows_inserted);
3540 }
3541
3542 self.transact(cx, |editor, cx| {
3543 editor.edit(edits, cx);
3544
3545 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3546 let mut index = 0;
3547 s.move_cursors_with(|map, _, _| {
3548 let row = rows[index];
3549 index += 1;
3550
3551 let point = Point::new(row, 0);
3552 let boundary = map.next_line_boundary(point).1;
3553 let clipped = map.clip_point(boundary, Bias::Left);
3554
3555 (clipped, SelectionGoal::None)
3556 });
3557 });
3558
3559 let mut indent_edits = Vec::new();
3560 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3561 for row in rows {
3562 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3563 for (row, indent) in indents {
3564 if indent.len == 0 {
3565 continue;
3566 }
3567
3568 let text = match indent.kind {
3569 IndentKind::Space => " ".repeat(indent.len as usize),
3570 IndentKind::Tab => "\t".repeat(indent.len as usize),
3571 };
3572 let point = Point::new(row.0, 0);
3573 indent_edits.push((point..point, text));
3574 }
3575 }
3576 editor.edit(indent_edits, cx);
3577 });
3578 }
3579
3580 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3581 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3582 original_indent_columns: Vec::new(),
3583 });
3584 self.insert_with_autoindent_mode(text, autoindent, cx);
3585 }
3586
3587 fn insert_with_autoindent_mode(
3588 &mut self,
3589 text: &str,
3590 autoindent_mode: Option<AutoindentMode>,
3591 cx: &mut ViewContext<Self>,
3592 ) {
3593 if self.read_only(cx) {
3594 return;
3595 }
3596
3597 let text: Arc<str> = text.into();
3598 self.transact(cx, |this, cx| {
3599 let old_selections = this.selections.all_adjusted(cx);
3600 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3601 let anchors = {
3602 let snapshot = buffer.read(cx);
3603 old_selections
3604 .iter()
3605 .map(|s| {
3606 let anchor = snapshot.anchor_after(s.head());
3607 s.map(|_| anchor)
3608 })
3609 .collect::<Vec<_>>()
3610 };
3611 buffer.edit(
3612 old_selections
3613 .iter()
3614 .map(|s| (s.start..s.end, text.clone())),
3615 autoindent_mode,
3616 cx,
3617 );
3618 anchors
3619 });
3620
3621 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3622 s.select_anchors(selection_anchors);
3623 })
3624 });
3625 }
3626
3627 fn trigger_completion_on_input(
3628 &mut self,
3629 text: &str,
3630 trigger_in_words: bool,
3631 cx: &mut ViewContext<Self>,
3632 ) {
3633 if self.is_completion_trigger(text, trigger_in_words, cx) {
3634 self.show_completions(
3635 &ShowCompletions {
3636 trigger: text.chars().last(),
3637 },
3638 cx,
3639 );
3640 } else {
3641 self.hide_context_menu(cx);
3642 }
3643 }
3644
3645 fn is_completion_trigger(
3646 &self,
3647 text: &str,
3648 trigger_in_words: bool,
3649 cx: &mut ViewContext<Self>,
3650 ) -> bool {
3651 let position = self.selections.newest_anchor().head();
3652 let multibuffer = self.buffer.read(cx);
3653 let Some(buffer) = position
3654 .buffer_id
3655 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3656 else {
3657 return false;
3658 };
3659
3660 if let Some(completion_provider) = &self.completion_provider {
3661 completion_provider.is_completion_trigger(
3662 &buffer,
3663 position.text_anchor,
3664 text,
3665 trigger_in_words,
3666 cx,
3667 )
3668 } else {
3669 false
3670 }
3671 }
3672
3673 /// If any empty selections is touching the start of its innermost containing autoclose
3674 /// region, expand it to select the brackets.
3675 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3676 let selections = self.selections.all::<usize>(cx);
3677 let buffer = self.buffer.read(cx).read(cx);
3678 let new_selections = self
3679 .selections_with_autoclose_regions(selections, &buffer)
3680 .map(|(mut selection, region)| {
3681 if !selection.is_empty() {
3682 return selection;
3683 }
3684
3685 if let Some(region) = region {
3686 let mut range = region.range.to_offset(&buffer);
3687 if selection.start == range.start && range.start >= region.pair.start.len() {
3688 range.start -= region.pair.start.len();
3689 if buffer.contains_str_at(range.start, ®ion.pair.start)
3690 && buffer.contains_str_at(range.end, ®ion.pair.end)
3691 {
3692 range.end += region.pair.end.len();
3693 selection.start = range.start;
3694 selection.end = range.end;
3695
3696 return selection;
3697 }
3698 }
3699 }
3700
3701 let always_treat_brackets_as_autoclosed = buffer
3702 .settings_at(selection.start, cx)
3703 .always_treat_brackets_as_autoclosed;
3704
3705 if !always_treat_brackets_as_autoclosed {
3706 return selection;
3707 }
3708
3709 if let Some(scope) = buffer.language_scope_at(selection.start) {
3710 for (pair, enabled) in scope.brackets() {
3711 if !enabled || !pair.close {
3712 continue;
3713 }
3714
3715 if buffer.contains_str_at(selection.start, &pair.end) {
3716 let pair_start_len = pair.start.len();
3717 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3718 {
3719 selection.start -= pair_start_len;
3720 selection.end += pair.end.len();
3721
3722 return selection;
3723 }
3724 }
3725 }
3726 }
3727
3728 selection
3729 })
3730 .collect();
3731
3732 drop(buffer);
3733 self.change_selections(None, cx, |selections| selections.select(new_selections));
3734 }
3735
3736 /// Iterate the given selections, and for each one, find the smallest surrounding
3737 /// autoclose region. This uses the ordering of the selections and the autoclose
3738 /// regions to avoid repeated comparisons.
3739 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3740 &'a self,
3741 selections: impl IntoIterator<Item = Selection<D>>,
3742 buffer: &'a MultiBufferSnapshot,
3743 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3744 let mut i = 0;
3745 let mut regions = self.autoclose_regions.as_slice();
3746 selections.into_iter().map(move |selection| {
3747 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3748
3749 let mut enclosing = None;
3750 while let Some(pair_state) = regions.get(i) {
3751 if pair_state.range.end.to_offset(buffer) < range.start {
3752 regions = ®ions[i + 1..];
3753 i = 0;
3754 } else if pair_state.range.start.to_offset(buffer) > range.end {
3755 break;
3756 } else {
3757 if pair_state.selection_id == selection.id {
3758 enclosing = Some(pair_state);
3759 }
3760 i += 1;
3761 }
3762 }
3763
3764 (selection.clone(), enclosing)
3765 })
3766 }
3767
3768 /// Remove any autoclose regions that no longer contain their selection.
3769 fn invalidate_autoclose_regions(
3770 &mut self,
3771 mut selections: &[Selection<Anchor>],
3772 buffer: &MultiBufferSnapshot,
3773 ) {
3774 self.autoclose_regions.retain(|state| {
3775 let mut i = 0;
3776 while let Some(selection) = selections.get(i) {
3777 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3778 selections = &selections[1..];
3779 continue;
3780 }
3781 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3782 break;
3783 }
3784 if selection.id == state.selection_id {
3785 return true;
3786 } else {
3787 i += 1;
3788 }
3789 }
3790 false
3791 });
3792 }
3793
3794 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3795 let offset = position.to_offset(buffer);
3796 let (word_range, kind) = buffer.surrounding_word(offset);
3797 if offset > word_range.start && kind == Some(CharKind::Word) {
3798 Some(
3799 buffer
3800 .text_for_range(word_range.start..offset)
3801 .collect::<String>(),
3802 )
3803 } else {
3804 None
3805 }
3806 }
3807
3808 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3809 self.refresh_inlay_hints(
3810 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3811 cx,
3812 );
3813 }
3814
3815 pub fn inlay_hints_enabled(&self) -> bool {
3816 self.inlay_hint_cache.enabled
3817 }
3818
3819 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3820 if self.project.is_none() || self.mode != EditorMode::Full {
3821 return;
3822 }
3823
3824 let reason_description = reason.description();
3825 let ignore_debounce = matches!(
3826 reason,
3827 InlayHintRefreshReason::SettingsChange(_)
3828 | InlayHintRefreshReason::Toggle(_)
3829 | InlayHintRefreshReason::ExcerptsRemoved(_)
3830 );
3831 let (invalidate_cache, required_languages) = match reason {
3832 InlayHintRefreshReason::Toggle(enabled) => {
3833 self.inlay_hint_cache.enabled = enabled;
3834 if enabled {
3835 (InvalidationStrategy::RefreshRequested, None)
3836 } else {
3837 self.inlay_hint_cache.clear();
3838 self.splice_inlays(
3839 self.visible_inlay_hints(cx)
3840 .iter()
3841 .map(|inlay| inlay.id)
3842 .collect(),
3843 Vec::new(),
3844 cx,
3845 );
3846 return;
3847 }
3848 }
3849 InlayHintRefreshReason::SettingsChange(new_settings) => {
3850 match self.inlay_hint_cache.update_settings(
3851 &self.buffer,
3852 new_settings,
3853 self.visible_inlay_hints(cx),
3854 cx,
3855 ) {
3856 ControlFlow::Break(Some(InlaySplice {
3857 to_remove,
3858 to_insert,
3859 })) => {
3860 self.splice_inlays(to_remove, to_insert, cx);
3861 return;
3862 }
3863 ControlFlow::Break(None) => return,
3864 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3865 }
3866 }
3867 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3868 if let Some(InlaySplice {
3869 to_remove,
3870 to_insert,
3871 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3872 {
3873 self.splice_inlays(to_remove, to_insert, cx);
3874 }
3875 return;
3876 }
3877 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3878 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3879 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3880 }
3881 InlayHintRefreshReason::RefreshRequested => {
3882 (InvalidationStrategy::RefreshRequested, None)
3883 }
3884 };
3885
3886 if let Some(InlaySplice {
3887 to_remove,
3888 to_insert,
3889 }) = self.inlay_hint_cache.spawn_hint_refresh(
3890 reason_description,
3891 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3892 invalidate_cache,
3893 ignore_debounce,
3894 cx,
3895 ) {
3896 self.splice_inlays(to_remove, to_insert, cx);
3897 }
3898 }
3899
3900 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3901 self.display_map
3902 .read(cx)
3903 .current_inlays()
3904 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3905 .cloned()
3906 .collect()
3907 }
3908
3909 pub fn excerpts_for_inlay_hints_query(
3910 &self,
3911 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3912 cx: &mut ViewContext<Editor>,
3913 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3914 let Some(project) = self.project.as_ref() else {
3915 return HashMap::default();
3916 };
3917 let project = project.read(cx);
3918 let multi_buffer = self.buffer().read(cx);
3919 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3920 let multi_buffer_visible_start = self
3921 .scroll_manager
3922 .anchor()
3923 .anchor
3924 .to_point(&multi_buffer_snapshot);
3925 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3926 multi_buffer_visible_start
3927 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3928 Bias::Left,
3929 );
3930 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3931 multi_buffer
3932 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3933 .into_iter()
3934 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3935 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3936 let buffer = buffer_handle.read(cx);
3937 let buffer_file = project::File::from_dyn(buffer.file())?;
3938 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3939 let worktree_entry = buffer_worktree
3940 .read(cx)
3941 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3942 if worktree_entry.is_ignored {
3943 return None;
3944 }
3945
3946 let language = buffer.language()?;
3947 if let Some(restrict_to_languages) = restrict_to_languages {
3948 if !restrict_to_languages.contains(language) {
3949 return None;
3950 }
3951 }
3952 Some((
3953 excerpt_id,
3954 (
3955 buffer_handle,
3956 buffer.version().clone(),
3957 excerpt_visible_range,
3958 ),
3959 ))
3960 })
3961 .collect()
3962 }
3963
3964 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3965 TextLayoutDetails {
3966 text_system: cx.text_system().clone(),
3967 editor_style: self.style.clone().unwrap(),
3968 rem_size: cx.rem_size(),
3969 scroll_anchor: self.scroll_manager.anchor(),
3970 visible_rows: self.visible_line_count(),
3971 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3972 }
3973 }
3974
3975 fn splice_inlays(
3976 &self,
3977 to_remove: Vec<InlayId>,
3978 to_insert: Vec<Inlay>,
3979 cx: &mut ViewContext<Self>,
3980 ) {
3981 self.display_map.update(cx, |display_map, cx| {
3982 display_map.splice_inlays(to_remove, to_insert, cx);
3983 });
3984 cx.notify();
3985 }
3986
3987 fn trigger_on_type_formatting(
3988 &self,
3989 input: String,
3990 cx: &mut ViewContext<Self>,
3991 ) -> Option<Task<Result<()>>> {
3992 if input.len() != 1 {
3993 return None;
3994 }
3995
3996 let project = self.project.as_ref()?;
3997 let position = self.selections.newest_anchor().head();
3998 let (buffer, buffer_position) = self
3999 .buffer
4000 .read(cx)
4001 .text_anchor_for_position(position, cx)?;
4002
4003 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4004 // hence we do LSP request & edit on host side only — add formats to host's history.
4005 let push_to_lsp_host_history = true;
4006 // If this is not the host, append its history with new edits.
4007 let push_to_client_history = project.read(cx).is_remote();
4008
4009 let on_type_formatting = project.update(cx, |project, cx| {
4010 project.on_type_format(
4011 buffer.clone(),
4012 buffer_position,
4013 input,
4014 push_to_lsp_host_history,
4015 cx,
4016 )
4017 });
4018 Some(cx.spawn(|editor, mut cx| async move {
4019 if let Some(transaction) = on_type_formatting.await? {
4020 if push_to_client_history {
4021 buffer
4022 .update(&mut cx, |buffer, _| {
4023 buffer.push_transaction(transaction, Instant::now());
4024 })
4025 .ok();
4026 }
4027 editor.update(&mut cx, |editor, cx| {
4028 editor.refresh_document_highlights(cx);
4029 })?;
4030 }
4031 Ok(())
4032 }))
4033 }
4034
4035 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4036 if self.pending_rename.is_some() {
4037 return;
4038 }
4039
4040 let Some(provider) = self.completion_provider.as_ref() else {
4041 return;
4042 };
4043
4044 let position = self.selections.newest_anchor().head();
4045 let (buffer, buffer_position) =
4046 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4047 output
4048 } else {
4049 return;
4050 };
4051
4052 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4053 let is_followup_invoke = {
4054 let context_menu_state = self.context_menu.read();
4055 matches!(
4056 context_menu_state.deref(),
4057 Some(ContextMenu::Completions(_))
4058 )
4059 };
4060 let trigger_kind = match (options.trigger, is_followup_invoke) {
4061 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4062 (Some(_), _) => CompletionTriggerKind::TRIGGER_CHARACTER,
4063 _ => CompletionTriggerKind::INVOKED,
4064 };
4065 let completion_context = CompletionContext {
4066 trigger_character: options.trigger.and_then(|c| {
4067 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4068 Some(String::from(c))
4069 } else {
4070 None
4071 }
4072 }),
4073 trigger_kind,
4074 };
4075 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4076
4077 let id = post_inc(&mut self.next_completion_id);
4078 let task = cx.spawn(|this, mut cx| {
4079 async move {
4080 this.update(&mut cx, |this, _| {
4081 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4082 })?;
4083 let completions = completions.await.log_err();
4084 let menu = if let Some(completions) = completions {
4085 let mut menu = CompletionsMenu {
4086 id,
4087 initial_position: position,
4088 match_candidates: completions
4089 .iter()
4090 .enumerate()
4091 .map(|(id, completion)| {
4092 StringMatchCandidate::new(
4093 id,
4094 completion.label.text[completion.label.filter_range.clone()]
4095 .into(),
4096 )
4097 })
4098 .collect(),
4099 buffer: buffer.clone(),
4100 completions: Arc::new(RwLock::new(completions.into())),
4101 matches: Vec::new().into(),
4102 selected_item: 0,
4103 scroll_handle: UniformListScrollHandle::new(),
4104 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4105 DebouncedDelay::new(),
4106 )),
4107 };
4108 menu.filter(query.as_deref(), cx.background_executor().clone())
4109 .await;
4110
4111 if menu.matches.is_empty() {
4112 None
4113 } else {
4114 this.update(&mut cx, |editor, cx| {
4115 let completions = menu.completions.clone();
4116 let matches = menu.matches.clone();
4117
4118 let delay_ms = EditorSettings::get_global(cx)
4119 .completion_documentation_secondary_query_debounce;
4120 let delay = Duration::from_millis(delay_ms);
4121 editor
4122 .completion_documentation_pre_resolve_debounce
4123 .fire_new(delay, cx, |editor, cx| {
4124 CompletionsMenu::pre_resolve_completion_documentation(
4125 buffer,
4126 completions,
4127 matches,
4128 editor,
4129 cx,
4130 )
4131 });
4132 })
4133 .ok();
4134 Some(menu)
4135 }
4136 } else {
4137 None
4138 };
4139
4140 this.update(&mut cx, |this, cx| {
4141 let mut context_menu = this.context_menu.write();
4142 match context_menu.as_ref() {
4143 None => {}
4144
4145 Some(ContextMenu::Completions(prev_menu)) => {
4146 if prev_menu.id > id {
4147 return;
4148 }
4149 }
4150
4151 _ => return,
4152 }
4153
4154 if this.focus_handle.is_focused(cx) && menu.is_some() {
4155 let menu = menu.unwrap();
4156 *context_menu = Some(ContextMenu::Completions(menu));
4157 drop(context_menu);
4158 this.discard_inline_completion(false, cx);
4159 cx.notify();
4160 } else if this.completion_tasks.len() <= 1 {
4161 // If there are no more completion tasks and the last menu was
4162 // empty, we should hide it. If it was already hidden, we should
4163 // also show the copilot completion when available.
4164 drop(context_menu);
4165 if this.hide_context_menu(cx).is_none() {
4166 this.update_visible_inline_completion(cx);
4167 }
4168 }
4169 })?;
4170
4171 Ok::<_, anyhow::Error>(())
4172 }
4173 .log_err()
4174 });
4175
4176 self.completion_tasks.push((id, task));
4177 }
4178
4179 pub fn confirm_completion(
4180 &mut self,
4181 action: &ConfirmCompletion,
4182 cx: &mut ViewContext<Self>,
4183 ) -> Option<Task<Result<()>>> {
4184 use language::ToOffset as _;
4185
4186 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4187 menu
4188 } else {
4189 return None;
4190 };
4191
4192 let mat = completions_menu
4193 .matches
4194 .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
4195 let buffer_handle = completions_menu.buffer;
4196 let completions = completions_menu.completions.read();
4197 let completion = completions.get(mat.candidate_id)?;
4198 cx.stop_propagation();
4199
4200 let snippet;
4201 let text;
4202
4203 if completion.is_snippet() {
4204 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4205 text = snippet.as_ref().unwrap().text.clone();
4206 } else {
4207 snippet = None;
4208 text = completion.new_text.clone();
4209 };
4210 let selections = self.selections.all::<usize>(cx);
4211 let buffer = buffer_handle.read(cx);
4212 let old_range = completion.old_range.to_offset(buffer);
4213 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4214
4215 let newest_selection = self.selections.newest_anchor();
4216 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4217 return None;
4218 }
4219
4220 let lookbehind = newest_selection
4221 .start
4222 .text_anchor
4223 .to_offset(buffer)
4224 .saturating_sub(old_range.start);
4225 let lookahead = old_range
4226 .end
4227 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4228 let mut common_prefix_len = old_text
4229 .bytes()
4230 .zip(text.bytes())
4231 .take_while(|(a, b)| a == b)
4232 .count();
4233
4234 let snapshot = self.buffer.read(cx).snapshot(cx);
4235 let mut range_to_replace: Option<Range<isize>> = None;
4236 let mut ranges = Vec::new();
4237 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4238 for selection in &selections {
4239 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4240 let start = selection.start.saturating_sub(lookbehind);
4241 let end = selection.end + lookahead;
4242 if selection.id == newest_selection.id {
4243 range_to_replace = Some(
4244 ((start + common_prefix_len) as isize - selection.start as isize)
4245 ..(end as isize - selection.start as isize),
4246 );
4247 }
4248 ranges.push(start + common_prefix_len..end);
4249 } else {
4250 common_prefix_len = 0;
4251 ranges.clear();
4252 ranges.extend(selections.iter().map(|s| {
4253 if s.id == newest_selection.id {
4254 range_to_replace = Some(
4255 old_range.start.to_offset_utf16(&snapshot).0 as isize
4256 - selection.start as isize
4257 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4258 - selection.start as isize,
4259 );
4260 old_range.clone()
4261 } else {
4262 s.start..s.end
4263 }
4264 }));
4265 break;
4266 }
4267 if !self.linked_edit_ranges.is_empty() {
4268 let start_anchor = snapshot.anchor_before(selection.head());
4269 let end_anchor = snapshot.anchor_after(selection.tail());
4270 if let Some(ranges) = self
4271 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4272 {
4273 for (buffer, edits) in ranges {
4274 linked_edits.entry(buffer.clone()).or_default().extend(
4275 edits
4276 .into_iter()
4277 .map(|range| (range, text[common_prefix_len..].to_owned())),
4278 );
4279 }
4280 }
4281 }
4282 }
4283 let text = &text[common_prefix_len..];
4284
4285 cx.emit(EditorEvent::InputHandled {
4286 utf16_range_to_replace: range_to_replace,
4287 text: text.into(),
4288 });
4289
4290 self.transact(cx, |this, cx| {
4291 if let Some(mut snippet) = snippet {
4292 snippet.text = text.to_string();
4293 for tabstop in snippet.tabstops.iter_mut().flatten() {
4294 tabstop.start -= common_prefix_len as isize;
4295 tabstop.end -= common_prefix_len as isize;
4296 }
4297
4298 this.insert_snippet(&ranges, snippet, cx).log_err();
4299 } else {
4300 this.buffer.update(cx, |buffer, cx| {
4301 buffer.edit(
4302 ranges.iter().map(|range| (range.clone(), text)),
4303 this.autoindent_mode.clone(),
4304 cx,
4305 );
4306 });
4307 }
4308 for (buffer, edits) in linked_edits {
4309 buffer.update(cx, |buffer, cx| {
4310 let snapshot = buffer.snapshot();
4311 let edits = edits
4312 .into_iter()
4313 .map(|(range, text)| {
4314 use text::ToPoint as TP;
4315 let end_point = TP::to_point(&range.end, &snapshot);
4316 let start_point = TP::to_point(&range.start, &snapshot);
4317 (start_point..end_point, text)
4318 })
4319 .sorted_by_key(|(range, _)| range.start)
4320 .collect::<Vec<_>>();
4321 buffer.edit(edits, None, cx);
4322 })
4323 }
4324
4325 this.refresh_inline_completion(true, cx);
4326 });
4327
4328 if let Some(confirm) = completion.confirm.as_ref() {
4329 (confirm)(cx);
4330 }
4331
4332 if completion.show_new_completions_on_confirm {
4333 self.show_completions(&ShowCompletions { trigger: None }, cx);
4334 }
4335
4336 let provider = self.completion_provider.as_ref()?;
4337 let apply_edits = provider.apply_additional_edits_for_completion(
4338 buffer_handle,
4339 completion.clone(),
4340 true,
4341 cx,
4342 );
4343
4344 let editor_settings = EditorSettings::get_global(cx);
4345 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4346 // After the code completion is finished, users often want to know what signatures are needed.
4347 // so we should automatically call signature_help
4348 self.show_signature_help(&ShowSignatureHelp, cx);
4349 }
4350
4351 Some(cx.foreground_executor().spawn(async move {
4352 apply_edits.await?;
4353 Ok(())
4354 }))
4355 }
4356
4357 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4358 let mut context_menu = self.context_menu.write();
4359 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4360 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4361 // Toggle if we're selecting the same one
4362 *context_menu = None;
4363 cx.notify();
4364 return;
4365 } else {
4366 // Otherwise, clear it and start a new one
4367 *context_menu = None;
4368 cx.notify();
4369 }
4370 }
4371 drop(context_menu);
4372 let snapshot = self.snapshot(cx);
4373 let deployed_from_indicator = action.deployed_from_indicator;
4374 let mut task = self.code_actions_task.take();
4375 let action = action.clone();
4376 cx.spawn(|editor, mut cx| async move {
4377 while let Some(prev_task) = task {
4378 prev_task.await;
4379 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4380 }
4381
4382 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4383 if editor.focus_handle.is_focused(cx) {
4384 let multibuffer_point = action
4385 .deployed_from_indicator
4386 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4387 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4388 let (buffer, buffer_row) = snapshot
4389 .buffer_snapshot
4390 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4391 .and_then(|(buffer_snapshot, range)| {
4392 editor
4393 .buffer
4394 .read(cx)
4395 .buffer(buffer_snapshot.remote_id())
4396 .map(|buffer| (buffer, range.start.row))
4397 })?;
4398 let (_, code_actions) = editor
4399 .available_code_actions
4400 .clone()
4401 .and_then(|(location, code_actions)| {
4402 let snapshot = location.buffer.read(cx).snapshot();
4403 let point_range = location.range.to_point(&snapshot);
4404 let point_range = point_range.start.row..=point_range.end.row;
4405 if point_range.contains(&buffer_row) {
4406 Some((location, code_actions))
4407 } else {
4408 None
4409 }
4410 })
4411 .unzip();
4412 let buffer_id = buffer.read(cx).remote_id();
4413 let tasks = editor
4414 .tasks
4415 .get(&(buffer_id, buffer_row))
4416 .map(|t| Arc::new(t.to_owned()));
4417 if tasks.is_none() && code_actions.is_none() {
4418 return None;
4419 }
4420
4421 editor.completion_tasks.clear();
4422 editor.discard_inline_completion(false, cx);
4423 let task_context =
4424 tasks
4425 .as_ref()
4426 .zip(editor.project.clone())
4427 .map(|(tasks, project)| {
4428 let position = Point::new(buffer_row, tasks.column);
4429 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4430 let location = Location {
4431 buffer: buffer.clone(),
4432 range: range_start..range_start,
4433 };
4434 // Fill in the environmental variables from the tree-sitter captures
4435 let mut captured_task_variables = TaskVariables::default();
4436 for (capture_name, value) in tasks.extra_variables.clone() {
4437 captured_task_variables.insert(
4438 task::VariableName::Custom(capture_name.into()),
4439 value.clone(),
4440 );
4441 }
4442 project.update(cx, |project, cx| {
4443 project.task_context_for_location(
4444 captured_task_variables,
4445 location,
4446 cx,
4447 )
4448 })
4449 });
4450
4451 Some(cx.spawn(|editor, mut cx| async move {
4452 let task_context = match task_context {
4453 Some(task_context) => task_context.await,
4454 None => None,
4455 };
4456 let resolved_tasks =
4457 tasks.zip(task_context).map(|(tasks, task_context)| {
4458 Arc::new(ResolvedTasks {
4459 templates: tasks
4460 .templates
4461 .iter()
4462 .filter_map(|(kind, template)| {
4463 template
4464 .resolve_task(&kind.to_id_base(), &task_context)
4465 .map(|task| (kind.clone(), task))
4466 })
4467 .collect(),
4468 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4469 multibuffer_point.row,
4470 tasks.column,
4471 )),
4472 })
4473 });
4474 let spawn_straight_away = resolved_tasks
4475 .as_ref()
4476 .map_or(false, |tasks| tasks.templates.len() == 1)
4477 && code_actions
4478 .as_ref()
4479 .map_or(true, |actions| actions.is_empty());
4480 if let Some(task) = editor
4481 .update(&mut cx, |editor, cx| {
4482 *editor.context_menu.write() =
4483 Some(ContextMenu::CodeActions(CodeActionsMenu {
4484 buffer,
4485 actions: CodeActionContents {
4486 tasks: resolved_tasks,
4487 actions: code_actions,
4488 },
4489 selected_item: Default::default(),
4490 scroll_handle: UniformListScrollHandle::default(),
4491 deployed_from_indicator,
4492 }));
4493 if spawn_straight_away {
4494 if let Some(task) = editor.confirm_code_action(
4495 &ConfirmCodeAction { item_ix: Some(0) },
4496 cx,
4497 ) {
4498 cx.notify();
4499 return task;
4500 }
4501 }
4502 cx.notify();
4503 Task::ready(Ok(()))
4504 })
4505 .ok()
4506 {
4507 task.await
4508 } else {
4509 Ok(())
4510 }
4511 }))
4512 } else {
4513 Some(Task::ready(Ok(())))
4514 }
4515 })?;
4516 if let Some(task) = spawned_test_task {
4517 task.await?;
4518 }
4519
4520 Ok::<_, anyhow::Error>(())
4521 })
4522 .detach_and_log_err(cx);
4523 }
4524
4525 pub fn confirm_code_action(
4526 &mut self,
4527 action: &ConfirmCodeAction,
4528 cx: &mut ViewContext<Self>,
4529 ) -> Option<Task<Result<()>>> {
4530 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4531 menu
4532 } else {
4533 return None;
4534 };
4535 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4536 let action = actions_menu.actions.get(action_ix)?;
4537 let title = action.label();
4538 let buffer = actions_menu.buffer;
4539 let workspace = self.workspace()?;
4540
4541 match action {
4542 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4543 workspace.update(cx, |workspace, cx| {
4544 workspace::tasks::schedule_resolved_task(
4545 workspace,
4546 task_source_kind,
4547 resolved_task,
4548 false,
4549 cx,
4550 );
4551
4552 Some(Task::ready(Ok(())))
4553 })
4554 }
4555 CodeActionsItem::CodeAction(action) => {
4556 let apply_code_actions = workspace
4557 .read(cx)
4558 .project()
4559 .clone()
4560 .update(cx, |project, cx| {
4561 project.apply_code_action(buffer, action, true, cx)
4562 });
4563 let workspace = workspace.downgrade();
4564 Some(cx.spawn(|editor, cx| async move {
4565 let project_transaction = apply_code_actions.await?;
4566 Self::open_project_transaction(
4567 &editor,
4568 workspace,
4569 project_transaction,
4570 title,
4571 cx,
4572 )
4573 .await
4574 }))
4575 }
4576 }
4577 }
4578
4579 pub async fn open_project_transaction(
4580 this: &WeakView<Editor>,
4581 workspace: WeakView<Workspace>,
4582 transaction: ProjectTransaction,
4583 title: String,
4584 mut cx: AsyncWindowContext,
4585 ) -> Result<()> {
4586 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4587
4588 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4589 cx.update(|cx| {
4590 entries.sort_unstable_by_key(|(buffer, _)| {
4591 buffer.read(cx).file().map(|f| f.path().clone())
4592 });
4593 })?;
4594
4595 // If the project transaction's edits are all contained within this editor, then
4596 // avoid opening a new editor to display them.
4597
4598 if let Some((buffer, transaction)) = entries.first() {
4599 if entries.len() == 1 {
4600 let excerpt = this.update(&mut cx, |editor, cx| {
4601 editor
4602 .buffer()
4603 .read(cx)
4604 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4605 })?;
4606 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4607 if excerpted_buffer == *buffer {
4608 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4609 let excerpt_range = excerpt_range.to_offset(buffer);
4610 buffer
4611 .edited_ranges_for_transaction::<usize>(transaction)
4612 .all(|range| {
4613 excerpt_range.start <= range.start
4614 && excerpt_range.end >= range.end
4615 })
4616 })?;
4617
4618 if all_edits_within_excerpt {
4619 return Ok(());
4620 }
4621 }
4622 }
4623 }
4624 } else {
4625 return Ok(());
4626 }
4627
4628 let mut ranges_to_highlight = Vec::new();
4629 let excerpt_buffer = cx.new_model(|cx| {
4630 let mut multibuffer =
4631 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4632 for (buffer_handle, transaction) in &entries {
4633 let buffer = buffer_handle.read(cx);
4634 ranges_to_highlight.extend(
4635 multibuffer.push_excerpts_with_context_lines(
4636 buffer_handle.clone(),
4637 buffer
4638 .edited_ranges_for_transaction::<usize>(transaction)
4639 .collect(),
4640 DEFAULT_MULTIBUFFER_CONTEXT,
4641 cx,
4642 ),
4643 );
4644 }
4645 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4646 multibuffer
4647 })?;
4648
4649 workspace.update(&mut cx, |workspace, cx| {
4650 let project = workspace.project().clone();
4651 let editor =
4652 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4653 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
4654 editor.update(cx, |editor, cx| {
4655 editor.highlight_background::<Self>(
4656 &ranges_to_highlight,
4657 |theme| theme.editor_highlighted_line_background,
4658 cx,
4659 );
4660 });
4661 })?;
4662
4663 Ok(())
4664 }
4665
4666 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4667 let project = self.project.clone()?;
4668 let buffer = self.buffer.read(cx);
4669 let newest_selection = self.selections.newest_anchor().clone();
4670 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4671 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4672 if start_buffer != end_buffer {
4673 return None;
4674 }
4675
4676 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4677 cx.background_executor()
4678 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4679 .await;
4680
4681 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4682 project.code_actions(&start_buffer, start..end, cx)
4683 }) {
4684 code_actions.await
4685 } else {
4686 Vec::new()
4687 };
4688
4689 this.update(&mut cx, |this, cx| {
4690 this.available_code_actions = if actions.is_empty() {
4691 None
4692 } else {
4693 Some((
4694 Location {
4695 buffer: start_buffer,
4696 range: start..end,
4697 },
4698 actions.into(),
4699 ))
4700 };
4701 cx.notify();
4702 })
4703 .log_err();
4704 }));
4705 None
4706 }
4707
4708 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4709 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4710 self.show_git_blame_inline = false;
4711
4712 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4713 cx.background_executor().timer(delay).await;
4714
4715 this.update(&mut cx, |this, cx| {
4716 this.show_git_blame_inline = true;
4717 cx.notify();
4718 })
4719 .log_err();
4720 }));
4721 }
4722 }
4723
4724 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4725 if self.pending_rename.is_some() {
4726 return None;
4727 }
4728
4729 let project = self.project.clone()?;
4730 let buffer = self.buffer.read(cx);
4731 let newest_selection = self.selections.newest_anchor().clone();
4732 let cursor_position = newest_selection.head();
4733 let (cursor_buffer, cursor_buffer_position) =
4734 buffer.text_anchor_for_position(cursor_position, cx)?;
4735 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4736 if cursor_buffer != tail_buffer {
4737 return None;
4738 }
4739
4740 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4741 cx.background_executor()
4742 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4743 .await;
4744
4745 let highlights = if let Some(highlights) = project
4746 .update(&mut cx, |project, cx| {
4747 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4748 })
4749 .log_err()
4750 {
4751 highlights.await.log_err()
4752 } else {
4753 None
4754 };
4755
4756 if let Some(highlights) = highlights {
4757 this.update(&mut cx, |this, cx| {
4758 if this.pending_rename.is_some() {
4759 return;
4760 }
4761
4762 let buffer_id = cursor_position.buffer_id;
4763 let buffer = this.buffer.read(cx);
4764 if !buffer
4765 .text_anchor_for_position(cursor_position, cx)
4766 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4767 {
4768 return;
4769 }
4770
4771 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4772 let mut write_ranges = Vec::new();
4773 let mut read_ranges = Vec::new();
4774 for highlight in highlights {
4775 for (excerpt_id, excerpt_range) in
4776 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4777 {
4778 let start = highlight
4779 .range
4780 .start
4781 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4782 let end = highlight
4783 .range
4784 .end
4785 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4786 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4787 continue;
4788 }
4789
4790 let range = Anchor {
4791 buffer_id,
4792 excerpt_id: excerpt_id,
4793 text_anchor: start,
4794 }..Anchor {
4795 buffer_id,
4796 excerpt_id,
4797 text_anchor: end,
4798 };
4799 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4800 write_ranges.push(range);
4801 } else {
4802 read_ranges.push(range);
4803 }
4804 }
4805 }
4806
4807 this.highlight_background::<DocumentHighlightRead>(
4808 &read_ranges,
4809 |theme| theme.editor_document_highlight_read_background,
4810 cx,
4811 );
4812 this.highlight_background::<DocumentHighlightWrite>(
4813 &write_ranges,
4814 |theme| theme.editor_document_highlight_write_background,
4815 cx,
4816 );
4817 cx.notify();
4818 })
4819 .log_err();
4820 }
4821 }));
4822 None
4823 }
4824
4825 fn refresh_inline_completion(
4826 &mut self,
4827 debounce: bool,
4828 cx: &mut ViewContext<Self>,
4829 ) -> Option<()> {
4830 let provider = self.inline_completion_provider()?;
4831 let cursor = self.selections.newest_anchor().head();
4832 let (buffer, cursor_buffer_position) =
4833 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4834 if !self.show_inline_completions
4835 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4836 {
4837 self.discard_inline_completion(false, cx);
4838 return None;
4839 }
4840
4841 self.update_visible_inline_completion(cx);
4842 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4843 Some(())
4844 }
4845
4846 fn cycle_inline_completion(
4847 &mut self,
4848 direction: Direction,
4849 cx: &mut ViewContext<Self>,
4850 ) -> Option<()> {
4851 let provider = self.inline_completion_provider()?;
4852 let cursor = self.selections.newest_anchor().head();
4853 let (buffer, cursor_buffer_position) =
4854 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4855 if !self.show_inline_completions
4856 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4857 {
4858 return None;
4859 }
4860
4861 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4862 self.update_visible_inline_completion(cx);
4863
4864 Some(())
4865 }
4866
4867 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4868 if !self.has_active_inline_completion(cx) {
4869 self.refresh_inline_completion(false, cx);
4870 return;
4871 }
4872
4873 self.update_visible_inline_completion(cx);
4874 }
4875
4876 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4877 self.show_cursor_names(cx);
4878 }
4879
4880 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4881 self.show_cursor_names = true;
4882 cx.notify();
4883 cx.spawn(|this, mut cx| async move {
4884 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4885 this.update(&mut cx, |this, cx| {
4886 this.show_cursor_names = false;
4887 cx.notify()
4888 })
4889 .ok()
4890 })
4891 .detach();
4892 }
4893
4894 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4895 if self.has_active_inline_completion(cx) {
4896 self.cycle_inline_completion(Direction::Next, cx);
4897 } else {
4898 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4899 if is_copilot_disabled {
4900 cx.propagate();
4901 }
4902 }
4903 }
4904
4905 pub fn previous_inline_completion(
4906 &mut self,
4907 _: &PreviousInlineCompletion,
4908 cx: &mut ViewContext<Self>,
4909 ) {
4910 if self.has_active_inline_completion(cx) {
4911 self.cycle_inline_completion(Direction::Prev, cx);
4912 } else {
4913 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4914 if is_copilot_disabled {
4915 cx.propagate();
4916 }
4917 }
4918 }
4919
4920 pub fn accept_inline_completion(
4921 &mut self,
4922 _: &AcceptInlineCompletion,
4923 cx: &mut ViewContext<Self>,
4924 ) {
4925 let Some(completion) = self.take_active_inline_completion(cx) else {
4926 return;
4927 };
4928 if let Some(provider) = self.inline_completion_provider() {
4929 provider.accept(cx);
4930 }
4931
4932 cx.emit(EditorEvent::InputHandled {
4933 utf16_range_to_replace: None,
4934 text: completion.text.to_string().into(),
4935 });
4936 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
4937 self.refresh_inline_completion(true, cx);
4938 cx.notify();
4939 }
4940
4941 pub fn accept_partial_inline_completion(
4942 &mut self,
4943 _: &AcceptPartialInlineCompletion,
4944 cx: &mut ViewContext<Self>,
4945 ) {
4946 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
4947 if let Some(completion) = self.take_active_inline_completion(cx) {
4948 let mut partial_completion = completion
4949 .text
4950 .chars()
4951 .by_ref()
4952 .take_while(|c| c.is_alphabetic())
4953 .collect::<String>();
4954 if partial_completion.is_empty() {
4955 partial_completion = completion
4956 .text
4957 .chars()
4958 .by_ref()
4959 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4960 .collect::<String>();
4961 }
4962
4963 cx.emit(EditorEvent::InputHandled {
4964 utf16_range_to_replace: None,
4965 text: partial_completion.clone().into(),
4966 });
4967 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4968 self.refresh_inline_completion(true, cx);
4969 cx.notify();
4970 }
4971 }
4972 }
4973
4974 fn discard_inline_completion(
4975 &mut self,
4976 should_report_inline_completion_event: bool,
4977 cx: &mut ViewContext<Self>,
4978 ) -> bool {
4979 if let Some(provider) = self.inline_completion_provider() {
4980 provider.discard(should_report_inline_completion_event, cx);
4981 }
4982
4983 self.take_active_inline_completion(cx).is_some()
4984 }
4985
4986 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
4987 if let Some(completion) = self.active_inline_completion.as_ref() {
4988 let buffer = self.buffer.read(cx).read(cx);
4989 completion.position.is_valid(&buffer)
4990 } else {
4991 false
4992 }
4993 }
4994
4995 fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
4996 let completion = self.active_inline_completion.take()?;
4997 self.display_map.update(cx, |map, cx| {
4998 map.splice_inlays(vec![completion.id], Default::default(), cx);
4999 });
5000 let buffer = self.buffer.read(cx).read(cx);
5001
5002 if completion.position.is_valid(&buffer) {
5003 Some(completion)
5004 } else {
5005 None
5006 }
5007 }
5008
5009 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5010 let selection = self.selections.newest_anchor();
5011 let cursor = selection.head();
5012
5013 if self.context_menu.read().is_none()
5014 && self.completion_tasks.is_empty()
5015 && selection.start == selection.end
5016 {
5017 if let Some(provider) = self.inline_completion_provider() {
5018 if let Some((buffer, cursor_buffer_position)) =
5019 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5020 {
5021 if let Some(text) =
5022 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5023 {
5024 let text = Rope::from(text);
5025 let mut to_remove = Vec::new();
5026 if let Some(completion) = self.active_inline_completion.take() {
5027 to_remove.push(completion.id);
5028 }
5029
5030 let completion_inlay =
5031 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5032 self.active_inline_completion = Some(completion_inlay.clone());
5033 self.display_map.update(cx, move |map, cx| {
5034 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5035 });
5036 cx.notify();
5037 return;
5038 }
5039 }
5040 }
5041 }
5042
5043 self.discard_inline_completion(false, cx);
5044 }
5045
5046 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5047 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5048 }
5049
5050 fn render_code_actions_indicator(
5051 &self,
5052 _style: &EditorStyle,
5053 row: DisplayRow,
5054 is_active: bool,
5055 cx: &mut ViewContext<Self>,
5056 ) -> Option<IconButton> {
5057 if self.available_code_actions.is_some() {
5058 Some(
5059 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5060 .shape(ui::IconButtonShape::Square)
5061 .icon_size(IconSize::XSmall)
5062 .icon_color(Color::Muted)
5063 .selected(is_active)
5064 .on_click(cx.listener(move |editor, _e, cx| {
5065 editor.focus(cx);
5066 editor.toggle_code_actions(
5067 &ToggleCodeActions {
5068 deployed_from_indicator: Some(row),
5069 },
5070 cx,
5071 );
5072 })),
5073 )
5074 } else {
5075 None
5076 }
5077 }
5078
5079 fn clear_tasks(&mut self) {
5080 self.tasks.clear()
5081 }
5082
5083 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5084 if let Some(_) = self.tasks.insert(key, value) {
5085 // This case should hopefully be rare, but just in case...
5086 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5087 }
5088 }
5089
5090 fn render_run_indicator(
5091 &self,
5092 _style: &EditorStyle,
5093 is_active: bool,
5094 row: DisplayRow,
5095 cx: &mut ViewContext<Self>,
5096 ) -> IconButton {
5097 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5098 .shape(ui::IconButtonShape::Square)
5099 .icon_size(IconSize::XSmall)
5100 .icon_color(Color::Muted)
5101 .selected(is_active)
5102 .on_click(cx.listener(move |editor, _e, cx| {
5103 editor.focus(cx);
5104 editor.toggle_code_actions(
5105 &ToggleCodeActions {
5106 deployed_from_indicator: Some(row),
5107 },
5108 cx,
5109 );
5110 }))
5111 }
5112
5113 pub fn context_menu_visible(&self) -> bool {
5114 self.context_menu
5115 .read()
5116 .as_ref()
5117 .map_or(false, |menu| menu.visible())
5118 }
5119
5120 fn render_context_menu(
5121 &self,
5122 cursor_position: DisplayPoint,
5123 style: &EditorStyle,
5124 max_height: Pixels,
5125 cx: &mut ViewContext<Editor>,
5126 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5127 self.context_menu.read().as_ref().map(|menu| {
5128 menu.render(
5129 cursor_position,
5130 style,
5131 max_height,
5132 self.workspace.as_ref().map(|(w, _)| w.clone()),
5133 cx,
5134 )
5135 })
5136 }
5137
5138 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5139 cx.notify();
5140 self.completion_tasks.clear();
5141 let context_menu = self.context_menu.write().take();
5142 if context_menu.is_some() {
5143 self.update_visible_inline_completion(cx);
5144 }
5145 context_menu
5146 }
5147
5148 pub fn insert_snippet(
5149 &mut self,
5150 insertion_ranges: &[Range<usize>],
5151 snippet: Snippet,
5152 cx: &mut ViewContext<Self>,
5153 ) -> Result<()> {
5154 struct Tabstop<T> {
5155 is_end_tabstop: bool,
5156 ranges: Vec<Range<T>>,
5157 }
5158
5159 let tabstops = self.buffer.update(cx, |buffer, cx| {
5160 let snippet_text: Arc<str> = snippet.text.clone().into();
5161 buffer.edit(
5162 insertion_ranges
5163 .iter()
5164 .cloned()
5165 .map(|range| (range, snippet_text.clone())),
5166 Some(AutoindentMode::EachLine),
5167 cx,
5168 );
5169
5170 let snapshot = &*buffer.read(cx);
5171 let snippet = &snippet;
5172 snippet
5173 .tabstops
5174 .iter()
5175 .map(|tabstop| {
5176 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5177 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5178 });
5179 let mut tabstop_ranges = tabstop
5180 .iter()
5181 .flat_map(|tabstop_range| {
5182 let mut delta = 0_isize;
5183 insertion_ranges.iter().map(move |insertion_range| {
5184 let insertion_start = insertion_range.start as isize + delta;
5185 delta +=
5186 snippet.text.len() as isize - insertion_range.len() as isize;
5187
5188 let start = ((insertion_start + tabstop_range.start) as usize)
5189 .min(snapshot.len());
5190 let end = ((insertion_start + tabstop_range.end) as usize)
5191 .min(snapshot.len());
5192 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5193 })
5194 })
5195 .collect::<Vec<_>>();
5196 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5197
5198 Tabstop {
5199 is_end_tabstop,
5200 ranges: tabstop_ranges,
5201 }
5202 })
5203 .collect::<Vec<_>>()
5204 });
5205 if let Some(tabstop) = tabstops.first() {
5206 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5207 s.select_ranges(tabstop.ranges.iter().cloned());
5208 });
5209
5210 // If we're already at the last tabstop and it's at the end of the snippet,
5211 // we're done, we don't need to keep the state around.
5212 if !tabstop.is_end_tabstop {
5213 let ranges = tabstops
5214 .into_iter()
5215 .map(|tabstop| tabstop.ranges)
5216 .collect::<Vec<_>>();
5217 self.snippet_stack.push(SnippetState {
5218 active_index: 0,
5219 ranges,
5220 });
5221 }
5222
5223 // Check whether the just-entered snippet ends with an auto-closable bracket.
5224 if self.autoclose_regions.is_empty() {
5225 let snapshot = self.buffer.read(cx).snapshot(cx);
5226 for selection in &mut self.selections.all::<Point>(cx) {
5227 let selection_head = selection.head();
5228 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5229 continue;
5230 };
5231
5232 let mut bracket_pair = None;
5233 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5234 let prev_chars = snapshot
5235 .reversed_chars_at(selection_head)
5236 .collect::<String>();
5237 for (pair, enabled) in scope.brackets() {
5238 if enabled
5239 && pair.close
5240 && prev_chars.starts_with(pair.start.as_str())
5241 && next_chars.starts_with(pair.end.as_str())
5242 {
5243 bracket_pair = Some(pair.clone());
5244 break;
5245 }
5246 }
5247 if let Some(pair) = bracket_pair {
5248 let start = snapshot.anchor_after(selection_head);
5249 let end = snapshot.anchor_after(selection_head);
5250 self.autoclose_regions.push(AutocloseRegion {
5251 selection_id: selection.id,
5252 range: start..end,
5253 pair,
5254 });
5255 }
5256 }
5257 }
5258 }
5259 Ok(())
5260 }
5261
5262 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5263 self.move_to_snippet_tabstop(Bias::Right, cx)
5264 }
5265
5266 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5267 self.move_to_snippet_tabstop(Bias::Left, cx)
5268 }
5269
5270 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5271 if let Some(mut snippet) = self.snippet_stack.pop() {
5272 match bias {
5273 Bias::Left => {
5274 if snippet.active_index > 0 {
5275 snippet.active_index -= 1;
5276 } else {
5277 self.snippet_stack.push(snippet);
5278 return false;
5279 }
5280 }
5281 Bias::Right => {
5282 if snippet.active_index + 1 < snippet.ranges.len() {
5283 snippet.active_index += 1;
5284 } else {
5285 self.snippet_stack.push(snippet);
5286 return false;
5287 }
5288 }
5289 }
5290 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5291 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5292 s.select_anchor_ranges(current_ranges.iter().cloned())
5293 });
5294 // If snippet state is not at the last tabstop, push it back on the stack
5295 if snippet.active_index + 1 < snippet.ranges.len() {
5296 self.snippet_stack.push(snippet);
5297 }
5298 return true;
5299 }
5300 }
5301
5302 false
5303 }
5304
5305 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5306 self.transact(cx, |this, cx| {
5307 this.select_all(&SelectAll, cx);
5308 this.insert("", cx);
5309 });
5310 }
5311
5312 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5313 self.transact(cx, |this, cx| {
5314 this.select_autoclose_pair(cx);
5315 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5316 if !this.linked_edit_ranges.is_empty() {
5317 let selections = this.selections.all::<MultiBufferPoint>(cx);
5318 let snapshot = this.buffer.read(cx).snapshot(cx);
5319
5320 for selection in selections.iter() {
5321 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5322 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5323 if selection_start.buffer_id != selection_end.buffer_id {
5324 continue;
5325 }
5326 if let Some(ranges) =
5327 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5328 {
5329 for (buffer, entries) in ranges {
5330 linked_ranges.entry(buffer).or_default().extend(entries);
5331 }
5332 }
5333 }
5334 }
5335
5336 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5337 if !this.selections.line_mode {
5338 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5339 for selection in &mut selections {
5340 if selection.is_empty() {
5341 let old_head = selection.head();
5342 let mut new_head =
5343 movement::left(&display_map, old_head.to_display_point(&display_map))
5344 .to_point(&display_map);
5345 if let Some((buffer, line_buffer_range)) = display_map
5346 .buffer_snapshot
5347 .buffer_line_for_row(MultiBufferRow(old_head.row))
5348 {
5349 let indent_size =
5350 buffer.indent_size_for_line(line_buffer_range.start.row);
5351 let indent_len = match indent_size.kind {
5352 IndentKind::Space => {
5353 buffer.settings_at(line_buffer_range.start, cx).tab_size
5354 }
5355 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5356 };
5357 if old_head.column <= indent_size.len && old_head.column > 0 {
5358 let indent_len = indent_len.get();
5359 new_head = cmp::min(
5360 new_head,
5361 MultiBufferPoint::new(
5362 old_head.row,
5363 ((old_head.column - 1) / indent_len) * indent_len,
5364 ),
5365 );
5366 }
5367 }
5368
5369 selection.set_head(new_head, SelectionGoal::None);
5370 }
5371 }
5372 }
5373
5374 this.signature_help_state.set_backspace_pressed(true);
5375 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5376 this.insert("", cx);
5377 let empty_str: Arc<str> = Arc::from("");
5378 for (buffer, edits) in linked_ranges {
5379 let snapshot = buffer.read(cx).snapshot();
5380 use text::ToPoint as TP;
5381
5382 let edits = edits
5383 .into_iter()
5384 .map(|range| {
5385 let end_point = TP::to_point(&range.end, &snapshot);
5386 let mut start_point = TP::to_point(&range.start, &snapshot);
5387
5388 if end_point == start_point {
5389 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5390 .saturating_sub(1);
5391 start_point = TP::to_point(&offset, &snapshot);
5392 };
5393
5394 (start_point..end_point, empty_str.clone())
5395 })
5396 .sorted_by_key(|(range, _)| range.start)
5397 .collect::<Vec<_>>();
5398 buffer.update(cx, |this, cx| {
5399 this.edit(edits, None, cx);
5400 })
5401 }
5402 this.refresh_inline_completion(true, cx);
5403 linked_editing_ranges::refresh_linked_ranges(this, cx);
5404 });
5405 }
5406
5407 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5408 self.transact(cx, |this, cx| {
5409 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5410 let line_mode = s.line_mode;
5411 s.move_with(|map, selection| {
5412 if selection.is_empty() && !line_mode {
5413 let cursor = movement::right(map, selection.head());
5414 selection.end = cursor;
5415 selection.reversed = true;
5416 selection.goal = SelectionGoal::None;
5417 }
5418 })
5419 });
5420 this.insert("", cx);
5421 this.refresh_inline_completion(true, cx);
5422 });
5423 }
5424
5425 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5426 if self.move_to_prev_snippet_tabstop(cx) {
5427 return;
5428 }
5429
5430 self.outdent(&Outdent, cx);
5431 }
5432
5433 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5434 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5435 return;
5436 }
5437
5438 let mut selections = self.selections.all_adjusted(cx);
5439 let buffer = self.buffer.read(cx);
5440 let snapshot = buffer.snapshot(cx);
5441 let rows_iter = selections.iter().map(|s| s.head().row);
5442 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5443
5444 let mut edits = Vec::new();
5445 let mut prev_edited_row = 0;
5446 let mut row_delta = 0;
5447 for selection in &mut selections {
5448 if selection.start.row != prev_edited_row {
5449 row_delta = 0;
5450 }
5451 prev_edited_row = selection.end.row;
5452
5453 // If the selection is non-empty, then increase the indentation of the selected lines.
5454 if !selection.is_empty() {
5455 row_delta =
5456 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5457 continue;
5458 }
5459
5460 // If the selection is empty and the cursor is in the leading whitespace before the
5461 // suggested indentation, then auto-indent the line.
5462 let cursor = selection.head();
5463 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5464 if let Some(suggested_indent) =
5465 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5466 {
5467 if cursor.column < suggested_indent.len
5468 && cursor.column <= current_indent.len
5469 && current_indent.len <= suggested_indent.len
5470 {
5471 selection.start = Point::new(cursor.row, suggested_indent.len);
5472 selection.end = selection.start;
5473 if row_delta == 0 {
5474 edits.extend(Buffer::edit_for_indent_size_adjustment(
5475 cursor.row,
5476 current_indent,
5477 suggested_indent,
5478 ));
5479 row_delta = suggested_indent.len - current_indent.len;
5480 }
5481 continue;
5482 }
5483 }
5484
5485 // Otherwise, insert a hard or soft tab.
5486 let settings = buffer.settings_at(cursor, cx);
5487 let tab_size = if settings.hard_tabs {
5488 IndentSize::tab()
5489 } else {
5490 let tab_size = settings.tab_size.get();
5491 let char_column = snapshot
5492 .text_for_range(Point::new(cursor.row, 0)..cursor)
5493 .flat_map(str::chars)
5494 .count()
5495 + row_delta as usize;
5496 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5497 IndentSize::spaces(chars_to_next_tab_stop)
5498 };
5499 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5500 selection.end = selection.start;
5501 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5502 row_delta += tab_size.len;
5503 }
5504
5505 self.transact(cx, |this, cx| {
5506 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5507 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5508 this.refresh_inline_completion(true, cx);
5509 });
5510 }
5511
5512 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5513 if self.read_only(cx) {
5514 return;
5515 }
5516 let mut selections = self.selections.all::<Point>(cx);
5517 let mut prev_edited_row = 0;
5518 let mut row_delta = 0;
5519 let mut edits = Vec::new();
5520 let buffer = self.buffer.read(cx);
5521 let snapshot = buffer.snapshot(cx);
5522 for selection in &mut selections {
5523 if selection.start.row != prev_edited_row {
5524 row_delta = 0;
5525 }
5526 prev_edited_row = selection.end.row;
5527
5528 row_delta =
5529 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5530 }
5531
5532 self.transact(cx, |this, cx| {
5533 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5534 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5535 });
5536 }
5537
5538 fn indent_selection(
5539 buffer: &MultiBuffer,
5540 snapshot: &MultiBufferSnapshot,
5541 selection: &mut Selection<Point>,
5542 edits: &mut Vec<(Range<Point>, String)>,
5543 delta_for_start_row: u32,
5544 cx: &AppContext,
5545 ) -> u32 {
5546 let settings = buffer.settings_at(selection.start, cx);
5547 let tab_size = settings.tab_size.get();
5548 let indent_kind = if settings.hard_tabs {
5549 IndentKind::Tab
5550 } else {
5551 IndentKind::Space
5552 };
5553 let mut start_row = selection.start.row;
5554 let mut end_row = selection.end.row + 1;
5555
5556 // If a selection ends at the beginning of a line, don't indent
5557 // that last line.
5558 if selection.end.column == 0 && selection.end.row > selection.start.row {
5559 end_row -= 1;
5560 }
5561
5562 // Avoid re-indenting a row that has already been indented by a
5563 // previous selection, but still update this selection's column
5564 // to reflect that indentation.
5565 if delta_for_start_row > 0 {
5566 start_row += 1;
5567 selection.start.column += delta_for_start_row;
5568 if selection.end.row == selection.start.row {
5569 selection.end.column += delta_for_start_row;
5570 }
5571 }
5572
5573 let mut delta_for_end_row = 0;
5574 let has_multiple_rows = start_row + 1 != end_row;
5575 for row in start_row..end_row {
5576 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5577 let indent_delta = match (current_indent.kind, indent_kind) {
5578 (IndentKind::Space, IndentKind::Space) => {
5579 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5580 IndentSize::spaces(columns_to_next_tab_stop)
5581 }
5582 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5583 (_, IndentKind::Tab) => IndentSize::tab(),
5584 };
5585
5586 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5587 0
5588 } else {
5589 selection.start.column
5590 };
5591 let row_start = Point::new(row, start);
5592 edits.push((
5593 row_start..row_start,
5594 indent_delta.chars().collect::<String>(),
5595 ));
5596
5597 // Update this selection's endpoints to reflect the indentation.
5598 if row == selection.start.row {
5599 selection.start.column += indent_delta.len;
5600 }
5601 if row == selection.end.row {
5602 selection.end.column += indent_delta.len;
5603 delta_for_end_row = indent_delta.len;
5604 }
5605 }
5606
5607 if selection.start.row == selection.end.row {
5608 delta_for_start_row + delta_for_end_row
5609 } else {
5610 delta_for_end_row
5611 }
5612 }
5613
5614 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5615 if self.read_only(cx) {
5616 return;
5617 }
5618 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5619 let selections = self.selections.all::<Point>(cx);
5620 let mut deletion_ranges = Vec::new();
5621 let mut last_outdent = None;
5622 {
5623 let buffer = self.buffer.read(cx);
5624 let snapshot = buffer.snapshot(cx);
5625 for selection in &selections {
5626 let settings = buffer.settings_at(selection.start, cx);
5627 let tab_size = settings.tab_size.get();
5628 let mut rows = selection.spanned_rows(false, &display_map);
5629
5630 // Avoid re-outdenting a row that has already been outdented by a
5631 // previous selection.
5632 if let Some(last_row) = last_outdent {
5633 if last_row == rows.start {
5634 rows.start = rows.start.next_row();
5635 }
5636 }
5637 let has_multiple_rows = rows.len() > 1;
5638 for row in rows.iter_rows() {
5639 let indent_size = snapshot.indent_size_for_line(row);
5640 if indent_size.len > 0 {
5641 let deletion_len = match indent_size.kind {
5642 IndentKind::Space => {
5643 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5644 if columns_to_prev_tab_stop == 0 {
5645 tab_size
5646 } else {
5647 columns_to_prev_tab_stop
5648 }
5649 }
5650 IndentKind::Tab => 1,
5651 };
5652 let start = if has_multiple_rows
5653 || deletion_len > selection.start.column
5654 || indent_size.len < selection.start.column
5655 {
5656 0
5657 } else {
5658 selection.start.column - deletion_len
5659 };
5660 deletion_ranges.push(
5661 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5662 );
5663 last_outdent = Some(row);
5664 }
5665 }
5666 }
5667 }
5668
5669 self.transact(cx, |this, cx| {
5670 this.buffer.update(cx, |buffer, cx| {
5671 let empty_str: Arc<str> = "".into();
5672 buffer.edit(
5673 deletion_ranges
5674 .into_iter()
5675 .map(|range| (range, empty_str.clone())),
5676 None,
5677 cx,
5678 );
5679 });
5680 let selections = this.selections.all::<usize>(cx);
5681 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5682 });
5683 }
5684
5685 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5686 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5687 let selections = self.selections.all::<Point>(cx);
5688
5689 let mut new_cursors = Vec::new();
5690 let mut edit_ranges = Vec::new();
5691 let mut selections = selections.iter().peekable();
5692 while let Some(selection) = selections.next() {
5693 let mut rows = selection.spanned_rows(false, &display_map);
5694 let goal_display_column = selection.head().to_display_point(&display_map).column();
5695
5696 // Accumulate contiguous regions of rows that we want to delete.
5697 while let Some(next_selection) = selections.peek() {
5698 let next_rows = next_selection.spanned_rows(false, &display_map);
5699 if next_rows.start <= rows.end {
5700 rows.end = next_rows.end;
5701 selections.next().unwrap();
5702 } else {
5703 break;
5704 }
5705 }
5706
5707 let buffer = &display_map.buffer_snapshot;
5708 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5709 let edit_end;
5710 let cursor_buffer_row;
5711 if buffer.max_point().row >= rows.end.0 {
5712 // If there's a line after the range, delete the \n from the end of the row range
5713 // and position the cursor on the next line.
5714 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5715 cursor_buffer_row = rows.end;
5716 } else {
5717 // If there isn't a line after the range, delete the \n from the line before the
5718 // start of the row range and position the cursor there.
5719 edit_start = edit_start.saturating_sub(1);
5720 edit_end = buffer.len();
5721 cursor_buffer_row = rows.start.previous_row();
5722 }
5723
5724 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5725 *cursor.column_mut() =
5726 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5727
5728 new_cursors.push((
5729 selection.id,
5730 buffer.anchor_after(cursor.to_point(&display_map)),
5731 ));
5732 edit_ranges.push(edit_start..edit_end);
5733 }
5734
5735 self.transact(cx, |this, cx| {
5736 let buffer = this.buffer.update(cx, |buffer, cx| {
5737 let empty_str: Arc<str> = "".into();
5738 buffer.edit(
5739 edit_ranges
5740 .into_iter()
5741 .map(|range| (range, empty_str.clone())),
5742 None,
5743 cx,
5744 );
5745 buffer.snapshot(cx)
5746 });
5747 let new_selections = new_cursors
5748 .into_iter()
5749 .map(|(id, cursor)| {
5750 let cursor = cursor.to_point(&buffer);
5751 Selection {
5752 id,
5753 start: cursor,
5754 end: cursor,
5755 reversed: false,
5756 goal: SelectionGoal::None,
5757 }
5758 })
5759 .collect();
5760
5761 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5762 s.select(new_selections);
5763 });
5764 });
5765 }
5766
5767 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5768 if self.read_only(cx) {
5769 return;
5770 }
5771 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5772 for selection in self.selections.all::<Point>(cx) {
5773 let start = MultiBufferRow(selection.start.row);
5774 let end = if selection.start.row == selection.end.row {
5775 MultiBufferRow(selection.start.row + 1)
5776 } else {
5777 MultiBufferRow(selection.end.row)
5778 };
5779
5780 if let Some(last_row_range) = row_ranges.last_mut() {
5781 if start <= last_row_range.end {
5782 last_row_range.end = end;
5783 continue;
5784 }
5785 }
5786 row_ranges.push(start..end);
5787 }
5788
5789 let snapshot = self.buffer.read(cx).snapshot(cx);
5790 let mut cursor_positions = Vec::new();
5791 for row_range in &row_ranges {
5792 let anchor = snapshot.anchor_before(Point::new(
5793 row_range.end.previous_row().0,
5794 snapshot.line_len(row_range.end.previous_row()),
5795 ));
5796 cursor_positions.push(anchor..anchor);
5797 }
5798
5799 self.transact(cx, |this, cx| {
5800 for row_range in row_ranges.into_iter().rev() {
5801 for row in row_range.iter_rows().rev() {
5802 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5803 let next_line_row = row.next_row();
5804 let indent = snapshot.indent_size_for_line(next_line_row);
5805 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5806
5807 let replace = if snapshot.line_len(next_line_row) > indent.len {
5808 " "
5809 } else {
5810 ""
5811 };
5812
5813 this.buffer.update(cx, |buffer, cx| {
5814 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5815 });
5816 }
5817 }
5818
5819 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5820 s.select_anchor_ranges(cursor_positions)
5821 });
5822 });
5823 }
5824
5825 pub fn sort_lines_case_sensitive(
5826 &mut self,
5827 _: &SortLinesCaseSensitive,
5828 cx: &mut ViewContext<Self>,
5829 ) {
5830 self.manipulate_lines(cx, |lines| lines.sort())
5831 }
5832
5833 pub fn sort_lines_case_insensitive(
5834 &mut self,
5835 _: &SortLinesCaseInsensitive,
5836 cx: &mut ViewContext<Self>,
5837 ) {
5838 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5839 }
5840
5841 pub fn unique_lines_case_insensitive(
5842 &mut self,
5843 _: &UniqueLinesCaseInsensitive,
5844 cx: &mut ViewContext<Self>,
5845 ) {
5846 self.manipulate_lines(cx, |lines| {
5847 let mut seen = HashSet::default();
5848 lines.retain(|line| seen.insert(line.to_lowercase()));
5849 })
5850 }
5851
5852 pub fn unique_lines_case_sensitive(
5853 &mut self,
5854 _: &UniqueLinesCaseSensitive,
5855 cx: &mut ViewContext<Self>,
5856 ) {
5857 self.manipulate_lines(cx, |lines| {
5858 let mut seen = HashSet::default();
5859 lines.retain(|line| seen.insert(*line));
5860 })
5861 }
5862
5863 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5864 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5865 if !revert_changes.is_empty() {
5866 self.transact(cx, |editor, cx| {
5867 editor.buffer().update(cx, |multi_buffer, cx| {
5868 for (buffer_id, changes) in revert_changes {
5869 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
5870 buffer.update(cx, |buffer, cx| {
5871 buffer.edit(
5872 changes.into_iter().map(|(range, text)| {
5873 (range, text.to_string().map(Arc::<str>::from))
5874 }),
5875 None,
5876 cx,
5877 );
5878 });
5879 }
5880 }
5881 });
5882 editor.change_selections(None, cx, |selections| selections.refresh());
5883 });
5884 }
5885 }
5886
5887 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5888 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5889 let project_path = buffer.read(cx).project_path(cx)?;
5890 let project = self.project.as_ref()?.read(cx);
5891 let entry = project.entry_for_path(&project_path, cx)?;
5892 let abs_path = project.absolute_path(&project_path, cx)?;
5893 let parent = if entry.is_symlink {
5894 abs_path.canonicalize().ok()?
5895 } else {
5896 abs_path
5897 }
5898 .parent()?
5899 .to_path_buf();
5900 Some(parent)
5901 }) {
5902 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5903 }
5904 }
5905
5906 fn gather_revert_changes(
5907 &mut self,
5908 selections: &[Selection<Anchor>],
5909 cx: &mut ViewContext<'_, Editor>,
5910 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5911 let mut revert_changes = HashMap::default();
5912 self.buffer.update(cx, |multi_buffer, cx| {
5913 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
5914 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
5915 Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
5916 }
5917 });
5918 revert_changes
5919 }
5920
5921 fn prepare_revert_change(
5922 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5923 multi_buffer: &MultiBuffer,
5924 hunk: &DiffHunk<MultiBufferRow>,
5925 cx: &mut AppContext,
5926 ) -> Option<()> {
5927 let buffer = multi_buffer.buffer(hunk.buffer_id)?;
5928 let buffer = buffer.read(cx);
5929 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
5930 let buffer_snapshot = buffer.snapshot();
5931 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5932 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5933 probe
5934 .0
5935 .start
5936 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5937 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5938 }) {
5939 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5940 Some(())
5941 } else {
5942 None
5943 }
5944 }
5945
5946 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5947 self.manipulate_lines(cx, |lines| lines.reverse())
5948 }
5949
5950 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5951 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5952 }
5953
5954 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5955 where
5956 Fn: FnMut(&mut Vec<&str>),
5957 {
5958 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5959 let buffer = self.buffer.read(cx).snapshot(cx);
5960
5961 let mut edits = Vec::new();
5962
5963 let selections = self.selections.all::<Point>(cx);
5964 let mut selections = selections.iter().peekable();
5965 let mut contiguous_row_selections = Vec::new();
5966 let mut new_selections = Vec::new();
5967 let mut added_lines = 0;
5968 let mut removed_lines = 0;
5969
5970 while let Some(selection) = selections.next() {
5971 let (start_row, end_row) = consume_contiguous_rows(
5972 &mut contiguous_row_selections,
5973 selection,
5974 &display_map,
5975 &mut selections,
5976 );
5977
5978 let start_point = Point::new(start_row.0, 0);
5979 let end_point = Point::new(
5980 end_row.previous_row().0,
5981 buffer.line_len(end_row.previous_row()),
5982 );
5983 let text = buffer
5984 .text_for_range(start_point..end_point)
5985 .collect::<String>();
5986
5987 let mut lines = text.split('\n').collect_vec();
5988
5989 let lines_before = lines.len();
5990 callback(&mut lines);
5991 let lines_after = lines.len();
5992
5993 edits.push((start_point..end_point, lines.join("\n")));
5994
5995 // Selections must change based on added and removed line count
5996 let start_row =
5997 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
5998 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
5999 new_selections.push(Selection {
6000 id: selection.id,
6001 start: start_row,
6002 end: end_row,
6003 goal: SelectionGoal::None,
6004 reversed: selection.reversed,
6005 });
6006
6007 if lines_after > lines_before {
6008 added_lines += lines_after - lines_before;
6009 } else if lines_before > lines_after {
6010 removed_lines += lines_before - lines_after;
6011 }
6012 }
6013
6014 self.transact(cx, |this, cx| {
6015 let buffer = this.buffer.update(cx, |buffer, cx| {
6016 buffer.edit(edits, None, cx);
6017 buffer.snapshot(cx)
6018 });
6019
6020 // Recalculate offsets on newly edited buffer
6021 let new_selections = new_selections
6022 .iter()
6023 .map(|s| {
6024 let start_point = Point::new(s.start.0, 0);
6025 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6026 Selection {
6027 id: s.id,
6028 start: buffer.point_to_offset(start_point),
6029 end: buffer.point_to_offset(end_point),
6030 goal: s.goal,
6031 reversed: s.reversed,
6032 }
6033 })
6034 .collect();
6035
6036 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6037 s.select(new_selections);
6038 });
6039
6040 this.request_autoscroll(Autoscroll::fit(), cx);
6041 });
6042 }
6043
6044 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6045 self.manipulate_text(cx, |text| text.to_uppercase())
6046 }
6047
6048 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6049 self.manipulate_text(cx, |text| text.to_lowercase())
6050 }
6051
6052 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6053 self.manipulate_text(cx, |text| {
6054 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6055 // https://github.com/rutrum/convert-case/issues/16
6056 text.split('\n')
6057 .map(|line| line.to_case(Case::Title))
6058 .join("\n")
6059 })
6060 }
6061
6062 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6063 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6064 }
6065
6066 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6067 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6068 }
6069
6070 pub fn convert_to_upper_camel_case(
6071 &mut self,
6072 _: &ConvertToUpperCamelCase,
6073 cx: &mut ViewContext<Self>,
6074 ) {
6075 self.manipulate_text(cx, |text| {
6076 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6077 // https://github.com/rutrum/convert-case/issues/16
6078 text.split('\n')
6079 .map(|line| line.to_case(Case::UpperCamel))
6080 .join("\n")
6081 })
6082 }
6083
6084 pub fn convert_to_lower_camel_case(
6085 &mut self,
6086 _: &ConvertToLowerCamelCase,
6087 cx: &mut ViewContext<Self>,
6088 ) {
6089 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6090 }
6091
6092 pub fn convert_to_opposite_case(
6093 &mut self,
6094 _: &ConvertToOppositeCase,
6095 cx: &mut ViewContext<Self>,
6096 ) {
6097 self.manipulate_text(cx, |text| {
6098 text.chars()
6099 .fold(String::with_capacity(text.len()), |mut t, c| {
6100 if c.is_uppercase() {
6101 t.extend(c.to_lowercase());
6102 } else {
6103 t.extend(c.to_uppercase());
6104 }
6105 t
6106 })
6107 })
6108 }
6109
6110 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6111 where
6112 Fn: FnMut(&str) -> String,
6113 {
6114 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6115 let buffer = self.buffer.read(cx).snapshot(cx);
6116
6117 let mut new_selections = Vec::new();
6118 let mut edits = Vec::new();
6119 let mut selection_adjustment = 0i32;
6120
6121 for selection in self.selections.all::<usize>(cx) {
6122 let selection_is_empty = selection.is_empty();
6123
6124 let (start, end) = if selection_is_empty {
6125 let word_range = movement::surrounding_word(
6126 &display_map,
6127 selection.start.to_display_point(&display_map),
6128 );
6129 let start = word_range.start.to_offset(&display_map, Bias::Left);
6130 let end = word_range.end.to_offset(&display_map, Bias::Left);
6131 (start, end)
6132 } else {
6133 (selection.start, selection.end)
6134 };
6135
6136 let text = buffer.text_for_range(start..end).collect::<String>();
6137 let old_length = text.len() as i32;
6138 let text = callback(&text);
6139
6140 new_selections.push(Selection {
6141 start: (start as i32 - selection_adjustment) as usize,
6142 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6143 goal: SelectionGoal::None,
6144 ..selection
6145 });
6146
6147 selection_adjustment += old_length - text.len() as i32;
6148
6149 edits.push((start..end, text));
6150 }
6151
6152 self.transact(cx, |this, cx| {
6153 this.buffer.update(cx, |buffer, cx| {
6154 buffer.edit(edits, None, cx);
6155 });
6156
6157 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6158 s.select(new_selections);
6159 });
6160
6161 this.request_autoscroll(Autoscroll::fit(), cx);
6162 });
6163 }
6164
6165 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6166 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6167 let buffer = &display_map.buffer_snapshot;
6168 let selections = self.selections.all::<Point>(cx);
6169
6170 let mut edits = Vec::new();
6171 let mut selections_iter = selections.iter().peekable();
6172 while let Some(selection) = selections_iter.next() {
6173 // Avoid duplicating the same lines twice.
6174 let mut rows = selection.spanned_rows(false, &display_map);
6175
6176 while let Some(next_selection) = selections_iter.peek() {
6177 let next_rows = next_selection.spanned_rows(false, &display_map);
6178 if next_rows.start < rows.end {
6179 rows.end = next_rows.end;
6180 selections_iter.next().unwrap();
6181 } else {
6182 break;
6183 }
6184 }
6185
6186 // Copy the text from the selected row region and splice it either at the start
6187 // or end of the region.
6188 let start = Point::new(rows.start.0, 0);
6189 let end = Point::new(
6190 rows.end.previous_row().0,
6191 buffer.line_len(rows.end.previous_row()),
6192 );
6193 let text = buffer
6194 .text_for_range(start..end)
6195 .chain(Some("\n"))
6196 .collect::<String>();
6197 let insert_location = if upwards {
6198 Point::new(rows.end.0, 0)
6199 } else {
6200 start
6201 };
6202 edits.push((insert_location..insert_location, text));
6203 }
6204
6205 self.transact(cx, |this, cx| {
6206 this.buffer.update(cx, |buffer, cx| {
6207 buffer.edit(edits, None, cx);
6208 });
6209
6210 this.request_autoscroll(Autoscroll::fit(), cx);
6211 });
6212 }
6213
6214 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6215 self.duplicate_line(true, cx);
6216 }
6217
6218 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6219 self.duplicate_line(false, cx);
6220 }
6221
6222 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6224 let buffer = self.buffer.read(cx).snapshot(cx);
6225
6226 let mut edits = Vec::new();
6227 let mut unfold_ranges = Vec::new();
6228 let mut refold_ranges = Vec::new();
6229
6230 let selections = self.selections.all::<Point>(cx);
6231 let mut selections = selections.iter().peekable();
6232 let mut contiguous_row_selections = Vec::new();
6233 let mut new_selections = Vec::new();
6234
6235 while let Some(selection) = selections.next() {
6236 // Find all the selections that span a contiguous row range
6237 let (start_row, end_row) = consume_contiguous_rows(
6238 &mut contiguous_row_selections,
6239 selection,
6240 &display_map,
6241 &mut selections,
6242 );
6243
6244 // Move the text spanned by the row range to be before the line preceding the row range
6245 if start_row.0 > 0 {
6246 let range_to_move = Point::new(
6247 start_row.previous_row().0,
6248 buffer.line_len(start_row.previous_row()),
6249 )
6250 ..Point::new(
6251 end_row.previous_row().0,
6252 buffer.line_len(end_row.previous_row()),
6253 );
6254 let insertion_point = display_map
6255 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6256 .0;
6257
6258 // Don't move lines across excerpts
6259 if buffer
6260 .excerpt_boundaries_in_range((
6261 Bound::Excluded(insertion_point),
6262 Bound::Included(range_to_move.end),
6263 ))
6264 .next()
6265 .is_none()
6266 {
6267 let text = buffer
6268 .text_for_range(range_to_move.clone())
6269 .flat_map(|s| s.chars())
6270 .skip(1)
6271 .chain(['\n'])
6272 .collect::<String>();
6273
6274 edits.push((
6275 buffer.anchor_after(range_to_move.start)
6276 ..buffer.anchor_before(range_to_move.end),
6277 String::new(),
6278 ));
6279 let insertion_anchor = buffer.anchor_after(insertion_point);
6280 edits.push((insertion_anchor..insertion_anchor, text));
6281
6282 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6283
6284 // Move selections up
6285 new_selections.extend(contiguous_row_selections.drain(..).map(
6286 |mut selection| {
6287 selection.start.row -= row_delta;
6288 selection.end.row -= row_delta;
6289 selection
6290 },
6291 ));
6292
6293 // Move folds up
6294 unfold_ranges.push(range_to_move.clone());
6295 for fold in display_map.folds_in_range(
6296 buffer.anchor_before(range_to_move.start)
6297 ..buffer.anchor_after(range_to_move.end),
6298 ) {
6299 let mut start = fold.range.start.to_point(&buffer);
6300 let mut end = fold.range.end.to_point(&buffer);
6301 start.row -= row_delta;
6302 end.row -= row_delta;
6303 refold_ranges.push((start..end, fold.placeholder.clone()));
6304 }
6305 }
6306 }
6307
6308 // If we didn't move line(s), preserve the existing selections
6309 new_selections.append(&mut contiguous_row_selections);
6310 }
6311
6312 self.transact(cx, |this, cx| {
6313 this.unfold_ranges(unfold_ranges, true, true, cx);
6314 this.buffer.update(cx, |buffer, cx| {
6315 for (range, text) in edits {
6316 buffer.edit([(range, text)], None, cx);
6317 }
6318 });
6319 this.fold_ranges(refold_ranges, true, cx);
6320 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6321 s.select(new_selections);
6322 })
6323 });
6324 }
6325
6326 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6327 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6328 let buffer = self.buffer.read(cx).snapshot(cx);
6329
6330 let mut edits = Vec::new();
6331 let mut unfold_ranges = Vec::new();
6332 let mut refold_ranges = Vec::new();
6333
6334 let selections = self.selections.all::<Point>(cx);
6335 let mut selections = selections.iter().peekable();
6336 let mut contiguous_row_selections = Vec::new();
6337 let mut new_selections = Vec::new();
6338
6339 while let Some(selection) = selections.next() {
6340 // Find all the selections that span a contiguous row range
6341 let (start_row, end_row) = consume_contiguous_rows(
6342 &mut contiguous_row_selections,
6343 selection,
6344 &display_map,
6345 &mut selections,
6346 );
6347
6348 // Move the text spanned by the row range to be after the last line of the row range
6349 if end_row.0 <= buffer.max_point().row {
6350 let range_to_move =
6351 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6352 let insertion_point = display_map
6353 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6354 .0;
6355
6356 // Don't move lines across excerpt boundaries
6357 if buffer
6358 .excerpt_boundaries_in_range((
6359 Bound::Excluded(range_to_move.start),
6360 Bound::Included(insertion_point),
6361 ))
6362 .next()
6363 .is_none()
6364 {
6365 let mut text = String::from("\n");
6366 text.extend(buffer.text_for_range(range_to_move.clone()));
6367 text.pop(); // Drop trailing newline
6368 edits.push((
6369 buffer.anchor_after(range_to_move.start)
6370 ..buffer.anchor_before(range_to_move.end),
6371 String::new(),
6372 ));
6373 let insertion_anchor = buffer.anchor_after(insertion_point);
6374 edits.push((insertion_anchor..insertion_anchor, text));
6375
6376 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6377
6378 // Move selections down
6379 new_selections.extend(contiguous_row_selections.drain(..).map(
6380 |mut selection| {
6381 selection.start.row += row_delta;
6382 selection.end.row += row_delta;
6383 selection
6384 },
6385 ));
6386
6387 // Move folds down
6388 unfold_ranges.push(range_to_move.clone());
6389 for fold in display_map.folds_in_range(
6390 buffer.anchor_before(range_to_move.start)
6391 ..buffer.anchor_after(range_to_move.end),
6392 ) {
6393 let mut start = fold.range.start.to_point(&buffer);
6394 let mut end = fold.range.end.to_point(&buffer);
6395 start.row += row_delta;
6396 end.row += row_delta;
6397 refold_ranges.push((start..end, fold.placeholder.clone()));
6398 }
6399 }
6400 }
6401
6402 // If we didn't move line(s), preserve the existing selections
6403 new_selections.append(&mut contiguous_row_selections);
6404 }
6405
6406 self.transact(cx, |this, cx| {
6407 this.unfold_ranges(unfold_ranges, true, true, cx);
6408 this.buffer.update(cx, |buffer, cx| {
6409 for (range, text) in edits {
6410 buffer.edit([(range, text)], None, cx);
6411 }
6412 });
6413 this.fold_ranges(refold_ranges, true, cx);
6414 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6415 });
6416 }
6417
6418 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6419 let text_layout_details = &self.text_layout_details(cx);
6420 self.transact(cx, |this, cx| {
6421 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6422 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6423 let line_mode = s.line_mode;
6424 s.move_with(|display_map, selection| {
6425 if !selection.is_empty() || line_mode {
6426 return;
6427 }
6428
6429 let mut head = selection.head();
6430 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6431 if head.column() == display_map.line_len(head.row()) {
6432 transpose_offset = display_map
6433 .buffer_snapshot
6434 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6435 }
6436
6437 if transpose_offset == 0 {
6438 return;
6439 }
6440
6441 *head.column_mut() += 1;
6442 head = display_map.clip_point(head, Bias::Right);
6443 let goal = SelectionGoal::HorizontalPosition(
6444 display_map
6445 .x_for_display_point(head, &text_layout_details)
6446 .into(),
6447 );
6448 selection.collapse_to(head, goal);
6449
6450 let transpose_start = display_map
6451 .buffer_snapshot
6452 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6453 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6454 let transpose_end = display_map
6455 .buffer_snapshot
6456 .clip_offset(transpose_offset + 1, Bias::Right);
6457 if let Some(ch) =
6458 display_map.buffer_snapshot.chars_at(transpose_start).next()
6459 {
6460 edits.push((transpose_start..transpose_offset, String::new()));
6461 edits.push((transpose_end..transpose_end, ch.to_string()));
6462 }
6463 }
6464 });
6465 edits
6466 });
6467 this.buffer
6468 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6469 let selections = this.selections.all::<usize>(cx);
6470 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6471 s.select(selections);
6472 });
6473 });
6474 }
6475
6476 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6477 let mut text = String::new();
6478 let buffer = self.buffer.read(cx).snapshot(cx);
6479 let mut selections = self.selections.all::<Point>(cx);
6480 let mut clipboard_selections = Vec::with_capacity(selections.len());
6481 {
6482 let max_point = buffer.max_point();
6483 let mut is_first = true;
6484 for selection in &mut selections {
6485 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6486 if is_entire_line {
6487 selection.start = Point::new(selection.start.row, 0);
6488 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6489 selection.goal = SelectionGoal::None;
6490 }
6491 if is_first {
6492 is_first = false;
6493 } else {
6494 text += "\n";
6495 }
6496 let mut len = 0;
6497 for chunk in buffer.text_for_range(selection.start..selection.end) {
6498 text.push_str(chunk);
6499 len += chunk.len();
6500 }
6501 clipboard_selections.push(ClipboardSelection {
6502 len,
6503 is_entire_line,
6504 first_line_indent: buffer
6505 .indent_size_for_line(MultiBufferRow(selection.start.row))
6506 .len,
6507 });
6508 }
6509 }
6510
6511 self.transact(cx, |this, cx| {
6512 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6513 s.select(selections);
6514 });
6515 this.insert("", cx);
6516 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6517 });
6518 }
6519
6520 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6521 let selections = self.selections.all::<Point>(cx);
6522 let buffer = self.buffer.read(cx).read(cx);
6523 let mut text = String::new();
6524
6525 let mut clipboard_selections = Vec::with_capacity(selections.len());
6526 {
6527 let max_point = buffer.max_point();
6528 let mut is_first = true;
6529 for selection in selections.iter() {
6530 let mut start = selection.start;
6531 let mut end = selection.end;
6532 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6533 if is_entire_line {
6534 start = Point::new(start.row, 0);
6535 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6536 }
6537 if is_first {
6538 is_first = false;
6539 } else {
6540 text += "\n";
6541 }
6542 let mut len = 0;
6543 for chunk in buffer.text_for_range(start..end) {
6544 text.push_str(chunk);
6545 len += chunk.len();
6546 }
6547 clipboard_selections.push(ClipboardSelection {
6548 len,
6549 is_entire_line,
6550 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6551 });
6552 }
6553 }
6554
6555 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6556 }
6557
6558 pub fn do_paste(
6559 &mut self,
6560 text: &String,
6561 clipboard_selections: Option<Vec<ClipboardSelection>>,
6562 handle_entire_lines: bool,
6563 cx: &mut ViewContext<Self>,
6564 ) {
6565 if self.read_only(cx) {
6566 return;
6567 }
6568
6569 let clipboard_text = Cow::Borrowed(text);
6570
6571 self.transact(cx, |this, cx| {
6572 if let Some(mut clipboard_selections) = clipboard_selections {
6573 let old_selections = this.selections.all::<usize>(cx);
6574 let all_selections_were_entire_line =
6575 clipboard_selections.iter().all(|s| s.is_entire_line);
6576 let first_selection_indent_column =
6577 clipboard_selections.first().map(|s| s.first_line_indent);
6578 if clipboard_selections.len() != old_selections.len() {
6579 clipboard_selections.drain(..);
6580 }
6581
6582 this.buffer.update(cx, |buffer, cx| {
6583 let snapshot = buffer.read(cx);
6584 let mut start_offset = 0;
6585 let mut edits = Vec::new();
6586 let mut original_indent_columns = Vec::new();
6587 for (ix, selection) in old_selections.iter().enumerate() {
6588 let to_insert;
6589 let entire_line;
6590 let original_indent_column;
6591 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6592 let end_offset = start_offset + clipboard_selection.len;
6593 to_insert = &clipboard_text[start_offset..end_offset];
6594 entire_line = clipboard_selection.is_entire_line;
6595 start_offset = end_offset + 1;
6596 original_indent_column = Some(clipboard_selection.first_line_indent);
6597 } else {
6598 to_insert = clipboard_text.as_str();
6599 entire_line = all_selections_were_entire_line;
6600 original_indent_column = first_selection_indent_column
6601 }
6602
6603 // If the corresponding selection was empty when this slice of the
6604 // clipboard text was written, then the entire line containing the
6605 // selection was copied. If this selection is also currently empty,
6606 // then paste the line before the current line of the buffer.
6607 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6608 let column = selection.start.to_point(&snapshot).column as usize;
6609 let line_start = selection.start - column;
6610 line_start..line_start
6611 } else {
6612 selection.range()
6613 };
6614
6615 edits.push((range, to_insert));
6616 original_indent_columns.extend(original_indent_column);
6617 }
6618 drop(snapshot);
6619
6620 buffer.edit(
6621 edits,
6622 Some(AutoindentMode::Block {
6623 original_indent_columns,
6624 }),
6625 cx,
6626 );
6627 });
6628
6629 let selections = this.selections.all::<usize>(cx);
6630 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6631 } else {
6632 this.insert(&clipboard_text, cx);
6633 }
6634 });
6635 }
6636
6637 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6638 if let Some(item) = cx.read_from_clipboard() {
6639 self.do_paste(
6640 item.text(),
6641 item.metadata::<Vec<ClipboardSelection>>(),
6642 true,
6643 cx,
6644 )
6645 };
6646 }
6647
6648 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6649 if self.read_only(cx) {
6650 return;
6651 }
6652
6653 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6654 if let Some((selections, _)) =
6655 self.selection_history.transaction(transaction_id).cloned()
6656 {
6657 self.change_selections(None, cx, |s| {
6658 s.select_anchors(selections.to_vec());
6659 });
6660 }
6661 self.request_autoscroll(Autoscroll::fit(), cx);
6662 self.unmark_text(cx);
6663 self.refresh_inline_completion(true, cx);
6664 cx.emit(EditorEvent::Edited { transaction_id });
6665 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6666 }
6667 }
6668
6669 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6670 if self.read_only(cx) {
6671 return;
6672 }
6673
6674 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6675 if let Some((_, Some(selections))) =
6676 self.selection_history.transaction(transaction_id).cloned()
6677 {
6678 self.change_selections(None, cx, |s| {
6679 s.select_anchors(selections.to_vec());
6680 });
6681 }
6682 self.request_autoscroll(Autoscroll::fit(), cx);
6683 self.unmark_text(cx);
6684 self.refresh_inline_completion(true, cx);
6685 cx.emit(EditorEvent::Edited { transaction_id });
6686 }
6687 }
6688
6689 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6690 self.buffer
6691 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6692 }
6693
6694 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6695 self.buffer
6696 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6697 }
6698
6699 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6700 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6701 let line_mode = s.line_mode;
6702 s.move_with(|map, selection| {
6703 let cursor = if selection.is_empty() && !line_mode {
6704 movement::left(map, selection.start)
6705 } else {
6706 selection.start
6707 };
6708 selection.collapse_to(cursor, SelectionGoal::None);
6709 });
6710 })
6711 }
6712
6713 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6714 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6715 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6716 })
6717 }
6718
6719 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6720 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6721 let line_mode = s.line_mode;
6722 s.move_with(|map, selection| {
6723 let cursor = if selection.is_empty() && !line_mode {
6724 movement::right(map, selection.end)
6725 } else {
6726 selection.end
6727 };
6728 selection.collapse_to(cursor, SelectionGoal::None)
6729 });
6730 })
6731 }
6732
6733 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6734 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6735 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6736 })
6737 }
6738
6739 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6740 if self.take_rename(true, cx).is_some() {
6741 return;
6742 }
6743
6744 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6745 cx.propagate();
6746 return;
6747 }
6748
6749 let text_layout_details = &self.text_layout_details(cx);
6750 let selection_count = self.selections.count();
6751 let first_selection = self.selections.first_anchor();
6752
6753 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6754 let line_mode = s.line_mode;
6755 s.move_with(|map, selection| {
6756 if !selection.is_empty() && !line_mode {
6757 selection.goal = SelectionGoal::None;
6758 }
6759 let (cursor, goal) = movement::up(
6760 map,
6761 selection.start,
6762 selection.goal,
6763 false,
6764 &text_layout_details,
6765 );
6766 selection.collapse_to(cursor, goal);
6767 });
6768 });
6769
6770 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6771 {
6772 cx.propagate();
6773 }
6774 }
6775
6776 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6777 if self.take_rename(true, cx).is_some() {
6778 return;
6779 }
6780
6781 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6782 cx.propagate();
6783 return;
6784 }
6785
6786 let text_layout_details = &self.text_layout_details(cx);
6787
6788 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6789 let line_mode = s.line_mode;
6790 s.move_with(|map, selection| {
6791 if !selection.is_empty() && !line_mode {
6792 selection.goal = SelectionGoal::None;
6793 }
6794 let (cursor, goal) = movement::up_by_rows(
6795 map,
6796 selection.start,
6797 action.lines,
6798 selection.goal,
6799 false,
6800 &text_layout_details,
6801 );
6802 selection.collapse_to(cursor, goal);
6803 });
6804 })
6805 }
6806
6807 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6808 if self.take_rename(true, cx).is_some() {
6809 return;
6810 }
6811
6812 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6813 cx.propagate();
6814 return;
6815 }
6816
6817 let text_layout_details = &self.text_layout_details(cx);
6818
6819 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6820 let line_mode = s.line_mode;
6821 s.move_with(|map, selection| {
6822 if !selection.is_empty() && !line_mode {
6823 selection.goal = SelectionGoal::None;
6824 }
6825 let (cursor, goal) = movement::down_by_rows(
6826 map,
6827 selection.start,
6828 action.lines,
6829 selection.goal,
6830 false,
6831 &text_layout_details,
6832 );
6833 selection.collapse_to(cursor, goal);
6834 });
6835 })
6836 }
6837
6838 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6839 let text_layout_details = &self.text_layout_details(cx);
6840 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6841 s.move_heads_with(|map, head, goal| {
6842 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6843 })
6844 })
6845 }
6846
6847 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6848 let text_layout_details = &self.text_layout_details(cx);
6849 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6850 s.move_heads_with(|map, head, goal| {
6851 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6852 })
6853 })
6854 }
6855
6856 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6857 let Some(row_count) = self.visible_row_count() else {
6858 return;
6859 };
6860
6861 let text_layout_details = &self.text_layout_details(cx);
6862
6863 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6864 s.move_heads_with(|map, head, goal| {
6865 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6866 })
6867 })
6868 }
6869
6870 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6871 if self.take_rename(true, cx).is_some() {
6872 return;
6873 }
6874
6875 if self
6876 .context_menu
6877 .write()
6878 .as_mut()
6879 .map(|menu| menu.select_first(self.project.as_ref(), cx))
6880 .unwrap_or(false)
6881 {
6882 return;
6883 }
6884
6885 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6886 cx.propagate();
6887 return;
6888 }
6889
6890 let Some(row_count) = self.visible_row_count() else {
6891 return;
6892 };
6893
6894 let autoscroll = if action.center_cursor {
6895 Autoscroll::center()
6896 } else {
6897 Autoscroll::fit()
6898 };
6899
6900 let text_layout_details = &self.text_layout_details(cx);
6901
6902 self.change_selections(Some(autoscroll), cx, |s| {
6903 let line_mode = s.line_mode;
6904 s.move_with(|map, selection| {
6905 if !selection.is_empty() && !line_mode {
6906 selection.goal = SelectionGoal::None;
6907 }
6908 let (cursor, goal) = movement::up_by_rows(
6909 map,
6910 selection.end,
6911 row_count,
6912 selection.goal,
6913 false,
6914 &text_layout_details,
6915 );
6916 selection.collapse_to(cursor, goal);
6917 });
6918 });
6919 }
6920
6921 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
6922 let text_layout_details = &self.text_layout_details(cx);
6923 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6924 s.move_heads_with(|map, head, goal| {
6925 movement::up(map, head, goal, false, &text_layout_details)
6926 })
6927 })
6928 }
6929
6930 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
6931 self.take_rename(true, cx);
6932
6933 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6934 cx.propagate();
6935 return;
6936 }
6937
6938 let text_layout_details = &self.text_layout_details(cx);
6939 let selection_count = self.selections.count();
6940 let first_selection = self.selections.first_anchor();
6941
6942 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6943 let line_mode = s.line_mode;
6944 s.move_with(|map, selection| {
6945 if !selection.is_empty() && !line_mode {
6946 selection.goal = SelectionGoal::None;
6947 }
6948 let (cursor, goal) = movement::down(
6949 map,
6950 selection.end,
6951 selection.goal,
6952 false,
6953 &text_layout_details,
6954 );
6955 selection.collapse_to(cursor, goal);
6956 });
6957 });
6958
6959 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6960 {
6961 cx.propagate();
6962 }
6963 }
6964
6965 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
6966 let Some(row_count) = self.visible_row_count() else {
6967 return;
6968 };
6969
6970 let text_layout_details = &self.text_layout_details(cx);
6971
6972 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6973 s.move_heads_with(|map, head, goal| {
6974 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
6975 })
6976 })
6977 }
6978
6979 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
6980 if self.take_rename(true, cx).is_some() {
6981 return;
6982 }
6983
6984 if self
6985 .context_menu
6986 .write()
6987 .as_mut()
6988 .map(|menu| menu.select_last(self.project.as_ref(), cx))
6989 .unwrap_or(false)
6990 {
6991 return;
6992 }
6993
6994 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6995 cx.propagate();
6996 return;
6997 }
6998
6999 let Some(row_count) = self.visible_row_count() else {
7000 return;
7001 };
7002
7003 let autoscroll = if action.center_cursor {
7004 Autoscroll::center()
7005 } else {
7006 Autoscroll::fit()
7007 };
7008
7009 let text_layout_details = &self.text_layout_details(cx);
7010 self.change_selections(Some(autoscroll), cx, |s| {
7011 let line_mode = s.line_mode;
7012 s.move_with(|map, selection| {
7013 if !selection.is_empty() && !line_mode {
7014 selection.goal = SelectionGoal::None;
7015 }
7016 let (cursor, goal) = movement::down_by_rows(
7017 map,
7018 selection.end,
7019 row_count,
7020 selection.goal,
7021 false,
7022 &text_layout_details,
7023 );
7024 selection.collapse_to(cursor, goal);
7025 });
7026 });
7027 }
7028
7029 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7030 let text_layout_details = &self.text_layout_details(cx);
7031 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7032 s.move_heads_with(|map, head, goal| {
7033 movement::down(map, head, goal, false, &text_layout_details)
7034 })
7035 });
7036 }
7037
7038 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7039 if let Some(context_menu) = self.context_menu.write().as_mut() {
7040 context_menu.select_first(self.project.as_ref(), cx);
7041 }
7042 }
7043
7044 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7045 if let Some(context_menu) = self.context_menu.write().as_mut() {
7046 context_menu.select_prev(self.project.as_ref(), cx);
7047 }
7048 }
7049
7050 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7051 if let Some(context_menu) = self.context_menu.write().as_mut() {
7052 context_menu.select_next(self.project.as_ref(), cx);
7053 }
7054 }
7055
7056 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7057 if let Some(context_menu) = self.context_menu.write().as_mut() {
7058 context_menu.select_last(self.project.as_ref(), cx);
7059 }
7060 }
7061
7062 pub fn move_to_previous_word_start(
7063 &mut self,
7064 _: &MoveToPreviousWordStart,
7065 cx: &mut ViewContext<Self>,
7066 ) {
7067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7068 s.move_cursors_with(|map, head, _| {
7069 (
7070 movement::previous_word_start(map, head),
7071 SelectionGoal::None,
7072 )
7073 });
7074 })
7075 }
7076
7077 pub fn move_to_previous_subword_start(
7078 &mut self,
7079 _: &MoveToPreviousSubwordStart,
7080 cx: &mut ViewContext<Self>,
7081 ) {
7082 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7083 s.move_cursors_with(|map, head, _| {
7084 (
7085 movement::previous_subword_start(map, head),
7086 SelectionGoal::None,
7087 )
7088 });
7089 })
7090 }
7091
7092 pub fn select_to_previous_word_start(
7093 &mut self,
7094 _: &SelectToPreviousWordStart,
7095 cx: &mut ViewContext<Self>,
7096 ) {
7097 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7098 s.move_heads_with(|map, head, _| {
7099 (
7100 movement::previous_word_start(map, head),
7101 SelectionGoal::None,
7102 )
7103 });
7104 })
7105 }
7106
7107 pub fn select_to_previous_subword_start(
7108 &mut self,
7109 _: &SelectToPreviousSubwordStart,
7110 cx: &mut ViewContext<Self>,
7111 ) {
7112 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7113 s.move_heads_with(|map, head, _| {
7114 (
7115 movement::previous_subword_start(map, head),
7116 SelectionGoal::None,
7117 )
7118 });
7119 })
7120 }
7121
7122 pub fn delete_to_previous_word_start(
7123 &mut self,
7124 _: &DeleteToPreviousWordStart,
7125 cx: &mut ViewContext<Self>,
7126 ) {
7127 self.transact(cx, |this, cx| {
7128 this.select_autoclose_pair(cx);
7129 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7130 let line_mode = s.line_mode;
7131 s.move_with(|map, selection| {
7132 if selection.is_empty() && !line_mode {
7133 let cursor = movement::previous_word_start(map, selection.head());
7134 selection.set_head(cursor, SelectionGoal::None);
7135 }
7136 });
7137 });
7138 this.insert("", cx);
7139 });
7140 }
7141
7142 pub fn delete_to_previous_subword_start(
7143 &mut self,
7144 _: &DeleteToPreviousSubwordStart,
7145 cx: &mut ViewContext<Self>,
7146 ) {
7147 self.transact(cx, |this, cx| {
7148 this.select_autoclose_pair(cx);
7149 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7150 let line_mode = s.line_mode;
7151 s.move_with(|map, selection| {
7152 if selection.is_empty() && !line_mode {
7153 let cursor = movement::previous_subword_start(map, selection.head());
7154 selection.set_head(cursor, SelectionGoal::None);
7155 }
7156 });
7157 });
7158 this.insert("", cx);
7159 });
7160 }
7161
7162 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7163 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7164 s.move_cursors_with(|map, head, _| {
7165 (movement::next_word_end(map, head), SelectionGoal::None)
7166 });
7167 })
7168 }
7169
7170 pub fn move_to_next_subword_end(
7171 &mut self,
7172 _: &MoveToNextSubwordEnd,
7173 cx: &mut ViewContext<Self>,
7174 ) {
7175 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7176 s.move_cursors_with(|map, head, _| {
7177 (movement::next_subword_end(map, head), SelectionGoal::None)
7178 });
7179 })
7180 }
7181
7182 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7183 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7184 s.move_heads_with(|map, head, _| {
7185 (movement::next_word_end(map, head), SelectionGoal::None)
7186 });
7187 })
7188 }
7189
7190 pub fn select_to_next_subword_end(
7191 &mut self,
7192 _: &SelectToNextSubwordEnd,
7193 cx: &mut ViewContext<Self>,
7194 ) {
7195 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7196 s.move_heads_with(|map, head, _| {
7197 (movement::next_subword_end(map, head), SelectionGoal::None)
7198 });
7199 })
7200 }
7201
7202 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7203 self.transact(cx, |this, cx| {
7204 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7205 let line_mode = s.line_mode;
7206 s.move_with(|map, selection| {
7207 if selection.is_empty() && !line_mode {
7208 let cursor = movement::next_word_end(map, selection.head());
7209 selection.set_head(cursor, SelectionGoal::None);
7210 }
7211 });
7212 });
7213 this.insert("", cx);
7214 });
7215 }
7216
7217 pub fn delete_to_next_subword_end(
7218 &mut self,
7219 _: &DeleteToNextSubwordEnd,
7220 cx: &mut ViewContext<Self>,
7221 ) {
7222 self.transact(cx, |this, cx| {
7223 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7224 s.move_with(|map, selection| {
7225 if selection.is_empty() {
7226 let cursor = movement::next_subword_end(map, selection.head());
7227 selection.set_head(cursor, SelectionGoal::None);
7228 }
7229 });
7230 });
7231 this.insert("", cx);
7232 });
7233 }
7234
7235 pub fn move_to_beginning_of_line(
7236 &mut self,
7237 action: &MoveToBeginningOfLine,
7238 cx: &mut ViewContext<Self>,
7239 ) {
7240 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7241 s.move_cursors_with(|map, head, _| {
7242 (
7243 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7244 SelectionGoal::None,
7245 )
7246 });
7247 })
7248 }
7249
7250 pub fn select_to_beginning_of_line(
7251 &mut self,
7252 action: &SelectToBeginningOfLine,
7253 cx: &mut ViewContext<Self>,
7254 ) {
7255 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7256 s.move_heads_with(|map, head, _| {
7257 (
7258 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7259 SelectionGoal::None,
7260 )
7261 });
7262 });
7263 }
7264
7265 pub fn delete_to_beginning_of_line(
7266 &mut self,
7267 _: &DeleteToBeginningOfLine,
7268 cx: &mut ViewContext<Self>,
7269 ) {
7270 self.transact(cx, |this, cx| {
7271 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7272 s.move_with(|_, selection| {
7273 selection.reversed = true;
7274 });
7275 });
7276
7277 this.select_to_beginning_of_line(
7278 &SelectToBeginningOfLine {
7279 stop_at_soft_wraps: false,
7280 },
7281 cx,
7282 );
7283 this.backspace(&Backspace, cx);
7284 });
7285 }
7286
7287 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7289 s.move_cursors_with(|map, head, _| {
7290 (
7291 movement::line_end(map, head, action.stop_at_soft_wraps),
7292 SelectionGoal::None,
7293 )
7294 });
7295 })
7296 }
7297
7298 pub fn select_to_end_of_line(
7299 &mut self,
7300 action: &SelectToEndOfLine,
7301 cx: &mut ViewContext<Self>,
7302 ) {
7303 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7304 s.move_heads_with(|map, head, _| {
7305 (
7306 movement::line_end(map, head, action.stop_at_soft_wraps),
7307 SelectionGoal::None,
7308 )
7309 });
7310 })
7311 }
7312
7313 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7314 self.transact(cx, |this, cx| {
7315 this.select_to_end_of_line(
7316 &SelectToEndOfLine {
7317 stop_at_soft_wraps: false,
7318 },
7319 cx,
7320 );
7321 this.delete(&Delete, cx);
7322 });
7323 }
7324
7325 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7326 self.transact(cx, |this, cx| {
7327 this.select_to_end_of_line(
7328 &SelectToEndOfLine {
7329 stop_at_soft_wraps: false,
7330 },
7331 cx,
7332 );
7333 this.cut(&Cut, cx);
7334 });
7335 }
7336
7337 pub fn move_to_start_of_paragraph(
7338 &mut self,
7339 _: &MoveToStartOfParagraph,
7340 cx: &mut ViewContext<Self>,
7341 ) {
7342 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7343 cx.propagate();
7344 return;
7345 }
7346
7347 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7348 s.move_with(|map, selection| {
7349 selection.collapse_to(
7350 movement::start_of_paragraph(map, selection.head(), 1),
7351 SelectionGoal::None,
7352 )
7353 });
7354 })
7355 }
7356
7357 pub fn move_to_end_of_paragraph(
7358 &mut self,
7359 _: &MoveToEndOfParagraph,
7360 cx: &mut ViewContext<Self>,
7361 ) {
7362 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7363 cx.propagate();
7364 return;
7365 }
7366
7367 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7368 s.move_with(|map, selection| {
7369 selection.collapse_to(
7370 movement::end_of_paragraph(map, selection.head(), 1),
7371 SelectionGoal::None,
7372 )
7373 });
7374 })
7375 }
7376
7377 pub fn select_to_start_of_paragraph(
7378 &mut self,
7379 _: &SelectToStartOfParagraph,
7380 cx: &mut ViewContext<Self>,
7381 ) {
7382 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7383 cx.propagate();
7384 return;
7385 }
7386
7387 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7388 s.move_heads_with(|map, head, _| {
7389 (
7390 movement::start_of_paragraph(map, head, 1),
7391 SelectionGoal::None,
7392 )
7393 });
7394 })
7395 }
7396
7397 pub fn select_to_end_of_paragraph(
7398 &mut self,
7399 _: &SelectToEndOfParagraph,
7400 cx: &mut ViewContext<Self>,
7401 ) {
7402 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7403 cx.propagate();
7404 return;
7405 }
7406
7407 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7408 s.move_heads_with(|map, head, _| {
7409 (
7410 movement::end_of_paragraph(map, head, 1),
7411 SelectionGoal::None,
7412 )
7413 });
7414 })
7415 }
7416
7417 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7418 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7419 cx.propagate();
7420 return;
7421 }
7422
7423 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7424 s.select_ranges(vec![0..0]);
7425 });
7426 }
7427
7428 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7429 let mut selection = self.selections.last::<Point>(cx);
7430 selection.set_head(Point::zero(), SelectionGoal::None);
7431
7432 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7433 s.select(vec![selection]);
7434 });
7435 }
7436
7437 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7438 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7439 cx.propagate();
7440 return;
7441 }
7442
7443 let cursor = self.buffer.read(cx).read(cx).len();
7444 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7445 s.select_ranges(vec![cursor..cursor])
7446 });
7447 }
7448
7449 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7450 self.nav_history = nav_history;
7451 }
7452
7453 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7454 self.nav_history.as_ref()
7455 }
7456
7457 fn push_to_nav_history(
7458 &mut self,
7459 cursor_anchor: Anchor,
7460 new_position: Option<Point>,
7461 cx: &mut ViewContext<Self>,
7462 ) {
7463 if let Some(nav_history) = self.nav_history.as_mut() {
7464 let buffer = self.buffer.read(cx).read(cx);
7465 let cursor_position = cursor_anchor.to_point(&buffer);
7466 let scroll_state = self.scroll_manager.anchor();
7467 let scroll_top_row = scroll_state.top_row(&buffer);
7468 drop(buffer);
7469
7470 if let Some(new_position) = new_position {
7471 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7472 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7473 return;
7474 }
7475 }
7476
7477 nav_history.push(
7478 Some(NavigationData {
7479 cursor_anchor,
7480 cursor_position,
7481 scroll_anchor: scroll_state,
7482 scroll_top_row,
7483 }),
7484 cx,
7485 );
7486 }
7487 }
7488
7489 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7490 let buffer = self.buffer.read(cx).snapshot(cx);
7491 let mut selection = self.selections.first::<usize>(cx);
7492 selection.set_head(buffer.len(), SelectionGoal::None);
7493 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7494 s.select(vec![selection]);
7495 });
7496 }
7497
7498 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7499 let end = self.buffer.read(cx).read(cx).len();
7500 self.change_selections(None, cx, |s| {
7501 s.select_ranges(vec![0..end]);
7502 });
7503 }
7504
7505 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7507 let mut selections = self.selections.all::<Point>(cx);
7508 let max_point = display_map.buffer_snapshot.max_point();
7509 for selection in &mut selections {
7510 let rows = selection.spanned_rows(true, &display_map);
7511 selection.start = Point::new(rows.start.0, 0);
7512 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7513 selection.reversed = false;
7514 }
7515 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7516 s.select(selections);
7517 });
7518 }
7519
7520 pub fn split_selection_into_lines(
7521 &mut self,
7522 _: &SplitSelectionIntoLines,
7523 cx: &mut ViewContext<Self>,
7524 ) {
7525 let mut to_unfold = Vec::new();
7526 let mut new_selection_ranges = Vec::new();
7527 {
7528 let selections = self.selections.all::<Point>(cx);
7529 let buffer = self.buffer.read(cx).read(cx);
7530 for selection in selections {
7531 for row in selection.start.row..selection.end.row {
7532 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7533 new_selection_ranges.push(cursor..cursor);
7534 }
7535 new_selection_ranges.push(selection.end..selection.end);
7536 to_unfold.push(selection.start..selection.end);
7537 }
7538 }
7539 self.unfold_ranges(to_unfold, true, true, cx);
7540 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7541 s.select_ranges(new_selection_ranges);
7542 });
7543 }
7544
7545 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7546 self.add_selection(true, cx);
7547 }
7548
7549 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7550 self.add_selection(false, cx);
7551 }
7552
7553 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7554 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7555 let mut selections = self.selections.all::<Point>(cx);
7556 let text_layout_details = self.text_layout_details(cx);
7557 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7558 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7559 let range = oldest_selection.display_range(&display_map).sorted();
7560
7561 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7562 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7563 let positions = start_x.min(end_x)..start_x.max(end_x);
7564
7565 selections.clear();
7566 let mut stack = Vec::new();
7567 for row in range.start.row().0..=range.end.row().0 {
7568 if let Some(selection) = self.selections.build_columnar_selection(
7569 &display_map,
7570 DisplayRow(row),
7571 &positions,
7572 oldest_selection.reversed,
7573 &text_layout_details,
7574 ) {
7575 stack.push(selection.id);
7576 selections.push(selection);
7577 }
7578 }
7579
7580 if above {
7581 stack.reverse();
7582 }
7583
7584 AddSelectionsState { above, stack }
7585 });
7586
7587 let last_added_selection = *state.stack.last().unwrap();
7588 let mut new_selections = Vec::new();
7589 if above == state.above {
7590 let end_row = if above {
7591 DisplayRow(0)
7592 } else {
7593 display_map.max_point().row()
7594 };
7595
7596 'outer: for selection in selections {
7597 if selection.id == last_added_selection {
7598 let range = selection.display_range(&display_map).sorted();
7599 debug_assert_eq!(range.start.row(), range.end.row());
7600 let mut row = range.start.row();
7601 let positions =
7602 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7603 px(start)..px(end)
7604 } else {
7605 let start_x =
7606 display_map.x_for_display_point(range.start, &text_layout_details);
7607 let end_x =
7608 display_map.x_for_display_point(range.end, &text_layout_details);
7609 start_x.min(end_x)..start_x.max(end_x)
7610 };
7611
7612 while row != end_row {
7613 if above {
7614 row.0 -= 1;
7615 } else {
7616 row.0 += 1;
7617 }
7618
7619 if let Some(new_selection) = self.selections.build_columnar_selection(
7620 &display_map,
7621 row,
7622 &positions,
7623 selection.reversed,
7624 &text_layout_details,
7625 ) {
7626 state.stack.push(new_selection.id);
7627 if above {
7628 new_selections.push(new_selection);
7629 new_selections.push(selection);
7630 } else {
7631 new_selections.push(selection);
7632 new_selections.push(new_selection);
7633 }
7634
7635 continue 'outer;
7636 }
7637 }
7638 }
7639
7640 new_selections.push(selection);
7641 }
7642 } else {
7643 new_selections = selections;
7644 new_selections.retain(|s| s.id != last_added_selection);
7645 state.stack.pop();
7646 }
7647
7648 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7649 s.select(new_selections);
7650 });
7651 if state.stack.len() > 1 {
7652 self.add_selections_state = Some(state);
7653 }
7654 }
7655
7656 pub fn select_next_match_internal(
7657 &mut self,
7658 display_map: &DisplaySnapshot,
7659 replace_newest: bool,
7660 autoscroll: Option<Autoscroll>,
7661 cx: &mut ViewContext<Self>,
7662 ) -> Result<()> {
7663 fn select_next_match_ranges(
7664 this: &mut Editor,
7665 range: Range<usize>,
7666 replace_newest: bool,
7667 auto_scroll: Option<Autoscroll>,
7668 cx: &mut ViewContext<Editor>,
7669 ) {
7670 this.unfold_ranges([range.clone()], false, true, cx);
7671 this.change_selections(auto_scroll, cx, |s| {
7672 if replace_newest {
7673 s.delete(s.newest_anchor().id);
7674 }
7675 s.insert_range(range.clone());
7676 });
7677 }
7678
7679 let buffer = &display_map.buffer_snapshot;
7680 let mut selections = self.selections.all::<usize>(cx);
7681 if let Some(mut select_next_state) = self.select_next_state.take() {
7682 let query = &select_next_state.query;
7683 if !select_next_state.done {
7684 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7685 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7686 let mut next_selected_range = None;
7687
7688 let bytes_after_last_selection =
7689 buffer.bytes_in_range(last_selection.end..buffer.len());
7690 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7691 let query_matches = query
7692 .stream_find_iter(bytes_after_last_selection)
7693 .map(|result| (last_selection.end, result))
7694 .chain(
7695 query
7696 .stream_find_iter(bytes_before_first_selection)
7697 .map(|result| (0, result)),
7698 );
7699
7700 for (start_offset, query_match) in query_matches {
7701 let query_match = query_match.unwrap(); // can only fail due to I/O
7702 let offset_range =
7703 start_offset + query_match.start()..start_offset + query_match.end();
7704 let display_range = offset_range.start.to_display_point(&display_map)
7705 ..offset_range.end.to_display_point(&display_map);
7706
7707 if !select_next_state.wordwise
7708 || (!movement::is_inside_word(&display_map, display_range.start)
7709 && !movement::is_inside_word(&display_map, display_range.end))
7710 {
7711 // TODO: This is n^2, because we might check all the selections
7712 if !selections
7713 .iter()
7714 .any(|selection| selection.range().overlaps(&offset_range))
7715 {
7716 next_selected_range = Some(offset_range);
7717 break;
7718 }
7719 }
7720 }
7721
7722 if let Some(next_selected_range) = next_selected_range {
7723 select_next_match_ranges(
7724 self,
7725 next_selected_range,
7726 replace_newest,
7727 autoscroll,
7728 cx,
7729 );
7730 } else {
7731 select_next_state.done = true;
7732 }
7733 }
7734
7735 self.select_next_state = Some(select_next_state);
7736 } else {
7737 let mut only_carets = true;
7738 let mut same_text_selected = true;
7739 let mut selected_text = None;
7740
7741 let mut selections_iter = selections.iter().peekable();
7742 while let Some(selection) = selections_iter.next() {
7743 if selection.start != selection.end {
7744 only_carets = false;
7745 }
7746
7747 if same_text_selected {
7748 if selected_text.is_none() {
7749 selected_text =
7750 Some(buffer.text_for_range(selection.range()).collect::<String>());
7751 }
7752
7753 if let Some(next_selection) = selections_iter.peek() {
7754 if next_selection.range().len() == selection.range().len() {
7755 let next_selected_text = buffer
7756 .text_for_range(next_selection.range())
7757 .collect::<String>();
7758 if Some(next_selected_text) != selected_text {
7759 same_text_selected = false;
7760 selected_text = None;
7761 }
7762 } else {
7763 same_text_selected = false;
7764 selected_text = None;
7765 }
7766 }
7767 }
7768 }
7769
7770 if only_carets {
7771 for selection in &mut selections {
7772 let word_range = movement::surrounding_word(
7773 &display_map,
7774 selection.start.to_display_point(&display_map),
7775 );
7776 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7777 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7778 selection.goal = SelectionGoal::None;
7779 selection.reversed = false;
7780 select_next_match_ranges(
7781 self,
7782 selection.start..selection.end,
7783 replace_newest,
7784 autoscroll,
7785 cx,
7786 );
7787 }
7788
7789 if selections.len() == 1 {
7790 let selection = selections
7791 .last()
7792 .expect("ensured that there's only one selection");
7793 let query = buffer
7794 .text_for_range(selection.start..selection.end)
7795 .collect::<String>();
7796 let is_empty = query.is_empty();
7797 let select_state = SelectNextState {
7798 query: AhoCorasick::new(&[query])?,
7799 wordwise: true,
7800 done: is_empty,
7801 };
7802 self.select_next_state = Some(select_state);
7803 } else {
7804 self.select_next_state = None;
7805 }
7806 } else if let Some(selected_text) = selected_text {
7807 self.select_next_state = Some(SelectNextState {
7808 query: AhoCorasick::new(&[selected_text])?,
7809 wordwise: false,
7810 done: false,
7811 });
7812 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7813 }
7814 }
7815 Ok(())
7816 }
7817
7818 pub fn select_all_matches(
7819 &mut self,
7820 _action: &SelectAllMatches,
7821 cx: &mut ViewContext<Self>,
7822 ) -> Result<()> {
7823 self.push_to_selection_history();
7824 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7825
7826 self.select_next_match_internal(&display_map, false, None, cx)?;
7827 let Some(select_next_state) = self.select_next_state.as_mut() else {
7828 return Ok(());
7829 };
7830 if select_next_state.done {
7831 return Ok(());
7832 }
7833
7834 let mut new_selections = self.selections.all::<usize>(cx);
7835
7836 let buffer = &display_map.buffer_snapshot;
7837 let query_matches = select_next_state
7838 .query
7839 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7840
7841 for query_match in query_matches {
7842 let query_match = query_match.unwrap(); // can only fail due to I/O
7843 let offset_range = query_match.start()..query_match.end();
7844 let display_range = offset_range.start.to_display_point(&display_map)
7845 ..offset_range.end.to_display_point(&display_map);
7846
7847 if !select_next_state.wordwise
7848 || (!movement::is_inside_word(&display_map, display_range.start)
7849 && !movement::is_inside_word(&display_map, display_range.end))
7850 {
7851 self.selections.change_with(cx, |selections| {
7852 new_selections.push(Selection {
7853 id: selections.new_selection_id(),
7854 start: offset_range.start,
7855 end: offset_range.end,
7856 reversed: false,
7857 goal: SelectionGoal::None,
7858 });
7859 });
7860 }
7861 }
7862
7863 new_selections.sort_by_key(|selection| selection.start);
7864 let mut ix = 0;
7865 while ix + 1 < new_selections.len() {
7866 let current_selection = &new_selections[ix];
7867 let next_selection = &new_selections[ix + 1];
7868 if current_selection.range().overlaps(&next_selection.range()) {
7869 if current_selection.id < next_selection.id {
7870 new_selections.remove(ix + 1);
7871 } else {
7872 new_selections.remove(ix);
7873 }
7874 } else {
7875 ix += 1;
7876 }
7877 }
7878
7879 select_next_state.done = true;
7880 self.unfold_ranges(
7881 new_selections.iter().map(|selection| selection.range()),
7882 false,
7883 false,
7884 cx,
7885 );
7886 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
7887 selections.select(new_selections)
7888 });
7889
7890 Ok(())
7891 }
7892
7893 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
7894 self.push_to_selection_history();
7895 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7896 self.select_next_match_internal(
7897 &display_map,
7898 action.replace_newest,
7899 Some(Autoscroll::newest()),
7900 cx,
7901 )?;
7902 Ok(())
7903 }
7904
7905 pub fn select_previous(
7906 &mut self,
7907 action: &SelectPrevious,
7908 cx: &mut ViewContext<Self>,
7909 ) -> Result<()> {
7910 self.push_to_selection_history();
7911 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7912 let buffer = &display_map.buffer_snapshot;
7913 let mut selections = self.selections.all::<usize>(cx);
7914 if let Some(mut select_prev_state) = self.select_prev_state.take() {
7915 let query = &select_prev_state.query;
7916 if !select_prev_state.done {
7917 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7918 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7919 let mut next_selected_range = None;
7920 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
7921 let bytes_before_last_selection =
7922 buffer.reversed_bytes_in_range(0..last_selection.start);
7923 let bytes_after_first_selection =
7924 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
7925 let query_matches = query
7926 .stream_find_iter(bytes_before_last_selection)
7927 .map(|result| (last_selection.start, result))
7928 .chain(
7929 query
7930 .stream_find_iter(bytes_after_first_selection)
7931 .map(|result| (buffer.len(), result)),
7932 );
7933 for (end_offset, query_match) in query_matches {
7934 let query_match = query_match.unwrap(); // can only fail due to I/O
7935 let offset_range =
7936 end_offset - query_match.end()..end_offset - query_match.start();
7937 let display_range = offset_range.start.to_display_point(&display_map)
7938 ..offset_range.end.to_display_point(&display_map);
7939
7940 if !select_prev_state.wordwise
7941 || (!movement::is_inside_word(&display_map, display_range.start)
7942 && !movement::is_inside_word(&display_map, display_range.end))
7943 {
7944 next_selected_range = Some(offset_range);
7945 break;
7946 }
7947 }
7948
7949 if let Some(next_selected_range) = next_selected_range {
7950 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
7951 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7952 if action.replace_newest {
7953 s.delete(s.newest_anchor().id);
7954 }
7955 s.insert_range(next_selected_range);
7956 });
7957 } else {
7958 select_prev_state.done = true;
7959 }
7960 }
7961
7962 self.select_prev_state = Some(select_prev_state);
7963 } else {
7964 let mut only_carets = true;
7965 let mut same_text_selected = true;
7966 let mut selected_text = None;
7967
7968 let mut selections_iter = selections.iter().peekable();
7969 while let Some(selection) = selections_iter.next() {
7970 if selection.start != selection.end {
7971 only_carets = false;
7972 }
7973
7974 if same_text_selected {
7975 if selected_text.is_none() {
7976 selected_text =
7977 Some(buffer.text_for_range(selection.range()).collect::<String>());
7978 }
7979
7980 if let Some(next_selection) = selections_iter.peek() {
7981 if next_selection.range().len() == selection.range().len() {
7982 let next_selected_text = buffer
7983 .text_for_range(next_selection.range())
7984 .collect::<String>();
7985 if Some(next_selected_text) != selected_text {
7986 same_text_selected = false;
7987 selected_text = None;
7988 }
7989 } else {
7990 same_text_selected = false;
7991 selected_text = None;
7992 }
7993 }
7994 }
7995 }
7996
7997 if only_carets {
7998 for selection in &mut selections {
7999 let word_range = movement::surrounding_word(
8000 &display_map,
8001 selection.start.to_display_point(&display_map),
8002 );
8003 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8004 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8005 selection.goal = SelectionGoal::None;
8006 selection.reversed = false;
8007 }
8008 if selections.len() == 1 {
8009 let selection = selections
8010 .last()
8011 .expect("ensured that there's only one selection");
8012 let query = buffer
8013 .text_for_range(selection.start..selection.end)
8014 .collect::<String>();
8015 let is_empty = query.is_empty();
8016 let select_state = SelectNextState {
8017 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8018 wordwise: true,
8019 done: is_empty,
8020 };
8021 self.select_prev_state = Some(select_state);
8022 } else {
8023 self.select_prev_state = None;
8024 }
8025
8026 self.unfold_ranges(
8027 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8028 false,
8029 true,
8030 cx,
8031 );
8032 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8033 s.select(selections);
8034 });
8035 } else if let Some(selected_text) = selected_text {
8036 self.select_prev_state = Some(SelectNextState {
8037 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8038 wordwise: false,
8039 done: false,
8040 });
8041 self.select_previous(action, cx)?;
8042 }
8043 }
8044 Ok(())
8045 }
8046
8047 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8048 let text_layout_details = &self.text_layout_details(cx);
8049 self.transact(cx, |this, cx| {
8050 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8051 let mut edits = Vec::new();
8052 let mut selection_edit_ranges = Vec::new();
8053 let mut last_toggled_row = None;
8054 let snapshot = this.buffer.read(cx).read(cx);
8055 let empty_str: Arc<str> = "".into();
8056 let mut suffixes_inserted = Vec::new();
8057
8058 fn comment_prefix_range(
8059 snapshot: &MultiBufferSnapshot,
8060 row: MultiBufferRow,
8061 comment_prefix: &str,
8062 comment_prefix_whitespace: &str,
8063 ) -> Range<Point> {
8064 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8065
8066 let mut line_bytes = snapshot
8067 .bytes_in_range(start..snapshot.max_point())
8068 .flatten()
8069 .copied();
8070
8071 // If this line currently begins with the line comment prefix, then record
8072 // the range containing the prefix.
8073 if line_bytes
8074 .by_ref()
8075 .take(comment_prefix.len())
8076 .eq(comment_prefix.bytes())
8077 {
8078 // Include any whitespace that matches the comment prefix.
8079 let matching_whitespace_len = line_bytes
8080 .zip(comment_prefix_whitespace.bytes())
8081 .take_while(|(a, b)| a == b)
8082 .count() as u32;
8083 let end = Point::new(
8084 start.row,
8085 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8086 );
8087 start..end
8088 } else {
8089 start..start
8090 }
8091 }
8092
8093 fn comment_suffix_range(
8094 snapshot: &MultiBufferSnapshot,
8095 row: MultiBufferRow,
8096 comment_suffix: &str,
8097 comment_suffix_has_leading_space: bool,
8098 ) -> Range<Point> {
8099 let end = Point::new(row.0, snapshot.line_len(row));
8100 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8101
8102 let mut line_end_bytes = snapshot
8103 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8104 .flatten()
8105 .copied();
8106
8107 let leading_space_len = if suffix_start_column > 0
8108 && line_end_bytes.next() == Some(b' ')
8109 && comment_suffix_has_leading_space
8110 {
8111 1
8112 } else {
8113 0
8114 };
8115
8116 // If this line currently begins with the line comment prefix, then record
8117 // the range containing the prefix.
8118 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8119 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8120 start..end
8121 } else {
8122 end..end
8123 }
8124 }
8125
8126 // TODO: Handle selections that cross excerpts
8127 for selection in &mut selections {
8128 let start_column = snapshot
8129 .indent_size_for_line(MultiBufferRow(selection.start.row))
8130 .len;
8131 let language = if let Some(language) =
8132 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8133 {
8134 language
8135 } else {
8136 continue;
8137 };
8138
8139 selection_edit_ranges.clear();
8140
8141 // If multiple selections contain a given row, avoid processing that
8142 // row more than once.
8143 let mut start_row = MultiBufferRow(selection.start.row);
8144 if last_toggled_row == Some(start_row) {
8145 start_row = start_row.next_row();
8146 }
8147 let end_row =
8148 if selection.end.row > selection.start.row && selection.end.column == 0 {
8149 MultiBufferRow(selection.end.row - 1)
8150 } else {
8151 MultiBufferRow(selection.end.row)
8152 };
8153 last_toggled_row = Some(end_row);
8154
8155 if start_row > end_row {
8156 continue;
8157 }
8158
8159 // If the language has line comments, toggle those.
8160 let full_comment_prefixes = language.line_comment_prefixes();
8161 if !full_comment_prefixes.is_empty() {
8162 let first_prefix = full_comment_prefixes
8163 .first()
8164 .expect("prefixes is non-empty");
8165 let prefix_trimmed_lengths = full_comment_prefixes
8166 .iter()
8167 .map(|p| p.trim_end_matches(' ').len())
8168 .collect::<SmallVec<[usize; 4]>>();
8169
8170 let mut all_selection_lines_are_comments = true;
8171
8172 for row in start_row.0..=end_row.0 {
8173 let row = MultiBufferRow(row);
8174 if start_row < end_row && snapshot.is_line_blank(row) {
8175 continue;
8176 }
8177
8178 let prefix_range = full_comment_prefixes
8179 .iter()
8180 .zip(prefix_trimmed_lengths.iter().copied())
8181 .map(|(prefix, trimmed_prefix_len)| {
8182 comment_prefix_range(
8183 snapshot.deref(),
8184 row,
8185 &prefix[..trimmed_prefix_len],
8186 &prefix[trimmed_prefix_len..],
8187 )
8188 })
8189 .max_by_key(|range| range.end.column - range.start.column)
8190 .expect("prefixes is non-empty");
8191
8192 if prefix_range.is_empty() {
8193 all_selection_lines_are_comments = false;
8194 }
8195
8196 selection_edit_ranges.push(prefix_range);
8197 }
8198
8199 if all_selection_lines_are_comments {
8200 edits.extend(
8201 selection_edit_ranges
8202 .iter()
8203 .cloned()
8204 .map(|range| (range, empty_str.clone())),
8205 );
8206 } else {
8207 let min_column = selection_edit_ranges
8208 .iter()
8209 .map(|range| range.start.column)
8210 .min()
8211 .unwrap_or(0);
8212 edits.extend(selection_edit_ranges.iter().map(|range| {
8213 let position = Point::new(range.start.row, min_column);
8214 (position..position, first_prefix.clone())
8215 }));
8216 }
8217 } else if let Some((full_comment_prefix, comment_suffix)) =
8218 language.block_comment_delimiters()
8219 {
8220 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8221 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8222 let prefix_range = comment_prefix_range(
8223 snapshot.deref(),
8224 start_row,
8225 comment_prefix,
8226 comment_prefix_whitespace,
8227 );
8228 let suffix_range = comment_suffix_range(
8229 snapshot.deref(),
8230 end_row,
8231 comment_suffix.trim_start_matches(' '),
8232 comment_suffix.starts_with(' '),
8233 );
8234
8235 if prefix_range.is_empty() || suffix_range.is_empty() {
8236 edits.push((
8237 prefix_range.start..prefix_range.start,
8238 full_comment_prefix.clone(),
8239 ));
8240 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8241 suffixes_inserted.push((end_row, comment_suffix.len()));
8242 } else {
8243 edits.push((prefix_range, empty_str.clone()));
8244 edits.push((suffix_range, empty_str.clone()));
8245 }
8246 } else {
8247 continue;
8248 }
8249 }
8250
8251 drop(snapshot);
8252 this.buffer.update(cx, |buffer, cx| {
8253 buffer.edit(edits, None, cx);
8254 });
8255
8256 // Adjust selections so that they end before any comment suffixes that
8257 // were inserted.
8258 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8259 let mut selections = this.selections.all::<Point>(cx);
8260 let snapshot = this.buffer.read(cx).read(cx);
8261 for selection in &mut selections {
8262 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8263 match row.cmp(&MultiBufferRow(selection.end.row)) {
8264 Ordering::Less => {
8265 suffixes_inserted.next();
8266 continue;
8267 }
8268 Ordering::Greater => break,
8269 Ordering::Equal => {
8270 if selection.end.column == snapshot.line_len(row) {
8271 if selection.is_empty() {
8272 selection.start.column -= suffix_len as u32;
8273 }
8274 selection.end.column -= suffix_len as u32;
8275 }
8276 break;
8277 }
8278 }
8279 }
8280 }
8281
8282 drop(snapshot);
8283 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8284
8285 let selections = this.selections.all::<Point>(cx);
8286 let selections_on_single_row = selections.windows(2).all(|selections| {
8287 selections[0].start.row == selections[1].start.row
8288 && selections[0].end.row == selections[1].end.row
8289 && selections[0].start.row == selections[0].end.row
8290 });
8291 let selections_selecting = selections
8292 .iter()
8293 .any(|selection| selection.start != selection.end);
8294 let advance_downwards = action.advance_downwards
8295 && selections_on_single_row
8296 && !selections_selecting
8297 && !matches!(this.mode, EditorMode::SingleLine { .. });
8298
8299 if advance_downwards {
8300 let snapshot = this.buffer.read(cx).snapshot(cx);
8301
8302 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8303 s.move_cursors_with(|display_snapshot, display_point, _| {
8304 let mut point = display_point.to_point(display_snapshot);
8305 point.row += 1;
8306 point = snapshot.clip_point(point, Bias::Left);
8307 let display_point = point.to_display_point(display_snapshot);
8308 let goal = SelectionGoal::HorizontalPosition(
8309 display_snapshot
8310 .x_for_display_point(display_point, &text_layout_details)
8311 .into(),
8312 );
8313 (display_point, goal)
8314 })
8315 });
8316 }
8317 });
8318 }
8319
8320 pub fn select_enclosing_symbol(
8321 &mut self,
8322 _: &SelectEnclosingSymbol,
8323 cx: &mut ViewContext<Self>,
8324 ) {
8325 let buffer = self.buffer.read(cx).snapshot(cx);
8326 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8327
8328 fn update_selection(
8329 selection: &Selection<usize>,
8330 buffer_snap: &MultiBufferSnapshot,
8331 ) -> Option<Selection<usize>> {
8332 let cursor = selection.head();
8333 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8334 for symbol in symbols.iter().rev() {
8335 let start = symbol.range.start.to_offset(&buffer_snap);
8336 let end = symbol.range.end.to_offset(&buffer_snap);
8337 let new_range = start..end;
8338 if start < selection.start || end > selection.end {
8339 return Some(Selection {
8340 id: selection.id,
8341 start: new_range.start,
8342 end: new_range.end,
8343 goal: SelectionGoal::None,
8344 reversed: selection.reversed,
8345 });
8346 }
8347 }
8348 None
8349 }
8350
8351 let mut selected_larger_symbol = false;
8352 let new_selections = old_selections
8353 .iter()
8354 .map(|selection| match update_selection(selection, &buffer) {
8355 Some(new_selection) => {
8356 if new_selection.range() != selection.range() {
8357 selected_larger_symbol = true;
8358 }
8359 new_selection
8360 }
8361 None => selection.clone(),
8362 })
8363 .collect::<Vec<_>>();
8364
8365 if selected_larger_symbol {
8366 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8367 s.select(new_selections);
8368 });
8369 }
8370 }
8371
8372 pub fn select_larger_syntax_node(
8373 &mut self,
8374 _: &SelectLargerSyntaxNode,
8375 cx: &mut ViewContext<Self>,
8376 ) {
8377 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8378 let buffer = self.buffer.read(cx).snapshot(cx);
8379 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8380
8381 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8382 let mut selected_larger_node = false;
8383 let new_selections = old_selections
8384 .iter()
8385 .map(|selection| {
8386 let old_range = selection.start..selection.end;
8387 let mut new_range = old_range.clone();
8388 while let Some(containing_range) =
8389 buffer.range_for_syntax_ancestor(new_range.clone())
8390 {
8391 new_range = containing_range;
8392 if !display_map.intersects_fold(new_range.start)
8393 && !display_map.intersects_fold(new_range.end)
8394 {
8395 break;
8396 }
8397 }
8398
8399 selected_larger_node |= new_range != old_range;
8400 Selection {
8401 id: selection.id,
8402 start: new_range.start,
8403 end: new_range.end,
8404 goal: SelectionGoal::None,
8405 reversed: selection.reversed,
8406 }
8407 })
8408 .collect::<Vec<_>>();
8409
8410 if selected_larger_node {
8411 stack.push(old_selections);
8412 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8413 s.select(new_selections);
8414 });
8415 }
8416 self.select_larger_syntax_node_stack = stack;
8417 }
8418
8419 pub fn select_smaller_syntax_node(
8420 &mut self,
8421 _: &SelectSmallerSyntaxNode,
8422 cx: &mut ViewContext<Self>,
8423 ) {
8424 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8425 if let Some(selections) = stack.pop() {
8426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8427 s.select(selections.to_vec());
8428 });
8429 }
8430 self.select_larger_syntax_node_stack = stack;
8431 }
8432
8433 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8434 if !EditorSettings::get_global(cx).gutter.runnables {
8435 self.clear_tasks();
8436 return Task::ready(());
8437 }
8438 let project = self.project.clone();
8439 cx.spawn(|this, mut cx| async move {
8440 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8441 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8442 }) else {
8443 return;
8444 };
8445
8446 let Some(project) = project else {
8447 return;
8448 };
8449
8450 let hide_runnables = project
8451 .update(&mut cx, |project, cx| {
8452 // Do not display any test indicators in non-dev server remote projects.
8453 project.is_remote() && project.ssh_connection_string(cx).is_none()
8454 })
8455 .unwrap_or(true);
8456 if hide_runnables {
8457 return;
8458 }
8459 let new_rows =
8460 cx.background_executor()
8461 .spawn({
8462 let snapshot = display_snapshot.clone();
8463 async move {
8464 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8465 }
8466 })
8467 .await;
8468 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8469
8470 this.update(&mut cx, |this, _| {
8471 this.clear_tasks();
8472 for (key, value) in rows {
8473 this.insert_tasks(key, value);
8474 }
8475 })
8476 .ok();
8477 })
8478 }
8479 fn fetch_runnable_ranges(
8480 snapshot: &DisplaySnapshot,
8481 range: Range<Anchor>,
8482 ) -> Vec<language::RunnableRange> {
8483 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8484 }
8485
8486 fn runnable_rows(
8487 project: Model<Project>,
8488 snapshot: DisplaySnapshot,
8489 runnable_ranges: Vec<RunnableRange>,
8490 mut cx: AsyncWindowContext,
8491 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8492 runnable_ranges
8493 .into_iter()
8494 .filter_map(|mut runnable| {
8495 let tasks = cx
8496 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8497 .ok()?;
8498 if tasks.is_empty() {
8499 return None;
8500 }
8501
8502 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8503
8504 let row = snapshot
8505 .buffer_snapshot
8506 .buffer_line_for_row(MultiBufferRow(point.row))?
8507 .1
8508 .start
8509 .row;
8510
8511 let context_range =
8512 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8513 Some((
8514 (runnable.buffer_id, row),
8515 RunnableTasks {
8516 templates: tasks,
8517 offset: MultiBufferOffset(runnable.run_range.start),
8518 context_range,
8519 column: point.column,
8520 extra_variables: runnable.extra_captures,
8521 },
8522 ))
8523 })
8524 .collect()
8525 }
8526
8527 fn templates_with_tags(
8528 project: &Model<Project>,
8529 runnable: &mut Runnable,
8530 cx: &WindowContext<'_>,
8531 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8532 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8533 let (worktree_id, file) = project
8534 .buffer_for_id(runnable.buffer, cx)
8535 .and_then(|buffer| buffer.read(cx).file())
8536 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8537 .unzip();
8538
8539 (project.task_inventory().clone(), worktree_id, file)
8540 });
8541
8542 let inventory = inventory.read(cx);
8543 let tags = mem::take(&mut runnable.tags);
8544 let mut tags: Vec<_> = tags
8545 .into_iter()
8546 .flat_map(|tag| {
8547 let tag = tag.0.clone();
8548 inventory
8549 .list_tasks(
8550 file.clone(),
8551 Some(runnable.language.clone()),
8552 worktree_id,
8553 cx,
8554 )
8555 .into_iter()
8556 .filter(move |(_, template)| {
8557 template.tags.iter().any(|source_tag| source_tag == &tag)
8558 })
8559 })
8560 .sorted_by_key(|(kind, _)| kind.to_owned())
8561 .collect();
8562 if let Some((leading_tag_source, _)) = tags.first() {
8563 // Strongest source wins; if we have worktree tag binding, prefer that to
8564 // global and language bindings;
8565 // if we have a global binding, prefer that to language binding.
8566 let first_mismatch = tags
8567 .iter()
8568 .position(|(tag_source, _)| tag_source != leading_tag_source);
8569 if let Some(index) = first_mismatch {
8570 tags.truncate(index);
8571 }
8572 }
8573
8574 tags
8575 }
8576
8577 pub fn move_to_enclosing_bracket(
8578 &mut self,
8579 _: &MoveToEnclosingBracket,
8580 cx: &mut ViewContext<Self>,
8581 ) {
8582 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8583 s.move_offsets_with(|snapshot, selection| {
8584 let Some(enclosing_bracket_ranges) =
8585 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8586 else {
8587 return;
8588 };
8589
8590 let mut best_length = usize::MAX;
8591 let mut best_inside = false;
8592 let mut best_in_bracket_range = false;
8593 let mut best_destination = None;
8594 for (open, close) in enclosing_bracket_ranges {
8595 let close = close.to_inclusive();
8596 let length = close.end() - open.start;
8597 let inside = selection.start >= open.end && selection.end <= *close.start();
8598 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8599 || close.contains(&selection.head());
8600
8601 // If best is next to a bracket and current isn't, skip
8602 if !in_bracket_range && best_in_bracket_range {
8603 continue;
8604 }
8605
8606 // Prefer smaller lengths unless best is inside and current isn't
8607 if length > best_length && (best_inside || !inside) {
8608 continue;
8609 }
8610
8611 best_length = length;
8612 best_inside = inside;
8613 best_in_bracket_range = in_bracket_range;
8614 best_destination = Some(
8615 if close.contains(&selection.start) && close.contains(&selection.end) {
8616 if inside {
8617 open.end
8618 } else {
8619 open.start
8620 }
8621 } else {
8622 if inside {
8623 *close.start()
8624 } else {
8625 *close.end()
8626 }
8627 },
8628 );
8629 }
8630
8631 if let Some(destination) = best_destination {
8632 selection.collapse_to(destination, SelectionGoal::None);
8633 }
8634 })
8635 });
8636 }
8637
8638 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8639 self.end_selection(cx);
8640 self.selection_history.mode = SelectionHistoryMode::Undoing;
8641 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8642 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8643 self.select_next_state = entry.select_next_state;
8644 self.select_prev_state = entry.select_prev_state;
8645 self.add_selections_state = entry.add_selections_state;
8646 self.request_autoscroll(Autoscroll::newest(), cx);
8647 }
8648 self.selection_history.mode = SelectionHistoryMode::Normal;
8649 }
8650
8651 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8652 self.end_selection(cx);
8653 self.selection_history.mode = SelectionHistoryMode::Redoing;
8654 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8655 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8656 self.select_next_state = entry.select_next_state;
8657 self.select_prev_state = entry.select_prev_state;
8658 self.add_selections_state = entry.add_selections_state;
8659 self.request_autoscroll(Autoscroll::newest(), cx);
8660 }
8661 self.selection_history.mode = SelectionHistoryMode::Normal;
8662 }
8663
8664 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8665 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8666 }
8667
8668 pub fn expand_excerpts_down(
8669 &mut self,
8670 action: &ExpandExcerptsDown,
8671 cx: &mut ViewContext<Self>,
8672 ) {
8673 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8674 }
8675
8676 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8677 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8678 }
8679
8680 pub fn expand_excerpts_for_direction(
8681 &mut self,
8682 lines: u32,
8683 direction: ExpandExcerptDirection,
8684 cx: &mut ViewContext<Self>,
8685 ) {
8686 let selections = self.selections.disjoint_anchors();
8687
8688 let lines = if lines == 0 {
8689 EditorSettings::get_global(cx).expand_excerpt_lines
8690 } else {
8691 lines
8692 };
8693
8694 self.buffer.update(cx, |buffer, cx| {
8695 buffer.expand_excerpts(
8696 selections
8697 .into_iter()
8698 .map(|selection| selection.head().excerpt_id)
8699 .dedup(),
8700 lines,
8701 direction,
8702 cx,
8703 )
8704 })
8705 }
8706
8707 pub fn expand_excerpt(
8708 &mut self,
8709 excerpt: ExcerptId,
8710 direction: ExpandExcerptDirection,
8711 cx: &mut ViewContext<Self>,
8712 ) {
8713 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8714 self.buffer.update(cx, |buffer, cx| {
8715 buffer.expand_excerpts([excerpt], lines, direction, cx)
8716 })
8717 }
8718
8719 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8720 self.go_to_diagnostic_impl(Direction::Next, cx)
8721 }
8722
8723 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8724 self.go_to_diagnostic_impl(Direction::Prev, cx)
8725 }
8726
8727 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8728 let buffer = self.buffer.read(cx).snapshot(cx);
8729 let selection = self.selections.newest::<usize>(cx);
8730
8731 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8732 if direction == Direction::Next {
8733 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8734 let (group_id, jump_to) = popover.activation_info();
8735 if self.activate_diagnostics(group_id, cx) {
8736 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8737 let mut new_selection = s.newest_anchor().clone();
8738 new_selection.collapse_to(jump_to, SelectionGoal::None);
8739 s.select_anchors(vec![new_selection.clone()]);
8740 });
8741 }
8742 return;
8743 }
8744 }
8745
8746 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8747 active_diagnostics
8748 .primary_range
8749 .to_offset(&buffer)
8750 .to_inclusive()
8751 });
8752 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8753 if active_primary_range.contains(&selection.head()) {
8754 *active_primary_range.start()
8755 } else {
8756 selection.head()
8757 }
8758 } else {
8759 selection.head()
8760 };
8761 let snapshot = self.snapshot(cx);
8762 loop {
8763 let diagnostics = if direction == Direction::Prev {
8764 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8765 } else {
8766 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8767 }
8768 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8769 let group = diagnostics
8770 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8771 // be sorted in a stable way
8772 // skip until we are at current active diagnostic, if it exists
8773 .skip_while(|entry| {
8774 (match direction {
8775 Direction::Prev => entry.range.start >= search_start,
8776 Direction::Next => entry.range.start <= search_start,
8777 }) && self
8778 .active_diagnostics
8779 .as_ref()
8780 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8781 })
8782 .find_map(|entry| {
8783 if entry.diagnostic.is_primary
8784 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8785 && !entry.range.is_empty()
8786 // if we match with the active diagnostic, skip it
8787 && Some(entry.diagnostic.group_id)
8788 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8789 {
8790 Some((entry.range, entry.diagnostic.group_id))
8791 } else {
8792 None
8793 }
8794 });
8795
8796 if let Some((primary_range, group_id)) = group {
8797 if self.activate_diagnostics(group_id, cx) {
8798 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8799 s.select(vec![Selection {
8800 id: selection.id,
8801 start: primary_range.start,
8802 end: primary_range.start,
8803 reversed: false,
8804 goal: SelectionGoal::None,
8805 }]);
8806 });
8807 }
8808 break;
8809 } else {
8810 // Cycle around to the start of the buffer, potentially moving back to the start of
8811 // the currently active diagnostic.
8812 active_primary_range.take();
8813 if direction == Direction::Prev {
8814 if search_start == buffer.len() {
8815 break;
8816 } else {
8817 search_start = buffer.len();
8818 }
8819 } else if search_start == 0 {
8820 break;
8821 } else {
8822 search_start = 0;
8823 }
8824 }
8825 }
8826 }
8827
8828 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8829 let snapshot = self
8830 .display_map
8831 .update(cx, |display_map, cx| display_map.snapshot(cx));
8832 let selection = self.selections.newest::<Point>(cx);
8833
8834 if !self.seek_in_direction(
8835 &snapshot,
8836 selection.head(),
8837 false,
8838 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8839 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8840 ),
8841 cx,
8842 ) {
8843 let wrapped_point = Point::zero();
8844 self.seek_in_direction(
8845 &snapshot,
8846 wrapped_point,
8847 true,
8848 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8849 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8850 ),
8851 cx,
8852 );
8853 }
8854 }
8855
8856 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8857 let snapshot = self
8858 .display_map
8859 .update(cx, |display_map, cx| display_map.snapshot(cx));
8860 let selection = self.selections.newest::<Point>(cx);
8861
8862 if !self.seek_in_direction(
8863 &snapshot,
8864 selection.head(),
8865 false,
8866 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8867 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8868 ),
8869 cx,
8870 ) {
8871 let wrapped_point = snapshot.buffer_snapshot.max_point();
8872 self.seek_in_direction(
8873 &snapshot,
8874 wrapped_point,
8875 true,
8876 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8877 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8878 ),
8879 cx,
8880 );
8881 }
8882 }
8883
8884 fn seek_in_direction(
8885 &mut self,
8886 snapshot: &DisplaySnapshot,
8887 initial_point: Point,
8888 is_wrapped: bool,
8889 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8890 cx: &mut ViewContext<Editor>,
8891 ) -> bool {
8892 let display_point = initial_point.to_display_point(snapshot);
8893 let mut hunks = hunks
8894 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8895 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
8896 .dedup();
8897
8898 if let Some(hunk) = hunks.next() {
8899 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8900 let row = hunk.start_display_row();
8901 let point = DisplayPoint::new(row, 0);
8902 s.select_display_ranges([point..point]);
8903 });
8904
8905 true
8906 } else {
8907 false
8908 }
8909 }
8910
8911 pub fn go_to_definition(
8912 &mut self,
8913 _: &GoToDefinition,
8914 cx: &mut ViewContext<Self>,
8915 ) -> Task<Result<bool>> {
8916 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8917 }
8918
8919 pub fn go_to_implementation(
8920 &mut self,
8921 _: &GoToImplementation,
8922 cx: &mut ViewContext<Self>,
8923 ) -> Task<Result<bool>> {
8924 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8925 }
8926
8927 pub fn go_to_implementation_split(
8928 &mut self,
8929 _: &GoToImplementationSplit,
8930 cx: &mut ViewContext<Self>,
8931 ) -> Task<Result<bool>> {
8932 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8933 }
8934
8935 pub fn go_to_type_definition(
8936 &mut self,
8937 _: &GoToTypeDefinition,
8938 cx: &mut ViewContext<Self>,
8939 ) -> Task<Result<bool>> {
8940 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8941 }
8942
8943 pub fn go_to_definition_split(
8944 &mut self,
8945 _: &GoToDefinitionSplit,
8946 cx: &mut ViewContext<Self>,
8947 ) -> Task<Result<bool>> {
8948 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
8949 }
8950
8951 pub fn go_to_type_definition_split(
8952 &mut self,
8953 _: &GoToTypeDefinitionSplit,
8954 cx: &mut ViewContext<Self>,
8955 ) -> Task<Result<bool>> {
8956 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
8957 }
8958
8959 fn go_to_definition_of_kind(
8960 &mut self,
8961 kind: GotoDefinitionKind,
8962 split: bool,
8963 cx: &mut ViewContext<Self>,
8964 ) -> Task<Result<bool>> {
8965 let Some(workspace) = self.workspace() else {
8966 return Task::ready(Ok(false));
8967 };
8968 let buffer = self.buffer.read(cx);
8969 let head = self.selections.newest::<usize>(cx).head();
8970 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
8971 text_anchor
8972 } else {
8973 return Task::ready(Ok(false));
8974 };
8975
8976 let project = workspace.read(cx).project().clone();
8977 let definitions = project.update(cx, |project, cx| match kind {
8978 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
8979 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
8980 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
8981 });
8982
8983 cx.spawn(|editor, mut cx| async move {
8984 let definitions = definitions.await?;
8985 let navigated = editor
8986 .update(&mut cx, |editor, cx| {
8987 editor.navigate_to_hover_links(
8988 Some(kind),
8989 definitions
8990 .into_iter()
8991 .filter(|location| {
8992 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
8993 })
8994 .map(HoverLink::Text)
8995 .collect::<Vec<_>>(),
8996 split,
8997 cx,
8998 )
8999 })?
9000 .await?;
9001 anyhow::Ok(navigated)
9002 })
9003 }
9004
9005 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9006 let position = self.selections.newest_anchor().head();
9007 let Some((buffer, buffer_position)) =
9008 self.buffer.read(cx).text_anchor_for_position(position, cx)
9009 else {
9010 return;
9011 };
9012
9013 cx.spawn(|editor, mut cx| async move {
9014 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9015 editor.update(&mut cx, |_, cx| {
9016 cx.open_url(&url);
9017 })
9018 } else {
9019 Ok(())
9020 }
9021 })
9022 .detach();
9023 }
9024
9025 pub(crate) fn navigate_to_hover_links(
9026 &mut self,
9027 kind: Option<GotoDefinitionKind>,
9028 mut definitions: Vec<HoverLink>,
9029 split: bool,
9030 cx: &mut ViewContext<Editor>,
9031 ) -> Task<Result<bool>> {
9032 // If there is one definition, just open it directly
9033 if definitions.len() == 1 {
9034 let definition = definitions.pop().unwrap();
9035 let target_task = match definition {
9036 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9037 HoverLink::InlayHint(lsp_location, server_id) => {
9038 self.compute_target_location(lsp_location, server_id, cx)
9039 }
9040 HoverLink::Url(url) => {
9041 cx.open_url(&url);
9042 Task::ready(Ok(None))
9043 }
9044 };
9045 cx.spawn(|editor, mut cx| async move {
9046 let target = target_task.await.context("target resolution task")?;
9047 if let Some(target) = target {
9048 editor.update(&mut cx, |editor, cx| {
9049 let Some(workspace) = editor.workspace() else {
9050 return false;
9051 };
9052 let pane = workspace.read(cx).active_pane().clone();
9053
9054 let range = target.range.to_offset(target.buffer.read(cx));
9055 let range = editor.range_for_match(&range);
9056
9057 /// If select range has more than one line, we
9058 /// just point the cursor to range.start.
9059 fn check_multiline_range(
9060 buffer: &Buffer,
9061 range: Range<usize>,
9062 ) -> Range<usize> {
9063 if buffer.offset_to_point(range.start).row
9064 == buffer.offset_to_point(range.end).row
9065 {
9066 range
9067 } else {
9068 range.start..range.start
9069 }
9070 }
9071
9072 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9073 let buffer = target.buffer.read(cx);
9074 let range = check_multiline_range(buffer, range);
9075 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9076 s.select_ranges([range]);
9077 });
9078 } else {
9079 cx.window_context().defer(move |cx| {
9080 let target_editor: View<Self> =
9081 workspace.update(cx, |workspace, cx| {
9082 let pane = if split {
9083 workspace.adjacent_pane(cx)
9084 } else {
9085 workspace.active_pane().clone()
9086 };
9087
9088 workspace.open_project_item(pane, target.buffer.clone(), cx)
9089 });
9090 target_editor.update(cx, |target_editor, cx| {
9091 // When selecting a definition in a different buffer, disable the nav history
9092 // to avoid creating a history entry at the previous cursor location.
9093 pane.update(cx, |pane, _| pane.disable_history());
9094 let buffer = target.buffer.read(cx);
9095 let range = check_multiline_range(buffer, range);
9096 target_editor.change_selections(
9097 Some(Autoscroll::focused()),
9098 cx,
9099 |s| {
9100 s.select_ranges([range]);
9101 },
9102 );
9103 pane.update(cx, |pane, _| pane.enable_history());
9104 });
9105 });
9106 }
9107 true
9108 })
9109 } else {
9110 Ok(false)
9111 }
9112 })
9113 } else if !definitions.is_empty() {
9114 let replica_id = self.replica_id(cx);
9115 cx.spawn(|editor, mut cx| async move {
9116 let (title, location_tasks, workspace) = editor
9117 .update(&mut cx, |editor, cx| {
9118 let tab_kind = match kind {
9119 Some(GotoDefinitionKind::Implementation) => "Implementations",
9120 _ => "Definitions",
9121 };
9122 let title = definitions
9123 .iter()
9124 .find_map(|definition| match definition {
9125 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9126 let buffer = origin.buffer.read(cx);
9127 format!(
9128 "{} for {}",
9129 tab_kind,
9130 buffer
9131 .text_for_range(origin.range.clone())
9132 .collect::<String>()
9133 )
9134 }),
9135 HoverLink::InlayHint(_, _) => None,
9136 HoverLink::Url(_) => None,
9137 })
9138 .unwrap_or(tab_kind.to_string());
9139 let location_tasks = definitions
9140 .into_iter()
9141 .map(|definition| match definition {
9142 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9143 HoverLink::InlayHint(lsp_location, server_id) => {
9144 editor.compute_target_location(lsp_location, server_id, cx)
9145 }
9146 HoverLink::Url(_) => Task::ready(Ok(None)),
9147 })
9148 .collect::<Vec<_>>();
9149 (title, location_tasks, editor.workspace().clone())
9150 })
9151 .context("location tasks preparation")?;
9152
9153 let locations = futures::future::join_all(location_tasks)
9154 .await
9155 .into_iter()
9156 .filter_map(|location| location.transpose())
9157 .collect::<Result<_>>()
9158 .context("location tasks")?;
9159
9160 let Some(workspace) = workspace else {
9161 return Ok(false);
9162 };
9163 let opened = workspace
9164 .update(&mut cx, |workspace, cx| {
9165 Self::open_locations_in_multibuffer(
9166 workspace, locations, replica_id, title, split, cx,
9167 )
9168 })
9169 .ok();
9170
9171 anyhow::Ok(opened.is_some())
9172 })
9173 } else {
9174 Task::ready(Ok(false))
9175 }
9176 }
9177
9178 fn compute_target_location(
9179 &self,
9180 lsp_location: lsp::Location,
9181 server_id: LanguageServerId,
9182 cx: &mut ViewContext<Editor>,
9183 ) -> Task<anyhow::Result<Option<Location>>> {
9184 let Some(project) = self.project.clone() else {
9185 return Task::Ready(Some(Ok(None)));
9186 };
9187
9188 cx.spawn(move |editor, mut cx| async move {
9189 let location_task = editor.update(&mut cx, |editor, cx| {
9190 project.update(cx, |project, cx| {
9191 let language_server_name =
9192 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9193 project
9194 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9195 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9196 });
9197 language_server_name.map(|language_server_name| {
9198 project.open_local_buffer_via_lsp(
9199 lsp_location.uri.clone(),
9200 server_id,
9201 language_server_name,
9202 cx,
9203 )
9204 })
9205 })
9206 })?;
9207 let location = match location_task {
9208 Some(task) => Some({
9209 let target_buffer_handle = task.await.context("open local buffer")?;
9210 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9211 let target_start = target_buffer
9212 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9213 let target_end = target_buffer
9214 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9215 target_buffer.anchor_after(target_start)
9216 ..target_buffer.anchor_before(target_end)
9217 })?;
9218 Location {
9219 buffer: target_buffer_handle,
9220 range,
9221 }
9222 }),
9223 None => None,
9224 };
9225 Ok(location)
9226 })
9227 }
9228
9229 pub fn find_all_references(
9230 &mut self,
9231 _: &FindAllReferences,
9232 cx: &mut ViewContext<Self>,
9233 ) -> Option<Task<Result<()>>> {
9234 let multi_buffer = self.buffer.read(cx);
9235 let selection = self.selections.newest::<usize>(cx);
9236 let head = selection.head();
9237
9238 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9239 let head_anchor = multi_buffer_snapshot.anchor_at(
9240 head,
9241 if head < selection.tail() {
9242 Bias::Right
9243 } else {
9244 Bias::Left
9245 },
9246 );
9247
9248 match self
9249 .find_all_references_task_sources
9250 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9251 {
9252 Ok(_) => {
9253 log::info!(
9254 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9255 );
9256 return None;
9257 }
9258 Err(i) => {
9259 self.find_all_references_task_sources.insert(i, head_anchor);
9260 }
9261 }
9262
9263 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9264 let replica_id = self.replica_id(cx);
9265 let workspace = self.workspace()?;
9266 let project = workspace.read(cx).project().clone();
9267 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9268 Some(cx.spawn(|editor, mut cx| async move {
9269 let _cleanup = defer({
9270 let mut cx = cx.clone();
9271 move || {
9272 let _ = editor.update(&mut cx, |editor, _| {
9273 if let Ok(i) =
9274 editor
9275 .find_all_references_task_sources
9276 .binary_search_by(|anchor| {
9277 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9278 })
9279 {
9280 editor.find_all_references_task_sources.remove(i);
9281 }
9282 });
9283 }
9284 });
9285
9286 let locations = references.await?;
9287 if locations.is_empty() {
9288 return anyhow::Ok(());
9289 }
9290
9291 workspace.update(&mut cx, |workspace, cx| {
9292 let title = locations
9293 .first()
9294 .as_ref()
9295 .map(|location| {
9296 let buffer = location.buffer.read(cx);
9297 format!(
9298 "References to `{}`",
9299 buffer
9300 .text_for_range(location.range.clone())
9301 .collect::<String>()
9302 )
9303 })
9304 .unwrap();
9305 Self::open_locations_in_multibuffer(
9306 workspace, locations, replica_id, title, false, cx,
9307 );
9308 })
9309 }))
9310 }
9311
9312 /// Opens a multibuffer with the given project locations in it
9313 pub fn open_locations_in_multibuffer(
9314 workspace: &mut Workspace,
9315 mut locations: Vec<Location>,
9316 replica_id: ReplicaId,
9317 title: String,
9318 split: bool,
9319 cx: &mut ViewContext<Workspace>,
9320 ) {
9321 // If there are multiple definitions, open them in a multibuffer
9322 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9323 let mut locations = locations.into_iter().peekable();
9324 let mut ranges_to_highlight = Vec::new();
9325 let capability = workspace.project().read(cx).capability();
9326
9327 let excerpt_buffer = cx.new_model(|cx| {
9328 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9329 while let Some(location) = locations.next() {
9330 let buffer = location.buffer.read(cx);
9331 let mut ranges_for_buffer = Vec::new();
9332 let range = location.range.to_offset(buffer);
9333 ranges_for_buffer.push(range.clone());
9334
9335 while let Some(next_location) = locations.peek() {
9336 if next_location.buffer == location.buffer {
9337 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9338 locations.next();
9339 } else {
9340 break;
9341 }
9342 }
9343
9344 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9345 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9346 location.buffer.clone(),
9347 ranges_for_buffer,
9348 DEFAULT_MULTIBUFFER_CONTEXT,
9349 cx,
9350 ))
9351 }
9352
9353 multibuffer.with_title(title)
9354 });
9355
9356 let editor = cx.new_view(|cx| {
9357 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9358 });
9359 editor.update(cx, |editor, cx| {
9360 if let Some(first_range) = ranges_to_highlight.first() {
9361 editor.change_selections(None, cx, |selections| {
9362 selections.clear_disjoint();
9363 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9364 });
9365 }
9366 editor.highlight_background::<Self>(
9367 &ranges_to_highlight,
9368 |theme| theme.editor_highlighted_line_background,
9369 cx,
9370 );
9371 });
9372
9373 let item = Box::new(editor);
9374 let item_id = item.item_id();
9375
9376 if split {
9377 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9378 } else {
9379 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9380 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9381 pane.close_current_preview_item(cx)
9382 } else {
9383 None
9384 }
9385 });
9386 workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
9387 }
9388 workspace.active_pane().update(cx, |pane, cx| {
9389 pane.set_preview_item_id(Some(item_id), cx);
9390 });
9391 }
9392
9393 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9394 use language::ToOffset as _;
9395
9396 let project = self.project.clone()?;
9397 let selection = self.selections.newest_anchor().clone();
9398 let (cursor_buffer, cursor_buffer_position) = self
9399 .buffer
9400 .read(cx)
9401 .text_anchor_for_position(selection.head(), cx)?;
9402 let (tail_buffer, cursor_buffer_position_end) = self
9403 .buffer
9404 .read(cx)
9405 .text_anchor_for_position(selection.tail(), cx)?;
9406 if tail_buffer != cursor_buffer {
9407 return None;
9408 }
9409
9410 let snapshot = cursor_buffer.read(cx).snapshot();
9411 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9412 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9413 let prepare_rename = project.update(cx, |project, cx| {
9414 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9415 });
9416 drop(snapshot);
9417
9418 Some(cx.spawn(|this, mut cx| async move {
9419 let rename_range = if let Some(range) = prepare_rename.await? {
9420 Some(range)
9421 } else {
9422 this.update(&mut cx, |this, cx| {
9423 let buffer = this.buffer.read(cx).snapshot(cx);
9424 let mut buffer_highlights = this
9425 .document_highlights_for_position(selection.head(), &buffer)
9426 .filter(|highlight| {
9427 highlight.start.excerpt_id == selection.head().excerpt_id
9428 && highlight.end.excerpt_id == selection.head().excerpt_id
9429 });
9430 buffer_highlights
9431 .next()
9432 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9433 })?
9434 };
9435 if let Some(rename_range) = rename_range {
9436 this.update(&mut cx, |this, cx| {
9437 let snapshot = cursor_buffer.read(cx).snapshot();
9438 let rename_buffer_range = rename_range.to_offset(&snapshot);
9439 let cursor_offset_in_rename_range =
9440 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9441 let cursor_offset_in_rename_range_end =
9442 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9443
9444 this.take_rename(false, cx);
9445 let buffer = this.buffer.read(cx).read(cx);
9446 let cursor_offset = selection.head().to_offset(&buffer);
9447 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9448 let rename_end = rename_start + rename_buffer_range.len();
9449 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9450 let mut old_highlight_id = None;
9451 let old_name: Arc<str> = buffer
9452 .chunks(rename_start..rename_end, true)
9453 .map(|chunk| {
9454 if old_highlight_id.is_none() {
9455 old_highlight_id = chunk.syntax_highlight_id;
9456 }
9457 chunk.text
9458 })
9459 .collect::<String>()
9460 .into();
9461
9462 drop(buffer);
9463
9464 // Position the selection in the rename editor so that it matches the current selection.
9465 this.show_local_selections = false;
9466 let rename_editor = cx.new_view(|cx| {
9467 let mut editor = Editor::single_line(cx);
9468 editor.buffer.update(cx, |buffer, cx| {
9469 buffer.edit([(0..0, old_name.clone())], None, cx)
9470 });
9471 let rename_selection_range = match cursor_offset_in_rename_range
9472 .cmp(&cursor_offset_in_rename_range_end)
9473 {
9474 Ordering::Equal => {
9475 editor.select_all(&SelectAll, cx);
9476 return editor;
9477 }
9478 Ordering::Less => {
9479 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9480 }
9481 Ordering::Greater => {
9482 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9483 }
9484 };
9485 if rename_selection_range.end > old_name.len() {
9486 editor.select_all(&SelectAll, cx);
9487 } else {
9488 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9489 s.select_ranges([rename_selection_range]);
9490 });
9491 }
9492 editor
9493 });
9494 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9495 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9496 _ => {}
9497 })
9498 .detach();
9499
9500 let write_highlights =
9501 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9502 let read_highlights =
9503 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9504 let ranges = write_highlights
9505 .iter()
9506 .flat_map(|(_, ranges)| ranges.iter())
9507 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9508 .cloned()
9509 .collect();
9510
9511 this.highlight_text::<Rename>(
9512 ranges,
9513 HighlightStyle {
9514 fade_out: Some(0.6),
9515 ..Default::default()
9516 },
9517 cx,
9518 );
9519 let rename_focus_handle = rename_editor.focus_handle(cx);
9520 cx.focus(&rename_focus_handle);
9521 let block_id = this.insert_blocks(
9522 [BlockProperties {
9523 style: BlockStyle::Flex,
9524 position: range.start,
9525 height: 1,
9526 render: Box::new({
9527 let rename_editor = rename_editor.clone();
9528 move |cx: &mut BlockContext| {
9529 let mut text_style = cx.editor_style.text.clone();
9530 if let Some(highlight_style) = old_highlight_id
9531 .and_then(|h| h.style(&cx.editor_style.syntax))
9532 {
9533 text_style = text_style.highlight(highlight_style);
9534 }
9535 div()
9536 .pl(cx.anchor_x)
9537 .child(EditorElement::new(
9538 &rename_editor,
9539 EditorStyle {
9540 background: cx.theme().system().transparent,
9541 local_player: cx.editor_style.local_player,
9542 text: text_style,
9543 scrollbar_width: cx.editor_style.scrollbar_width,
9544 syntax: cx.editor_style.syntax.clone(),
9545 status: cx.editor_style.status.clone(),
9546 inlay_hints_style: HighlightStyle {
9547 color: Some(cx.theme().status().hint),
9548 font_weight: Some(FontWeight::BOLD),
9549 ..HighlightStyle::default()
9550 },
9551 suggestions_style: HighlightStyle {
9552 color: Some(cx.theme().status().predictive),
9553 ..HighlightStyle::default()
9554 },
9555 },
9556 ))
9557 .into_any_element()
9558 }
9559 }),
9560 disposition: BlockDisposition::Below,
9561 }],
9562 Some(Autoscroll::fit()),
9563 cx,
9564 )[0];
9565 this.pending_rename = Some(RenameState {
9566 range,
9567 old_name,
9568 editor: rename_editor,
9569 block_id,
9570 });
9571 })?;
9572 }
9573
9574 Ok(())
9575 }))
9576 }
9577
9578 pub fn confirm_rename(
9579 &mut self,
9580 _: &ConfirmRename,
9581 cx: &mut ViewContext<Self>,
9582 ) -> Option<Task<Result<()>>> {
9583 let rename = self.take_rename(false, cx)?;
9584 let workspace = self.workspace()?;
9585 let (start_buffer, start) = self
9586 .buffer
9587 .read(cx)
9588 .text_anchor_for_position(rename.range.start, cx)?;
9589 let (end_buffer, end) = self
9590 .buffer
9591 .read(cx)
9592 .text_anchor_for_position(rename.range.end, cx)?;
9593 if start_buffer != end_buffer {
9594 return None;
9595 }
9596
9597 let buffer = start_buffer;
9598 let range = start..end;
9599 let old_name = rename.old_name;
9600 let new_name = rename.editor.read(cx).text(cx);
9601
9602 let rename = workspace
9603 .read(cx)
9604 .project()
9605 .clone()
9606 .update(cx, |project, cx| {
9607 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9608 });
9609 let workspace = workspace.downgrade();
9610
9611 Some(cx.spawn(|editor, mut cx| async move {
9612 let project_transaction = rename.await?;
9613 Self::open_project_transaction(
9614 &editor,
9615 workspace,
9616 project_transaction,
9617 format!("Rename: {} → {}", old_name, new_name),
9618 cx.clone(),
9619 )
9620 .await?;
9621
9622 editor.update(&mut cx, |editor, cx| {
9623 editor.refresh_document_highlights(cx);
9624 })?;
9625 Ok(())
9626 }))
9627 }
9628
9629 fn take_rename(
9630 &mut self,
9631 moving_cursor: bool,
9632 cx: &mut ViewContext<Self>,
9633 ) -> Option<RenameState> {
9634 let rename = self.pending_rename.take()?;
9635 if rename.editor.focus_handle(cx).is_focused(cx) {
9636 cx.focus(&self.focus_handle);
9637 }
9638
9639 self.remove_blocks(
9640 [rename.block_id].into_iter().collect(),
9641 Some(Autoscroll::fit()),
9642 cx,
9643 );
9644 self.clear_highlights::<Rename>(cx);
9645 self.show_local_selections = true;
9646
9647 if moving_cursor {
9648 let rename_editor = rename.editor.read(cx);
9649 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9650
9651 // Update the selection to match the position of the selection inside
9652 // the rename editor.
9653 let snapshot = self.buffer.read(cx).read(cx);
9654 let rename_range = rename.range.to_offset(&snapshot);
9655 let cursor_in_editor = snapshot
9656 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9657 .min(rename_range.end);
9658 drop(snapshot);
9659
9660 self.change_selections(None, cx, |s| {
9661 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9662 });
9663 } else {
9664 self.refresh_document_highlights(cx);
9665 }
9666
9667 Some(rename)
9668 }
9669
9670 pub fn pending_rename(&self) -> Option<&RenameState> {
9671 self.pending_rename.as_ref()
9672 }
9673
9674 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9675 let project = match &self.project {
9676 Some(project) => project.clone(),
9677 None => return None,
9678 };
9679
9680 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9681 }
9682
9683 fn perform_format(
9684 &mut self,
9685 project: Model<Project>,
9686 trigger: FormatTrigger,
9687 cx: &mut ViewContext<Self>,
9688 ) -> Task<Result<()>> {
9689 let buffer = self.buffer().clone();
9690 let mut buffers = buffer.read(cx).all_buffers();
9691 if trigger == FormatTrigger::Save {
9692 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9693 }
9694
9695 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9696 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9697
9698 cx.spawn(|_, mut cx| async move {
9699 let transaction = futures::select_biased! {
9700 () = timeout => {
9701 log::warn!("timed out waiting for formatting");
9702 None
9703 }
9704 transaction = format.log_err().fuse() => transaction,
9705 };
9706
9707 buffer
9708 .update(&mut cx, |buffer, cx| {
9709 if let Some(transaction) = transaction {
9710 if !buffer.is_singleton() {
9711 buffer.push_transaction(&transaction.0, cx);
9712 }
9713 }
9714
9715 cx.notify();
9716 })
9717 .ok();
9718
9719 Ok(())
9720 })
9721 }
9722
9723 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9724 if let Some(project) = self.project.clone() {
9725 self.buffer.update(cx, |multi_buffer, cx| {
9726 project.update(cx, |project, cx| {
9727 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9728 });
9729 })
9730 }
9731 }
9732
9733 fn cancel_language_server_work(
9734 &mut self,
9735 _: &CancelLanguageServerWork,
9736 cx: &mut ViewContext<Self>,
9737 ) {
9738 if let Some(project) = self.project.clone() {
9739 self.buffer.update(cx, |multi_buffer, cx| {
9740 project.update(cx, |project, cx| {
9741 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9742 });
9743 })
9744 }
9745 }
9746
9747 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9748 cx.show_character_palette();
9749 }
9750
9751 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9752 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9753 let buffer = self.buffer.read(cx).snapshot(cx);
9754 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9755 let is_valid = buffer
9756 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9757 .any(|entry| {
9758 entry.diagnostic.is_primary
9759 && !entry.range.is_empty()
9760 && entry.range.start == primary_range_start
9761 && entry.diagnostic.message == active_diagnostics.primary_message
9762 });
9763
9764 if is_valid != active_diagnostics.is_valid {
9765 active_diagnostics.is_valid = is_valid;
9766 let mut new_styles = HashMap::default();
9767 for (block_id, diagnostic) in &active_diagnostics.blocks {
9768 new_styles.insert(
9769 *block_id,
9770 (
9771 None,
9772 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9773 ),
9774 );
9775 }
9776 self.display_map.update(cx, |display_map, cx| {
9777 display_map.replace_blocks(new_styles, cx)
9778 });
9779 }
9780 }
9781 }
9782
9783 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9784 self.dismiss_diagnostics(cx);
9785 let snapshot = self.snapshot(cx);
9786 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9787 let buffer = self.buffer.read(cx).snapshot(cx);
9788
9789 let mut primary_range = None;
9790 let mut primary_message = None;
9791 let mut group_end = Point::zero();
9792 let diagnostic_group = buffer
9793 .diagnostic_group::<MultiBufferPoint>(group_id)
9794 .filter_map(|entry| {
9795 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9796 && (entry.range.start.row == entry.range.end.row
9797 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9798 {
9799 return None;
9800 }
9801 if entry.range.end > group_end {
9802 group_end = entry.range.end;
9803 }
9804 if entry.diagnostic.is_primary {
9805 primary_range = Some(entry.range.clone());
9806 primary_message = Some(entry.diagnostic.message.clone());
9807 }
9808 Some(entry)
9809 })
9810 .collect::<Vec<_>>();
9811 let primary_range = primary_range?;
9812 let primary_message = primary_message?;
9813 let primary_range =
9814 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9815
9816 let blocks = display_map
9817 .insert_blocks(
9818 diagnostic_group.iter().map(|entry| {
9819 let diagnostic = entry.diagnostic.clone();
9820 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
9821 BlockProperties {
9822 style: BlockStyle::Fixed,
9823 position: buffer.anchor_after(entry.range.start),
9824 height: message_height,
9825 render: diagnostic_block_renderer(diagnostic, None, true, true),
9826 disposition: BlockDisposition::Below,
9827 }
9828 }),
9829 cx,
9830 )
9831 .into_iter()
9832 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9833 .collect();
9834
9835 Some(ActiveDiagnosticGroup {
9836 primary_range,
9837 primary_message,
9838 group_id,
9839 blocks,
9840 is_valid: true,
9841 })
9842 });
9843 self.active_diagnostics.is_some()
9844 }
9845
9846 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9847 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9848 self.display_map.update(cx, |display_map, cx| {
9849 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9850 });
9851 cx.notify();
9852 }
9853 }
9854
9855 pub fn set_selections_from_remote(
9856 &mut self,
9857 selections: Vec<Selection<Anchor>>,
9858 pending_selection: Option<Selection<Anchor>>,
9859 cx: &mut ViewContext<Self>,
9860 ) {
9861 let old_cursor_position = self.selections.newest_anchor().head();
9862 self.selections.change_with(cx, |s| {
9863 s.select_anchors(selections);
9864 if let Some(pending_selection) = pending_selection {
9865 s.set_pending(pending_selection, SelectMode::Character);
9866 } else {
9867 s.clear_pending();
9868 }
9869 });
9870 self.selections_did_change(false, &old_cursor_position, true, cx);
9871 }
9872
9873 fn push_to_selection_history(&mut self) {
9874 self.selection_history.push(SelectionHistoryEntry {
9875 selections: self.selections.disjoint_anchors(),
9876 select_next_state: self.select_next_state.clone(),
9877 select_prev_state: self.select_prev_state.clone(),
9878 add_selections_state: self.add_selections_state.clone(),
9879 });
9880 }
9881
9882 pub fn transact(
9883 &mut self,
9884 cx: &mut ViewContext<Self>,
9885 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
9886 ) -> Option<TransactionId> {
9887 self.start_transaction_at(Instant::now(), cx);
9888 update(self, cx);
9889 self.end_transaction_at(Instant::now(), cx)
9890 }
9891
9892 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
9893 self.end_selection(cx);
9894 if let Some(tx_id) = self
9895 .buffer
9896 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9897 {
9898 self.selection_history
9899 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9900 cx.emit(EditorEvent::TransactionBegun {
9901 transaction_id: tx_id,
9902 })
9903 }
9904 }
9905
9906 fn end_transaction_at(
9907 &mut self,
9908 now: Instant,
9909 cx: &mut ViewContext<Self>,
9910 ) -> Option<TransactionId> {
9911 if let Some(transaction_id) = self
9912 .buffer
9913 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9914 {
9915 if let Some((_, end_selections)) =
9916 self.selection_history.transaction_mut(transaction_id)
9917 {
9918 *end_selections = Some(self.selections.disjoint_anchors());
9919 } else {
9920 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9921 }
9922
9923 cx.emit(EditorEvent::Edited { transaction_id });
9924 Some(transaction_id)
9925 } else {
9926 None
9927 }
9928 }
9929
9930 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9931 let mut fold_ranges = Vec::new();
9932
9933 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9934
9935 let selections = self.selections.all_adjusted(cx);
9936 for selection in selections {
9937 let range = selection.range().sorted();
9938 let buffer_start_row = range.start.row;
9939
9940 for row in (0..=range.end.row).rev() {
9941 if let Some((foldable_range, fold_text)) =
9942 display_map.foldable_range(MultiBufferRow(row))
9943 {
9944 if foldable_range.end.row >= buffer_start_row {
9945 fold_ranges.push((foldable_range, fold_text));
9946 if row <= range.start.row {
9947 break;
9948 }
9949 }
9950 }
9951 }
9952 }
9953
9954 self.fold_ranges(fold_ranges, true, cx);
9955 }
9956
9957 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
9958 let buffer_row = fold_at.buffer_row;
9959 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9960
9961 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
9962 let autoscroll = self
9963 .selections
9964 .all::<Point>(cx)
9965 .iter()
9966 .any(|selection| fold_range.overlaps(&selection.range()));
9967
9968 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
9969 }
9970 }
9971
9972 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
9973 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9974 let buffer = &display_map.buffer_snapshot;
9975 let selections = self.selections.all::<Point>(cx);
9976 let ranges = selections
9977 .iter()
9978 .map(|s| {
9979 let range = s.display_range(&display_map).sorted();
9980 let mut start = range.start.to_point(&display_map);
9981 let mut end = range.end.to_point(&display_map);
9982 start.column = 0;
9983 end.column = buffer.line_len(MultiBufferRow(end.row));
9984 start..end
9985 })
9986 .collect::<Vec<_>>();
9987
9988 self.unfold_ranges(ranges, true, true, cx);
9989 }
9990
9991 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
9992 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9993
9994 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
9995 ..Point::new(
9996 unfold_at.buffer_row.0,
9997 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
9998 );
9999
10000 let autoscroll = self
10001 .selections
10002 .all::<Point>(cx)
10003 .iter()
10004 .any(|selection| selection.range().overlaps(&intersection_range));
10005
10006 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10007 }
10008
10009 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10010 let selections = self.selections.all::<Point>(cx);
10011 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10012 let line_mode = self.selections.line_mode;
10013 let ranges = selections.into_iter().map(|s| {
10014 if line_mode {
10015 let start = Point::new(s.start.row, 0);
10016 let end = Point::new(
10017 s.end.row,
10018 display_map
10019 .buffer_snapshot
10020 .line_len(MultiBufferRow(s.end.row)),
10021 );
10022 (start..end, display_map.fold_placeholder.clone())
10023 } else {
10024 (s.start..s.end, display_map.fold_placeholder.clone())
10025 }
10026 });
10027 self.fold_ranges(ranges, true, cx);
10028 }
10029
10030 pub fn fold_ranges<T: ToOffset + Clone>(
10031 &mut self,
10032 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10033 auto_scroll: bool,
10034 cx: &mut ViewContext<Self>,
10035 ) {
10036 let mut fold_ranges = Vec::new();
10037 let mut buffers_affected = HashMap::default();
10038 let multi_buffer = self.buffer().read(cx);
10039 for (fold_range, fold_text) in ranges {
10040 if let Some((_, buffer, _)) =
10041 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10042 {
10043 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10044 };
10045 fold_ranges.push((fold_range, fold_text));
10046 }
10047
10048 let mut ranges = fold_ranges.into_iter().peekable();
10049 if ranges.peek().is_some() {
10050 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10051
10052 if auto_scroll {
10053 self.request_autoscroll(Autoscroll::fit(), cx);
10054 }
10055
10056 for buffer in buffers_affected.into_values() {
10057 self.sync_expanded_diff_hunks(buffer, cx);
10058 }
10059
10060 cx.notify();
10061
10062 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10063 // Clear diagnostics block when folding a range that contains it.
10064 let snapshot = self.snapshot(cx);
10065 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10066 drop(snapshot);
10067 self.active_diagnostics = Some(active_diagnostics);
10068 self.dismiss_diagnostics(cx);
10069 } else {
10070 self.active_diagnostics = Some(active_diagnostics);
10071 }
10072 }
10073
10074 self.scrollbar_marker_state.dirty = true;
10075 }
10076 }
10077
10078 pub fn unfold_ranges<T: ToOffset + Clone>(
10079 &mut self,
10080 ranges: impl IntoIterator<Item = Range<T>>,
10081 inclusive: bool,
10082 auto_scroll: bool,
10083 cx: &mut ViewContext<Self>,
10084 ) {
10085 let mut unfold_ranges = Vec::new();
10086 let mut buffers_affected = HashMap::default();
10087 let multi_buffer = self.buffer().read(cx);
10088 for range in ranges {
10089 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10090 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10091 };
10092 unfold_ranges.push(range);
10093 }
10094
10095 let mut ranges = unfold_ranges.into_iter().peekable();
10096 if ranges.peek().is_some() {
10097 self.display_map
10098 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10099 if auto_scroll {
10100 self.request_autoscroll(Autoscroll::fit(), cx);
10101 }
10102
10103 for buffer in buffers_affected.into_values() {
10104 self.sync_expanded_diff_hunks(buffer, cx);
10105 }
10106
10107 cx.notify();
10108 self.scrollbar_marker_state.dirty = true;
10109 self.active_indent_guides_state.dirty = true;
10110 }
10111 }
10112
10113 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10114 if hovered != self.gutter_hovered {
10115 self.gutter_hovered = hovered;
10116 cx.notify();
10117 }
10118 }
10119
10120 pub fn insert_blocks(
10121 &mut self,
10122 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10123 autoscroll: Option<Autoscroll>,
10124 cx: &mut ViewContext<Self>,
10125 ) -> Vec<BlockId> {
10126 let blocks = self
10127 .display_map
10128 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10129 if let Some(autoscroll) = autoscroll {
10130 self.request_autoscroll(autoscroll, cx);
10131 }
10132 blocks
10133 }
10134
10135 pub fn replace_blocks(
10136 &mut self,
10137 blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10138 autoscroll: Option<Autoscroll>,
10139 cx: &mut ViewContext<Self>,
10140 ) {
10141 self.display_map
10142 .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10143 if let Some(autoscroll) = autoscroll {
10144 self.request_autoscroll(autoscroll, cx);
10145 }
10146 }
10147
10148 pub fn remove_blocks(
10149 &mut self,
10150 block_ids: HashSet<BlockId>,
10151 autoscroll: Option<Autoscroll>,
10152 cx: &mut ViewContext<Self>,
10153 ) {
10154 self.display_map.update(cx, |display_map, cx| {
10155 display_map.remove_blocks(block_ids, cx)
10156 });
10157 if let Some(autoscroll) = autoscroll {
10158 self.request_autoscroll(autoscroll, cx);
10159 }
10160 }
10161
10162 pub fn row_for_block(
10163 &self,
10164 block_id: BlockId,
10165 cx: &mut ViewContext<Self>,
10166 ) -> Option<DisplayRow> {
10167 self.display_map
10168 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10169 }
10170
10171 pub fn insert_creases(
10172 &mut self,
10173 creases: impl IntoIterator<Item = Crease>,
10174 cx: &mut ViewContext<Self>,
10175 ) -> Vec<CreaseId> {
10176 self.display_map
10177 .update(cx, |map, cx| map.insert_creases(creases, cx))
10178 }
10179
10180 pub fn remove_creases(
10181 &mut self,
10182 ids: impl IntoIterator<Item = CreaseId>,
10183 cx: &mut ViewContext<Self>,
10184 ) {
10185 self.display_map
10186 .update(cx, |map, cx| map.remove_creases(ids, cx));
10187 }
10188
10189 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10190 self.display_map
10191 .update(cx, |map, cx| map.snapshot(cx))
10192 .longest_row()
10193 }
10194
10195 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10196 self.display_map
10197 .update(cx, |map, cx| map.snapshot(cx))
10198 .max_point()
10199 }
10200
10201 pub fn text(&self, cx: &AppContext) -> String {
10202 self.buffer.read(cx).read(cx).text()
10203 }
10204
10205 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10206 let text = self.text(cx);
10207 let text = text.trim();
10208
10209 if text.is_empty() {
10210 return None;
10211 }
10212
10213 Some(text.to_string())
10214 }
10215
10216 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10217 self.transact(cx, |this, cx| {
10218 this.buffer
10219 .read(cx)
10220 .as_singleton()
10221 .expect("you can only call set_text on editors for singleton buffers")
10222 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10223 });
10224 }
10225
10226 pub fn display_text(&self, cx: &mut AppContext) -> String {
10227 self.display_map
10228 .update(cx, |map, cx| map.snapshot(cx))
10229 .text()
10230 }
10231
10232 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10233 let mut wrap_guides = smallvec::smallvec![];
10234
10235 if self.show_wrap_guides == Some(false) {
10236 return wrap_guides;
10237 }
10238
10239 let settings = self.buffer.read(cx).settings_at(0, cx);
10240 if settings.show_wrap_guides {
10241 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10242 wrap_guides.push((soft_wrap as usize, true));
10243 }
10244 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10245 }
10246
10247 wrap_guides
10248 }
10249
10250 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10251 let settings = self.buffer.read(cx).settings_at(0, cx);
10252 let mode = self
10253 .soft_wrap_mode_override
10254 .unwrap_or_else(|| settings.soft_wrap);
10255 match mode {
10256 language_settings::SoftWrap::None => SoftWrap::None,
10257 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10258 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10259 language_settings::SoftWrap::PreferredLineLength => {
10260 SoftWrap::Column(settings.preferred_line_length)
10261 }
10262 }
10263 }
10264
10265 pub fn set_soft_wrap_mode(
10266 &mut self,
10267 mode: language_settings::SoftWrap,
10268 cx: &mut ViewContext<Self>,
10269 ) {
10270 self.soft_wrap_mode_override = Some(mode);
10271 cx.notify();
10272 }
10273
10274 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10275 let rem_size = cx.rem_size();
10276 self.display_map.update(cx, |map, cx| {
10277 map.set_font(
10278 style.text.font(),
10279 style.text.font_size.to_pixels(rem_size),
10280 cx,
10281 )
10282 });
10283 self.style = Some(style);
10284 }
10285
10286 pub fn style(&self) -> Option<&EditorStyle> {
10287 self.style.as_ref()
10288 }
10289
10290 // Called by the element. This method is not designed to be called outside of the editor
10291 // element's layout code because it does not notify when rewrapping is computed synchronously.
10292 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10293 self.display_map
10294 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10295 }
10296
10297 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10298 if self.soft_wrap_mode_override.is_some() {
10299 self.soft_wrap_mode_override.take();
10300 } else {
10301 let soft_wrap = match self.soft_wrap_mode(cx) {
10302 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10303 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10304 language_settings::SoftWrap::PreferLine
10305 }
10306 };
10307 self.soft_wrap_mode_override = Some(soft_wrap);
10308 }
10309 cx.notify();
10310 }
10311
10312 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10313 let Some(workspace) = self.workspace() else {
10314 return;
10315 };
10316 let fs = workspace.read(cx).app_state().fs.clone();
10317 let current_show = TabBarSettings::get_global(cx).show;
10318 update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10319 setting.show = Some(!current_show);
10320 });
10321 }
10322
10323 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10324 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10325 self.buffer
10326 .read(cx)
10327 .settings_at(0, cx)
10328 .indent_guides
10329 .enabled
10330 });
10331 self.show_indent_guides = Some(!currently_enabled);
10332 cx.notify();
10333 }
10334
10335 fn should_show_indent_guides(&self) -> Option<bool> {
10336 self.show_indent_guides
10337 }
10338
10339 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10340 let mut editor_settings = EditorSettings::get_global(cx).clone();
10341 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10342 EditorSettings::override_global(editor_settings, cx);
10343 }
10344
10345 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10346 self.show_gutter = show_gutter;
10347 cx.notify();
10348 }
10349
10350 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10351 self.show_line_numbers = Some(show_line_numbers);
10352 cx.notify();
10353 }
10354
10355 pub fn set_show_git_diff_gutter(
10356 &mut self,
10357 show_git_diff_gutter: bool,
10358 cx: &mut ViewContext<Self>,
10359 ) {
10360 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10361 cx.notify();
10362 }
10363
10364 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10365 self.show_code_actions = Some(show_code_actions);
10366 cx.notify();
10367 }
10368
10369 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10370 self.show_runnables = Some(show_runnables);
10371 cx.notify();
10372 }
10373
10374 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10375 self.show_wrap_guides = Some(show_wrap_guides);
10376 cx.notify();
10377 }
10378
10379 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10380 self.show_indent_guides = Some(show_indent_guides);
10381 cx.notify();
10382 }
10383
10384 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10385 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10386 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10387 cx.reveal_path(&file.abs_path(cx));
10388 }
10389 }
10390 }
10391
10392 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10393 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10394 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10395 if let Some(path) = file.abs_path(cx).to_str() {
10396 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10397 }
10398 }
10399 }
10400 }
10401
10402 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10403 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10404 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10405 if let Some(path) = file.path().to_str() {
10406 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10407 }
10408 }
10409 }
10410 }
10411
10412 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10413 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10414
10415 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10416 self.start_git_blame(true, cx);
10417 }
10418
10419 cx.notify();
10420 }
10421
10422 pub fn toggle_git_blame_inline(
10423 &mut self,
10424 _: &ToggleGitBlameInline,
10425 cx: &mut ViewContext<Self>,
10426 ) {
10427 self.toggle_git_blame_inline_internal(true, cx);
10428 cx.notify();
10429 }
10430
10431 pub fn git_blame_inline_enabled(&self) -> bool {
10432 self.git_blame_inline_enabled
10433 }
10434
10435 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10436 self.show_selection_menu = self
10437 .show_selection_menu
10438 .map(|show_selections_menu| !show_selections_menu)
10439 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10440
10441 cx.notify();
10442 }
10443
10444 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10445 self.show_selection_menu
10446 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10447 }
10448
10449 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10450 if let Some(project) = self.project.as_ref() {
10451 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10452 return;
10453 };
10454
10455 if buffer.read(cx).file().is_none() {
10456 return;
10457 }
10458
10459 let focused = self.focus_handle(cx).contains_focused(cx);
10460
10461 let project = project.clone();
10462 let blame =
10463 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10464 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10465 self.blame = Some(blame);
10466 }
10467 }
10468
10469 fn toggle_git_blame_inline_internal(
10470 &mut self,
10471 user_triggered: bool,
10472 cx: &mut ViewContext<Self>,
10473 ) {
10474 if self.git_blame_inline_enabled {
10475 self.git_blame_inline_enabled = false;
10476 self.show_git_blame_inline = false;
10477 self.show_git_blame_inline_delay_task.take();
10478 } else {
10479 self.git_blame_inline_enabled = true;
10480 self.start_git_blame_inline(user_triggered, cx);
10481 }
10482
10483 cx.notify();
10484 }
10485
10486 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10487 self.start_git_blame(user_triggered, cx);
10488
10489 if ProjectSettings::get_global(cx)
10490 .git
10491 .inline_blame_delay()
10492 .is_some()
10493 {
10494 self.start_inline_blame_timer(cx);
10495 } else {
10496 self.show_git_blame_inline = true
10497 }
10498 }
10499
10500 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10501 self.blame.as_ref()
10502 }
10503
10504 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10505 self.show_git_blame_gutter && self.has_blame_entries(cx)
10506 }
10507
10508 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10509 self.show_git_blame_inline
10510 && self.focus_handle.is_focused(cx)
10511 && !self.newest_selection_head_on_empty_line(cx)
10512 && self.has_blame_entries(cx)
10513 }
10514
10515 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10516 self.blame()
10517 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10518 }
10519
10520 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10521 let cursor_anchor = self.selections.newest_anchor().head();
10522
10523 let snapshot = self.buffer.read(cx).snapshot(cx);
10524 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10525
10526 snapshot.line_len(buffer_row) == 0
10527 }
10528
10529 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10530 let (path, selection, repo) = maybe!({
10531 let project_handle = self.project.as_ref()?.clone();
10532 let project = project_handle.read(cx);
10533
10534 let selection = self.selections.newest::<Point>(cx);
10535 let selection_range = selection.range();
10536
10537 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10538 (buffer, selection_range.start.row..selection_range.end.row)
10539 } else {
10540 let buffer_ranges = self
10541 .buffer()
10542 .read(cx)
10543 .range_to_buffer_ranges(selection_range, cx);
10544
10545 let (buffer, range, _) = if selection.reversed {
10546 buffer_ranges.first()
10547 } else {
10548 buffer_ranges.last()
10549 }?;
10550
10551 let snapshot = buffer.read(cx).snapshot();
10552 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10553 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10554 (buffer.clone(), selection)
10555 };
10556
10557 let path = buffer
10558 .read(cx)
10559 .file()?
10560 .as_local()?
10561 .path()
10562 .to_str()?
10563 .to_string();
10564 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10565 Some((path, selection, repo))
10566 })
10567 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10568
10569 const REMOTE_NAME: &str = "origin";
10570 let origin_url = repo
10571 .remote_url(REMOTE_NAME)
10572 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10573 let sha = repo
10574 .head_sha()
10575 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10576
10577 let (provider, remote) =
10578 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10579 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10580
10581 Ok(provider.build_permalink(
10582 remote,
10583 BuildPermalinkParams {
10584 sha: &sha,
10585 path: &path,
10586 selection: Some(selection),
10587 },
10588 ))
10589 }
10590
10591 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10592 let permalink = self.get_permalink_to_line(cx);
10593
10594 match permalink {
10595 Ok(permalink) => {
10596 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10597 }
10598 Err(err) => {
10599 let message = format!("Failed to copy permalink: {err}");
10600
10601 Err::<(), anyhow::Error>(err).log_err();
10602
10603 if let Some(workspace) = self.workspace() {
10604 workspace.update(cx, |workspace, cx| {
10605 struct CopyPermalinkToLine;
10606
10607 workspace.show_toast(
10608 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10609 cx,
10610 )
10611 })
10612 }
10613 }
10614 }
10615 }
10616
10617 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10618 let permalink = self.get_permalink_to_line(cx);
10619
10620 match permalink {
10621 Ok(permalink) => {
10622 cx.open_url(permalink.as_ref());
10623 }
10624 Err(err) => {
10625 let message = format!("Failed to open permalink: {err}");
10626
10627 Err::<(), anyhow::Error>(err).log_err();
10628
10629 if let Some(workspace) = self.workspace() {
10630 workspace.update(cx, |workspace, cx| {
10631 struct OpenPermalinkToLine;
10632
10633 workspace.show_toast(
10634 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10635 cx,
10636 )
10637 })
10638 }
10639 }
10640 }
10641 }
10642
10643 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10644 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10645 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10646 pub fn highlight_rows<T: 'static>(
10647 &mut self,
10648 rows: RangeInclusive<Anchor>,
10649 color: Option<Hsla>,
10650 should_autoscroll: bool,
10651 cx: &mut ViewContext<Self>,
10652 ) {
10653 let snapshot = self.buffer().read(cx).snapshot(cx);
10654 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10655 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10656 highlight
10657 .range
10658 .start()
10659 .cmp(&rows.start(), &snapshot)
10660 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10661 });
10662 match (color, existing_highlight_index) {
10663 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10664 ix,
10665 RowHighlight {
10666 index: post_inc(&mut self.highlight_order),
10667 range: rows,
10668 should_autoscroll,
10669 color,
10670 },
10671 ),
10672 (None, Ok(i)) => {
10673 row_highlights.remove(i);
10674 }
10675 }
10676 }
10677
10678 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10679 pub fn clear_row_highlights<T: 'static>(&mut self) {
10680 self.highlighted_rows.remove(&TypeId::of::<T>());
10681 }
10682
10683 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10684 pub fn highlighted_rows<T: 'static>(
10685 &self,
10686 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10687 Some(
10688 self.highlighted_rows
10689 .get(&TypeId::of::<T>())?
10690 .iter()
10691 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10692 )
10693 }
10694
10695 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10696 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10697 /// Allows to ignore certain kinds of highlights.
10698 pub fn highlighted_display_rows(
10699 &mut self,
10700 cx: &mut WindowContext,
10701 ) -> BTreeMap<DisplayRow, Hsla> {
10702 let snapshot = self.snapshot(cx);
10703 let mut used_highlight_orders = HashMap::default();
10704 self.highlighted_rows
10705 .iter()
10706 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10707 .fold(
10708 BTreeMap::<DisplayRow, Hsla>::new(),
10709 |mut unique_rows, highlight| {
10710 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10711 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10712 for row in start_row.0..=end_row.0 {
10713 let used_index =
10714 used_highlight_orders.entry(row).or_insert(highlight.index);
10715 if highlight.index >= *used_index {
10716 *used_index = highlight.index;
10717 match highlight.color {
10718 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10719 None => unique_rows.remove(&DisplayRow(row)),
10720 };
10721 }
10722 }
10723 unique_rows
10724 },
10725 )
10726 }
10727
10728 pub fn highlighted_display_row_for_autoscroll(
10729 &self,
10730 snapshot: &DisplaySnapshot,
10731 ) -> Option<DisplayRow> {
10732 self.highlighted_rows
10733 .values()
10734 .flat_map(|highlighted_rows| highlighted_rows.iter())
10735 .filter_map(|highlight| {
10736 if highlight.color.is_none() || !highlight.should_autoscroll {
10737 return None;
10738 }
10739 Some(highlight.range.start().to_display_point(&snapshot).row())
10740 })
10741 .min()
10742 }
10743
10744 pub fn set_search_within_ranges(
10745 &mut self,
10746 ranges: &[Range<Anchor>],
10747 cx: &mut ViewContext<Self>,
10748 ) {
10749 self.highlight_background::<SearchWithinRange>(
10750 ranges,
10751 |colors| colors.editor_document_highlight_read_background,
10752 cx,
10753 )
10754 }
10755
10756 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10757 self.breadcrumb_header = Some(new_header);
10758 }
10759
10760 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10761 self.clear_background_highlights::<SearchWithinRange>(cx);
10762 }
10763
10764 pub fn highlight_background<T: 'static>(
10765 &mut self,
10766 ranges: &[Range<Anchor>],
10767 color_fetcher: fn(&ThemeColors) -> Hsla,
10768 cx: &mut ViewContext<Self>,
10769 ) {
10770 let snapshot = self.snapshot(cx);
10771 // this is to try and catch a panic sooner
10772 for range in ranges {
10773 snapshot
10774 .buffer_snapshot
10775 .summary_for_anchor::<usize>(&range.start);
10776 snapshot
10777 .buffer_snapshot
10778 .summary_for_anchor::<usize>(&range.end);
10779 }
10780
10781 self.background_highlights
10782 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10783 self.scrollbar_marker_state.dirty = true;
10784 cx.notify();
10785 }
10786
10787 pub fn clear_background_highlights<T: 'static>(
10788 &mut self,
10789 cx: &mut ViewContext<Self>,
10790 ) -> Option<BackgroundHighlight> {
10791 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10792 if !text_highlights.1.is_empty() {
10793 self.scrollbar_marker_state.dirty = true;
10794 cx.notify();
10795 }
10796 Some(text_highlights)
10797 }
10798
10799 pub fn highlight_gutter<T: 'static>(
10800 &mut self,
10801 ranges: &[Range<Anchor>],
10802 color_fetcher: fn(&AppContext) -> Hsla,
10803 cx: &mut ViewContext<Self>,
10804 ) {
10805 self.gutter_highlights
10806 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10807 cx.notify();
10808 }
10809
10810 pub fn clear_gutter_highlights<T: 'static>(
10811 &mut self,
10812 cx: &mut ViewContext<Self>,
10813 ) -> Option<GutterHighlight> {
10814 cx.notify();
10815 self.gutter_highlights.remove(&TypeId::of::<T>())
10816 }
10817
10818 #[cfg(feature = "test-support")]
10819 pub fn all_text_background_highlights(
10820 &mut self,
10821 cx: &mut ViewContext<Self>,
10822 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10823 let snapshot = self.snapshot(cx);
10824 let buffer = &snapshot.buffer_snapshot;
10825 let start = buffer.anchor_before(0);
10826 let end = buffer.anchor_after(buffer.len());
10827 let theme = cx.theme().colors();
10828 self.background_highlights_in_range(start..end, &snapshot, theme)
10829 }
10830
10831 #[cfg(feature = "test-support")]
10832 pub fn search_background_highlights(
10833 &mut self,
10834 cx: &mut ViewContext<Self>,
10835 ) -> Vec<Range<Point>> {
10836 let snapshot = self.buffer().read(cx).snapshot(cx);
10837
10838 let highlights = self
10839 .background_highlights
10840 .get(&TypeId::of::<items::BufferSearchHighlights>());
10841
10842 if let Some((_color, ranges)) = highlights {
10843 ranges
10844 .iter()
10845 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10846 .collect_vec()
10847 } else {
10848 vec![]
10849 }
10850 }
10851
10852 fn document_highlights_for_position<'a>(
10853 &'a self,
10854 position: Anchor,
10855 buffer: &'a MultiBufferSnapshot,
10856 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10857 let read_highlights = self
10858 .background_highlights
10859 .get(&TypeId::of::<DocumentHighlightRead>())
10860 .map(|h| &h.1);
10861 let write_highlights = self
10862 .background_highlights
10863 .get(&TypeId::of::<DocumentHighlightWrite>())
10864 .map(|h| &h.1);
10865 let left_position = position.bias_left(buffer);
10866 let right_position = position.bias_right(buffer);
10867 read_highlights
10868 .into_iter()
10869 .chain(write_highlights)
10870 .flat_map(move |ranges| {
10871 let start_ix = match ranges.binary_search_by(|probe| {
10872 let cmp = probe.end.cmp(&left_position, buffer);
10873 if cmp.is_ge() {
10874 Ordering::Greater
10875 } else {
10876 Ordering::Less
10877 }
10878 }) {
10879 Ok(i) | Err(i) => i,
10880 };
10881
10882 ranges[start_ix..]
10883 .iter()
10884 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10885 })
10886 }
10887
10888 pub fn has_background_highlights<T: 'static>(&self) -> bool {
10889 self.background_highlights
10890 .get(&TypeId::of::<T>())
10891 .map_or(false, |(_, highlights)| !highlights.is_empty())
10892 }
10893
10894 pub fn background_highlights_in_range(
10895 &self,
10896 search_range: Range<Anchor>,
10897 display_snapshot: &DisplaySnapshot,
10898 theme: &ThemeColors,
10899 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10900 let mut results = Vec::new();
10901 for (color_fetcher, ranges) in self.background_highlights.values() {
10902 let color = color_fetcher(theme);
10903 let start_ix = match ranges.binary_search_by(|probe| {
10904 let cmp = probe
10905 .end
10906 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10907 if cmp.is_gt() {
10908 Ordering::Greater
10909 } else {
10910 Ordering::Less
10911 }
10912 }) {
10913 Ok(i) | Err(i) => i,
10914 };
10915 for range in &ranges[start_ix..] {
10916 if range
10917 .start
10918 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10919 .is_ge()
10920 {
10921 break;
10922 }
10923
10924 let start = range.start.to_display_point(&display_snapshot);
10925 let end = range.end.to_display_point(&display_snapshot);
10926 results.push((start..end, color))
10927 }
10928 }
10929 results
10930 }
10931
10932 pub fn background_highlight_row_ranges<T: 'static>(
10933 &self,
10934 search_range: Range<Anchor>,
10935 display_snapshot: &DisplaySnapshot,
10936 count: usize,
10937 ) -> Vec<RangeInclusive<DisplayPoint>> {
10938 let mut results = Vec::new();
10939 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10940 return vec![];
10941 };
10942
10943 let start_ix = match ranges.binary_search_by(|probe| {
10944 let cmp = probe
10945 .end
10946 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10947 if cmp.is_gt() {
10948 Ordering::Greater
10949 } else {
10950 Ordering::Less
10951 }
10952 }) {
10953 Ok(i) | Err(i) => i,
10954 };
10955 let mut push_region = |start: Option<Point>, end: Option<Point>| {
10956 if let (Some(start_display), Some(end_display)) = (start, end) {
10957 results.push(
10958 start_display.to_display_point(display_snapshot)
10959 ..=end_display.to_display_point(display_snapshot),
10960 );
10961 }
10962 };
10963 let mut start_row: Option<Point> = None;
10964 let mut end_row: Option<Point> = None;
10965 if ranges.len() > count {
10966 return Vec::new();
10967 }
10968 for range in &ranges[start_ix..] {
10969 if range
10970 .start
10971 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10972 .is_ge()
10973 {
10974 break;
10975 }
10976 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10977 if let Some(current_row) = &end_row {
10978 if end.row == current_row.row {
10979 continue;
10980 }
10981 }
10982 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10983 if start_row.is_none() {
10984 assert_eq!(end_row, None);
10985 start_row = Some(start);
10986 end_row = Some(end);
10987 continue;
10988 }
10989 if let Some(current_end) = end_row.as_mut() {
10990 if start.row > current_end.row + 1 {
10991 push_region(start_row, end_row);
10992 start_row = Some(start);
10993 end_row = Some(end);
10994 } else {
10995 // Merge two hunks.
10996 *current_end = end;
10997 }
10998 } else {
10999 unreachable!();
11000 }
11001 }
11002 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11003 push_region(start_row, end_row);
11004 results
11005 }
11006
11007 pub fn gutter_highlights_in_range(
11008 &self,
11009 search_range: Range<Anchor>,
11010 display_snapshot: &DisplaySnapshot,
11011 cx: &AppContext,
11012 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11013 let mut results = Vec::new();
11014 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11015 let color = color_fetcher(cx);
11016 let start_ix = match ranges.binary_search_by(|probe| {
11017 let cmp = probe
11018 .end
11019 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11020 if cmp.is_gt() {
11021 Ordering::Greater
11022 } else {
11023 Ordering::Less
11024 }
11025 }) {
11026 Ok(i) | Err(i) => i,
11027 };
11028 for range in &ranges[start_ix..] {
11029 if range
11030 .start
11031 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11032 .is_ge()
11033 {
11034 break;
11035 }
11036
11037 let start = range.start.to_display_point(&display_snapshot);
11038 let end = range.end.to_display_point(&display_snapshot);
11039 results.push((start..end, color))
11040 }
11041 }
11042 results
11043 }
11044
11045 /// Get the text ranges corresponding to the redaction query
11046 pub fn redacted_ranges(
11047 &self,
11048 search_range: Range<Anchor>,
11049 display_snapshot: &DisplaySnapshot,
11050 cx: &WindowContext,
11051 ) -> Vec<Range<DisplayPoint>> {
11052 display_snapshot
11053 .buffer_snapshot
11054 .redacted_ranges(search_range, |file| {
11055 if let Some(file) = file {
11056 file.is_private()
11057 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11058 } else {
11059 false
11060 }
11061 })
11062 .map(|range| {
11063 range.start.to_display_point(display_snapshot)
11064 ..range.end.to_display_point(display_snapshot)
11065 })
11066 .collect()
11067 }
11068
11069 pub fn highlight_text<T: 'static>(
11070 &mut self,
11071 ranges: Vec<Range<Anchor>>,
11072 style: HighlightStyle,
11073 cx: &mut ViewContext<Self>,
11074 ) {
11075 self.display_map.update(cx, |map, _| {
11076 map.highlight_text(TypeId::of::<T>(), ranges, style)
11077 });
11078 cx.notify();
11079 }
11080
11081 pub(crate) fn highlight_inlays<T: 'static>(
11082 &mut self,
11083 highlights: Vec<InlayHighlight>,
11084 style: HighlightStyle,
11085 cx: &mut ViewContext<Self>,
11086 ) {
11087 self.display_map.update(cx, |map, _| {
11088 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11089 });
11090 cx.notify();
11091 }
11092
11093 pub fn text_highlights<'a, T: 'static>(
11094 &'a self,
11095 cx: &'a AppContext,
11096 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11097 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11098 }
11099
11100 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11101 let cleared = self
11102 .display_map
11103 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11104 if cleared {
11105 cx.notify();
11106 }
11107 }
11108
11109 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11110 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11111 && self.focus_handle.is_focused(cx)
11112 }
11113
11114 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11115 self.show_cursor_when_unfocused = is_enabled;
11116 cx.notify();
11117 }
11118
11119 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11120 cx.notify();
11121 }
11122
11123 fn on_buffer_event(
11124 &mut self,
11125 multibuffer: Model<MultiBuffer>,
11126 event: &multi_buffer::Event,
11127 cx: &mut ViewContext<Self>,
11128 ) {
11129 match event {
11130 multi_buffer::Event::Edited {
11131 singleton_buffer_edited,
11132 } => {
11133 self.scrollbar_marker_state.dirty = true;
11134 self.active_indent_guides_state.dirty = true;
11135 self.refresh_active_diagnostics(cx);
11136 self.refresh_code_actions(cx);
11137 if self.has_active_inline_completion(cx) {
11138 self.update_visible_inline_completion(cx);
11139 }
11140 cx.emit(EditorEvent::BufferEdited);
11141 cx.emit(SearchEvent::MatchesInvalidated);
11142 if *singleton_buffer_edited {
11143 if let Some(project) = &self.project {
11144 let project = project.read(cx);
11145 #[allow(clippy::mutable_key_type)]
11146 let languages_affected = multibuffer
11147 .read(cx)
11148 .all_buffers()
11149 .into_iter()
11150 .filter_map(|buffer| {
11151 let buffer = buffer.read(cx);
11152 let language = buffer.language()?;
11153 if project.is_local()
11154 && project.language_servers_for_buffer(buffer, cx).count() == 0
11155 {
11156 None
11157 } else {
11158 Some(language)
11159 }
11160 })
11161 .cloned()
11162 .collect::<HashSet<_>>();
11163 if !languages_affected.is_empty() {
11164 self.refresh_inlay_hints(
11165 InlayHintRefreshReason::BufferEdited(languages_affected),
11166 cx,
11167 );
11168 }
11169 }
11170 }
11171
11172 let Some(project) = &self.project else { return };
11173 let telemetry = project.read(cx).client().telemetry().clone();
11174 refresh_linked_ranges(self, cx);
11175 telemetry.log_edit_event("editor");
11176 }
11177 multi_buffer::Event::ExcerptsAdded {
11178 buffer,
11179 predecessor,
11180 excerpts,
11181 } => {
11182 self.tasks_update_task = Some(self.refresh_runnables(cx));
11183 cx.emit(EditorEvent::ExcerptsAdded {
11184 buffer: buffer.clone(),
11185 predecessor: *predecessor,
11186 excerpts: excerpts.clone(),
11187 });
11188 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11189 }
11190 multi_buffer::Event::ExcerptsRemoved { ids } => {
11191 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11192 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11193 }
11194 multi_buffer::Event::ExcerptsEdited { ids } => {
11195 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11196 }
11197 multi_buffer::Event::ExcerptsExpanded { ids } => {
11198 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11199 }
11200 multi_buffer::Event::Reparsed(buffer_id) => {
11201 self.tasks_update_task = Some(self.refresh_runnables(cx));
11202
11203 cx.emit(EditorEvent::Reparsed(*buffer_id));
11204 }
11205 multi_buffer::Event::LanguageChanged(buffer_id) => {
11206 linked_editing_ranges::refresh_linked_ranges(self, cx);
11207 cx.emit(EditorEvent::Reparsed(*buffer_id));
11208 cx.notify();
11209 }
11210 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11211 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11212 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11213 cx.emit(EditorEvent::TitleChanged)
11214 }
11215 multi_buffer::Event::DiffBaseChanged => {
11216 self.scrollbar_marker_state.dirty = true;
11217 cx.emit(EditorEvent::DiffBaseChanged);
11218 cx.notify();
11219 }
11220 multi_buffer::Event::DiffUpdated { buffer } => {
11221 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11222 cx.notify();
11223 }
11224 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11225 multi_buffer::Event::DiagnosticsUpdated => {
11226 self.refresh_active_diagnostics(cx);
11227 self.scrollbar_marker_state.dirty = true;
11228 cx.notify();
11229 }
11230 _ => {}
11231 };
11232 }
11233
11234 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11235 cx.notify();
11236 }
11237
11238 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11239 self.tasks_update_task = Some(self.refresh_runnables(cx));
11240 self.refresh_inline_completion(true, cx);
11241 self.refresh_inlay_hints(
11242 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11243 self.selections.newest_anchor().head(),
11244 &self.buffer.read(cx).snapshot(cx),
11245 cx,
11246 )),
11247 cx,
11248 );
11249 let editor_settings = EditorSettings::get_global(cx);
11250 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11251 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11252
11253 if self.mode == EditorMode::Full {
11254 let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11255 if self.git_blame_inline_enabled != inline_blame_enabled {
11256 self.toggle_git_blame_inline_internal(false, cx);
11257 }
11258 }
11259
11260 cx.notify();
11261 }
11262
11263 pub fn set_searchable(&mut self, searchable: bool) {
11264 self.searchable = searchable;
11265 }
11266
11267 pub fn searchable(&self) -> bool {
11268 self.searchable
11269 }
11270
11271 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11272 self.open_excerpts_common(true, cx)
11273 }
11274
11275 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11276 self.open_excerpts_common(false, cx)
11277 }
11278
11279 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11280 let buffer = self.buffer.read(cx);
11281 if buffer.is_singleton() {
11282 cx.propagate();
11283 return;
11284 }
11285
11286 let Some(workspace) = self.workspace() else {
11287 cx.propagate();
11288 return;
11289 };
11290
11291 let mut new_selections_by_buffer = HashMap::default();
11292 for selection in self.selections.all::<usize>(cx) {
11293 for (buffer, mut range, _) in
11294 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11295 {
11296 if selection.reversed {
11297 mem::swap(&mut range.start, &mut range.end);
11298 }
11299 new_selections_by_buffer
11300 .entry(buffer)
11301 .or_insert(Vec::new())
11302 .push(range)
11303 }
11304 }
11305
11306 // We defer the pane interaction because we ourselves are a workspace item
11307 // and activating a new item causes the pane to call a method on us reentrantly,
11308 // which panics if we're on the stack.
11309 cx.window_context().defer(move |cx| {
11310 workspace.update(cx, |workspace, cx| {
11311 let pane = if split {
11312 workspace.adjacent_pane(cx)
11313 } else {
11314 workspace.active_pane().clone()
11315 };
11316
11317 for (buffer, ranges) in new_selections_by_buffer {
11318 let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11319 editor.update(cx, |editor, cx| {
11320 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11321 s.select_ranges(ranges);
11322 });
11323 });
11324 }
11325 })
11326 });
11327 }
11328
11329 fn jump(
11330 &mut self,
11331 path: ProjectPath,
11332 position: Point,
11333 anchor: language::Anchor,
11334 offset_from_top: u32,
11335 cx: &mut ViewContext<Self>,
11336 ) {
11337 let workspace = self.workspace();
11338 cx.spawn(|_, mut cx| async move {
11339 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11340 let editor = workspace.update(&mut cx, |workspace, cx| {
11341 // Reset the preview item id before opening the new item
11342 workspace.active_pane().update(cx, |pane, cx| {
11343 pane.set_preview_item_id(None, cx);
11344 });
11345 workspace.open_path_preview(path, None, true, true, cx)
11346 })?;
11347 let editor = editor
11348 .await?
11349 .downcast::<Editor>()
11350 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11351 .downgrade();
11352 editor.update(&mut cx, |editor, cx| {
11353 let buffer = editor
11354 .buffer()
11355 .read(cx)
11356 .as_singleton()
11357 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11358 let buffer = buffer.read(cx);
11359 let cursor = if buffer.can_resolve(&anchor) {
11360 language::ToPoint::to_point(&anchor, buffer)
11361 } else {
11362 buffer.clip_point(position, Bias::Left)
11363 };
11364
11365 let nav_history = editor.nav_history.take();
11366 editor.change_selections(
11367 Some(Autoscroll::top_relative(offset_from_top as usize)),
11368 cx,
11369 |s| {
11370 s.select_ranges([cursor..cursor]);
11371 },
11372 );
11373 editor.nav_history = nav_history;
11374
11375 anyhow::Ok(())
11376 })??;
11377
11378 anyhow::Ok(())
11379 })
11380 .detach_and_log_err(cx);
11381 }
11382
11383 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11384 let snapshot = self.buffer.read(cx).read(cx);
11385 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11386 Some(
11387 ranges
11388 .iter()
11389 .map(move |range| {
11390 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11391 })
11392 .collect(),
11393 )
11394 }
11395
11396 fn selection_replacement_ranges(
11397 &self,
11398 range: Range<OffsetUtf16>,
11399 cx: &AppContext,
11400 ) -> Vec<Range<OffsetUtf16>> {
11401 let selections = self.selections.all::<OffsetUtf16>(cx);
11402 let newest_selection = selections
11403 .iter()
11404 .max_by_key(|selection| selection.id)
11405 .unwrap();
11406 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11407 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11408 let snapshot = self.buffer.read(cx).read(cx);
11409 selections
11410 .into_iter()
11411 .map(|mut selection| {
11412 selection.start.0 =
11413 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11414 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11415 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11416 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11417 })
11418 .collect()
11419 }
11420
11421 fn report_editor_event(
11422 &self,
11423 operation: &'static str,
11424 file_extension: Option<String>,
11425 cx: &AppContext,
11426 ) {
11427 if cfg!(any(test, feature = "test-support")) {
11428 return;
11429 }
11430
11431 let Some(project) = &self.project else { return };
11432
11433 // If None, we are in a file without an extension
11434 let file = self
11435 .buffer
11436 .read(cx)
11437 .as_singleton()
11438 .and_then(|b| b.read(cx).file());
11439 let file_extension = file_extension.or(file
11440 .as_ref()
11441 .and_then(|file| Path::new(file.file_name(cx)).extension())
11442 .and_then(|e| e.to_str())
11443 .map(|a| a.to_string()));
11444
11445 let vim_mode = cx
11446 .global::<SettingsStore>()
11447 .raw_user_settings()
11448 .get("vim_mode")
11449 == Some(&serde_json::Value::Bool(true));
11450
11451 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11452 == language::language_settings::InlineCompletionProvider::Copilot;
11453 let copilot_enabled_for_language = self
11454 .buffer
11455 .read(cx)
11456 .settings_at(0, cx)
11457 .show_inline_completions;
11458
11459 let telemetry = project.read(cx).client().telemetry().clone();
11460 telemetry.report_editor_event(
11461 file_extension,
11462 vim_mode,
11463 operation,
11464 copilot_enabled,
11465 copilot_enabled_for_language,
11466 )
11467 }
11468
11469 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11470 /// with each line being an array of {text, highlight} objects.
11471 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11472 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11473 return;
11474 };
11475
11476 #[derive(Serialize)]
11477 struct Chunk<'a> {
11478 text: String,
11479 highlight: Option<&'a str>,
11480 }
11481
11482 let snapshot = buffer.read(cx).snapshot();
11483 let range = self
11484 .selected_text_range(cx)
11485 .and_then(|selected_range| {
11486 if selected_range.is_empty() {
11487 None
11488 } else {
11489 Some(selected_range)
11490 }
11491 })
11492 .unwrap_or_else(|| 0..snapshot.len());
11493
11494 let chunks = snapshot.chunks(range, true);
11495 let mut lines = Vec::new();
11496 let mut line: VecDeque<Chunk> = VecDeque::new();
11497
11498 let Some(style) = self.style.as_ref() else {
11499 return;
11500 };
11501
11502 for chunk in chunks {
11503 let highlight = chunk
11504 .syntax_highlight_id
11505 .and_then(|id| id.name(&style.syntax));
11506 let mut chunk_lines = chunk.text.split('\n').peekable();
11507 while let Some(text) = chunk_lines.next() {
11508 let mut merged_with_last_token = false;
11509 if let Some(last_token) = line.back_mut() {
11510 if last_token.highlight == highlight {
11511 last_token.text.push_str(text);
11512 merged_with_last_token = true;
11513 }
11514 }
11515
11516 if !merged_with_last_token {
11517 line.push_back(Chunk {
11518 text: text.into(),
11519 highlight,
11520 });
11521 }
11522
11523 if chunk_lines.peek().is_some() {
11524 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11525 line.pop_front();
11526 }
11527 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11528 line.pop_back();
11529 }
11530
11531 lines.push(mem::take(&mut line));
11532 }
11533 }
11534 }
11535
11536 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11537 return;
11538 };
11539 cx.write_to_clipboard(ClipboardItem::new(lines));
11540 }
11541
11542 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11543 &self.inlay_hint_cache
11544 }
11545
11546 pub fn replay_insert_event(
11547 &mut self,
11548 text: &str,
11549 relative_utf16_range: Option<Range<isize>>,
11550 cx: &mut ViewContext<Self>,
11551 ) {
11552 if !self.input_enabled {
11553 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11554 return;
11555 }
11556 if let Some(relative_utf16_range) = relative_utf16_range {
11557 let selections = self.selections.all::<OffsetUtf16>(cx);
11558 self.change_selections(None, cx, |s| {
11559 let new_ranges = selections.into_iter().map(|range| {
11560 let start = OffsetUtf16(
11561 range
11562 .head()
11563 .0
11564 .saturating_add_signed(relative_utf16_range.start),
11565 );
11566 let end = OffsetUtf16(
11567 range
11568 .head()
11569 .0
11570 .saturating_add_signed(relative_utf16_range.end),
11571 );
11572 start..end
11573 });
11574 s.select_ranges(new_ranges);
11575 });
11576 }
11577
11578 self.handle_input(text, cx);
11579 }
11580
11581 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11582 let Some(project) = self.project.as_ref() else {
11583 return false;
11584 };
11585 let project = project.read(cx);
11586
11587 let mut supports = false;
11588 self.buffer().read(cx).for_each_buffer(|buffer| {
11589 if !supports {
11590 supports = project
11591 .language_servers_for_buffer(buffer.read(cx), cx)
11592 .any(
11593 |(_, server)| match server.capabilities().inlay_hint_provider {
11594 Some(lsp::OneOf::Left(enabled)) => enabled,
11595 Some(lsp::OneOf::Right(_)) => true,
11596 None => false,
11597 },
11598 )
11599 }
11600 });
11601 supports
11602 }
11603
11604 pub fn focus(&self, cx: &mut WindowContext) {
11605 cx.focus(&self.focus_handle)
11606 }
11607
11608 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11609 self.focus_handle.is_focused(cx)
11610 }
11611
11612 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11613 cx.emit(EditorEvent::Focused);
11614
11615 if let Some(descendant) = self
11616 .last_focused_descendant
11617 .take()
11618 .and_then(|descendant| descendant.upgrade())
11619 {
11620 cx.focus(&descendant);
11621 } else {
11622 if let Some(blame) = self.blame.as_ref() {
11623 blame.update(cx, GitBlame::focus)
11624 }
11625
11626 self.blink_manager.update(cx, BlinkManager::enable);
11627 self.show_cursor_names(cx);
11628 self.buffer.update(cx, |buffer, cx| {
11629 buffer.finalize_last_transaction(cx);
11630 if self.leader_peer_id.is_none() {
11631 buffer.set_active_selections(
11632 &self.selections.disjoint_anchors(),
11633 self.selections.line_mode,
11634 self.cursor_shape,
11635 cx,
11636 );
11637 }
11638 });
11639 }
11640 }
11641
11642 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11643 cx.emit(EditorEvent::FocusedIn)
11644 }
11645
11646 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11647 if event.blurred != self.focus_handle {
11648 self.last_focused_descendant = Some(event.blurred);
11649 }
11650 }
11651
11652 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11653 self.blink_manager.update(cx, BlinkManager::disable);
11654 self.buffer
11655 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11656
11657 if let Some(blame) = self.blame.as_ref() {
11658 blame.update(cx, GitBlame::blur)
11659 }
11660 if !self.hover_state.focused(cx) {
11661 hide_hover(self, cx);
11662 }
11663
11664 self.hide_context_menu(cx);
11665 cx.emit(EditorEvent::Blurred);
11666 cx.notify();
11667 }
11668
11669 pub fn register_action<A: Action>(
11670 &mut self,
11671 listener: impl Fn(&A, &mut WindowContext) + 'static,
11672 ) -> Subscription {
11673 let id = self.next_editor_action_id.post_inc();
11674 let listener = Arc::new(listener);
11675 self.editor_actions.borrow_mut().insert(
11676 id,
11677 Box::new(move |cx| {
11678 let _view = cx.view().clone();
11679 let cx = cx.window_context();
11680 let listener = listener.clone();
11681 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11682 let action = action.downcast_ref().unwrap();
11683 if phase == DispatchPhase::Bubble {
11684 listener(action, cx)
11685 }
11686 })
11687 }),
11688 );
11689
11690 let editor_actions = self.editor_actions.clone();
11691 Subscription::new(move || {
11692 editor_actions.borrow_mut().remove(&id);
11693 })
11694 }
11695
11696 pub fn file_header_size(&self) -> u8 {
11697 self.file_header_size
11698 }
11699}
11700
11701fn hunks_for_selections(
11702 multi_buffer_snapshot: &MultiBufferSnapshot,
11703 selections: &[Selection<Anchor>],
11704) -> Vec<DiffHunk<MultiBufferRow>> {
11705 let mut hunks = Vec::with_capacity(selections.len());
11706 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11707 HashMap::default();
11708 let buffer_rows_for_selections = selections.iter().map(|selection| {
11709 let head = selection.head();
11710 let tail = selection.tail();
11711 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11712 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11713 if start > end {
11714 end..start
11715 } else {
11716 start..end
11717 }
11718 });
11719
11720 for selected_multi_buffer_rows in buffer_rows_for_selections {
11721 let query_rows =
11722 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11723 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11724 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11725 // when the caret is just above or just below the deleted hunk.
11726 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11727 let related_to_selection = if allow_adjacent {
11728 hunk.associated_range.overlaps(&query_rows)
11729 || hunk.associated_range.start == query_rows.end
11730 || hunk.associated_range.end == query_rows.start
11731 } else {
11732 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11733 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11734 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11735 || selected_multi_buffer_rows.end == hunk.associated_range.start
11736 };
11737 if related_to_selection {
11738 if !processed_buffer_rows
11739 .entry(hunk.buffer_id)
11740 .or_default()
11741 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11742 {
11743 continue;
11744 }
11745 hunks.push(hunk);
11746 }
11747 }
11748 }
11749
11750 hunks
11751}
11752
11753pub trait CollaborationHub {
11754 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11755 fn user_participant_indices<'a>(
11756 &self,
11757 cx: &'a AppContext,
11758 ) -> &'a HashMap<u64, ParticipantIndex>;
11759 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11760}
11761
11762impl CollaborationHub for Model<Project> {
11763 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11764 self.read(cx).collaborators()
11765 }
11766
11767 fn user_participant_indices<'a>(
11768 &self,
11769 cx: &'a AppContext,
11770 ) -> &'a HashMap<u64, ParticipantIndex> {
11771 self.read(cx).user_store().read(cx).participant_indices()
11772 }
11773
11774 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11775 let this = self.read(cx);
11776 let user_ids = this.collaborators().values().map(|c| c.user_id);
11777 this.user_store().read_with(cx, |user_store, cx| {
11778 user_store.participant_names(user_ids, cx)
11779 })
11780 }
11781}
11782
11783pub trait CompletionProvider {
11784 fn completions(
11785 &self,
11786 buffer: &Model<Buffer>,
11787 buffer_position: text::Anchor,
11788 trigger: CompletionContext,
11789 cx: &mut ViewContext<Editor>,
11790 ) -> Task<Result<Vec<Completion>>>;
11791
11792 fn resolve_completions(
11793 &self,
11794 buffer: Model<Buffer>,
11795 completion_indices: Vec<usize>,
11796 completions: Arc<RwLock<Box<[Completion]>>>,
11797 cx: &mut ViewContext<Editor>,
11798 ) -> Task<Result<bool>>;
11799
11800 fn apply_additional_edits_for_completion(
11801 &self,
11802 buffer: Model<Buffer>,
11803 completion: Completion,
11804 push_to_history: bool,
11805 cx: &mut ViewContext<Editor>,
11806 ) -> Task<Result<Option<language::Transaction>>>;
11807
11808 fn is_completion_trigger(
11809 &self,
11810 buffer: &Model<Buffer>,
11811 position: language::Anchor,
11812 text: &str,
11813 trigger_in_words: bool,
11814 cx: &mut ViewContext<Editor>,
11815 ) -> bool;
11816}
11817
11818fn snippet_completions(
11819 project: &Project,
11820 buffer: &Model<Buffer>,
11821 buffer_position: text::Anchor,
11822 cx: &mut AppContext,
11823) -> Vec<Completion> {
11824 let language = buffer.read(cx).language_at(buffer_position);
11825 let language_name = language.as_ref().map(|language| language.lsp_id());
11826 let snippet_store = project.snippets().read(cx);
11827 let snippets = snippet_store.snippets_for(language_name, cx);
11828
11829 if snippets.is_empty() {
11830 return vec![];
11831 }
11832 let snapshot = buffer.read(cx).text_snapshot();
11833 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11834
11835 let mut lines = chunks.lines();
11836 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11837 return vec![];
11838 };
11839
11840 let scope = language.map(|language| language.default_scope());
11841 let mut last_word = line_at
11842 .chars()
11843 .rev()
11844 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
11845 .collect::<String>();
11846 last_word = last_word.chars().rev().collect();
11847 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
11848 let to_lsp = |point: &text::Anchor| {
11849 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
11850 point_to_lsp(end)
11851 };
11852 let lsp_end = to_lsp(&buffer_position);
11853 snippets
11854 .into_iter()
11855 .filter_map(|snippet| {
11856 let matching_prefix = snippet
11857 .prefix
11858 .iter()
11859 .find(|prefix| prefix.starts_with(&last_word))?;
11860 let start = as_offset - last_word.len();
11861 let start = snapshot.anchor_before(start);
11862 let range = start..buffer_position;
11863 let lsp_start = to_lsp(&start);
11864 let lsp_range = lsp::Range {
11865 start: lsp_start,
11866 end: lsp_end,
11867 };
11868 Some(Completion {
11869 old_range: range,
11870 new_text: snippet.body.clone(),
11871 label: CodeLabel {
11872 text: matching_prefix.clone(),
11873 runs: vec![],
11874 filter_range: 0..matching_prefix.len(),
11875 },
11876 server_id: LanguageServerId(usize::MAX),
11877 documentation: snippet
11878 .description
11879 .clone()
11880 .map(|description| Documentation::SingleLine(description)),
11881 lsp_completion: lsp::CompletionItem {
11882 label: snippet.prefix.first().unwrap().clone(),
11883 kind: Some(CompletionItemKind::SNIPPET),
11884 label_details: snippet.description.as_ref().map(|description| {
11885 lsp::CompletionItemLabelDetails {
11886 detail: Some(description.clone()),
11887 description: None,
11888 }
11889 }),
11890 insert_text_format: Some(InsertTextFormat::SNIPPET),
11891 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
11892 lsp::InsertReplaceEdit {
11893 new_text: snippet.body.clone(),
11894 insert: lsp_range,
11895 replace: lsp_range,
11896 },
11897 )),
11898 filter_text: Some(snippet.body.clone()),
11899 sort_text: Some(char::MAX.to_string()),
11900 ..Default::default()
11901 },
11902 confirm: None,
11903 show_new_completions_on_confirm: false,
11904 })
11905 })
11906 .collect()
11907}
11908
11909impl CompletionProvider for Model<Project> {
11910 fn completions(
11911 &self,
11912 buffer: &Model<Buffer>,
11913 buffer_position: text::Anchor,
11914 options: CompletionContext,
11915 cx: &mut ViewContext<Editor>,
11916 ) -> Task<Result<Vec<Completion>>> {
11917 self.update(cx, |project, cx| {
11918 let snippets = snippet_completions(project, buffer, buffer_position, cx);
11919 let project_completions = project.completions(&buffer, buffer_position, options, cx);
11920 cx.background_executor().spawn(async move {
11921 let mut completions = project_completions.await?;
11922 //let snippets = snippets.into_iter().;
11923 completions.extend(snippets);
11924 Ok(completions)
11925 })
11926 })
11927 }
11928
11929 fn resolve_completions(
11930 &self,
11931 buffer: Model<Buffer>,
11932 completion_indices: Vec<usize>,
11933 completions: Arc<RwLock<Box<[Completion]>>>,
11934 cx: &mut ViewContext<Editor>,
11935 ) -> Task<Result<bool>> {
11936 self.update(cx, |project, cx| {
11937 project.resolve_completions(buffer, completion_indices, completions, cx)
11938 })
11939 }
11940
11941 fn apply_additional_edits_for_completion(
11942 &self,
11943 buffer: Model<Buffer>,
11944 completion: Completion,
11945 push_to_history: bool,
11946 cx: &mut ViewContext<Editor>,
11947 ) -> Task<Result<Option<language::Transaction>>> {
11948 self.update(cx, |project, cx| {
11949 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11950 })
11951 }
11952
11953 fn is_completion_trigger(
11954 &self,
11955 buffer: &Model<Buffer>,
11956 position: language::Anchor,
11957 text: &str,
11958 trigger_in_words: bool,
11959 cx: &mut ViewContext<Editor>,
11960 ) -> bool {
11961 if !EditorSettings::get_global(cx).show_completions_on_input {
11962 return false;
11963 }
11964
11965 let mut chars = text.chars();
11966 let char = if let Some(char) = chars.next() {
11967 char
11968 } else {
11969 return false;
11970 };
11971 if chars.next().is_some() {
11972 return false;
11973 }
11974
11975 let buffer = buffer.read(cx);
11976 let scope = buffer.snapshot().language_scope_at(position);
11977 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11978 return true;
11979 }
11980
11981 buffer
11982 .completion_triggers()
11983 .iter()
11984 .any(|string| string == text)
11985 }
11986}
11987
11988fn inlay_hint_settings(
11989 location: Anchor,
11990 snapshot: &MultiBufferSnapshot,
11991 cx: &mut ViewContext<'_, Editor>,
11992) -> InlayHintSettings {
11993 let file = snapshot.file_at(location);
11994 let language = snapshot.language_at(location);
11995 let settings = all_language_settings(file, cx);
11996 settings
11997 .language(language.map(|l| l.name()).as_deref())
11998 .inlay_hints
11999}
12000
12001fn consume_contiguous_rows(
12002 contiguous_row_selections: &mut Vec<Selection<Point>>,
12003 selection: &Selection<Point>,
12004 display_map: &DisplaySnapshot,
12005 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12006) -> (MultiBufferRow, MultiBufferRow) {
12007 contiguous_row_selections.push(selection.clone());
12008 let start_row = MultiBufferRow(selection.start.row);
12009 let mut end_row = ending_row(selection, display_map);
12010
12011 while let Some(next_selection) = selections.peek() {
12012 if next_selection.start.row <= end_row.0 {
12013 end_row = ending_row(next_selection, display_map);
12014 contiguous_row_selections.push(selections.next().unwrap().clone());
12015 } else {
12016 break;
12017 }
12018 }
12019 (start_row, end_row)
12020}
12021
12022fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12023 if next_selection.end.column > 0 || next_selection.is_empty() {
12024 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12025 } else {
12026 MultiBufferRow(next_selection.end.row)
12027 }
12028}
12029
12030impl EditorSnapshot {
12031 pub fn remote_selections_in_range<'a>(
12032 &'a self,
12033 range: &'a Range<Anchor>,
12034 collaboration_hub: &dyn CollaborationHub,
12035 cx: &'a AppContext,
12036 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12037 let participant_names = collaboration_hub.user_names(cx);
12038 let participant_indices = collaboration_hub.user_participant_indices(cx);
12039 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12040 let collaborators_by_replica_id = collaborators_by_peer_id
12041 .iter()
12042 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12043 .collect::<HashMap<_, _>>();
12044 self.buffer_snapshot
12045 .selections_in_range(range, false)
12046 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12047 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12048 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12049 let user_name = participant_names.get(&collaborator.user_id).cloned();
12050 Some(RemoteSelection {
12051 replica_id,
12052 selection,
12053 cursor_shape,
12054 line_mode,
12055 participant_index,
12056 peer_id: collaborator.peer_id,
12057 user_name,
12058 })
12059 })
12060 }
12061
12062 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12063 self.display_snapshot.buffer_snapshot.language_at(position)
12064 }
12065
12066 pub fn is_focused(&self) -> bool {
12067 self.is_focused
12068 }
12069
12070 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12071 self.placeholder_text.as_ref()
12072 }
12073
12074 pub fn scroll_position(&self) -> gpui::Point<f32> {
12075 self.scroll_anchor.scroll_position(&self.display_snapshot)
12076 }
12077
12078 pub fn gutter_dimensions(
12079 &self,
12080 font_id: FontId,
12081 font_size: Pixels,
12082 em_width: Pixels,
12083 max_line_number_width: Pixels,
12084 cx: &AppContext,
12085 ) -> GutterDimensions {
12086 if !self.show_gutter {
12087 return GutterDimensions::default();
12088 }
12089 let descent = cx.text_system().descent(font_id, font_size);
12090
12091 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12092 matches!(
12093 ProjectSettings::get_global(cx).git.git_gutter,
12094 Some(GitGutterSetting::TrackedFiles)
12095 )
12096 });
12097 let gutter_settings = EditorSettings::get_global(cx).gutter;
12098 let show_line_numbers = self
12099 .show_line_numbers
12100 .unwrap_or(gutter_settings.line_numbers);
12101 let line_gutter_width = if show_line_numbers {
12102 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12103 let min_width_for_number_on_gutter = em_width * 4.0;
12104 max_line_number_width.max(min_width_for_number_on_gutter)
12105 } else {
12106 0.0.into()
12107 };
12108
12109 let show_code_actions = self
12110 .show_code_actions
12111 .unwrap_or(gutter_settings.code_actions);
12112
12113 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12114
12115 let git_blame_entries_width = self
12116 .render_git_blame_gutter
12117 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12118
12119 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12120 left_padding += if show_code_actions || show_runnables {
12121 em_width * 3.0
12122 } else if show_git_gutter && show_line_numbers {
12123 em_width * 2.0
12124 } else if show_git_gutter || show_line_numbers {
12125 em_width
12126 } else {
12127 px(0.)
12128 };
12129
12130 let right_padding = if gutter_settings.folds && show_line_numbers {
12131 em_width * 4.0
12132 } else if gutter_settings.folds {
12133 em_width * 3.0
12134 } else if show_line_numbers {
12135 em_width
12136 } else {
12137 px(0.)
12138 };
12139
12140 GutterDimensions {
12141 left_padding,
12142 right_padding,
12143 width: line_gutter_width + left_padding + right_padding,
12144 margin: -descent,
12145 git_blame_entries_width,
12146 }
12147 }
12148
12149 pub fn render_fold_toggle(
12150 &self,
12151 buffer_row: MultiBufferRow,
12152 row_contains_cursor: bool,
12153 editor: View<Editor>,
12154 cx: &mut WindowContext,
12155 ) -> Option<AnyElement> {
12156 let folded = self.is_line_folded(buffer_row);
12157
12158 if let Some(crease) = self
12159 .crease_snapshot
12160 .query_row(buffer_row, &self.buffer_snapshot)
12161 {
12162 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12163 if folded {
12164 editor.update(cx, |editor, cx| {
12165 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12166 });
12167 } else {
12168 editor.update(cx, |editor, cx| {
12169 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12170 });
12171 }
12172 });
12173
12174 Some((crease.render_toggle)(
12175 buffer_row,
12176 folded,
12177 toggle_callback,
12178 cx,
12179 ))
12180 } else if folded
12181 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12182 {
12183 Some(
12184 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12185 .selected(folded)
12186 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12187 if folded {
12188 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12189 } else {
12190 this.fold_at(&FoldAt { buffer_row }, cx);
12191 }
12192 }))
12193 .into_any_element(),
12194 )
12195 } else {
12196 None
12197 }
12198 }
12199
12200 pub fn render_crease_trailer(
12201 &self,
12202 buffer_row: MultiBufferRow,
12203 cx: &mut WindowContext,
12204 ) -> Option<AnyElement> {
12205 let folded = self.is_line_folded(buffer_row);
12206 let crease = self
12207 .crease_snapshot
12208 .query_row(buffer_row, &self.buffer_snapshot)?;
12209 Some((crease.render_trailer)(buffer_row, folded, cx))
12210 }
12211}
12212
12213impl Deref for EditorSnapshot {
12214 type Target = DisplaySnapshot;
12215
12216 fn deref(&self) -> &Self::Target {
12217 &self.display_snapshot
12218 }
12219}
12220
12221#[derive(Clone, Debug, PartialEq, Eq)]
12222pub enum EditorEvent {
12223 InputIgnored {
12224 text: Arc<str>,
12225 },
12226 InputHandled {
12227 utf16_range_to_replace: Option<Range<isize>>,
12228 text: Arc<str>,
12229 },
12230 ExcerptsAdded {
12231 buffer: Model<Buffer>,
12232 predecessor: ExcerptId,
12233 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12234 },
12235 ExcerptsRemoved {
12236 ids: Vec<ExcerptId>,
12237 },
12238 ExcerptsEdited {
12239 ids: Vec<ExcerptId>,
12240 },
12241 ExcerptsExpanded {
12242 ids: Vec<ExcerptId>,
12243 },
12244 BufferEdited,
12245 Edited {
12246 transaction_id: clock::Lamport,
12247 },
12248 Reparsed(BufferId),
12249 Focused,
12250 FocusedIn,
12251 Blurred,
12252 DirtyChanged,
12253 Saved,
12254 TitleChanged,
12255 DiffBaseChanged,
12256 SelectionsChanged {
12257 local: bool,
12258 },
12259 ScrollPositionChanged {
12260 local: bool,
12261 autoscroll: bool,
12262 },
12263 Closed,
12264 TransactionUndone {
12265 transaction_id: clock::Lamport,
12266 },
12267 TransactionBegun {
12268 transaction_id: clock::Lamport,
12269 },
12270}
12271
12272impl EventEmitter<EditorEvent> for Editor {}
12273
12274impl FocusableView for Editor {
12275 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12276 self.focus_handle.clone()
12277 }
12278}
12279
12280impl Render for Editor {
12281 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12282 let settings = ThemeSettings::get_global(cx);
12283
12284 let text_style = match self.mode {
12285 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12286 color: cx.theme().colors().editor_foreground,
12287 font_family: settings.ui_font.family.clone(),
12288 font_features: settings.ui_font.features.clone(),
12289 font_size: rems(0.875).into(),
12290 font_weight: settings.ui_font.weight,
12291 font_style: FontStyle::Normal,
12292 line_height: relative(settings.buffer_line_height.value()),
12293 background_color: None,
12294 underline: None,
12295 strikethrough: None,
12296 white_space: WhiteSpace::Normal,
12297 },
12298 EditorMode::Full => TextStyle {
12299 color: cx.theme().colors().editor_foreground,
12300 font_family: settings.buffer_font.family.clone(),
12301 font_features: settings.buffer_font.features.clone(),
12302 font_size: settings.buffer_font_size(cx).into(),
12303 font_weight: settings.buffer_font.weight,
12304 font_style: FontStyle::Normal,
12305 line_height: relative(settings.buffer_line_height.value()),
12306 background_color: None,
12307 underline: None,
12308 strikethrough: None,
12309 white_space: WhiteSpace::Normal,
12310 },
12311 };
12312
12313 let background = match self.mode {
12314 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12315 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12316 EditorMode::Full => cx.theme().colors().editor_background,
12317 };
12318
12319 EditorElement::new(
12320 cx.view(),
12321 EditorStyle {
12322 background,
12323 local_player: cx.theme().players().local(),
12324 text: text_style,
12325 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12326 syntax: cx.theme().syntax().clone(),
12327 status: cx.theme().status().clone(),
12328 inlay_hints_style: HighlightStyle {
12329 color: Some(cx.theme().status().hint),
12330 ..HighlightStyle::default()
12331 },
12332 suggestions_style: HighlightStyle {
12333 color: Some(cx.theme().status().predictive),
12334 ..HighlightStyle::default()
12335 },
12336 },
12337 )
12338 }
12339}
12340
12341impl ViewInputHandler for Editor {
12342 fn text_for_range(
12343 &mut self,
12344 range_utf16: Range<usize>,
12345 cx: &mut ViewContext<Self>,
12346 ) -> Option<String> {
12347 Some(
12348 self.buffer
12349 .read(cx)
12350 .read(cx)
12351 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12352 .collect(),
12353 )
12354 }
12355
12356 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12357 // Prevent the IME menu from appearing when holding down an alphabetic key
12358 // while input is disabled.
12359 if !self.input_enabled {
12360 return None;
12361 }
12362
12363 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12364 Some(range.start.0..range.end.0)
12365 }
12366
12367 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12368 let snapshot = self.buffer.read(cx).read(cx);
12369 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12370 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12371 }
12372
12373 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12374 self.clear_highlights::<InputComposition>(cx);
12375 self.ime_transaction.take();
12376 }
12377
12378 fn replace_text_in_range(
12379 &mut self,
12380 range_utf16: Option<Range<usize>>,
12381 text: &str,
12382 cx: &mut ViewContext<Self>,
12383 ) {
12384 if !self.input_enabled {
12385 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12386 return;
12387 }
12388
12389 self.transact(cx, |this, cx| {
12390 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12391 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12392 Some(this.selection_replacement_ranges(range_utf16, cx))
12393 } else {
12394 this.marked_text_ranges(cx)
12395 };
12396
12397 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12398 let newest_selection_id = this.selections.newest_anchor().id;
12399 this.selections
12400 .all::<OffsetUtf16>(cx)
12401 .iter()
12402 .zip(ranges_to_replace.iter())
12403 .find_map(|(selection, range)| {
12404 if selection.id == newest_selection_id {
12405 Some(
12406 (range.start.0 as isize - selection.head().0 as isize)
12407 ..(range.end.0 as isize - selection.head().0 as isize),
12408 )
12409 } else {
12410 None
12411 }
12412 })
12413 });
12414
12415 cx.emit(EditorEvent::InputHandled {
12416 utf16_range_to_replace: range_to_replace,
12417 text: text.into(),
12418 });
12419
12420 if let Some(new_selected_ranges) = new_selected_ranges {
12421 this.change_selections(None, cx, |selections| {
12422 selections.select_ranges(new_selected_ranges)
12423 });
12424 this.backspace(&Default::default(), cx);
12425 }
12426
12427 this.handle_input(text, cx);
12428 });
12429
12430 if let Some(transaction) = self.ime_transaction {
12431 self.buffer.update(cx, |buffer, cx| {
12432 buffer.group_until_transaction(transaction, cx);
12433 });
12434 }
12435
12436 self.unmark_text(cx);
12437 }
12438
12439 fn replace_and_mark_text_in_range(
12440 &mut self,
12441 range_utf16: Option<Range<usize>>,
12442 text: &str,
12443 new_selected_range_utf16: Option<Range<usize>>,
12444 cx: &mut ViewContext<Self>,
12445 ) {
12446 if !self.input_enabled {
12447 return;
12448 }
12449
12450 let transaction = self.transact(cx, |this, cx| {
12451 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12452 let snapshot = this.buffer.read(cx).read(cx);
12453 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12454 for marked_range in &mut marked_ranges {
12455 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12456 marked_range.start.0 += relative_range_utf16.start;
12457 marked_range.start =
12458 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12459 marked_range.end =
12460 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12461 }
12462 }
12463 Some(marked_ranges)
12464 } else if let Some(range_utf16) = range_utf16 {
12465 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12466 Some(this.selection_replacement_ranges(range_utf16, cx))
12467 } else {
12468 None
12469 };
12470
12471 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12472 let newest_selection_id = this.selections.newest_anchor().id;
12473 this.selections
12474 .all::<OffsetUtf16>(cx)
12475 .iter()
12476 .zip(ranges_to_replace.iter())
12477 .find_map(|(selection, range)| {
12478 if selection.id == newest_selection_id {
12479 Some(
12480 (range.start.0 as isize - selection.head().0 as isize)
12481 ..(range.end.0 as isize - selection.head().0 as isize),
12482 )
12483 } else {
12484 None
12485 }
12486 })
12487 });
12488
12489 cx.emit(EditorEvent::InputHandled {
12490 utf16_range_to_replace: range_to_replace,
12491 text: text.into(),
12492 });
12493
12494 if let Some(ranges) = ranges_to_replace {
12495 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12496 }
12497
12498 let marked_ranges = {
12499 let snapshot = this.buffer.read(cx).read(cx);
12500 this.selections
12501 .disjoint_anchors()
12502 .iter()
12503 .map(|selection| {
12504 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12505 })
12506 .collect::<Vec<_>>()
12507 };
12508
12509 if text.is_empty() {
12510 this.unmark_text(cx);
12511 } else {
12512 this.highlight_text::<InputComposition>(
12513 marked_ranges.clone(),
12514 HighlightStyle {
12515 underline: Some(UnderlineStyle {
12516 thickness: px(1.),
12517 color: None,
12518 wavy: false,
12519 }),
12520 ..Default::default()
12521 },
12522 cx,
12523 );
12524 }
12525
12526 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12527 let use_autoclose = this.use_autoclose;
12528 let use_auto_surround = this.use_auto_surround;
12529 this.set_use_autoclose(false);
12530 this.set_use_auto_surround(false);
12531 this.handle_input(text, cx);
12532 this.set_use_autoclose(use_autoclose);
12533 this.set_use_auto_surround(use_auto_surround);
12534
12535 if let Some(new_selected_range) = new_selected_range_utf16 {
12536 let snapshot = this.buffer.read(cx).read(cx);
12537 let new_selected_ranges = marked_ranges
12538 .into_iter()
12539 .map(|marked_range| {
12540 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12541 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12542 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12543 snapshot.clip_offset_utf16(new_start, Bias::Left)
12544 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12545 })
12546 .collect::<Vec<_>>();
12547
12548 drop(snapshot);
12549 this.change_selections(None, cx, |selections| {
12550 selections.select_ranges(new_selected_ranges)
12551 });
12552 }
12553 });
12554
12555 self.ime_transaction = self.ime_transaction.or(transaction);
12556 if let Some(transaction) = self.ime_transaction {
12557 self.buffer.update(cx, |buffer, cx| {
12558 buffer.group_until_transaction(transaction, cx);
12559 });
12560 }
12561
12562 if self.text_highlights::<InputComposition>(cx).is_none() {
12563 self.ime_transaction.take();
12564 }
12565 }
12566
12567 fn bounds_for_range(
12568 &mut self,
12569 range_utf16: Range<usize>,
12570 element_bounds: gpui::Bounds<Pixels>,
12571 cx: &mut ViewContext<Self>,
12572 ) -> Option<gpui::Bounds<Pixels>> {
12573 let text_layout_details = self.text_layout_details(cx);
12574 let style = &text_layout_details.editor_style;
12575 let font_id = cx.text_system().resolve_font(&style.text.font());
12576 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12577 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12578
12579 let em_width = cx
12580 .text_system()
12581 .typographic_bounds(font_id, font_size, 'm')
12582 .unwrap()
12583 .size
12584 .width;
12585
12586 let snapshot = self.snapshot(cx);
12587 let scroll_position = snapshot.scroll_position();
12588 let scroll_left = scroll_position.x * em_width;
12589
12590 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12591 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12592 + self.gutter_dimensions.width;
12593 let y = line_height * (start.row().as_f32() - scroll_position.y);
12594
12595 Some(Bounds {
12596 origin: element_bounds.origin + point(x, y),
12597 size: size(em_width, line_height),
12598 })
12599 }
12600}
12601
12602trait SelectionExt {
12603 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12604 fn spanned_rows(
12605 &self,
12606 include_end_if_at_line_start: bool,
12607 map: &DisplaySnapshot,
12608 ) -> Range<MultiBufferRow>;
12609}
12610
12611impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12612 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12613 let start = self
12614 .start
12615 .to_point(&map.buffer_snapshot)
12616 .to_display_point(map);
12617 let end = self
12618 .end
12619 .to_point(&map.buffer_snapshot)
12620 .to_display_point(map);
12621 if self.reversed {
12622 end..start
12623 } else {
12624 start..end
12625 }
12626 }
12627
12628 fn spanned_rows(
12629 &self,
12630 include_end_if_at_line_start: bool,
12631 map: &DisplaySnapshot,
12632 ) -> Range<MultiBufferRow> {
12633 let start = self.start.to_point(&map.buffer_snapshot);
12634 let mut end = self.end.to_point(&map.buffer_snapshot);
12635 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12636 end.row -= 1;
12637 }
12638
12639 let buffer_start = map.prev_line_boundary(start).0;
12640 let buffer_end = map.next_line_boundary(end).0;
12641 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12642 }
12643}
12644
12645impl<T: InvalidationRegion> InvalidationStack<T> {
12646 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12647 where
12648 S: Clone + ToOffset,
12649 {
12650 while let Some(region) = self.last() {
12651 let all_selections_inside_invalidation_ranges =
12652 if selections.len() == region.ranges().len() {
12653 selections
12654 .iter()
12655 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12656 .all(|(selection, invalidation_range)| {
12657 let head = selection.head().to_offset(buffer);
12658 invalidation_range.start <= head && invalidation_range.end >= head
12659 })
12660 } else {
12661 false
12662 };
12663
12664 if all_selections_inside_invalidation_ranges {
12665 break;
12666 } else {
12667 self.pop();
12668 }
12669 }
12670 }
12671}
12672
12673impl<T> Default for InvalidationStack<T> {
12674 fn default() -> Self {
12675 Self(Default::default())
12676 }
12677}
12678
12679impl<T> Deref for InvalidationStack<T> {
12680 type Target = Vec<T>;
12681
12682 fn deref(&self) -> &Self::Target {
12683 &self.0
12684 }
12685}
12686
12687impl<T> DerefMut for InvalidationStack<T> {
12688 fn deref_mut(&mut self) -> &mut Self::Target {
12689 &mut self.0
12690 }
12691}
12692
12693impl InvalidationRegion for SnippetState {
12694 fn ranges(&self) -> &[Range<Anchor>] {
12695 &self.ranges[self.active_index]
12696 }
12697}
12698
12699pub fn diagnostic_block_renderer(
12700 diagnostic: Diagnostic,
12701 max_message_rows: Option<u8>,
12702 allow_closing: bool,
12703 _is_valid: bool,
12704) -> RenderBlock {
12705 let (text_without_backticks, code_ranges) =
12706 highlight_diagnostic_message(&diagnostic, max_message_rows);
12707
12708 Box::new(move |cx: &mut BlockContext| {
12709 let group_id: SharedString = cx.transform_block_id.to_string().into();
12710
12711 let mut text_style = cx.text_style().clone();
12712 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12713 let theme_settings = ThemeSettings::get_global(cx);
12714 text_style.font_family = theme_settings.buffer_font.family.clone();
12715 text_style.font_style = theme_settings.buffer_font.style;
12716 text_style.font_features = theme_settings.buffer_font.features.clone();
12717 text_style.font_weight = theme_settings.buffer_font.weight;
12718
12719 let multi_line_diagnostic = diagnostic.message.contains('\n');
12720
12721 let buttons = |diagnostic: &Diagnostic, block_id: TransformBlockId| {
12722 if multi_line_diagnostic {
12723 v_flex()
12724 } else {
12725 h_flex()
12726 }
12727 .when(allow_closing, |div| {
12728 div.children(diagnostic.is_primary.then(|| {
12729 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12730 .icon_color(Color::Muted)
12731 .size(ButtonSize::Compact)
12732 .style(ButtonStyle::Transparent)
12733 .visible_on_hover(group_id.clone())
12734 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12735 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12736 }))
12737 })
12738 .child(
12739 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12740 .icon_color(Color::Muted)
12741 .size(ButtonSize::Compact)
12742 .style(ButtonStyle::Transparent)
12743 .visible_on_hover(group_id.clone())
12744 .on_click({
12745 let message = diagnostic.message.clone();
12746 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12747 })
12748 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12749 )
12750 };
12751
12752 let icon_size = buttons(&diagnostic, cx.transform_block_id)
12753 .into_any_element()
12754 .layout_as_root(AvailableSpace::min_size(), cx);
12755
12756 h_flex()
12757 .id(cx.transform_block_id)
12758 .group(group_id.clone())
12759 .relative()
12760 .size_full()
12761 .pl(cx.gutter_dimensions.width)
12762 .w(cx.max_width + cx.gutter_dimensions.width)
12763 .child(
12764 div()
12765 .flex()
12766 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12767 .flex_shrink(),
12768 )
12769 .child(buttons(&diagnostic, cx.transform_block_id))
12770 .child(div().flex().flex_shrink_0().child(
12771 StyledText::new(text_without_backticks.clone()).with_highlights(
12772 &text_style,
12773 code_ranges.iter().map(|range| {
12774 (
12775 range.clone(),
12776 HighlightStyle {
12777 font_weight: Some(FontWeight::BOLD),
12778 ..Default::default()
12779 },
12780 )
12781 }),
12782 ),
12783 ))
12784 .into_any_element()
12785 })
12786}
12787
12788pub fn highlight_diagnostic_message(
12789 diagnostic: &Diagnostic,
12790 mut max_message_rows: Option<u8>,
12791) -> (SharedString, Vec<Range<usize>>) {
12792 let mut text_without_backticks = String::new();
12793 let mut code_ranges = Vec::new();
12794
12795 if let Some(source) = &diagnostic.source {
12796 text_without_backticks.push_str(&source);
12797 code_ranges.push(0..source.len());
12798 text_without_backticks.push_str(": ");
12799 }
12800
12801 let mut prev_offset = 0;
12802 let mut in_code_block = false;
12803 let mut newline_indices = diagnostic
12804 .message
12805 .match_indices('\n')
12806 .map(|(ix, _)| ix)
12807 .fuse()
12808 .peekable();
12809 for (ix, _) in diagnostic
12810 .message
12811 .match_indices('`')
12812 .chain([(diagnostic.message.len(), "")])
12813 {
12814 let mut trimmed_ix = ix;
12815 while let Some(newline_index) = newline_indices.peek() {
12816 if *newline_index < ix {
12817 if let Some(rows_left) = &mut max_message_rows {
12818 if *rows_left == 0 {
12819 trimmed_ix = newline_index.saturating_sub(1);
12820 break;
12821 } else {
12822 *rows_left -= 1;
12823 }
12824 }
12825 let _ = newline_indices.next();
12826 } else {
12827 break;
12828 }
12829 }
12830 let prev_len = text_without_backticks.len();
12831 let new_text = &diagnostic.message[prev_offset..trimmed_ix];
12832 text_without_backticks.push_str(new_text);
12833 if in_code_block {
12834 code_ranges.push(prev_len..text_without_backticks.len());
12835 }
12836 prev_offset = trimmed_ix + 1;
12837 in_code_block = !in_code_block;
12838 if trimmed_ix != ix {
12839 text_without_backticks.push_str("...");
12840 break;
12841 }
12842 }
12843
12844 (text_without_backticks.into(), code_ranges)
12845}
12846
12847fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12848 match severity {
12849 DiagnosticSeverity::ERROR => colors.error,
12850 DiagnosticSeverity::WARNING => colors.warning,
12851 DiagnosticSeverity::INFORMATION => colors.info,
12852 DiagnosticSeverity::HINT => colors.info,
12853 _ => colors.ignored,
12854 }
12855}
12856
12857pub fn styled_runs_for_code_label<'a>(
12858 label: &'a CodeLabel,
12859 syntax_theme: &'a theme::SyntaxTheme,
12860) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12861 let fade_out = HighlightStyle {
12862 fade_out: Some(0.35),
12863 ..Default::default()
12864 };
12865
12866 let mut prev_end = label.filter_range.end;
12867 label
12868 .runs
12869 .iter()
12870 .enumerate()
12871 .flat_map(move |(ix, (range, highlight_id))| {
12872 let style = if let Some(style) = highlight_id.style(syntax_theme) {
12873 style
12874 } else {
12875 return Default::default();
12876 };
12877 let mut muted_style = style;
12878 muted_style.highlight(fade_out);
12879
12880 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12881 if range.start >= label.filter_range.end {
12882 if range.start > prev_end {
12883 runs.push((prev_end..range.start, fade_out));
12884 }
12885 runs.push((range.clone(), muted_style));
12886 } else if range.end <= label.filter_range.end {
12887 runs.push((range.clone(), style));
12888 } else {
12889 runs.push((range.start..label.filter_range.end, style));
12890 runs.push((label.filter_range.end..range.end, muted_style));
12891 }
12892 prev_end = cmp::max(prev_end, range.end);
12893
12894 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12895 runs.push((prev_end..label.text.len(), fade_out));
12896 }
12897
12898 runs
12899 })
12900}
12901
12902pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12903 let mut prev_index = 0;
12904 let mut prev_codepoint: Option<char> = None;
12905 text.char_indices()
12906 .chain([(text.len(), '\0')])
12907 .filter_map(move |(index, codepoint)| {
12908 let prev_codepoint = prev_codepoint.replace(codepoint)?;
12909 let is_boundary = index == text.len()
12910 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12911 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12912 if is_boundary {
12913 let chunk = &text[prev_index..index];
12914 prev_index = index;
12915 Some(chunk)
12916 } else {
12917 None
12918 }
12919 })
12920}
12921
12922pub trait RangeToAnchorExt {
12923 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12924}
12925
12926impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12927 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12928 let start_offset = self.start.to_offset(snapshot);
12929 let end_offset = self.end.to_offset(snapshot);
12930 if start_offset == end_offset {
12931 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12932 } else {
12933 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12934 }
12935 }
12936}
12937
12938pub trait RowExt {
12939 fn as_f32(&self) -> f32;
12940
12941 fn next_row(&self) -> Self;
12942
12943 fn previous_row(&self) -> Self;
12944
12945 fn minus(&self, other: Self) -> u32;
12946}
12947
12948impl RowExt for DisplayRow {
12949 fn as_f32(&self) -> f32 {
12950 self.0 as f32
12951 }
12952
12953 fn next_row(&self) -> Self {
12954 Self(self.0 + 1)
12955 }
12956
12957 fn previous_row(&self) -> Self {
12958 Self(self.0.saturating_sub(1))
12959 }
12960
12961 fn minus(&self, other: Self) -> u32 {
12962 self.0 - other.0
12963 }
12964}
12965
12966impl RowExt for MultiBufferRow {
12967 fn as_f32(&self) -> f32 {
12968 self.0 as f32
12969 }
12970
12971 fn next_row(&self) -> Self {
12972 Self(self.0 + 1)
12973 }
12974
12975 fn previous_row(&self) -> Self {
12976 Self(self.0.saturating_sub(1))
12977 }
12978
12979 fn minus(&self, other: Self) -> u32 {
12980 self.0 - other.0
12981 }
12982}
12983
12984trait RowRangeExt {
12985 type Row;
12986
12987 fn len(&self) -> usize;
12988
12989 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12990}
12991
12992impl RowRangeExt for Range<MultiBufferRow> {
12993 type Row = MultiBufferRow;
12994
12995 fn len(&self) -> usize {
12996 (self.end.0 - self.start.0) as usize
12997 }
12998
12999 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13000 (self.start.0..self.end.0).map(MultiBufferRow)
13001 }
13002}
13003
13004impl RowRangeExt for Range<DisplayRow> {
13005 type Row = DisplayRow;
13006
13007 fn len(&self) -> usize {
13008 (self.end.0 - self.start.0) as usize
13009 }
13010
13011 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13012 (self.start.0..self.end.0).map(DisplayRow)
13013 }
13014}
13015
13016fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13017 if hunk.diff_base_byte_range.is_empty() {
13018 DiffHunkStatus::Added
13019 } else if hunk.associated_range.is_empty() {
13020 DiffHunkStatus::Removed
13021 } else {
13022 DiffHunkStatus::Modified
13023 }
13024}