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