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 behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{CurrentLineHighlight, EditorSettings};
63pub use editor_settings_controls::*;
64use element::LineWithInvisibles;
65pub use element::{
66 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
67};
68use futures::FutureExt;
69use fuzzy::{StringMatch, StringMatchCandidate};
70use git::blame::GitBlame;
71use git::diff_hunk_to_display;
72use gpui::{
73 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
74 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
75 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
76 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
77 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
78 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
79 UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
80 WeakFocusHandle, WeakView, WindowContext,
81};
82use highlight_matching_bracket::refresh_matching_bracket_highlights;
83use hover_popover::{hide_hover, HoverState};
84use hunk_diff::ExpandedHunks;
85pub(crate) use hunk_diff::HoveredHunk;
86use indent_guides::ActiveIndentGuidesState;
87use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
88pub use inline_completion_provider::*;
89pub use items::MAX_TAB_TITLE_LEN;
90use itertools::Itertools;
91use language::{
92 char_kind,
93 language_settings::{self, all_language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
99use linked_editing_ranges::refresh_linked_ranges;
100use task::{ResolvedTask, TaskTemplate, TaskVariables};
101
102use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
103pub use lsp::CompletionContext;
104use lsp::{
105 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
106 LanguageServerId,
107};
108use mouse_context_menu::MouseContextMenu;
109use movement::TextLayoutDetails;
110pub use multi_buffer::{
111 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
112 ToPoint,
113};
114use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
115use ordered_float::OrderedFloat;
116use parking_lot::{Mutex, RwLock};
117use project::project_settings::{GitGutterSetting, ProjectSettings};
118use project::{
119 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
120 ProjectTransaction, TaskSourceKind, WorktreeId,
121};
122use rand::prelude::*;
123use rpc::{proto::*, ErrorExt};
124use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
125use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
126use serde::{Deserialize, Serialize};
127use settings::{update_settings_file, Settings, SettingsStore};
128use smallvec::SmallVec;
129use snippet::Snippet;
130use std::{
131 any::TypeId,
132 borrow::Cow,
133 cell::RefCell,
134 cmp::{self, Ordering, Reverse},
135 mem,
136 num::NonZeroU32,
137 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
138 path::{Path, PathBuf},
139 rc::Rc,
140 sync::Arc,
141 time::{Duration, Instant},
142};
143pub use sum_tree::Bias;
144use sum_tree::TreeMap;
145use text::{BufferId, OffsetUtf16, Rope};
146use theme::{
147 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
148 ThemeColors, ThemeSettings,
149};
150use ui::{
151 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
152 ListItem, Popover, Tooltip,
153};
154use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
155use workspace::item::{ItemHandle, PreviewTabsSettings};
156use workspace::notifications::{DetachAndPromptErr, NotificationId};
157use workspace::{
158 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
159};
160use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
161
162use crate::hover_links::find_url;
163use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
164
165pub const FILE_HEADER_HEIGHT: u32 = 1;
166pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
167pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
168pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
169const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
170const MAX_LINE_LEN: usize = 1024;
171const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
172const MAX_SELECTION_HISTORY_LEN: usize = 1024;
173pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
174#[doc(hidden)]
175pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
176#[doc(hidden)]
177pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
178
179pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
180pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
181
182pub fn render_parsed_markdown(
183 element_id: impl Into<ElementId>,
184 parsed: &language::ParsedMarkdown,
185 editor_style: &EditorStyle,
186 workspace: Option<WeakView<Workspace>>,
187 cx: &mut WindowContext,
188) -> InteractiveText {
189 let code_span_background_color = cx
190 .theme()
191 .colors()
192 .editor_document_highlight_read_background;
193
194 let highlights = gpui::combine_highlights(
195 parsed.highlights.iter().filter_map(|(range, highlight)| {
196 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
197 Some((range.clone(), highlight))
198 }),
199 parsed
200 .regions
201 .iter()
202 .zip(&parsed.region_ranges)
203 .filter_map(|(region, range)| {
204 if region.code {
205 Some((
206 range.clone(),
207 HighlightStyle {
208 background_color: Some(code_span_background_color),
209 ..Default::default()
210 },
211 ))
212 } else {
213 None
214 }
215 }),
216 );
217
218 let mut links = Vec::new();
219 let mut link_ranges = Vec::new();
220 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
221 if let Some(link) = region.link.clone() {
222 links.push(link);
223 link_ranges.push(range.clone());
224 }
225 }
226
227 InteractiveText::new(
228 element_id,
229 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
230 )
231 .on_click(link_ranges, move |clicked_range_ix, cx| {
232 match &links[clicked_range_ix] {
233 markdown::Link::Web { url } => cx.open_url(url),
234 markdown::Link::Path { path } => {
235 if let Some(workspace) = &workspace {
236 _ = workspace.update(cx, |workspace, cx| {
237 workspace.open_abs_path(path.clone(), false, cx).detach();
238 });
239 }
240 }
241 }
242 })
243}
244
245#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
246pub(crate) enum InlayId {
247 Suggestion(usize),
248 Hint(usize),
249}
250
251impl InlayId {
252 fn id(&self) -> usize {
253 match self {
254 Self::Suggestion(id) => *id,
255 Self::Hint(id) => *id,
256 }
257 }
258}
259
260enum DiffRowHighlight {}
261enum DocumentHighlightRead {}
262enum DocumentHighlightWrite {}
263enum InputComposition {}
264
265#[derive(Copy, Clone, PartialEq, Eq)]
266pub enum Direction {
267 Prev,
268 Next,
269}
270
271#[derive(Debug, Copy, Clone, PartialEq, Eq)]
272pub enum Navigated {
273 Yes,
274 No,
275}
276
277impl Navigated {
278 pub fn from_bool(yes: bool) -> Navigated {
279 if yes {
280 Navigated::Yes
281 } else {
282 Navigated::No
283 }
284 }
285}
286
287pub fn init_settings(cx: &mut AppContext) {
288 EditorSettings::register(cx);
289}
290
291pub fn init(cx: &mut AppContext) {
292 init_settings(cx);
293
294 workspace::register_project_item::<Editor>(cx);
295 workspace::FollowableViewRegistry::register::<Editor>(cx);
296 workspace::register_serializable_item::<Editor>(cx);
297
298 cx.observe_new_views(
299 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
300 workspace.register_action(Editor::new_file);
301 workspace.register_action(Editor::new_file_in_direction);
302 },
303 )
304 .detach();
305
306 cx.on_action(move |_: &workspace::NewFile, cx| {
307 let app_state = workspace::AppState::global(cx);
308 if let Some(app_state) = app_state.upgrade() {
309 workspace::open_new(app_state, cx, |workspace, cx| {
310 Editor::new_file(workspace, &Default::default(), cx)
311 })
312 .detach();
313 }
314 });
315 cx.on_action(move |_: &workspace::NewWindow, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(app_state, cx, |workspace, cx| {
319 Editor::new_file(workspace, &Default::default(), cx)
320 })
321 .detach();
322 }
323 });
324}
325
326pub struct SearchWithinRange;
327
328trait InvalidationRegion {
329 fn ranges(&self) -> &[Range<Anchor>];
330}
331
332#[derive(Clone, Debug, PartialEq)]
333pub enum SelectPhase {
334 Begin {
335 position: DisplayPoint,
336 add: bool,
337 click_count: usize,
338 },
339 BeginColumnar {
340 position: DisplayPoint,
341 reset: bool,
342 goal_column: u32,
343 },
344 Extend {
345 position: DisplayPoint,
346 click_count: usize,
347 },
348 Update {
349 position: DisplayPoint,
350 goal_column: u32,
351 scroll_delta: gpui::Point<f32>,
352 },
353 End,
354}
355
356#[derive(Clone, Debug)]
357pub enum SelectMode {
358 Character,
359 Word(Range<Anchor>),
360 Line(Range<Anchor>),
361 All,
362}
363
364#[derive(Copy, Clone, PartialEq, Eq, Debug)]
365pub enum EditorMode {
366 SingleLine { auto_width: bool },
367 AutoHeight { max_lines: usize },
368 Full,
369}
370
371#[derive(Clone, Debug)]
372pub enum SoftWrap {
373 None,
374 PreferLine,
375 EditorWidth,
376 Column(u32),
377}
378
379#[derive(Clone)]
380pub struct EditorStyle {
381 pub background: Hsla,
382 pub local_player: PlayerColor,
383 pub text: TextStyle,
384 pub scrollbar_width: Pixels,
385 pub syntax: Arc<SyntaxTheme>,
386 pub status: StatusColors,
387 pub inlay_hints_style: HighlightStyle,
388 pub suggestions_style: HighlightStyle,
389 pub unnecessary_code_fade: f32,
390}
391
392impl Default for EditorStyle {
393 fn default() -> Self {
394 Self {
395 background: Hsla::default(),
396 local_player: PlayerColor::default(),
397 text: TextStyle::default(),
398 scrollbar_width: Pixels::default(),
399 syntax: Default::default(),
400 // HACK: Status colors don't have a real default.
401 // We should look into removing the status colors from the editor
402 // style and retrieve them directly from the theme.
403 status: StatusColors::dark(),
404 inlay_hints_style: HighlightStyle::default(),
405 suggestions_style: HighlightStyle::default(),
406 unnecessary_code_fade: Default::default(),
407 }
408 }
409}
410
411type CompletionId = usize;
412
413#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
414struct EditorActionId(usize);
415
416impl EditorActionId {
417 pub fn post_inc(&mut self) -> Self {
418 let answer = self.0;
419
420 *self = Self(answer + 1);
421
422 Self(answer)
423 }
424}
425
426// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
427// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
428
429type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
430type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
431
432#[derive(Default)]
433struct ScrollbarMarkerState {
434 scrollbar_size: Size<Pixels>,
435 dirty: bool,
436 markers: Arc<[PaintQuad]>,
437 pending_refresh: Option<Task<Result<()>>>,
438}
439
440impl ScrollbarMarkerState {
441 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
442 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
443 }
444}
445
446#[derive(Clone, Debug)]
447struct RunnableTasks {
448 templates: Vec<(TaskSourceKind, TaskTemplate)>,
449 offset: MultiBufferOffset,
450 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
451 column: u32,
452 // Values of all named captures, including those starting with '_'
453 extra_variables: HashMap<String, String>,
454 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
455 context_range: Range<BufferOffset>,
456}
457
458#[derive(Clone)]
459struct ResolvedTasks {
460 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
461 position: Anchor,
462}
463#[derive(Copy, Clone, Debug)]
464struct MultiBufferOffset(usize);
465#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
466struct BufferOffset(usize);
467
468// Addons allow storing per-editor state in other crates (e.g. Vim)
469pub trait Addon: 'static {
470 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
471
472 fn to_any(&self) -> &dyn std::any::Any;
473}
474
475/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
476///
477/// See the [module level documentation](self) for more information.
478pub struct Editor {
479 focus_handle: FocusHandle,
480 last_focused_descendant: Option<WeakFocusHandle>,
481 /// The text buffer being edited
482 buffer: Model<MultiBuffer>,
483 /// Map of how text in the buffer should be displayed.
484 /// Handles soft wraps, folds, fake inlay text insertions, etc.
485 pub display_map: Model<DisplayMap>,
486 pub selections: SelectionsCollection,
487 pub scroll_manager: ScrollManager,
488 /// When inline assist editors are linked, they all render cursors because
489 /// typing enters text into each of them, even the ones that aren't focused.
490 pub(crate) show_cursor_when_unfocused: bool,
491 columnar_selection_tail: Option<Anchor>,
492 add_selections_state: Option<AddSelectionsState>,
493 select_next_state: Option<SelectNextState>,
494 select_prev_state: Option<SelectNextState>,
495 selection_history: SelectionHistory,
496 autoclose_regions: Vec<AutocloseRegion>,
497 snippet_stack: InvalidationStack<SnippetState>,
498 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
499 ime_transaction: Option<TransactionId>,
500 active_diagnostics: Option<ActiveDiagnosticGroup>,
501 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
502 project: Option<Model<Project>>,
503 completion_provider: Option<Box<dyn CompletionProvider>>,
504 collaboration_hub: Option<Box<dyn CollaborationHub>>,
505 blink_manager: Model<BlinkManager>,
506 show_cursor_names: bool,
507 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
508 pub show_local_selections: bool,
509 mode: EditorMode,
510 show_breadcrumbs: bool,
511 show_gutter: bool,
512 show_line_numbers: Option<bool>,
513 show_git_diff_gutter: Option<bool>,
514 show_code_actions: Option<bool>,
515 show_runnables: Option<bool>,
516 show_wrap_guides: Option<bool>,
517 show_indent_guides: Option<bool>,
518 placeholder_text: Option<Arc<str>>,
519 highlight_order: usize,
520 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
521 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
522 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
523 scrollbar_marker_state: ScrollbarMarkerState,
524 active_indent_guides_state: ActiveIndentGuidesState,
525 nav_history: Option<ItemNavHistory>,
526 context_menu: RwLock<Option<ContextMenu>>,
527 mouse_context_menu: Option<MouseContextMenu>,
528 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
529 signature_help_state: SignatureHelpState,
530 auto_signature_help: Option<bool>,
531 find_all_references_task_sources: Vec<Anchor>,
532 next_completion_id: CompletionId,
533 completion_documentation_pre_resolve_debounce: DebouncedDelay,
534 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
535 code_actions_task: Option<Task<()>>,
536 document_highlights_task: Option<Task<()>>,
537 linked_editing_range_task: Option<Task<Option<()>>>,
538 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
539 pending_rename: Option<RenameState>,
540 searchable: bool,
541 cursor_shape: CursorShape,
542 current_line_highlight: Option<CurrentLineHighlight>,
543 collapse_matches: bool,
544 autoindent_mode: Option<AutoindentMode>,
545 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
546 input_enabled: bool,
547 use_modal_editing: bool,
548 read_only: bool,
549 leader_peer_id: Option<PeerId>,
550 remote_id: Option<ViewId>,
551 hover_state: HoverState,
552 gutter_hovered: bool,
553 hovered_link_state: Option<HoveredLinkState>,
554 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
555 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
556 show_inline_completions: bool,
557 inlay_hint_cache: InlayHintCache,
558 expanded_hunks: ExpandedHunks,
559 next_inlay_id: usize,
560 _subscriptions: Vec<Subscription>,
561 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
562 gutter_dimensions: GutterDimensions,
563 style: Option<EditorStyle>,
564 next_editor_action_id: EditorActionId,
565 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
566 use_autoclose: bool,
567 use_auto_surround: bool,
568 auto_replace_emoji_shortcode: bool,
569 show_git_blame_gutter: bool,
570 show_git_blame_inline: bool,
571 show_git_blame_inline_delay_task: Option<Task<()>>,
572 git_blame_inline_enabled: bool,
573 serialize_dirty_buffers: bool,
574 show_selection_menu: Option<bool>,
575 blame: Option<Model<GitBlame>>,
576 blame_subscription: Option<Subscription>,
577 custom_context_menu: Option<
578 Box<
579 dyn 'static
580 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
581 >,
582 >,
583 last_bounds: Option<Bounds<Pixels>>,
584 expect_bounds_change: Option<Bounds<Pixels>>,
585 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
586 tasks_update_task: Option<Task<()>>,
587 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
588 file_header_size: u32,
589 breadcrumb_header: Option<String>,
590 focused_block: Option<FocusedBlock>,
591 next_scroll_position: NextScrollCursorCenterTopBottom,
592 addons: HashMap<TypeId, Box<dyn Addon>>,
593 _scroll_cursor_center_top_bottom_task: Task<()>,
594}
595
596#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
597enum NextScrollCursorCenterTopBottom {
598 #[default]
599 Center,
600 Top,
601 Bottom,
602}
603
604impl NextScrollCursorCenterTopBottom {
605 fn next(&self) -> Self {
606 match self {
607 Self::Center => Self::Top,
608 Self::Top => Self::Bottom,
609 Self::Bottom => Self::Center,
610 }
611 }
612}
613
614#[derive(Clone)]
615pub struct EditorSnapshot {
616 pub mode: EditorMode,
617 show_gutter: bool,
618 show_line_numbers: Option<bool>,
619 show_git_diff_gutter: Option<bool>,
620 show_code_actions: Option<bool>,
621 show_runnables: Option<bool>,
622 render_git_blame_gutter: bool,
623 pub display_snapshot: DisplaySnapshot,
624 pub placeholder_text: Option<Arc<str>>,
625 is_focused: bool,
626 scroll_anchor: ScrollAnchor,
627 ongoing_scroll: OngoingScroll,
628 current_line_highlight: CurrentLineHighlight,
629 gutter_hovered: bool,
630}
631
632const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
633
634#[derive(Default, Debug, Clone, Copy)]
635pub struct GutterDimensions {
636 pub left_padding: Pixels,
637 pub right_padding: Pixels,
638 pub width: Pixels,
639 pub margin: Pixels,
640 pub git_blame_entries_width: Option<Pixels>,
641}
642
643impl GutterDimensions {
644 /// The full width of the space taken up by the gutter.
645 pub fn full_width(&self) -> Pixels {
646 self.margin + self.width
647 }
648
649 /// The width of the space reserved for the fold indicators,
650 /// use alongside 'justify_end' and `gutter_width` to
651 /// right align content with the line numbers
652 pub fn fold_area_width(&self) -> Pixels {
653 self.margin + self.right_padding
654 }
655}
656
657#[derive(Debug)]
658pub struct RemoteSelection {
659 pub replica_id: ReplicaId,
660 pub selection: Selection<Anchor>,
661 pub cursor_shape: CursorShape,
662 pub peer_id: PeerId,
663 pub line_mode: bool,
664 pub participant_index: Option<ParticipantIndex>,
665 pub user_name: Option<SharedString>,
666}
667
668#[derive(Clone, Debug)]
669struct SelectionHistoryEntry {
670 selections: Arc<[Selection<Anchor>]>,
671 select_next_state: Option<SelectNextState>,
672 select_prev_state: Option<SelectNextState>,
673 add_selections_state: Option<AddSelectionsState>,
674}
675
676enum SelectionHistoryMode {
677 Normal,
678 Undoing,
679 Redoing,
680}
681
682#[derive(Clone, PartialEq, Eq, Hash)]
683struct HoveredCursor {
684 replica_id: u16,
685 selection_id: usize,
686}
687
688impl Default for SelectionHistoryMode {
689 fn default() -> Self {
690 Self::Normal
691 }
692}
693
694#[derive(Default)]
695struct SelectionHistory {
696 #[allow(clippy::type_complexity)]
697 selections_by_transaction:
698 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
699 mode: SelectionHistoryMode,
700 undo_stack: VecDeque<SelectionHistoryEntry>,
701 redo_stack: VecDeque<SelectionHistoryEntry>,
702}
703
704impl SelectionHistory {
705 fn insert_transaction(
706 &mut self,
707 transaction_id: TransactionId,
708 selections: Arc<[Selection<Anchor>]>,
709 ) {
710 self.selections_by_transaction
711 .insert(transaction_id, (selections, None));
712 }
713
714 #[allow(clippy::type_complexity)]
715 fn transaction(
716 &self,
717 transaction_id: TransactionId,
718 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
719 self.selections_by_transaction.get(&transaction_id)
720 }
721
722 #[allow(clippy::type_complexity)]
723 fn transaction_mut(
724 &mut self,
725 transaction_id: TransactionId,
726 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
727 self.selections_by_transaction.get_mut(&transaction_id)
728 }
729
730 fn push(&mut self, entry: SelectionHistoryEntry) {
731 if !entry.selections.is_empty() {
732 match self.mode {
733 SelectionHistoryMode::Normal => {
734 self.push_undo(entry);
735 self.redo_stack.clear();
736 }
737 SelectionHistoryMode::Undoing => self.push_redo(entry),
738 SelectionHistoryMode::Redoing => self.push_undo(entry),
739 }
740 }
741 }
742
743 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
744 if self
745 .undo_stack
746 .back()
747 .map_or(true, |e| e.selections != entry.selections)
748 {
749 self.undo_stack.push_back(entry);
750 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
751 self.undo_stack.pop_front();
752 }
753 }
754 }
755
756 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
757 if self
758 .redo_stack
759 .back()
760 .map_or(true, |e| e.selections != entry.selections)
761 {
762 self.redo_stack.push_back(entry);
763 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
764 self.redo_stack.pop_front();
765 }
766 }
767 }
768}
769
770struct RowHighlight {
771 index: usize,
772 range: RangeInclusive<Anchor>,
773 color: Option<Hsla>,
774 should_autoscroll: bool,
775}
776
777#[derive(Clone, Debug)]
778struct AddSelectionsState {
779 above: bool,
780 stack: Vec<usize>,
781}
782
783#[derive(Clone)]
784struct SelectNextState {
785 query: AhoCorasick,
786 wordwise: bool,
787 done: bool,
788}
789
790impl std::fmt::Debug for SelectNextState {
791 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
792 f.debug_struct(std::any::type_name::<Self>())
793 .field("wordwise", &self.wordwise)
794 .field("done", &self.done)
795 .finish()
796 }
797}
798
799#[derive(Debug)]
800struct AutocloseRegion {
801 selection_id: usize,
802 range: Range<Anchor>,
803 pair: BracketPair,
804}
805
806#[derive(Debug)]
807struct SnippetState {
808 ranges: Vec<Vec<Range<Anchor>>>,
809 active_index: usize,
810}
811
812#[doc(hidden)]
813pub struct RenameState {
814 pub range: Range<Anchor>,
815 pub old_name: Arc<str>,
816 pub editor: View<Editor>,
817 block_id: CustomBlockId,
818}
819
820struct InvalidationStack<T>(Vec<T>);
821
822struct RegisteredInlineCompletionProvider {
823 provider: Arc<dyn InlineCompletionProviderHandle>,
824 _subscription: Subscription,
825}
826
827enum ContextMenu {
828 Completions(CompletionsMenu),
829 CodeActions(CodeActionsMenu),
830}
831
832impl ContextMenu {
833 fn select_first(
834 &mut self,
835 project: Option<&Model<Project>>,
836 cx: &mut ViewContext<Editor>,
837 ) -> bool {
838 if self.visible() {
839 match self {
840 ContextMenu::Completions(menu) => menu.select_first(project, cx),
841 ContextMenu::CodeActions(menu) => menu.select_first(cx),
842 }
843 true
844 } else {
845 false
846 }
847 }
848
849 fn select_prev(
850 &mut self,
851 project: Option<&Model<Project>>,
852 cx: &mut ViewContext<Editor>,
853 ) -> bool {
854 if self.visible() {
855 match self {
856 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
857 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
858 }
859 true
860 } else {
861 false
862 }
863 }
864
865 fn select_next(
866 &mut self,
867 project: Option<&Model<Project>>,
868 cx: &mut ViewContext<Editor>,
869 ) -> bool {
870 if self.visible() {
871 match self {
872 ContextMenu::Completions(menu) => menu.select_next(project, cx),
873 ContextMenu::CodeActions(menu) => menu.select_next(cx),
874 }
875 true
876 } else {
877 false
878 }
879 }
880
881 fn select_last(
882 &mut self,
883 project: Option<&Model<Project>>,
884 cx: &mut ViewContext<Editor>,
885 ) -> bool {
886 if self.visible() {
887 match self {
888 ContextMenu::Completions(menu) => menu.select_last(project, cx),
889 ContextMenu::CodeActions(menu) => menu.select_last(cx),
890 }
891 true
892 } else {
893 false
894 }
895 }
896
897 fn visible(&self) -> bool {
898 match self {
899 ContextMenu::Completions(menu) => menu.visible(),
900 ContextMenu::CodeActions(menu) => menu.visible(),
901 }
902 }
903
904 fn render(
905 &self,
906 cursor_position: DisplayPoint,
907 style: &EditorStyle,
908 max_height: Pixels,
909 workspace: Option<WeakView<Workspace>>,
910 cx: &mut ViewContext<Editor>,
911 ) -> (ContextMenuOrigin, AnyElement) {
912 match self {
913 ContextMenu::Completions(menu) => (
914 ContextMenuOrigin::EditorPoint(cursor_position),
915 menu.render(style, max_height, workspace, cx),
916 ),
917 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
918 }
919 }
920}
921
922enum ContextMenuOrigin {
923 EditorPoint(DisplayPoint),
924 GutterIndicator(DisplayRow),
925}
926
927#[derive(Clone)]
928struct CompletionsMenu {
929 id: CompletionId,
930 sort_completions: bool,
931 initial_position: Anchor,
932 buffer: Model<Buffer>,
933 completions: Arc<RwLock<Box<[Completion]>>>,
934 match_candidates: Arc<[StringMatchCandidate]>,
935 matches: Arc<[StringMatch]>,
936 selected_item: usize,
937 scroll_handle: UniformListScrollHandle,
938 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
939}
940
941impl CompletionsMenu {
942 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
943 self.selected_item = 0;
944 self.scroll_handle.scroll_to_item(self.selected_item);
945 self.attempt_resolve_selected_completion_documentation(project, cx);
946 cx.notify();
947 }
948
949 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
950 if self.selected_item > 0 {
951 self.selected_item -= 1;
952 } else {
953 self.selected_item = self.matches.len() - 1;
954 }
955 self.scroll_handle.scroll_to_item(self.selected_item);
956 self.attempt_resolve_selected_completion_documentation(project, cx);
957 cx.notify();
958 }
959
960 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
961 if self.selected_item + 1 < self.matches.len() {
962 self.selected_item += 1;
963 } else {
964 self.selected_item = 0;
965 }
966 self.scroll_handle.scroll_to_item(self.selected_item);
967 self.attempt_resolve_selected_completion_documentation(project, cx);
968 cx.notify();
969 }
970
971 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
972 self.selected_item = self.matches.len() - 1;
973 self.scroll_handle.scroll_to_item(self.selected_item);
974 self.attempt_resolve_selected_completion_documentation(project, cx);
975 cx.notify();
976 }
977
978 fn pre_resolve_completion_documentation(
979 buffer: Model<Buffer>,
980 completions: Arc<RwLock<Box<[Completion]>>>,
981 matches: Arc<[StringMatch]>,
982 editor: &Editor,
983 cx: &mut ViewContext<Editor>,
984 ) -> Task<()> {
985 let settings = EditorSettings::get_global(cx);
986 if !settings.show_completion_documentation {
987 return Task::ready(());
988 }
989
990 let Some(provider) = editor.completion_provider.as_ref() else {
991 return Task::ready(());
992 };
993
994 let resolve_task = provider.resolve_completions(
995 buffer,
996 matches.iter().map(|m| m.candidate_id).collect(),
997 completions.clone(),
998 cx,
999 );
1000
1001 return cx.spawn(move |this, mut cx| async move {
1002 if let Some(true) = resolve_task.await.log_err() {
1003 this.update(&mut cx, |_, cx| cx.notify()).ok();
1004 }
1005 });
1006 }
1007
1008 fn attempt_resolve_selected_completion_documentation(
1009 &mut self,
1010 project: Option<&Model<Project>>,
1011 cx: &mut ViewContext<Editor>,
1012 ) {
1013 let settings = EditorSettings::get_global(cx);
1014 if !settings.show_completion_documentation {
1015 return;
1016 }
1017
1018 let completion_index = self.matches[self.selected_item].candidate_id;
1019 let Some(project) = project else {
1020 return;
1021 };
1022
1023 let resolve_task = project.update(cx, |project, cx| {
1024 project.resolve_completions(
1025 self.buffer.clone(),
1026 vec![completion_index],
1027 self.completions.clone(),
1028 cx,
1029 )
1030 });
1031
1032 let delay_ms =
1033 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1034 let delay = Duration::from_millis(delay_ms);
1035
1036 self.selected_completion_documentation_resolve_debounce
1037 .lock()
1038 .fire_new(delay, cx, |_, cx| {
1039 cx.spawn(move |this, mut cx| async move {
1040 if let Some(true) = resolve_task.await.log_err() {
1041 this.update(&mut cx, |_, cx| cx.notify()).ok();
1042 }
1043 })
1044 });
1045 }
1046
1047 fn visible(&self) -> bool {
1048 !self.matches.is_empty()
1049 }
1050
1051 fn render(
1052 &self,
1053 style: &EditorStyle,
1054 max_height: Pixels,
1055 workspace: Option<WeakView<Workspace>>,
1056 cx: &mut ViewContext<Editor>,
1057 ) -> AnyElement {
1058 let settings = EditorSettings::get_global(cx);
1059 let show_completion_documentation = settings.show_completion_documentation;
1060
1061 let widest_completion_ix = self
1062 .matches
1063 .iter()
1064 .enumerate()
1065 .max_by_key(|(_, mat)| {
1066 let completions = self.completions.read();
1067 let completion = &completions[mat.candidate_id];
1068 let documentation = &completion.documentation;
1069
1070 let mut len = completion.label.text.chars().count();
1071 if let Some(Documentation::SingleLine(text)) = documentation {
1072 if show_completion_documentation {
1073 len += text.chars().count();
1074 }
1075 }
1076
1077 len
1078 })
1079 .map(|(ix, _)| ix);
1080
1081 let completions = self.completions.clone();
1082 let matches = self.matches.clone();
1083 let selected_item = self.selected_item;
1084 let style = style.clone();
1085
1086 let multiline_docs = if show_completion_documentation {
1087 let mat = &self.matches[selected_item];
1088 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1089 Some(Documentation::MultiLinePlainText(text)) => {
1090 Some(div().child(SharedString::from(text.clone())))
1091 }
1092 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1093 Some(div().child(render_parsed_markdown(
1094 "completions_markdown",
1095 parsed,
1096 &style,
1097 workspace,
1098 cx,
1099 )))
1100 }
1101 _ => None,
1102 };
1103 multiline_docs.map(|div| {
1104 div.id("multiline_docs")
1105 .max_h(max_height)
1106 .flex_1()
1107 .px_1p5()
1108 .py_1()
1109 .min_w(px(260.))
1110 .max_w(px(640.))
1111 .w(px(500.))
1112 .overflow_y_scroll()
1113 .occlude()
1114 })
1115 } else {
1116 None
1117 };
1118
1119 let list = uniform_list(
1120 cx.view().clone(),
1121 "completions",
1122 matches.len(),
1123 move |_editor, range, cx| {
1124 let start_ix = range.start;
1125 let completions_guard = completions.read();
1126
1127 matches[range]
1128 .iter()
1129 .enumerate()
1130 .map(|(ix, mat)| {
1131 let item_ix = start_ix + ix;
1132 let candidate_id = mat.candidate_id;
1133 let completion = &completions_guard[candidate_id];
1134
1135 let documentation = if show_completion_documentation {
1136 &completion.documentation
1137 } else {
1138 &None
1139 };
1140
1141 let highlights = gpui::combine_highlights(
1142 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1143 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1144 |(range, mut highlight)| {
1145 // Ignore font weight for syntax highlighting, as we'll use it
1146 // for fuzzy matches.
1147 highlight.font_weight = None;
1148
1149 if completion.lsp_completion.deprecated.unwrap_or(false) {
1150 highlight.strikethrough = Some(StrikethroughStyle {
1151 thickness: 1.0.into(),
1152 ..Default::default()
1153 });
1154 highlight.color = Some(cx.theme().colors().text_muted);
1155 }
1156
1157 (range, highlight)
1158 },
1159 ),
1160 );
1161 let completion_label = StyledText::new(completion.label.text.clone())
1162 .with_highlights(&style.text, highlights);
1163 let documentation_label =
1164 if let Some(Documentation::SingleLine(text)) = documentation {
1165 if text.trim().is_empty() {
1166 None
1167 } else {
1168 Some(
1169 Label::new(text.clone())
1170 .ml_4()
1171 .size(LabelSize::Small)
1172 .color(Color::Muted),
1173 )
1174 }
1175 } else {
1176 None
1177 };
1178
1179 div().min_w(px(220.)).max_w(px(540.)).child(
1180 ListItem::new(mat.candidate_id)
1181 .inset(true)
1182 .selected(item_ix == selected_item)
1183 .on_click(cx.listener(move |editor, _event, cx| {
1184 cx.stop_propagation();
1185 if let Some(task) = editor.confirm_completion(
1186 &ConfirmCompletion {
1187 item_ix: Some(item_ix),
1188 },
1189 cx,
1190 ) {
1191 task.detach_and_log_err(cx)
1192 }
1193 }))
1194 .child(h_flex().overflow_hidden().child(completion_label))
1195 .end_slot::<Label>(documentation_label),
1196 )
1197 })
1198 .collect()
1199 },
1200 )
1201 .occlude()
1202 .max_h(max_height)
1203 .track_scroll(self.scroll_handle.clone())
1204 .with_width_from_item(widest_completion_ix)
1205 .with_sizing_behavior(ListSizingBehavior::Infer);
1206
1207 Popover::new()
1208 .child(list)
1209 .when_some(multiline_docs, |popover, multiline_docs| {
1210 popover.aside(multiline_docs)
1211 })
1212 .into_any_element()
1213 }
1214
1215 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1216 let mut matches = if let Some(query) = query {
1217 fuzzy::match_strings(
1218 &self.match_candidates,
1219 query,
1220 query.chars().any(|c| c.is_uppercase()),
1221 100,
1222 &Default::default(),
1223 executor,
1224 )
1225 .await
1226 } else {
1227 self.match_candidates
1228 .iter()
1229 .enumerate()
1230 .map(|(candidate_id, candidate)| StringMatch {
1231 candidate_id,
1232 score: Default::default(),
1233 positions: Default::default(),
1234 string: candidate.string.clone(),
1235 })
1236 .collect()
1237 };
1238
1239 // Remove all candidates where the query's start does not match the start of any word in the candidate
1240 if let Some(query) = query {
1241 if let Some(query_start) = query.chars().next() {
1242 matches.retain(|string_match| {
1243 split_words(&string_match.string).any(|word| {
1244 // Check that the first codepoint of the word as lowercase matches the first
1245 // codepoint of the query as lowercase
1246 word.chars()
1247 .flat_map(|codepoint| codepoint.to_lowercase())
1248 .zip(query_start.to_lowercase())
1249 .all(|(word_cp, query_cp)| word_cp == query_cp)
1250 })
1251 });
1252 }
1253 }
1254
1255 let completions = self.completions.read();
1256 if self.sort_completions {
1257 matches.sort_unstable_by_key(|mat| {
1258 // We do want to strike a balance here between what the language server tells us
1259 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1260 // `Creat` and there is a local variable called `CreateComponent`).
1261 // So what we do is: we bucket all matches into two buckets
1262 // - Strong matches
1263 // - Weak matches
1264 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1265 // and the Weak matches are the rest.
1266 //
1267 // For the strong matches, we sort by the language-servers score first and for the weak
1268 // matches, we prefer our fuzzy finder first.
1269 //
1270 // The thinking behind that: it's useless to take the sort_text the language-server gives
1271 // us into account when it's obviously a bad match.
1272
1273 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1274 enum MatchScore<'a> {
1275 Strong {
1276 sort_text: Option<&'a str>,
1277 score: Reverse<OrderedFloat<f64>>,
1278 sort_key: (usize, &'a str),
1279 },
1280 Weak {
1281 score: Reverse<OrderedFloat<f64>>,
1282 sort_text: Option<&'a str>,
1283 sort_key: (usize, &'a str),
1284 },
1285 }
1286
1287 let completion = &completions[mat.candidate_id];
1288 let sort_key = completion.sort_key();
1289 let sort_text = completion.lsp_completion.sort_text.as_deref();
1290 let score = Reverse(OrderedFloat(mat.score));
1291
1292 if mat.score >= 0.2 {
1293 MatchScore::Strong {
1294 sort_text,
1295 score,
1296 sort_key,
1297 }
1298 } else {
1299 MatchScore::Weak {
1300 score,
1301 sort_text,
1302 sort_key,
1303 }
1304 }
1305 });
1306 }
1307
1308 for mat in &mut matches {
1309 let completion = &completions[mat.candidate_id];
1310 mat.string.clone_from(&completion.label.text);
1311 for position in &mut mat.positions {
1312 *position += completion.label.filter_range.start;
1313 }
1314 }
1315 drop(completions);
1316
1317 self.matches = matches.into();
1318 self.selected_item = 0;
1319 }
1320}
1321
1322#[derive(Clone)]
1323struct CodeActionContents {
1324 tasks: Option<Arc<ResolvedTasks>>,
1325 actions: Option<Arc<[CodeAction]>>,
1326}
1327
1328impl CodeActionContents {
1329 fn len(&self) -> usize {
1330 match (&self.tasks, &self.actions) {
1331 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1332 (Some(tasks), None) => tasks.templates.len(),
1333 (None, Some(actions)) => actions.len(),
1334 (None, None) => 0,
1335 }
1336 }
1337
1338 fn is_empty(&self) -> bool {
1339 match (&self.tasks, &self.actions) {
1340 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1341 (Some(tasks), None) => tasks.templates.is_empty(),
1342 (None, Some(actions)) => actions.is_empty(),
1343 (None, None) => true,
1344 }
1345 }
1346
1347 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1348 self.tasks
1349 .iter()
1350 .flat_map(|tasks| {
1351 tasks
1352 .templates
1353 .iter()
1354 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1355 })
1356 .chain(self.actions.iter().flat_map(|actions| {
1357 actions
1358 .iter()
1359 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1360 }))
1361 }
1362 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1363 match (&self.tasks, &self.actions) {
1364 (Some(tasks), Some(actions)) => {
1365 if index < tasks.templates.len() {
1366 tasks
1367 .templates
1368 .get(index)
1369 .cloned()
1370 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1371 } else {
1372 actions
1373 .get(index - tasks.templates.len())
1374 .cloned()
1375 .map(CodeActionsItem::CodeAction)
1376 }
1377 }
1378 (Some(tasks), None) => tasks
1379 .templates
1380 .get(index)
1381 .cloned()
1382 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1383 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1384 (None, None) => None,
1385 }
1386 }
1387}
1388
1389#[allow(clippy::large_enum_variant)]
1390#[derive(Clone)]
1391enum CodeActionsItem {
1392 Task(TaskSourceKind, ResolvedTask),
1393 CodeAction(CodeAction),
1394}
1395
1396impl CodeActionsItem {
1397 fn as_task(&self) -> Option<&ResolvedTask> {
1398 let Self::Task(_, task) = self else {
1399 return None;
1400 };
1401 Some(task)
1402 }
1403 fn as_code_action(&self) -> Option<&CodeAction> {
1404 let Self::CodeAction(action) = self else {
1405 return None;
1406 };
1407 Some(action)
1408 }
1409 fn label(&self) -> String {
1410 match self {
1411 Self::CodeAction(action) => action.lsp_action.title.clone(),
1412 Self::Task(_, task) => task.resolved_label.clone(),
1413 }
1414 }
1415}
1416
1417struct CodeActionsMenu {
1418 actions: CodeActionContents,
1419 buffer: Model<Buffer>,
1420 selected_item: usize,
1421 scroll_handle: UniformListScrollHandle,
1422 deployed_from_indicator: Option<DisplayRow>,
1423}
1424
1425impl CodeActionsMenu {
1426 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1427 self.selected_item = 0;
1428 self.scroll_handle.scroll_to_item(self.selected_item);
1429 cx.notify()
1430 }
1431
1432 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1433 if self.selected_item > 0 {
1434 self.selected_item -= 1;
1435 } else {
1436 self.selected_item = self.actions.len() - 1;
1437 }
1438 self.scroll_handle.scroll_to_item(self.selected_item);
1439 cx.notify();
1440 }
1441
1442 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1443 if self.selected_item + 1 < self.actions.len() {
1444 self.selected_item += 1;
1445 } else {
1446 self.selected_item = 0;
1447 }
1448 self.scroll_handle.scroll_to_item(self.selected_item);
1449 cx.notify();
1450 }
1451
1452 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1453 self.selected_item = self.actions.len() - 1;
1454 self.scroll_handle.scroll_to_item(self.selected_item);
1455 cx.notify()
1456 }
1457
1458 fn visible(&self) -> bool {
1459 !self.actions.is_empty()
1460 }
1461
1462 fn render(
1463 &self,
1464 cursor_position: DisplayPoint,
1465 _style: &EditorStyle,
1466 max_height: Pixels,
1467 cx: &mut ViewContext<Editor>,
1468 ) -> (ContextMenuOrigin, AnyElement) {
1469 let actions = self.actions.clone();
1470 let selected_item = self.selected_item;
1471 let element = uniform_list(
1472 cx.view().clone(),
1473 "code_actions_menu",
1474 self.actions.len(),
1475 move |_this, range, cx| {
1476 actions
1477 .iter()
1478 .skip(range.start)
1479 .take(range.end - range.start)
1480 .enumerate()
1481 .map(|(ix, action)| {
1482 let item_ix = range.start + ix;
1483 let selected = selected_item == item_ix;
1484 let colors = cx.theme().colors();
1485 div()
1486 .px_2()
1487 .text_color(colors.text)
1488 .when(selected, |style| {
1489 style
1490 .bg(colors.element_active)
1491 .text_color(colors.text_accent)
1492 })
1493 .hover(|style| {
1494 style
1495 .bg(colors.element_hover)
1496 .text_color(colors.text_accent)
1497 })
1498 .whitespace_nowrap()
1499 .when_some(action.as_code_action(), |this, action| {
1500 this.on_mouse_down(
1501 MouseButton::Left,
1502 cx.listener(move |editor, _, cx| {
1503 cx.stop_propagation();
1504 if let Some(task) = editor.confirm_code_action(
1505 &ConfirmCodeAction {
1506 item_ix: Some(item_ix),
1507 },
1508 cx,
1509 ) {
1510 task.detach_and_log_err(cx)
1511 }
1512 }),
1513 )
1514 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1515 .child(SharedString::from(action.lsp_action.title.clone()))
1516 })
1517 .when_some(action.as_task(), |this, task| {
1518 this.on_mouse_down(
1519 MouseButton::Left,
1520 cx.listener(move |editor, _, cx| {
1521 cx.stop_propagation();
1522 if let Some(task) = editor.confirm_code_action(
1523 &ConfirmCodeAction {
1524 item_ix: Some(item_ix),
1525 },
1526 cx,
1527 ) {
1528 task.detach_and_log_err(cx)
1529 }
1530 }),
1531 )
1532 .child(SharedString::from(task.resolved_label.clone()))
1533 })
1534 })
1535 .collect()
1536 },
1537 )
1538 .elevation_1(cx)
1539 .px_2()
1540 .py_1()
1541 .max_h(max_height)
1542 .occlude()
1543 .track_scroll(self.scroll_handle.clone())
1544 .with_width_from_item(
1545 self.actions
1546 .iter()
1547 .enumerate()
1548 .max_by_key(|(_, action)| match action {
1549 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1550 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1551 })
1552 .map(|(ix, _)| ix),
1553 )
1554 .with_sizing_behavior(ListSizingBehavior::Infer)
1555 .into_any_element();
1556
1557 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1558 ContextMenuOrigin::GutterIndicator(row)
1559 } else {
1560 ContextMenuOrigin::EditorPoint(cursor_position)
1561 };
1562
1563 (cursor_position, element)
1564 }
1565}
1566
1567#[derive(Debug)]
1568struct ActiveDiagnosticGroup {
1569 primary_range: Range<Anchor>,
1570 primary_message: String,
1571 group_id: usize,
1572 blocks: HashMap<CustomBlockId, Diagnostic>,
1573 is_valid: bool,
1574}
1575
1576#[derive(Serialize, Deserialize, Clone, Debug)]
1577pub struct ClipboardSelection {
1578 pub len: usize,
1579 pub is_entire_line: bool,
1580 pub first_line_indent: u32,
1581}
1582
1583#[derive(Debug)]
1584pub(crate) struct NavigationData {
1585 cursor_anchor: Anchor,
1586 cursor_position: Point,
1587 scroll_anchor: ScrollAnchor,
1588 scroll_top_row: u32,
1589}
1590
1591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1592enum GotoDefinitionKind {
1593 Symbol,
1594 Declaration,
1595 Type,
1596 Implementation,
1597}
1598
1599#[derive(Debug, Clone)]
1600enum InlayHintRefreshReason {
1601 Toggle(bool),
1602 SettingsChange(InlayHintSettings),
1603 NewLinesShown,
1604 BufferEdited(HashSet<Arc<Language>>),
1605 RefreshRequested,
1606 ExcerptsRemoved(Vec<ExcerptId>),
1607}
1608
1609impl InlayHintRefreshReason {
1610 fn description(&self) -> &'static str {
1611 match self {
1612 Self::Toggle(_) => "toggle",
1613 Self::SettingsChange(_) => "settings change",
1614 Self::NewLinesShown => "new lines shown",
1615 Self::BufferEdited(_) => "buffer edited",
1616 Self::RefreshRequested => "refresh requested",
1617 Self::ExcerptsRemoved(_) => "excerpts removed",
1618 }
1619 }
1620}
1621
1622pub(crate) struct FocusedBlock {
1623 id: BlockId,
1624 focus_handle: WeakFocusHandle,
1625}
1626
1627impl Editor {
1628 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1629 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1630 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1631 Self::new(
1632 EditorMode::SingleLine { auto_width: false },
1633 buffer,
1634 None,
1635 false,
1636 cx,
1637 )
1638 }
1639
1640 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1641 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1642 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1643 Self::new(EditorMode::Full, buffer, None, false, cx)
1644 }
1645
1646 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1647 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1648 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1649 Self::new(
1650 EditorMode::SingleLine { auto_width: true },
1651 buffer,
1652 None,
1653 false,
1654 cx,
1655 )
1656 }
1657
1658 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1659 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1660 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1661 Self::new(
1662 EditorMode::AutoHeight { max_lines },
1663 buffer,
1664 None,
1665 false,
1666 cx,
1667 )
1668 }
1669
1670 pub fn for_buffer(
1671 buffer: Model<Buffer>,
1672 project: Option<Model<Project>>,
1673 cx: &mut ViewContext<Self>,
1674 ) -> Self {
1675 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1676 Self::new(EditorMode::Full, buffer, project, false, cx)
1677 }
1678
1679 pub fn for_multibuffer(
1680 buffer: Model<MultiBuffer>,
1681 project: Option<Model<Project>>,
1682 show_excerpt_controls: bool,
1683 cx: &mut ViewContext<Self>,
1684 ) -> Self {
1685 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1686 }
1687
1688 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1689 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1690 let mut clone = Self::new(
1691 self.mode,
1692 self.buffer.clone(),
1693 self.project.clone(),
1694 show_excerpt_controls,
1695 cx,
1696 );
1697 self.display_map.update(cx, |display_map, cx| {
1698 let snapshot = display_map.snapshot(cx);
1699 clone.display_map.update(cx, |display_map, cx| {
1700 display_map.set_state(&snapshot, cx);
1701 });
1702 });
1703 clone.selections.clone_state(&self.selections);
1704 clone.scroll_manager.clone_state(&self.scroll_manager);
1705 clone.searchable = self.searchable;
1706 clone
1707 }
1708
1709 pub fn new(
1710 mode: EditorMode,
1711 buffer: Model<MultiBuffer>,
1712 project: Option<Model<Project>>,
1713 show_excerpt_controls: bool,
1714 cx: &mut ViewContext<Self>,
1715 ) -> Self {
1716 let style = cx.text_style();
1717 let font_size = style.font_size.to_pixels(cx.rem_size());
1718 let editor = cx.view().downgrade();
1719 let fold_placeholder = FoldPlaceholder {
1720 constrain_width: true,
1721 render: Arc::new(move |fold_id, fold_range, cx| {
1722 let editor = editor.clone();
1723 div()
1724 .id(fold_id)
1725 .bg(cx.theme().colors().ghost_element_background)
1726 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1727 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1728 .rounded_sm()
1729 .size_full()
1730 .cursor_pointer()
1731 .child("⋯")
1732 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1733 .on_click(move |_, cx| {
1734 editor
1735 .update(cx, |editor, cx| {
1736 editor.unfold_ranges(
1737 [fold_range.start..fold_range.end],
1738 true,
1739 false,
1740 cx,
1741 );
1742 cx.stop_propagation();
1743 })
1744 .ok();
1745 })
1746 .into_any()
1747 }),
1748 merge_adjacent: true,
1749 };
1750 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1751 let display_map = cx.new_model(|cx| {
1752 DisplayMap::new(
1753 buffer.clone(),
1754 style.font(),
1755 font_size,
1756 None,
1757 show_excerpt_controls,
1758 file_header_size,
1759 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1760 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1761 fold_placeholder,
1762 cx,
1763 )
1764 });
1765
1766 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1767
1768 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1769
1770 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1771 .then(|| language_settings::SoftWrap::PreferLine);
1772
1773 let mut project_subscriptions = Vec::new();
1774 if mode == EditorMode::Full {
1775 if let Some(project) = project.as_ref() {
1776 if buffer.read(cx).is_singleton() {
1777 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1778 cx.emit(EditorEvent::TitleChanged);
1779 }));
1780 }
1781 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1782 if let project::Event::RefreshInlayHints = event {
1783 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1784 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1785 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1786 let focus_handle = editor.focus_handle(cx);
1787 if focus_handle.is_focused(cx) {
1788 let snapshot = buffer.read(cx).snapshot();
1789 for (range, snippet) in snippet_edits {
1790 let editor_range =
1791 language::range_from_lsp(*range).to_offset(&snapshot);
1792 editor
1793 .insert_snippet(&[editor_range], snippet.clone(), cx)
1794 .ok();
1795 }
1796 }
1797 }
1798 }
1799 }));
1800 let task_inventory = project.read(cx).task_inventory().clone();
1801 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1802 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1803 }));
1804 }
1805 }
1806
1807 let inlay_hint_settings = inlay_hint_settings(
1808 selections.newest_anchor().head(),
1809 &buffer.read(cx).snapshot(cx),
1810 cx,
1811 );
1812 let focus_handle = cx.focus_handle();
1813 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1814 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1815 .detach();
1816 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1817 .detach();
1818 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1819
1820 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1821 Some(false)
1822 } else {
1823 None
1824 };
1825
1826 let mut this = Self {
1827 focus_handle,
1828 show_cursor_when_unfocused: false,
1829 last_focused_descendant: None,
1830 buffer: buffer.clone(),
1831 display_map: display_map.clone(),
1832 selections,
1833 scroll_manager: ScrollManager::new(cx),
1834 columnar_selection_tail: None,
1835 add_selections_state: None,
1836 select_next_state: None,
1837 select_prev_state: None,
1838 selection_history: Default::default(),
1839 autoclose_regions: Default::default(),
1840 snippet_stack: Default::default(),
1841 select_larger_syntax_node_stack: Vec::new(),
1842 ime_transaction: Default::default(),
1843 active_diagnostics: None,
1844 soft_wrap_mode_override,
1845 completion_provider: project.clone().map(|project| Box::new(project) as _),
1846 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1847 project,
1848 blink_manager: blink_manager.clone(),
1849 show_local_selections: true,
1850 mode,
1851 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1852 show_gutter: mode == EditorMode::Full,
1853 show_line_numbers: None,
1854 show_git_diff_gutter: None,
1855 show_code_actions: None,
1856 show_runnables: None,
1857 show_wrap_guides: None,
1858 show_indent_guides,
1859 placeholder_text: None,
1860 highlight_order: 0,
1861 highlighted_rows: HashMap::default(),
1862 background_highlights: Default::default(),
1863 gutter_highlights: TreeMap::default(),
1864 scrollbar_marker_state: ScrollbarMarkerState::default(),
1865 active_indent_guides_state: ActiveIndentGuidesState::default(),
1866 nav_history: None,
1867 context_menu: RwLock::new(None),
1868 mouse_context_menu: None,
1869 completion_tasks: Default::default(),
1870 signature_help_state: SignatureHelpState::default(),
1871 auto_signature_help: None,
1872 find_all_references_task_sources: Vec::new(),
1873 next_completion_id: 0,
1874 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1875 next_inlay_id: 0,
1876 available_code_actions: Default::default(),
1877 code_actions_task: Default::default(),
1878 document_highlights_task: Default::default(),
1879 linked_editing_range_task: Default::default(),
1880 pending_rename: Default::default(),
1881 searchable: true,
1882 cursor_shape: Default::default(),
1883 current_line_highlight: None,
1884 autoindent_mode: Some(AutoindentMode::EachLine),
1885 collapse_matches: false,
1886 workspace: None,
1887 input_enabled: true,
1888 use_modal_editing: mode == EditorMode::Full,
1889 read_only: false,
1890 use_autoclose: true,
1891 use_auto_surround: true,
1892 auto_replace_emoji_shortcode: false,
1893 leader_peer_id: None,
1894 remote_id: None,
1895 hover_state: Default::default(),
1896 hovered_link_state: Default::default(),
1897 inline_completion_provider: None,
1898 active_inline_completion: None,
1899 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1900 expanded_hunks: ExpandedHunks::default(),
1901 gutter_hovered: false,
1902 pixel_position_of_newest_cursor: None,
1903 last_bounds: None,
1904 expect_bounds_change: None,
1905 gutter_dimensions: GutterDimensions::default(),
1906 style: None,
1907 show_cursor_names: false,
1908 hovered_cursors: Default::default(),
1909 next_editor_action_id: EditorActionId::default(),
1910 editor_actions: Rc::default(),
1911 show_inline_completions: mode == EditorMode::Full,
1912 custom_context_menu: None,
1913 show_git_blame_gutter: false,
1914 show_git_blame_inline: false,
1915 show_selection_menu: None,
1916 show_git_blame_inline_delay_task: None,
1917 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1918 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1919 .session
1920 .restore_unsaved_buffers,
1921 blame: None,
1922 blame_subscription: None,
1923 file_header_size,
1924 tasks: Default::default(),
1925 _subscriptions: vec![
1926 cx.observe(&buffer, Self::on_buffer_changed),
1927 cx.subscribe(&buffer, Self::on_buffer_event),
1928 cx.observe(&display_map, Self::on_display_map_changed),
1929 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1930 cx.observe_global::<SettingsStore>(Self::settings_changed),
1931 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1932 cx.observe_window_activation(|editor, cx| {
1933 let active = cx.is_window_active();
1934 editor.blink_manager.update(cx, |blink_manager, cx| {
1935 if active {
1936 blink_manager.enable(cx);
1937 } else {
1938 blink_manager.disable(cx);
1939 }
1940 });
1941 }),
1942 ],
1943 tasks_update_task: None,
1944 linked_edit_ranges: Default::default(),
1945 previous_search_ranges: None,
1946 breadcrumb_header: None,
1947 focused_block: None,
1948 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1949 addons: HashMap::default(),
1950 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1951 };
1952 this.tasks_update_task = Some(this.refresh_runnables(cx));
1953 this._subscriptions.extend(project_subscriptions);
1954
1955 this.end_selection(cx);
1956 this.scroll_manager.show_scrollbar(cx);
1957
1958 if mode == EditorMode::Full {
1959 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1960 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1961
1962 if this.git_blame_inline_enabled {
1963 this.git_blame_inline_enabled = true;
1964 this.start_git_blame_inline(false, cx);
1965 }
1966 }
1967
1968 this.report_editor_event("open", None, cx);
1969 this
1970 }
1971
1972 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1973 self.mouse_context_menu
1974 .as_ref()
1975 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1976 }
1977
1978 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1979 let mut key_context = KeyContext::new_with_defaults();
1980 key_context.add("Editor");
1981 let mode = match self.mode {
1982 EditorMode::SingleLine { .. } => "single_line",
1983 EditorMode::AutoHeight { .. } => "auto_height",
1984 EditorMode::Full => "full",
1985 };
1986
1987 if EditorSettings::jupyter_enabled(cx) {
1988 key_context.add("jupyter");
1989 }
1990
1991 key_context.set("mode", mode);
1992 if self.pending_rename.is_some() {
1993 key_context.add("renaming");
1994 }
1995 if self.context_menu_visible() {
1996 match self.context_menu.read().as_ref() {
1997 Some(ContextMenu::Completions(_)) => {
1998 key_context.add("menu");
1999 key_context.add("showing_completions")
2000 }
2001 Some(ContextMenu::CodeActions(_)) => {
2002 key_context.add("menu");
2003 key_context.add("showing_code_actions")
2004 }
2005 None => {}
2006 }
2007 }
2008
2009 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2010 if !self.focus_handle(cx).contains_focused(cx)
2011 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2012 {
2013 for addon in self.addons.values() {
2014 addon.extend_key_context(&mut key_context, cx)
2015 }
2016 }
2017
2018 if let Some(extension) = self
2019 .buffer
2020 .read(cx)
2021 .as_singleton()
2022 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2023 {
2024 key_context.set("extension", extension.to_string());
2025 }
2026
2027 if self.has_active_inline_completion(cx) {
2028 key_context.add("copilot_suggestion");
2029 key_context.add("inline_completion");
2030 }
2031
2032 key_context
2033 }
2034
2035 pub fn new_file(
2036 workspace: &mut Workspace,
2037 _: &workspace::NewFile,
2038 cx: &mut ViewContext<Workspace>,
2039 ) {
2040 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2041 "Failed to create buffer",
2042 cx,
2043 |e, _| match e.error_code() {
2044 ErrorCode::RemoteUpgradeRequired => Some(format!(
2045 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2046 e.error_tag("required").unwrap_or("the latest version")
2047 )),
2048 _ => None,
2049 },
2050 );
2051 }
2052
2053 pub fn new_in_workspace(
2054 workspace: &mut Workspace,
2055 cx: &mut ViewContext<Workspace>,
2056 ) -> Task<Result<View<Editor>>> {
2057 let project = workspace.project().clone();
2058 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2059
2060 cx.spawn(|workspace, mut cx| async move {
2061 let buffer = create.await?;
2062 workspace.update(&mut cx, |workspace, cx| {
2063 let editor =
2064 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2065 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2066 editor
2067 })
2068 })
2069 }
2070
2071 pub fn new_file_in_direction(
2072 workspace: &mut Workspace,
2073 action: &workspace::NewFileInDirection,
2074 cx: &mut ViewContext<Workspace>,
2075 ) {
2076 let project = workspace.project().clone();
2077 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2078 let direction = action.0;
2079
2080 cx.spawn(|workspace, mut cx| async move {
2081 let buffer = create.await?;
2082 workspace.update(&mut cx, move |workspace, cx| {
2083 workspace.split_item(
2084 direction,
2085 Box::new(
2086 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2087 ),
2088 cx,
2089 )
2090 })?;
2091 anyhow::Ok(())
2092 })
2093 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2094 ErrorCode::RemoteUpgradeRequired => Some(format!(
2095 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2096 e.error_tag("required").unwrap_or("the latest version")
2097 )),
2098 _ => None,
2099 });
2100 }
2101
2102 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2103 self.buffer.read(cx).replica_id()
2104 }
2105
2106 pub fn leader_peer_id(&self) -> Option<PeerId> {
2107 self.leader_peer_id
2108 }
2109
2110 pub fn buffer(&self) -> &Model<MultiBuffer> {
2111 &self.buffer
2112 }
2113
2114 pub fn workspace(&self) -> Option<View<Workspace>> {
2115 self.workspace.as_ref()?.0.upgrade()
2116 }
2117
2118 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2119 self.buffer().read(cx).title(cx)
2120 }
2121
2122 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2123 EditorSnapshot {
2124 mode: self.mode,
2125 show_gutter: self.show_gutter,
2126 show_line_numbers: self.show_line_numbers,
2127 show_git_diff_gutter: self.show_git_diff_gutter,
2128 show_code_actions: self.show_code_actions,
2129 show_runnables: self.show_runnables,
2130 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2131 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2132 scroll_anchor: self.scroll_manager.anchor(),
2133 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2134 placeholder_text: self.placeholder_text.clone(),
2135 is_focused: self.focus_handle.is_focused(cx),
2136 current_line_highlight: self
2137 .current_line_highlight
2138 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2139 gutter_hovered: self.gutter_hovered,
2140 }
2141 }
2142
2143 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2144 self.buffer.read(cx).language_at(point, cx)
2145 }
2146
2147 pub fn file_at<T: ToOffset>(
2148 &self,
2149 point: T,
2150 cx: &AppContext,
2151 ) -> Option<Arc<dyn language::File>> {
2152 self.buffer.read(cx).read(cx).file_at(point).cloned()
2153 }
2154
2155 pub fn active_excerpt(
2156 &self,
2157 cx: &AppContext,
2158 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2159 self.buffer
2160 .read(cx)
2161 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2162 }
2163
2164 pub fn mode(&self) -> EditorMode {
2165 self.mode
2166 }
2167
2168 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2169 self.collaboration_hub.as_deref()
2170 }
2171
2172 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2173 self.collaboration_hub = Some(hub);
2174 }
2175
2176 pub fn set_custom_context_menu(
2177 &mut self,
2178 f: impl 'static
2179 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2180 ) {
2181 self.custom_context_menu = Some(Box::new(f))
2182 }
2183
2184 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2185 self.completion_provider = Some(provider);
2186 }
2187
2188 pub fn set_inline_completion_provider<T>(
2189 &mut self,
2190 provider: Option<Model<T>>,
2191 cx: &mut ViewContext<Self>,
2192 ) where
2193 T: InlineCompletionProvider,
2194 {
2195 self.inline_completion_provider =
2196 provider.map(|provider| RegisteredInlineCompletionProvider {
2197 _subscription: cx.observe(&provider, |this, _, cx| {
2198 if this.focus_handle.is_focused(cx) {
2199 this.update_visible_inline_completion(cx);
2200 }
2201 }),
2202 provider: Arc::new(provider),
2203 });
2204 self.refresh_inline_completion(false, cx);
2205 }
2206
2207 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2208 self.placeholder_text.as_deref()
2209 }
2210
2211 pub fn set_placeholder_text(
2212 &mut self,
2213 placeholder_text: impl Into<Arc<str>>,
2214 cx: &mut ViewContext<Self>,
2215 ) {
2216 let placeholder_text = Some(placeholder_text.into());
2217 if self.placeholder_text != placeholder_text {
2218 self.placeholder_text = placeholder_text;
2219 cx.notify();
2220 }
2221 }
2222
2223 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2224 self.cursor_shape = cursor_shape;
2225
2226 // Disrupt blink for immediate user feedback that the cursor shape has changed
2227 self.blink_manager.update(cx, BlinkManager::show_cursor);
2228
2229 cx.notify();
2230 }
2231
2232 pub fn set_current_line_highlight(
2233 &mut self,
2234 current_line_highlight: Option<CurrentLineHighlight>,
2235 ) {
2236 self.current_line_highlight = current_line_highlight;
2237 }
2238
2239 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2240 self.collapse_matches = collapse_matches;
2241 }
2242
2243 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2244 if self.collapse_matches {
2245 return range.start..range.start;
2246 }
2247 range.clone()
2248 }
2249
2250 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2251 if self.display_map.read(cx).clip_at_line_ends != clip {
2252 self.display_map
2253 .update(cx, |map, _| map.clip_at_line_ends = clip);
2254 }
2255 }
2256
2257 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2258 self.input_enabled = input_enabled;
2259 }
2260
2261 pub fn set_autoindent(&mut self, autoindent: bool) {
2262 if autoindent {
2263 self.autoindent_mode = Some(AutoindentMode::EachLine);
2264 } else {
2265 self.autoindent_mode = None;
2266 }
2267 }
2268
2269 pub fn read_only(&self, cx: &AppContext) -> bool {
2270 self.read_only || self.buffer.read(cx).read_only()
2271 }
2272
2273 pub fn set_read_only(&mut self, read_only: bool) {
2274 self.read_only = read_only;
2275 }
2276
2277 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2278 self.use_autoclose = autoclose;
2279 }
2280
2281 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2282 self.use_auto_surround = auto_surround;
2283 }
2284
2285 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2286 self.auto_replace_emoji_shortcode = auto_replace;
2287 }
2288
2289 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2290 self.show_inline_completions = show_inline_completions;
2291 }
2292
2293 pub fn set_use_modal_editing(&mut self, to: bool) {
2294 self.use_modal_editing = to;
2295 }
2296
2297 pub fn use_modal_editing(&self) -> bool {
2298 self.use_modal_editing
2299 }
2300
2301 fn selections_did_change(
2302 &mut self,
2303 local: bool,
2304 old_cursor_position: &Anchor,
2305 show_completions: bool,
2306 cx: &mut ViewContext<Self>,
2307 ) {
2308 // Copy selections to primary selection buffer
2309 #[cfg(target_os = "linux")]
2310 if local {
2311 let selections = self.selections.all::<usize>(cx);
2312 let buffer_handle = self.buffer.read(cx).read(cx);
2313
2314 let mut text = String::new();
2315 for (index, selection) in selections.iter().enumerate() {
2316 let text_for_selection = buffer_handle
2317 .text_for_range(selection.start..selection.end)
2318 .collect::<String>();
2319
2320 text.push_str(&text_for_selection);
2321 if index != selections.len() - 1 {
2322 text.push('\n');
2323 }
2324 }
2325
2326 if !text.is_empty() {
2327 cx.write_to_primary(ClipboardItem::new_string(text));
2328 }
2329 }
2330
2331 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2332 self.buffer.update(cx, |buffer, cx| {
2333 buffer.set_active_selections(
2334 &self.selections.disjoint_anchors(),
2335 self.selections.line_mode,
2336 self.cursor_shape,
2337 cx,
2338 )
2339 });
2340 }
2341 let display_map = self
2342 .display_map
2343 .update(cx, |display_map, cx| display_map.snapshot(cx));
2344 let buffer = &display_map.buffer_snapshot;
2345 self.add_selections_state = None;
2346 self.select_next_state = None;
2347 self.select_prev_state = None;
2348 self.select_larger_syntax_node_stack.clear();
2349 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2350 self.snippet_stack
2351 .invalidate(&self.selections.disjoint_anchors(), buffer);
2352 self.take_rename(false, cx);
2353
2354 let new_cursor_position = self.selections.newest_anchor().head();
2355
2356 self.push_to_nav_history(
2357 *old_cursor_position,
2358 Some(new_cursor_position.to_point(buffer)),
2359 cx,
2360 );
2361
2362 if local {
2363 let new_cursor_position = self.selections.newest_anchor().head();
2364 let mut context_menu = self.context_menu.write();
2365 let completion_menu = match context_menu.as_ref() {
2366 Some(ContextMenu::Completions(menu)) => Some(menu),
2367
2368 _ => {
2369 *context_menu = None;
2370 None
2371 }
2372 };
2373
2374 if let Some(completion_menu) = completion_menu {
2375 let cursor_position = new_cursor_position.to_offset(buffer);
2376 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2377 if kind == Some(CharKind::Word)
2378 && word_range.to_inclusive().contains(&cursor_position)
2379 {
2380 let mut completion_menu = completion_menu.clone();
2381 drop(context_menu);
2382
2383 let query = Self::completion_query(buffer, cursor_position);
2384 cx.spawn(move |this, mut cx| async move {
2385 completion_menu
2386 .filter(query.as_deref(), cx.background_executor().clone())
2387 .await;
2388
2389 this.update(&mut cx, |this, cx| {
2390 let mut context_menu = this.context_menu.write();
2391 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2392 return;
2393 };
2394
2395 if menu.id > completion_menu.id {
2396 return;
2397 }
2398
2399 *context_menu = Some(ContextMenu::Completions(completion_menu));
2400 drop(context_menu);
2401 cx.notify();
2402 })
2403 })
2404 .detach();
2405
2406 if show_completions {
2407 self.show_completions(&ShowCompletions { trigger: None }, cx);
2408 }
2409 } else {
2410 drop(context_menu);
2411 self.hide_context_menu(cx);
2412 }
2413 } else {
2414 drop(context_menu);
2415 }
2416
2417 hide_hover(self, cx);
2418
2419 if old_cursor_position.to_display_point(&display_map).row()
2420 != new_cursor_position.to_display_point(&display_map).row()
2421 {
2422 self.available_code_actions.take();
2423 }
2424 self.refresh_code_actions(cx);
2425 self.refresh_document_highlights(cx);
2426 refresh_matching_bracket_highlights(self, cx);
2427 self.discard_inline_completion(false, cx);
2428 linked_editing_ranges::refresh_linked_ranges(self, cx);
2429 if self.git_blame_inline_enabled {
2430 self.start_inline_blame_timer(cx);
2431 }
2432 }
2433
2434 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2435 cx.emit(EditorEvent::SelectionsChanged { local });
2436
2437 if self.selections.disjoint_anchors().len() == 1 {
2438 cx.emit(SearchEvent::ActiveMatchChanged)
2439 }
2440 cx.notify();
2441 }
2442
2443 pub fn change_selections<R>(
2444 &mut self,
2445 autoscroll: Option<Autoscroll>,
2446 cx: &mut ViewContext<Self>,
2447 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2448 ) -> R {
2449 self.change_selections_inner(autoscroll, true, cx, change)
2450 }
2451
2452 pub fn change_selections_inner<R>(
2453 &mut self,
2454 autoscroll: Option<Autoscroll>,
2455 request_completions: bool,
2456 cx: &mut ViewContext<Self>,
2457 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2458 ) -> R {
2459 let old_cursor_position = self.selections.newest_anchor().head();
2460 self.push_to_selection_history();
2461
2462 let (changed, result) = self.selections.change_with(cx, change);
2463
2464 if changed {
2465 if let Some(autoscroll) = autoscroll {
2466 self.request_autoscroll(autoscroll, cx);
2467 }
2468 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2469
2470 if self.should_open_signature_help_automatically(
2471 &old_cursor_position,
2472 self.signature_help_state.backspace_pressed(),
2473 cx,
2474 ) {
2475 self.show_signature_help(&ShowSignatureHelp, cx);
2476 }
2477 self.signature_help_state.set_backspace_pressed(false);
2478 }
2479
2480 result
2481 }
2482
2483 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2484 where
2485 I: IntoIterator<Item = (Range<S>, T)>,
2486 S: ToOffset,
2487 T: Into<Arc<str>>,
2488 {
2489 if self.read_only(cx) {
2490 return;
2491 }
2492
2493 self.buffer
2494 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2495 }
2496
2497 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2498 where
2499 I: IntoIterator<Item = (Range<S>, T)>,
2500 S: ToOffset,
2501 T: Into<Arc<str>>,
2502 {
2503 if self.read_only(cx) {
2504 return;
2505 }
2506
2507 self.buffer.update(cx, |buffer, cx| {
2508 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2509 });
2510 }
2511
2512 pub fn edit_with_block_indent<I, S, T>(
2513 &mut self,
2514 edits: I,
2515 original_indent_columns: Vec<u32>,
2516 cx: &mut ViewContext<Self>,
2517 ) where
2518 I: IntoIterator<Item = (Range<S>, T)>,
2519 S: ToOffset,
2520 T: Into<Arc<str>>,
2521 {
2522 if self.read_only(cx) {
2523 return;
2524 }
2525
2526 self.buffer.update(cx, |buffer, cx| {
2527 buffer.edit(
2528 edits,
2529 Some(AutoindentMode::Block {
2530 original_indent_columns,
2531 }),
2532 cx,
2533 )
2534 });
2535 }
2536
2537 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2538 self.hide_context_menu(cx);
2539
2540 match phase {
2541 SelectPhase::Begin {
2542 position,
2543 add,
2544 click_count,
2545 } => self.begin_selection(position, add, click_count, cx),
2546 SelectPhase::BeginColumnar {
2547 position,
2548 goal_column,
2549 reset,
2550 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2551 SelectPhase::Extend {
2552 position,
2553 click_count,
2554 } => self.extend_selection(position, click_count, cx),
2555 SelectPhase::Update {
2556 position,
2557 goal_column,
2558 scroll_delta,
2559 } => self.update_selection(position, goal_column, scroll_delta, cx),
2560 SelectPhase::End => self.end_selection(cx),
2561 }
2562 }
2563
2564 fn extend_selection(
2565 &mut self,
2566 position: DisplayPoint,
2567 click_count: usize,
2568 cx: &mut ViewContext<Self>,
2569 ) {
2570 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2571 let tail = self.selections.newest::<usize>(cx).tail();
2572 self.begin_selection(position, false, click_count, cx);
2573
2574 let position = position.to_offset(&display_map, Bias::Left);
2575 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2576
2577 let mut pending_selection = self
2578 .selections
2579 .pending_anchor()
2580 .expect("extend_selection not called with pending selection");
2581 if position >= tail {
2582 pending_selection.start = tail_anchor;
2583 } else {
2584 pending_selection.end = tail_anchor;
2585 pending_selection.reversed = true;
2586 }
2587
2588 let mut pending_mode = self.selections.pending_mode().unwrap();
2589 match &mut pending_mode {
2590 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2591 _ => {}
2592 }
2593
2594 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2595 s.set_pending(pending_selection, pending_mode)
2596 });
2597 }
2598
2599 fn begin_selection(
2600 &mut self,
2601 position: DisplayPoint,
2602 add: bool,
2603 click_count: usize,
2604 cx: &mut ViewContext<Self>,
2605 ) {
2606 if !self.focus_handle.is_focused(cx) {
2607 self.last_focused_descendant = None;
2608 cx.focus(&self.focus_handle);
2609 }
2610
2611 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2612 let buffer = &display_map.buffer_snapshot;
2613 let newest_selection = self.selections.newest_anchor().clone();
2614 let position = display_map.clip_point(position, Bias::Left);
2615
2616 let start;
2617 let end;
2618 let mode;
2619 let auto_scroll;
2620 match click_count {
2621 1 => {
2622 start = buffer.anchor_before(position.to_point(&display_map));
2623 end = start;
2624 mode = SelectMode::Character;
2625 auto_scroll = true;
2626 }
2627 2 => {
2628 let range = movement::surrounding_word(&display_map, position);
2629 start = buffer.anchor_before(range.start.to_point(&display_map));
2630 end = buffer.anchor_before(range.end.to_point(&display_map));
2631 mode = SelectMode::Word(start..end);
2632 auto_scroll = true;
2633 }
2634 3 => {
2635 let position = display_map
2636 .clip_point(position, Bias::Left)
2637 .to_point(&display_map);
2638 let line_start = display_map.prev_line_boundary(position).0;
2639 let next_line_start = buffer.clip_point(
2640 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2641 Bias::Left,
2642 );
2643 start = buffer.anchor_before(line_start);
2644 end = buffer.anchor_before(next_line_start);
2645 mode = SelectMode::Line(start..end);
2646 auto_scroll = true;
2647 }
2648 _ => {
2649 start = buffer.anchor_before(0);
2650 end = buffer.anchor_before(buffer.len());
2651 mode = SelectMode::All;
2652 auto_scroll = false;
2653 }
2654 }
2655
2656 let point_to_delete: Option<usize> = {
2657 let selected_points: Vec<Selection<Point>> =
2658 self.selections.disjoint_in_range(start..end, cx);
2659
2660 if !add || click_count > 1 {
2661 None
2662 } else if selected_points.len() > 0 {
2663 Some(selected_points[0].id)
2664 } else {
2665 let clicked_point_already_selected =
2666 self.selections.disjoint.iter().find(|selection| {
2667 selection.start.to_point(buffer) == start.to_point(buffer)
2668 || selection.end.to_point(buffer) == end.to_point(buffer)
2669 });
2670
2671 if let Some(selection) = clicked_point_already_selected {
2672 Some(selection.id)
2673 } else {
2674 None
2675 }
2676 }
2677 };
2678
2679 let selections_count = self.selections.count();
2680
2681 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2682 if let Some(point_to_delete) = point_to_delete {
2683 s.delete(point_to_delete);
2684
2685 if selections_count == 1 {
2686 s.set_pending_anchor_range(start..end, mode);
2687 }
2688 } else {
2689 if !add {
2690 s.clear_disjoint();
2691 } else if click_count > 1 {
2692 s.delete(newest_selection.id)
2693 }
2694
2695 s.set_pending_anchor_range(start..end, mode);
2696 }
2697 });
2698 }
2699
2700 fn begin_columnar_selection(
2701 &mut self,
2702 position: DisplayPoint,
2703 goal_column: u32,
2704 reset: bool,
2705 cx: &mut ViewContext<Self>,
2706 ) {
2707 if !self.focus_handle.is_focused(cx) {
2708 self.last_focused_descendant = None;
2709 cx.focus(&self.focus_handle);
2710 }
2711
2712 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2713
2714 if reset {
2715 let pointer_position = display_map
2716 .buffer_snapshot
2717 .anchor_before(position.to_point(&display_map));
2718
2719 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2720 s.clear_disjoint();
2721 s.set_pending_anchor_range(
2722 pointer_position..pointer_position,
2723 SelectMode::Character,
2724 );
2725 });
2726 }
2727
2728 let tail = self.selections.newest::<Point>(cx).tail();
2729 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2730
2731 if !reset {
2732 self.select_columns(
2733 tail.to_display_point(&display_map),
2734 position,
2735 goal_column,
2736 &display_map,
2737 cx,
2738 );
2739 }
2740 }
2741
2742 fn update_selection(
2743 &mut self,
2744 position: DisplayPoint,
2745 goal_column: u32,
2746 scroll_delta: gpui::Point<f32>,
2747 cx: &mut ViewContext<Self>,
2748 ) {
2749 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2750
2751 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2752 let tail = tail.to_display_point(&display_map);
2753 self.select_columns(tail, position, goal_column, &display_map, cx);
2754 } else if let Some(mut pending) = self.selections.pending_anchor() {
2755 let buffer = self.buffer.read(cx).snapshot(cx);
2756 let head;
2757 let tail;
2758 let mode = self.selections.pending_mode().unwrap();
2759 match &mode {
2760 SelectMode::Character => {
2761 head = position.to_point(&display_map);
2762 tail = pending.tail().to_point(&buffer);
2763 }
2764 SelectMode::Word(original_range) => {
2765 let original_display_range = original_range.start.to_display_point(&display_map)
2766 ..original_range.end.to_display_point(&display_map);
2767 let original_buffer_range = original_display_range.start.to_point(&display_map)
2768 ..original_display_range.end.to_point(&display_map);
2769 if movement::is_inside_word(&display_map, position)
2770 || original_display_range.contains(&position)
2771 {
2772 let word_range = movement::surrounding_word(&display_map, position);
2773 if word_range.start < original_display_range.start {
2774 head = word_range.start.to_point(&display_map);
2775 } else {
2776 head = word_range.end.to_point(&display_map);
2777 }
2778 } else {
2779 head = position.to_point(&display_map);
2780 }
2781
2782 if head <= original_buffer_range.start {
2783 tail = original_buffer_range.end;
2784 } else {
2785 tail = original_buffer_range.start;
2786 }
2787 }
2788 SelectMode::Line(original_range) => {
2789 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2790
2791 let position = display_map
2792 .clip_point(position, Bias::Left)
2793 .to_point(&display_map);
2794 let line_start = display_map.prev_line_boundary(position).0;
2795 let next_line_start = buffer.clip_point(
2796 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2797 Bias::Left,
2798 );
2799
2800 if line_start < original_range.start {
2801 head = line_start
2802 } else {
2803 head = next_line_start
2804 }
2805
2806 if head <= original_range.start {
2807 tail = original_range.end;
2808 } else {
2809 tail = original_range.start;
2810 }
2811 }
2812 SelectMode::All => {
2813 return;
2814 }
2815 };
2816
2817 if head < tail {
2818 pending.start = buffer.anchor_before(head);
2819 pending.end = buffer.anchor_before(tail);
2820 pending.reversed = true;
2821 } else {
2822 pending.start = buffer.anchor_before(tail);
2823 pending.end = buffer.anchor_before(head);
2824 pending.reversed = false;
2825 }
2826
2827 self.change_selections(None, cx, |s| {
2828 s.set_pending(pending, mode);
2829 });
2830 } else {
2831 log::error!("update_selection dispatched with no pending selection");
2832 return;
2833 }
2834
2835 self.apply_scroll_delta(scroll_delta, cx);
2836 cx.notify();
2837 }
2838
2839 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2840 self.columnar_selection_tail.take();
2841 if self.selections.pending_anchor().is_some() {
2842 let selections = self.selections.all::<usize>(cx);
2843 self.change_selections(None, cx, |s| {
2844 s.select(selections);
2845 s.clear_pending();
2846 });
2847 }
2848 }
2849
2850 fn select_columns(
2851 &mut self,
2852 tail: DisplayPoint,
2853 head: DisplayPoint,
2854 goal_column: u32,
2855 display_map: &DisplaySnapshot,
2856 cx: &mut ViewContext<Self>,
2857 ) {
2858 let start_row = cmp::min(tail.row(), head.row());
2859 let end_row = cmp::max(tail.row(), head.row());
2860 let start_column = cmp::min(tail.column(), goal_column);
2861 let end_column = cmp::max(tail.column(), goal_column);
2862 let reversed = start_column < tail.column();
2863
2864 let selection_ranges = (start_row.0..=end_row.0)
2865 .map(DisplayRow)
2866 .filter_map(|row| {
2867 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2868 let start = display_map
2869 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2870 .to_point(display_map);
2871 let end = display_map
2872 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2873 .to_point(display_map);
2874 if reversed {
2875 Some(end..start)
2876 } else {
2877 Some(start..end)
2878 }
2879 } else {
2880 None
2881 }
2882 })
2883 .collect::<Vec<_>>();
2884
2885 self.change_selections(None, cx, |s| {
2886 s.select_ranges(selection_ranges);
2887 });
2888 cx.notify();
2889 }
2890
2891 pub fn has_pending_nonempty_selection(&self) -> bool {
2892 let pending_nonempty_selection = match self.selections.pending_anchor() {
2893 Some(Selection { start, end, .. }) => start != end,
2894 None => false,
2895 };
2896
2897 pending_nonempty_selection
2898 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2899 }
2900
2901 pub fn has_pending_selection(&self) -> bool {
2902 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2903 }
2904
2905 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2906 if self.clear_clicked_diff_hunks(cx) {
2907 cx.notify();
2908 return;
2909 }
2910 if self.dismiss_menus_and_popups(true, cx) {
2911 return;
2912 }
2913
2914 if self.mode == EditorMode::Full {
2915 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2916 return;
2917 }
2918 }
2919
2920 cx.propagate();
2921 }
2922
2923 pub fn dismiss_menus_and_popups(
2924 &mut self,
2925 should_report_inline_completion_event: bool,
2926 cx: &mut ViewContext<Self>,
2927 ) -> bool {
2928 if self.take_rename(false, cx).is_some() {
2929 return true;
2930 }
2931
2932 if hide_hover(self, cx) {
2933 return true;
2934 }
2935
2936 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2937 return true;
2938 }
2939
2940 if self.hide_context_menu(cx).is_some() {
2941 return true;
2942 }
2943
2944 if self.mouse_context_menu.take().is_some() {
2945 return true;
2946 }
2947
2948 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2949 return true;
2950 }
2951
2952 if self.snippet_stack.pop().is_some() {
2953 return true;
2954 }
2955
2956 if self.mode == EditorMode::Full {
2957 if self.active_diagnostics.is_some() {
2958 self.dismiss_diagnostics(cx);
2959 return true;
2960 }
2961 }
2962
2963 false
2964 }
2965
2966 fn linked_editing_ranges_for(
2967 &self,
2968 selection: Range<text::Anchor>,
2969 cx: &AppContext,
2970 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2971 if self.linked_edit_ranges.is_empty() {
2972 return None;
2973 }
2974 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2975 selection.end.buffer_id.and_then(|end_buffer_id| {
2976 if selection.start.buffer_id != Some(end_buffer_id) {
2977 return None;
2978 }
2979 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2980 let snapshot = buffer.read(cx).snapshot();
2981 self.linked_edit_ranges
2982 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2983 .map(|ranges| (ranges, snapshot, buffer))
2984 })?;
2985 use text::ToOffset as TO;
2986 // find offset from the start of current range to current cursor position
2987 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2988
2989 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2990 let start_difference = start_offset - start_byte_offset;
2991 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2992 let end_difference = end_offset - start_byte_offset;
2993 // Current range has associated linked ranges.
2994 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2995 for range in linked_ranges.iter() {
2996 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2997 let end_offset = start_offset + end_difference;
2998 let start_offset = start_offset + start_difference;
2999 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3000 continue;
3001 }
3002 let start = buffer_snapshot.anchor_after(start_offset);
3003 let end = buffer_snapshot.anchor_after(end_offset);
3004 linked_edits
3005 .entry(buffer.clone())
3006 .or_default()
3007 .push(start..end);
3008 }
3009 Some(linked_edits)
3010 }
3011
3012 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3013 let text: Arc<str> = text.into();
3014
3015 if self.read_only(cx) {
3016 return;
3017 }
3018
3019 let selections = self.selections.all_adjusted(cx);
3020 let mut bracket_inserted = false;
3021 let mut edits = Vec::new();
3022 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3023 let mut new_selections = Vec::with_capacity(selections.len());
3024 let mut new_autoclose_regions = Vec::new();
3025 let snapshot = self.buffer.read(cx).read(cx);
3026
3027 for (selection, autoclose_region) in
3028 self.selections_with_autoclose_regions(selections, &snapshot)
3029 {
3030 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3031 // Determine if the inserted text matches the opening or closing
3032 // bracket of any of this language's bracket pairs.
3033 let mut bracket_pair = None;
3034 let mut is_bracket_pair_start = false;
3035 let mut is_bracket_pair_end = false;
3036 if !text.is_empty() {
3037 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3038 // and they are removing the character that triggered IME popup.
3039 for (pair, enabled) in scope.brackets() {
3040 if !pair.close && !pair.surround {
3041 continue;
3042 }
3043
3044 if enabled && pair.start.ends_with(text.as_ref()) {
3045 bracket_pair = Some(pair.clone());
3046 is_bracket_pair_start = true;
3047 break;
3048 }
3049 if pair.end.as_str() == text.as_ref() {
3050 bracket_pair = Some(pair.clone());
3051 is_bracket_pair_end = true;
3052 break;
3053 }
3054 }
3055 }
3056
3057 if let Some(bracket_pair) = bracket_pair {
3058 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3059 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3060 let auto_surround =
3061 self.use_auto_surround && snapshot_settings.use_auto_surround;
3062 if selection.is_empty() {
3063 if is_bracket_pair_start {
3064 let prefix_len = bracket_pair.start.len() - text.len();
3065
3066 // If the inserted text is a suffix of an opening bracket and the
3067 // selection is preceded by the rest of the opening bracket, then
3068 // insert the closing bracket.
3069 let following_text_allows_autoclose = snapshot
3070 .chars_at(selection.start)
3071 .next()
3072 .map_or(true, |c| scope.should_autoclose_before(c));
3073 let preceding_text_matches_prefix = prefix_len == 0
3074 || (selection.start.column >= (prefix_len as u32)
3075 && snapshot.contains_str_at(
3076 Point::new(
3077 selection.start.row,
3078 selection.start.column - (prefix_len as u32),
3079 ),
3080 &bracket_pair.start[..prefix_len],
3081 ));
3082
3083 if autoclose
3084 && bracket_pair.close
3085 && following_text_allows_autoclose
3086 && preceding_text_matches_prefix
3087 {
3088 let anchor = snapshot.anchor_before(selection.end);
3089 new_selections.push((selection.map(|_| anchor), text.len()));
3090 new_autoclose_regions.push((
3091 anchor,
3092 text.len(),
3093 selection.id,
3094 bracket_pair.clone(),
3095 ));
3096 edits.push((
3097 selection.range(),
3098 format!("{}{}", text, bracket_pair.end).into(),
3099 ));
3100 bracket_inserted = true;
3101 continue;
3102 }
3103 }
3104
3105 if let Some(region) = autoclose_region {
3106 // If the selection is followed by an auto-inserted closing bracket,
3107 // then don't insert that closing bracket again; just move the selection
3108 // past the closing bracket.
3109 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3110 && text.as_ref() == region.pair.end.as_str();
3111 if should_skip {
3112 let anchor = snapshot.anchor_after(selection.end);
3113 new_selections
3114 .push((selection.map(|_| anchor), region.pair.end.len()));
3115 continue;
3116 }
3117 }
3118
3119 let always_treat_brackets_as_autoclosed = snapshot
3120 .settings_at(selection.start, cx)
3121 .always_treat_brackets_as_autoclosed;
3122 if always_treat_brackets_as_autoclosed
3123 && is_bracket_pair_end
3124 && snapshot.contains_str_at(selection.end, text.as_ref())
3125 {
3126 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3127 // and the inserted text is a closing bracket and the selection is followed
3128 // by the closing bracket then move the selection past the closing bracket.
3129 let anchor = snapshot.anchor_after(selection.end);
3130 new_selections.push((selection.map(|_| anchor), text.len()));
3131 continue;
3132 }
3133 }
3134 // If an opening bracket is 1 character long and is typed while
3135 // text is selected, then surround that text with the bracket pair.
3136 else if auto_surround
3137 && bracket_pair.surround
3138 && is_bracket_pair_start
3139 && bracket_pair.start.chars().count() == 1
3140 {
3141 edits.push((selection.start..selection.start, text.clone()));
3142 edits.push((
3143 selection.end..selection.end,
3144 bracket_pair.end.as_str().into(),
3145 ));
3146 bracket_inserted = true;
3147 new_selections.push((
3148 Selection {
3149 id: selection.id,
3150 start: snapshot.anchor_after(selection.start),
3151 end: snapshot.anchor_before(selection.end),
3152 reversed: selection.reversed,
3153 goal: selection.goal,
3154 },
3155 0,
3156 ));
3157 continue;
3158 }
3159 }
3160 }
3161
3162 if self.auto_replace_emoji_shortcode
3163 && selection.is_empty()
3164 && text.as_ref().ends_with(':')
3165 {
3166 if let Some(possible_emoji_short_code) =
3167 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3168 {
3169 if !possible_emoji_short_code.is_empty() {
3170 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3171 let emoji_shortcode_start = Point::new(
3172 selection.start.row,
3173 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3174 );
3175
3176 // Remove shortcode from buffer
3177 edits.push((
3178 emoji_shortcode_start..selection.start,
3179 "".to_string().into(),
3180 ));
3181 new_selections.push((
3182 Selection {
3183 id: selection.id,
3184 start: snapshot.anchor_after(emoji_shortcode_start),
3185 end: snapshot.anchor_before(selection.start),
3186 reversed: selection.reversed,
3187 goal: selection.goal,
3188 },
3189 0,
3190 ));
3191
3192 // Insert emoji
3193 let selection_start_anchor = snapshot.anchor_after(selection.start);
3194 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3195 edits.push((selection.start..selection.end, emoji.to_string().into()));
3196
3197 continue;
3198 }
3199 }
3200 }
3201 }
3202
3203 // If not handling any auto-close operation, then just replace the selected
3204 // text with the given input and move the selection to the end of the
3205 // newly inserted text.
3206 let anchor = snapshot.anchor_after(selection.end);
3207 if !self.linked_edit_ranges.is_empty() {
3208 let start_anchor = snapshot.anchor_before(selection.start);
3209
3210 let is_word_char = text.chars().next().map_or(true, |char| {
3211 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3212 let kind = char_kind(&scope, char);
3213
3214 kind == CharKind::Word
3215 });
3216
3217 if is_word_char {
3218 if let Some(ranges) = self
3219 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3220 {
3221 for (buffer, edits) in ranges {
3222 linked_edits
3223 .entry(buffer.clone())
3224 .or_default()
3225 .extend(edits.into_iter().map(|range| (range, text.clone())));
3226 }
3227 }
3228 }
3229 }
3230
3231 new_selections.push((selection.map(|_| anchor), 0));
3232 edits.push((selection.start..selection.end, text.clone()));
3233 }
3234
3235 drop(snapshot);
3236
3237 self.transact(cx, |this, cx| {
3238 this.buffer.update(cx, |buffer, cx| {
3239 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3240 });
3241 for (buffer, edits) in linked_edits {
3242 buffer.update(cx, |buffer, cx| {
3243 let snapshot = buffer.snapshot();
3244 let edits = edits
3245 .into_iter()
3246 .map(|(range, text)| {
3247 use text::ToPoint as TP;
3248 let end_point = TP::to_point(&range.end, &snapshot);
3249 let start_point = TP::to_point(&range.start, &snapshot);
3250 (start_point..end_point, text)
3251 })
3252 .sorted_by_key(|(range, _)| range.start)
3253 .collect::<Vec<_>>();
3254 buffer.edit(edits, None, cx);
3255 })
3256 }
3257 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3258 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3259 let snapshot = this.buffer.read(cx).read(cx);
3260 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3261 .zip(new_selection_deltas)
3262 .map(|(selection, delta)| Selection {
3263 id: selection.id,
3264 start: selection.start + delta,
3265 end: selection.end + delta,
3266 reversed: selection.reversed,
3267 goal: SelectionGoal::None,
3268 })
3269 .collect::<Vec<_>>();
3270
3271 let mut i = 0;
3272 for (position, delta, selection_id, pair) in new_autoclose_regions {
3273 let position = position.to_offset(&snapshot) + delta;
3274 let start = snapshot.anchor_before(position);
3275 let end = snapshot.anchor_after(position);
3276 while let Some(existing_state) = this.autoclose_regions.get(i) {
3277 match existing_state.range.start.cmp(&start, &snapshot) {
3278 Ordering::Less => i += 1,
3279 Ordering::Greater => break,
3280 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3281 Ordering::Less => i += 1,
3282 Ordering::Equal => break,
3283 Ordering::Greater => break,
3284 },
3285 }
3286 }
3287 this.autoclose_regions.insert(
3288 i,
3289 AutocloseRegion {
3290 selection_id,
3291 range: start..end,
3292 pair,
3293 },
3294 );
3295 }
3296
3297 drop(snapshot);
3298 let had_active_inline_completion = this.has_active_inline_completion(cx);
3299 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3300 s.select(new_selections)
3301 });
3302
3303 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3304 if let Some(on_type_format_task) =
3305 this.trigger_on_type_formatting(text.to_string(), cx)
3306 {
3307 on_type_format_task.detach_and_log_err(cx);
3308 }
3309 }
3310
3311 let editor_settings = EditorSettings::get_global(cx);
3312 if bracket_inserted
3313 && (editor_settings.auto_signature_help
3314 || editor_settings.show_signature_help_after_edits)
3315 {
3316 this.show_signature_help(&ShowSignatureHelp, cx);
3317 }
3318
3319 let trigger_in_words = !had_active_inline_completion;
3320 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3321 linked_editing_ranges::refresh_linked_ranges(this, cx);
3322 this.refresh_inline_completion(true, cx);
3323 });
3324 }
3325
3326 fn find_possible_emoji_shortcode_at_position(
3327 snapshot: &MultiBufferSnapshot,
3328 position: Point,
3329 ) -> Option<String> {
3330 let mut chars = Vec::new();
3331 let mut found_colon = false;
3332 for char in snapshot.reversed_chars_at(position).take(100) {
3333 // Found a possible emoji shortcode in the middle of the buffer
3334 if found_colon {
3335 if char.is_whitespace() {
3336 chars.reverse();
3337 return Some(chars.iter().collect());
3338 }
3339 // If the previous character is not a whitespace, we are in the middle of a word
3340 // and we only want to complete the shortcode if the word is made up of other emojis
3341 let mut containing_word = String::new();
3342 for ch in snapshot
3343 .reversed_chars_at(position)
3344 .skip(chars.len() + 1)
3345 .take(100)
3346 {
3347 if ch.is_whitespace() {
3348 break;
3349 }
3350 containing_word.push(ch);
3351 }
3352 let containing_word = containing_word.chars().rev().collect::<String>();
3353 if util::word_consists_of_emojis(containing_word.as_str()) {
3354 chars.reverse();
3355 return Some(chars.iter().collect());
3356 }
3357 }
3358
3359 if char.is_whitespace() || !char.is_ascii() {
3360 return None;
3361 }
3362 if char == ':' {
3363 found_colon = true;
3364 } else {
3365 chars.push(char);
3366 }
3367 }
3368 // Found a possible emoji shortcode at the beginning of the buffer
3369 chars.reverse();
3370 Some(chars.iter().collect())
3371 }
3372
3373 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3374 self.transact(cx, |this, cx| {
3375 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3376 let selections = this.selections.all::<usize>(cx);
3377 let multi_buffer = this.buffer.read(cx);
3378 let buffer = multi_buffer.snapshot(cx);
3379 selections
3380 .iter()
3381 .map(|selection| {
3382 let start_point = selection.start.to_point(&buffer);
3383 let mut indent =
3384 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3385 indent.len = cmp::min(indent.len, start_point.column);
3386 let start = selection.start;
3387 let end = selection.end;
3388 let selection_is_empty = start == end;
3389 let language_scope = buffer.language_scope_at(start);
3390 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3391 &language_scope
3392 {
3393 let leading_whitespace_len = buffer
3394 .reversed_chars_at(start)
3395 .take_while(|c| c.is_whitespace() && *c != '\n')
3396 .map(|c| c.len_utf8())
3397 .sum::<usize>();
3398
3399 let trailing_whitespace_len = buffer
3400 .chars_at(end)
3401 .take_while(|c| c.is_whitespace() && *c != '\n')
3402 .map(|c| c.len_utf8())
3403 .sum::<usize>();
3404
3405 let insert_extra_newline =
3406 language.brackets().any(|(pair, enabled)| {
3407 let pair_start = pair.start.trim_end();
3408 let pair_end = pair.end.trim_start();
3409
3410 enabled
3411 && pair.newline
3412 && buffer.contains_str_at(
3413 end + trailing_whitespace_len,
3414 pair_end,
3415 )
3416 && buffer.contains_str_at(
3417 (start - leading_whitespace_len)
3418 .saturating_sub(pair_start.len()),
3419 pair_start,
3420 )
3421 });
3422
3423 // Comment extension on newline is allowed only for cursor selections
3424 let comment_delimiter = maybe!({
3425 if !selection_is_empty {
3426 return None;
3427 }
3428
3429 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3430 return None;
3431 }
3432
3433 let delimiters = language.line_comment_prefixes();
3434 let max_len_of_delimiter =
3435 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3436 let (snapshot, range) =
3437 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3438
3439 let mut index_of_first_non_whitespace = 0;
3440 let comment_candidate = snapshot
3441 .chars_for_range(range)
3442 .skip_while(|c| {
3443 let should_skip = c.is_whitespace();
3444 if should_skip {
3445 index_of_first_non_whitespace += 1;
3446 }
3447 should_skip
3448 })
3449 .take(max_len_of_delimiter)
3450 .collect::<String>();
3451 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3452 comment_candidate.starts_with(comment_prefix.as_ref())
3453 })?;
3454 let cursor_is_placed_after_comment_marker =
3455 index_of_first_non_whitespace + comment_prefix.len()
3456 <= start_point.column as usize;
3457 if cursor_is_placed_after_comment_marker {
3458 Some(comment_prefix.clone())
3459 } else {
3460 None
3461 }
3462 });
3463 (comment_delimiter, insert_extra_newline)
3464 } else {
3465 (None, false)
3466 };
3467
3468 let capacity_for_delimiter = comment_delimiter
3469 .as_deref()
3470 .map(str::len)
3471 .unwrap_or_default();
3472 let mut new_text =
3473 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3474 new_text.push_str("\n");
3475 new_text.extend(indent.chars());
3476 if let Some(delimiter) = &comment_delimiter {
3477 new_text.push_str(&delimiter);
3478 }
3479 if insert_extra_newline {
3480 new_text = new_text.repeat(2);
3481 }
3482
3483 let anchor = buffer.anchor_after(end);
3484 let new_selection = selection.map(|_| anchor);
3485 (
3486 (start..end, new_text),
3487 (insert_extra_newline, new_selection),
3488 )
3489 })
3490 .unzip()
3491 };
3492
3493 this.edit_with_autoindent(edits, cx);
3494 let buffer = this.buffer.read(cx).snapshot(cx);
3495 let new_selections = selection_fixup_info
3496 .into_iter()
3497 .map(|(extra_newline_inserted, new_selection)| {
3498 let mut cursor = new_selection.end.to_point(&buffer);
3499 if extra_newline_inserted {
3500 cursor.row -= 1;
3501 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3502 }
3503 new_selection.map(|_| cursor)
3504 })
3505 .collect();
3506
3507 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3508 this.refresh_inline_completion(true, cx);
3509 });
3510 }
3511
3512 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3513 let buffer = self.buffer.read(cx);
3514 let snapshot = buffer.snapshot(cx);
3515
3516 let mut edits = Vec::new();
3517 let mut rows = Vec::new();
3518
3519 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3520 let cursor = selection.head();
3521 let row = cursor.row;
3522
3523 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3524
3525 let newline = "\n".to_string();
3526 edits.push((start_of_line..start_of_line, newline));
3527
3528 rows.push(row + rows_inserted as u32);
3529 }
3530
3531 self.transact(cx, |editor, cx| {
3532 editor.edit(edits, cx);
3533
3534 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3535 let mut index = 0;
3536 s.move_cursors_with(|map, _, _| {
3537 let row = rows[index];
3538 index += 1;
3539
3540 let point = Point::new(row, 0);
3541 let boundary = map.next_line_boundary(point).1;
3542 let clipped = map.clip_point(boundary, Bias::Left);
3543
3544 (clipped, SelectionGoal::None)
3545 });
3546 });
3547
3548 let mut indent_edits = Vec::new();
3549 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3550 for row in rows {
3551 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3552 for (row, indent) in indents {
3553 if indent.len == 0 {
3554 continue;
3555 }
3556
3557 let text = match indent.kind {
3558 IndentKind::Space => " ".repeat(indent.len as usize),
3559 IndentKind::Tab => "\t".repeat(indent.len as usize),
3560 };
3561 let point = Point::new(row.0, 0);
3562 indent_edits.push((point..point, text));
3563 }
3564 }
3565 editor.edit(indent_edits, cx);
3566 });
3567 }
3568
3569 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3570 let buffer = self.buffer.read(cx);
3571 let snapshot = buffer.snapshot(cx);
3572
3573 let mut edits = Vec::new();
3574 let mut rows = Vec::new();
3575 let mut rows_inserted = 0;
3576
3577 for selection in self.selections.all_adjusted(cx) {
3578 let cursor = selection.head();
3579 let row = cursor.row;
3580
3581 let point = Point::new(row + 1, 0);
3582 let start_of_line = snapshot.clip_point(point, Bias::Left);
3583
3584 let newline = "\n".to_string();
3585 edits.push((start_of_line..start_of_line, newline));
3586
3587 rows_inserted += 1;
3588 rows.push(row + rows_inserted);
3589 }
3590
3591 self.transact(cx, |editor, cx| {
3592 editor.edit(edits, cx);
3593
3594 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3595 let mut index = 0;
3596 s.move_cursors_with(|map, _, _| {
3597 let row = rows[index];
3598 index += 1;
3599
3600 let point = Point::new(row, 0);
3601 let boundary = map.next_line_boundary(point).1;
3602 let clipped = map.clip_point(boundary, Bias::Left);
3603
3604 (clipped, SelectionGoal::None)
3605 });
3606 });
3607
3608 let mut indent_edits = Vec::new();
3609 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3610 for row in rows {
3611 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3612 for (row, indent) in indents {
3613 if indent.len == 0 {
3614 continue;
3615 }
3616
3617 let text = match indent.kind {
3618 IndentKind::Space => " ".repeat(indent.len as usize),
3619 IndentKind::Tab => "\t".repeat(indent.len as usize),
3620 };
3621 let point = Point::new(row.0, 0);
3622 indent_edits.push((point..point, text));
3623 }
3624 }
3625 editor.edit(indent_edits, cx);
3626 });
3627 }
3628
3629 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3630 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3631 original_indent_columns: Vec::new(),
3632 });
3633 self.insert_with_autoindent_mode(text, autoindent, cx);
3634 }
3635
3636 fn insert_with_autoindent_mode(
3637 &mut self,
3638 text: &str,
3639 autoindent_mode: Option<AutoindentMode>,
3640 cx: &mut ViewContext<Self>,
3641 ) {
3642 if self.read_only(cx) {
3643 return;
3644 }
3645
3646 let text: Arc<str> = text.into();
3647 self.transact(cx, |this, cx| {
3648 let old_selections = this.selections.all_adjusted(cx);
3649 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3650 let anchors = {
3651 let snapshot = buffer.read(cx);
3652 old_selections
3653 .iter()
3654 .map(|s| {
3655 let anchor = snapshot.anchor_after(s.head());
3656 s.map(|_| anchor)
3657 })
3658 .collect::<Vec<_>>()
3659 };
3660 buffer.edit(
3661 old_selections
3662 .iter()
3663 .map(|s| (s.start..s.end, text.clone())),
3664 autoindent_mode,
3665 cx,
3666 );
3667 anchors
3668 });
3669
3670 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3671 s.select_anchors(selection_anchors);
3672 })
3673 });
3674 }
3675
3676 fn trigger_completion_on_input(
3677 &mut self,
3678 text: &str,
3679 trigger_in_words: bool,
3680 cx: &mut ViewContext<Self>,
3681 ) {
3682 if self.is_completion_trigger(text, trigger_in_words, cx) {
3683 self.show_completions(
3684 &ShowCompletions {
3685 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3686 },
3687 cx,
3688 );
3689 } else {
3690 self.hide_context_menu(cx);
3691 }
3692 }
3693
3694 fn is_completion_trigger(
3695 &self,
3696 text: &str,
3697 trigger_in_words: bool,
3698 cx: &mut ViewContext<Self>,
3699 ) -> bool {
3700 let position = self.selections.newest_anchor().head();
3701 let multibuffer = self.buffer.read(cx);
3702 let Some(buffer) = position
3703 .buffer_id
3704 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3705 else {
3706 return false;
3707 };
3708
3709 if let Some(completion_provider) = &self.completion_provider {
3710 completion_provider.is_completion_trigger(
3711 &buffer,
3712 position.text_anchor,
3713 text,
3714 trigger_in_words,
3715 cx,
3716 )
3717 } else {
3718 false
3719 }
3720 }
3721
3722 /// If any empty selections is touching the start of its innermost containing autoclose
3723 /// region, expand it to select the brackets.
3724 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3725 let selections = self.selections.all::<usize>(cx);
3726 let buffer = self.buffer.read(cx).read(cx);
3727 let new_selections = self
3728 .selections_with_autoclose_regions(selections, &buffer)
3729 .map(|(mut selection, region)| {
3730 if !selection.is_empty() {
3731 return selection;
3732 }
3733
3734 if let Some(region) = region {
3735 let mut range = region.range.to_offset(&buffer);
3736 if selection.start == range.start && range.start >= region.pair.start.len() {
3737 range.start -= region.pair.start.len();
3738 if buffer.contains_str_at(range.start, ®ion.pair.start)
3739 && buffer.contains_str_at(range.end, ®ion.pair.end)
3740 {
3741 range.end += region.pair.end.len();
3742 selection.start = range.start;
3743 selection.end = range.end;
3744
3745 return selection;
3746 }
3747 }
3748 }
3749
3750 let always_treat_brackets_as_autoclosed = buffer
3751 .settings_at(selection.start, cx)
3752 .always_treat_brackets_as_autoclosed;
3753
3754 if !always_treat_brackets_as_autoclosed {
3755 return selection;
3756 }
3757
3758 if let Some(scope) = buffer.language_scope_at(selection.start) {
3759 for (pair, enabled) in scope.brackets() {
3760 if !enabled || !pair.close {
3761 continue;
3762 }
3763
3764 if buffer.contains_str_at(selection.start, &pair.end) {
3765 let pair_start_len = pair.start.len();
3766 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3767 {
3768 selection.start -= pair_start_len;
3769 selection.end += pair.end.len();
3770
3771 return selection;
3772 }
3773 }
3774 }
3775 }
3776
3777 selection
3778 })
3779 .collect();
3780
3781 drop(buffer);
3782 self.change_selections(None, cx, |selections| selections.select(new_selections));
3783 }
3784
3785 /// Iterate the given selections, and for each one, find the smallest surrounding
3786 /// autoclose region. This uses the ordering of the selections and the autoclose
3787 /// regions to avoid repeated comparisons.
3788 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3789 &'a self,
3790 selections: impl IntoIterator<Item = Selection<D>>,
3791 buffer: &'a MultiBufferSnapshot,
3792 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3793 let mut i = 0;
3794 let mut regions = self.autoclose_regions.as_slice();
3795 selections.into_iter().map(move |selection| {
3796 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3797
3798 let mut enclosing = None;
3799 while let Some(pair_state) = regions.get(i) {
3800 if pair_state.range.end.to_offset(buffer) < range.start {
3801 regions = ®ions[i + 1..];
3802 i = 0;
3803 } else if pair_state.range.start.to_offset(buffer) > range.end {
3804 break;
3805 } else {
3806 if pair_state.selection_id == selection.id {
3807 enclosing = Some(pair_state);
3808 }
3809 i += 1;
3810 }
3811 }
3812
3813 (selection.clone(), enclosing)
3814 })
3815 }
3816
3817 /// Remove any autoclose regions that no longer contain their selection.
3818 fn invalidate_autoclose_regions(
3819 &mut self,
3820 mut selections: &[Selection<Anchor>],
3821 buffer: &MultiBufferSnapshot,
3822 ) {
3823 self.autoclose_regions.retain(|state| {
3824 let mut i = 0;
3825 while let Some(selection) = selections.get(i) {
3826 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3827 selections = &selections[1..];
3828 continue;
3829 }
3830 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3831 break;
3832 }
3833 if selection.id == state.selection_id {
3834 return true;
3835 } else {
3836 i += 1;
3837 }
3838 }
3839 false
3840 });
3841 }
3842
3843 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3844 let offset = position.to_offset(buffer);
3845 let (word_range, kind) = buffer.surrounding_word(offset);
3846 if offset > word_range.start && kind == Some(CharKind::Word) {
3847 Some(
3848 buffer
3849 .text_for_range(word_range.start..offset)
3850 .collect::<String>(),
3851 )
3852 } else {
3853 None
3854 }
3855 }
3856
3857 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3858 self.refresh_inlay_hints(
3859 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3860 cx,
3861 );
3862 }
3863
3864 pub fn inlay_hints_enabled(&self) -> bool {
3865 self.inlay_hint_cache.enabled
3866 }
3867
3868 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3869 if self.project.is_none() || self.mode != EditorMode::Full {
3870 return;
3871 }
3872
3873 let reason_description = reason.description();
3874 let ignore_debounce = matches!(
3875 reason,
3876 InlayHintRefreshReason::SettingsChange(_)
3877 | InlayHintRefreshReason::Toggle(_)
3878 | InlayHintRefreshReason::ExcerptsRemoved(_)
3879 );
3880 let (invalidate_cache, required_languages) = match reason {
3881 InlayHintRefreshReason::Toggle(enabled) => {
3882 self.inlay_hint_cache.enabled = enabled;
3883 if enabled {
3884 (InvalidationStrategy::RefreshRequested, None)
3885 } else {
3886 self.inlay_hint_cache.clear();
3887 self.splice_inlays(
3888 self.visible_inlay_hints(cx)
3889 .iter()
3890 .map(|inlay| inlay.id)
3891 .collect(),
3892 Vec::new(),
3893 cx,
3894 );
3895 return;
3896 }
3897 }
3898 InlayHintRefreshReason::SettingsChange(new_settings) => {
3899 match self.inlay_hint_cache.update_settings(
3900 &self.buffer,
3901 new_settings,
3902 self.visible_inlay_hints(cx),
3903 cx,
3904 ) {
3905 ControlFlow::Break(Some(InlaySplice {
3906 to_remove,
3907 to_insert,
3908 })) => {
3909 self.splice_inlays(to_remove, to_insert, cx);
3910 return;
3911 }
3912 ControlFlow::Break(None) => return,
3913 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3914 }
3915 }
3916 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3917 if let Some(InlaySplice {
3918 to_remove,
3919 to_insert,
3920 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3921 {
3922 self.splice_inlays(to_remove, to_insert, cx);
3923 }
3924 return;
3925 }
3926 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3927 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3928 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3929 }
3930 InlayHintRefreshReason::RefreshRequested => {
3931 (InvalidationStrategy::RefreshRequested, None)
3932 }
3933 };
3934
3935 if let Some(InlaySplice {
3936 to_remove,
3937 to_insert,
3938 }) = self.inlay_hint_cache.spawn_hint_refresh(
3939 reason_description,
3940 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3941 invalidate_cache,
3942 ignore_debounce,
3943 cx,
3944 ) {
3945 self.splice_inlays(to_remove, to_insert, cx);
3946 }
3947 }
3948
3949 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3950 self.display_map
3951 .read(cx)
3952 .current_inlays()
3953 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3954 .cloned()
3955 .collect()
3956 }
3957
3958 pub fn excerpts_for_inlay_hints_query(
3959 &self,
3960 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3961 cx: &mut ViewContext<Editor>,
3962 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3963 let Some(project) = self.project.as_ref() else {
3964 return HashMap::default();
3965 };
3966 let project = project.read(cx);
3967 let multi_buffer = self.buffer().read(cx);
3968 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3969 let multi_buffer_visible_start = self
3970 .scroll_manager
3971 .anchor()
3972 .anchor
3973 .to_point(&multi_buffer_snapshot);
3974 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3975 multi_buffer_visible_start
3976 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3977 Bias::Left,
3978 );
3979 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3980 multi_buffer
3981 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3982 .into_iter()
3983 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3984 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3985 let buffer = buffer_handle.read(cx);
3986 let buffer_file = project::File::from_dyn(buffer.file())?;
3987 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3988 let worktree_entry = buffer_worktree
3989 .read(cx)
3990 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3991 if worktree_entry.is_ignored {
3992 return None;
3993 }
3994
3995 let language = buffer.language()?;
3996 if let Some(restrict_to_languages) = restrict_to_languages {
3997 if !restrict_to_languages.contains(language) {
3998 return None;
3999 }
4000 }
4001 Some((
4002 excerpt_id,
4003 (
4004 buffer_handle,
4005 buffer.version().clone(),
4006 excerpt_visible_range,
4007 ),
4008 ))
4009 })
4010 .collect()
4011 }
4012
4013 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4014 TextLayoutDetails {
4015 text_system: cx.text_system().clone(),
4016 editor_style: self.style.clone().unwrap(),
4017 rem_size: cx.rem_size(),
4018 scroll_anchor: self.scroll_manager.anchor(),
4019 visible_rows: self.visible_line_count(),
4020 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4021 }
4022 }
4023
4024 fn splice_inlays(
4025 &self,
4026 to_remove: Vec<InlayId>,
4027 to_insert: Vec<Inlay>,
4028 cx: &mut ViewContext<Self>,
4029 ) {
4030 self.display_map.update(cx, |display_map, cx| {
4031 display_map.splice_inlays(to_remove, to_insert, cx);
4032 });
4033 cx.notify();
4034 }
4035
4036 fn trigger_on_type_formatting(
4037 &self,
4038 input: String,
4039 cx: &mut ViewContext<Self>,
4040 ) -> Option<Task<Result<()>>> {
4041 if input.len() != 1 {
4042 return None;
4043 }
4044
4045 let project = self.project.as_ref()?;
4046 let position = self.selections.newest_anchor().head();
4047 let (buffer, buffer_position) = self
4048 .buffer
4049 .read(cx)
4050 .text_anchor_for_position(position, cx)?;
4051
4052 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4053 // hence we do LSP request & edit on host side only — add formats to host's history.
4054 let push_to_lsp_host_history = true;
4055 // If this is not the host, append its history with new edits.
4056 let push_to_client_history = project.read(cx).is_remote();
4057
4058 let on_type_formatting = project.update(cx, |project, cx| {
4059 project.on_type_format(
4060 buffer.clone(),
4061 buffer_position,
4062 input,
4063 push_to_lsp_host_history,
4064 cx,
4065 )
4066 });
4067 Some(cx.spawn(|editor, mut cx| async move {
4068 if let Some(transaction) = on_type_formatting.await? {
4069 if push_to_client_history {
4070 buffer
4071 .update(&mut cx, |buffer, _| {
4072 buffer.push_transaction(transaction, Instant::now());
4073 })
4074 .ok();
4075 }
4076 editor.update(&mut cx, |editor, cx| {
4077 editor.refresh_document_highlights(cx);
4078 })?;
4079 }
4080 Ok(())
4081 }))
4082 }
4083
4084 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4085 if self.pending_rename.is_some() {
4086 return;
4087 }
4088
4089 let Some(provider) = self.completion_provider.as_ref() else {
4090 return;
4091 };
4092
4093 let position = self.selections.newest_anchor().head();
4094 let (buffer, buffer_position) =
4095 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4096 output
4097 } else {
4098 return;
4099 };
4100
4101 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4102 let is_followup_invoke = {
4103 let context_menu_state = self.context_menu.read();
4104 matches!(
4105 context_menu_state.deref(),
4106 Some(ContextMenu::Completions(_))
4107 )
4108 };
4109 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4110 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4111 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4112 CompletionTriggerKind::TRIGGER_CHARACTER
4113 }
4114
4115 _ => CompletionTriggerKind::INVOKED,
4116 };
4117 let completion_context = CompletionContext {
4118 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4119 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4120 Some(String::from(trigger))
4121 } else {
4122 None
4123 }
4124 }),
4125 trigger_kind,
4126 };
4127 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4128 let sort_completions = provider.sort_completions();
4129
4130 let id = post_inc(&mut self.next_completion_id);
4131 let task = cx.spawn(|this, mut cx| {
4132 async move {
4133 this.update(&mut cx, |this, _| {
4134 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4135 })?;
4136 let completions = completions.await.log_err();
4137 let menu = if let Some(completions) = completions {
4138 let mut menu = CompletionsMenu {
4139 id,
4140 sort_completions,
4141 initial_position: position,
4142 match_candidates: completions
4143 .iter()
4144 .enumerate()
4145 .map(|(id, completion)| {
4146 StringMatchCandidate::new(
4147 id,
4148 completion.label.text[completion.label.filter_range.clone()]
4149 .into(),
4150 )
4151 })
4152 .collect(),
4153 buffer: buffer.clone(),
4154 completions: Arc::new(RwLock::new(completions.into())),
4155 matches: Vec::new().into(),
4156 selected_item: 0,
4157 scroll_handle: UniformListScrollHandle::new(),
4158 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4159 DebouncedDelay::new(),
4160 )),
4161 };
4162 menu.filter(query.as_deref(), cx.background_executor().clone())
4163 .await;
4164
4165 if menu.matches.is_empty() {
4166 None
4167 } else {
4168 this.update(&mut cx, |editor, cx| {
4169 let completions = menu.completions.clone();
4170 let matches = menu.matches.clone();
4171
4172 let delay_ms = EditorSettings::get_global(cx)
4173 .completion_documentation_secondary_query_debounce;
4174 let delay = Duration::from_millis(delay_ms);
4175 editor
4176 .completion_documentation_pre_resolve_debounce
4177 .fire_new(delay, cx, |editor, cx| {
4178 CompletionsMenu::pre_resolve_completion_documentation(
4179 buffer,
4180 completions,
4181 matches,
4182 editor,
4183 cx,
4184 )
4185 });
4186 })
4187 .ok();
4188 Some(menu)
4189 }
4190 } else {
4191 None
4192 };
4193
4194 this.update(&mut cx, |this, cx| {
4195 let mut context_menu = this.context_menu.write();
4196 match context_menu.as_ref() {
4197 None => {}
4198
4199 Some(ContextMenu::Completions(prev_menu)) => {
4200 if prev_menu.id > id {
4201 return;
4202 }
4203 }
4204
4205 _ => return,
4206 }
4207
4208 if this.focus_handle.is_focused(cx) && menu.is_some() {
4209 let menu = menu.unwrap();
4210 *context_menu = Some(ContextMenu::Completions(menu));
4211 drop(context_menu);
4212 this.discard_inline_completion(false, cx);
4213 cx.notify();
4214 } else if this.completion_tasks.len() <= 1 {
4215 // If there are no more completion tasks and the last menu was
4216 // empty, we should hide it. If it was already hidden, we should
4217 // also show the copilot completion when available.
4218 drop(context_menu);
4219 if this.hide_context_menu(cx).is_none() {
4220 this.update_visible_inline_completion(cx);
4221 }
4222 }
4223 })?;
4224
4225 Ok::<_, anyhow::Error>(())
4226 }
4227 .log_err()
4228 });
4229
4230 self.completion_tasks.push((id, task));
4231 }
4232
4233 pub fn confirm_completion(
4234 &mut self,
4235 action: &ConfirmCompletion,
4236 cx: &mut ViewContext<Self>,
4237 ) -> Option<Task<Result<()>>> {
4238 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4239 }
4240
4241 pub fn compose_completion(
4242 &mut self,
4243 action: &ComposeCompletion,
4244 cx: &mut ViewContext<Self>,
4245 ) -> Option<Task<Result<()>>> {
4246 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4247 }
4248
4249 fn do_completion(
4250 &mut self,
4251 item_ix: Option<usize>,
4252 intent: CompletionIntent,
4253 cx: &mut ViewContext<Editor>,
4254 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4255 use language::ToOffset as _;
4256
4257 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4258 menu
4259 } else {
4260 return None;
4261 };
4262
4263 let mat = completions_menu
4264 .matches
4265 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4266 let buffer_handle = completions_menu.buffer;
4267 let completions = completions_menu.completions.read();
4268 let completion = completions.get(mat.candidate_id)?;
4269 cx.stop_propagation();
4270
4271 let snippet;
4272 let text;
4273
4274 if completion.is_snippet() {
4275 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4276 text = snippet.as_ref().unwrap().text.clone();
4277 } else {
4278 snippet = None;
4279 text = completion.new_text.clone();
4280 };
4281 let selections = self.selections.all::<usize>(cx);
4282 let buffer = buffer_handle.read(cx);
4283 let old_range = completion.old_range.to_offset(buffer);
4284 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4285
4286 let newest_selection = self.selections.newest_anchor();
4287 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4288 return None;
4289 }
4290
4291 let lookbehind = newest_selection
4292 .start
4293 .text_anchor
4294 .to_offset(buffer)
4295 .saturating_sub(old_range.start);
4296 let lookahead = old_range
4297 .end
4298 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4299 let mut common_prefix_len = old_text
4300 .bytes()
4301 .zip(text.bytes())
4302 .take_while(|(a, b)| a == b)
4303 .count();
4304
4305 let snapshot = self.buffer.read(cx).snapshot(cx);
4306 let mut range_to_replace: Option<Range<isize>> = None;
4307 let mut ranges = Vec::new();
4308 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4309 for selection in &selections {
4310 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4311 let start = selection.start.saturating_sub(lookbehind);
4312 let end = selection.end + lookahead;
4313 if selection.id == newest_selection.id {
4314 range_to_replace = Some(
4315 ((start + common_prefix_len) as isize - selection.start as isize)
4316 ..(end as isize - selection.start as isize),
4317 );
4318 }
4319 ranges.push(start + common_prefix_len..end);
4320 } else {
4321 common_prefix_len = 0;
4322 ranges.clear();
4323 ranges.extend(selections.iter().map(|s| {
4324 if s.id == newest_selection.id {
4325 range_to_replace = Some(
4326 old_range.start.to_offset_utf16(&snapshot).0 as isize
4327 - selection.start as isize
4328 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4329 - selection.start as isize,
4330 );
4331 old_range.clone()
4332 } else {
4333 s.start..s.end
4334 }
4335 }));
4336 break;
4337 }
4338 if !self.linked_edit_ranges.is_empty() {
4339 let start_anchor = snapshot.anchor_before(selection.head());
4340 let end_anchor = snapshot.anchor_after(selection.tail());
4341 if let Some(ranges) = self
4342 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4343 {
4344 for (buffer, edits) in ranges {
4345 linked_edits.entry(buffer.clone()).or_default().extend(
4346 edits
4347 .into_iter()
4348 .map(|range| (range, text[common_prefix_len..].to_owned())),
4349 );
4350 }
4351 }
4352 }
4353 }
4354 let text = &text[common_prefix_len..];
4355
4356 cx.emit(EditorEvent::InputHandled {
4357 utf16_range_to_replace: range_to_replace,
4358 text: text.into(),
4359 });
4360
4361 self.transact(cx, |this, cx| {
4362 if let Some(mut snippet) = snippet {
4363 snippet.text = text.to_string();
4364 for tabstop in snippet.tabstops.iter_mut().flatten() {
4365 tabstop.start -= common_prefix_len as isize;
4366 tabstop.end -= common_prefix_len as isize;
4367 }
4368
4369 this.insert_snippet(&ranges, snippet, cx).log_err();
4370 } else {
4371 this.buffer.update(cx, |buffer, cx| {
4372 buffer.edit(
4373 ranges.iter().map(|range| (range.clone(), text)),
4374 this.autoindent_mode.clone(),
4375 cx,
4376 );
4377 });
4378 }
4379 for (buffer, edits) in linked_edits {
4380 buffer.update(cx, |buffer, cx| {
4381 let snapshot = buffer.snapshot();
4382 let edits = edits
4383 .into_iter()
4384 .map(|(range, text)| {
4385 use text::ToPoint as TP;
4386 let end_point = TP::to_point(&range.end, &snapshot);
4387 let start_point = TP::to_point(&range.start, &snapshot);
4388 (start_point..end_point, text)
4389 })
4390 .sorted_by_key(|(range, _)| range.start)
4391 .collect::<Vec<_>>();
4392 buffer.edit(edits, None, cx);
4393 })
4394 }
4395
4396 this.refresh_inline_completion(true, cx);
4397 });
4398
4399 let show_new_completions_on_confirm = completion
4400 .confirm
4401 .as_ref()
4402 .map_or(false, |confirm| confirm(intent, cx));
4403 if show_new_completions_on_confirm {
4404 self.show_completions(&ShowCompletions { trigger: None }, cx);
4405 }
4406
4407 let provider = self.completion_provider.as_ref()?;
4408 let apply_edits = provider.apply_additional_edits_for_completion(
4409 buffer_handle,
4410 completion.clone(),
4411 true,
4412 cx,
4413 );
4414
4415 let editor_settings = EditorSettings::get_global(cx);
4416 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4417 // After the code completion is finished, users often want to know what signatures are needed.
4418 // so we should automatically call signature_help
4419 self.show_signature_help(&ShowSignatureHelp, cx);
4420 }
4421
4422 Some(cx.foreground_executor().spawn(async move {
4423 apply_edits.await?;
4424 Ok(())
4425 }))
4426 }
4427
4428 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4429 let mut context_menu = self.context_menu.write();
4430 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4431 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4432 // Toggle if we're selecting the same one
4433 *context_menu = None;
4434 cx.notify();
4435 return;
4436 } else {
4437 // Otherwise, clear it and start a new one
4438 *context_menu = None;
4439 cx.notify();
4440 }
4441 }
4442 drop(context_menu);
4443 let snapshot = self.snapshot(cx);
4444 let deployed_from_indicator = action.deployed_from_indicator;
4445 let mut task = self.code_actions_task.take();
4446 let action = action.clone();
4447 cx.spawn(|editor, mut cx| async move {
4448 while let Some(prev_task) = task {
4449 prev_task.await;
4450 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4451 }
4452
4453 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4454 if editor.focus_handle.is_focused(cx) {
4455 let multibuffer_point = action
4456 .deployed_from_indicator
4457 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4458 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4459 let (buffer, buffer_row) = snapshot
4460 .buffer_snapshot
4461 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4462 .and_then(|(buffer_snapshot, range)| {
4463 editor
4464 .buffer
4465 .read(cx)
4466 .buffer(buffer_snapshot.remote_id())
4467 .map(|buffer| (buffer, range.start.row))
4468 })?;
4469 let (_, code_actions) = editor
4470 .available_code_actions
4471 .clone()
4472 .and_then(|(location, code_actions)| {
4473 let snapshot = location.buffer.read(cx).snapshot();
4474 let point_range = location.range.to_point(&snapshot);
4475 let point_range = point_range.start.row..=point_range.end.row;
4476 if point_range.contains(&buffer_row) {
4477 Some((location, code_actions))
4478 } else {
4479 None
4480 }
4481 })
4482 .unzip();
4483 let buffer_id = buffer.read(cx).remote_id();
4484 let tasks = editor
4485 .tasks
4486 .get(&(buffer_id, buffer_row))
4487 .map(|t| Arc::new(t.to_owned()));
4488 if tasks.is_none() && code_actions.is_none() {
4489 return None;
4490 }
4491
4492 editor.completion_tasks.clear();
4493 editor.discard_inline_completion(false, cx);
4494 let task_context =
4495 tasks
4496 .as_ref()
4497 .zip(editor.project.clone())
4498 .map(|(tasks, project)| {
4499 let position = Point::new(buffer_row, tasks.column);
4500 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4501 let location = Location {
4502 buffer: buffer.clone(),
4503 range: range_start..range_start,
4504 };
4505 // Fill in the environmental variables from the tree-sitter captures
4506 let mut captured_task_variables = TaskVariables::default();
4507 for (capture_name, value) in tasks.extra_variables.clone() {
4508 captured_task_variables.insert(
4509 task::VariableName::Custom(capture_name.into()),
4510 value.clone(),
4511 );
4512 }
4513 project.update(cx, |project, cx| {
4514 project.task_context_for_location(
4515 captured_task_variables,
4516 location,
4517 cx,
4518 )
4519 })
4520 });
4521
4522 Some(cx.spawn(|editor, mut cx| async move {
4523 let task_context = match task_context {
4524 Some(task_context) => task_context.await,
4525 None => None,
4526 };
4527 let resolved_tasks =
4528 tasks.zip(task_context).map(|(tasks, task_context)| {
4529 Arc::new(ResolvedTasks {
4530 templates: tasks
4531 .templates
4532 .iter()
4533 .filter_map(|(kind, template)| {
4534 template
4535 .resolve_task(&kind.to_id_base(), &task_context)
4536 .map(|task| (kind.clone(), task))
4537 })
4538 .collect(),
4539 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4540 multibuffer_point.row,
4541 tasks.column,
4542 )),
4543 })
4544 });
4545 let spawn_straight_away = resolved_tasks
4546 .as_ref()
4547 .map_or(false, |tasks| tasks.templates.len() == 1)
4548 && code_actions
4549 .as_ref()
4550 .map_or(true, |actions| actions.is_empty());
4551 if let Some(task) = editor
4552 .update(&mut cx, |editor, cx| {
4553 *editor.context_menu.write() =
4554 Some(ContextMenu::CodeActions(CodeActionsMenu {
4555 buffer,
4556 actions: CodeActionContents {
4557 tasks: resolved_tasks,
4558 actions: code_actions,
4559 },
4560 selected_item: Default::default(),
4561 scroll_handle: UniformListScrollHandle::default(),
4562 deployed_from_indicator,
4563 }));
4564 if spawn_straight_away {
4565 if let Some(task) = editor.confirm_code_action(
4566 &ConfirmCodeAction { item_ix: Some(0) },
4567 cx,
4568 ) {
4569 cx.notify();
4570 return task;
4571 }
4572 }
4573 cx.notify();
4574 Task::ready(Ok(()))
4575 })
4576 .ok()
4577 {
4578 task.await
4579 } else {
4580 Ok(())
4581 }
4582 }))
4583 } else {
4584 Some(Task::ready(Ok(())))
4585 }
4586 })?;
4587 if let Some(task) = spawned_test_task {
4588 task.await?;
4589 }
4590
4591 Ok::<_, anyhow::Error>(())
4592 })
4593 .detach_and_log_err(cx);
4594 }
4595
4596 pub fn confirm_code_action(
4597 &mut self,
4598 action: &ConfirmCodeAction,
4599 cx: &mut ViewContext<Self>,
4600 ) -> Option<Task<Result<()>>> {
4601 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4602 menu
4603 } else {
4604 return None;
4605 };
4606 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4607 let action = actions_menu.actions.get(action_ix)?;
4608 let title = action.label();
4609 let buffer = actions_menu.buffer;
4610 let workspace = self.workspace()?;
4611
4612 match action {
4613 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4614 workspace.update(cx, |workspace, cx| {
4615 workspace::tasks::schedule_resolved_task(
4616 workspace,
4617 task_source_kind,
4618 resolved_task,
4619 false,
4620 cx,
4621 );
4622
4623 Some(Task::ready(Ok(())))
4624 })
4625 }
4626 CodeActionsItem::CodeAction(action) => {
4627 let apply_code_actions = workspace
4628 .read(cx)
4629 .project()
4630 .clone()
4631 .update(cx, |project, cx| {
4632 project.apply_code_action(buffer, action, true, cx)
4633 });
4634 let workspace = workspace.downgrade();
4635 Some(cx.spawn(|editor, cx| async move {
4636 let project_transaction = apply_code_actions.await?;
4637 Self::open_project_transaction(
4638 &editor,
4639 workspace,
4640 project_transaction,
4641 title,
4642 cx,
4643 )
4644 .await
4645 }))
4646 }
4647 }
4648 }
4649
4650 pub async fn open_project_transaction(
4651 this: &WeakView<Editor>,
4652 workspace: WeakView<Workspace>,
4653 transaction: ProjectTransaction,
4654 title: String,
4655 mut cx: AsyncWindowContext,
4656 ) -> Result<()> {
4657 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4658
4659 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4660 cx.update(|cx| {
4661 entries.sort_unstable_by_key(|(buffer, _)| {
4662 buffer.read(cx).file().map(|f| f.path().clone())
4663 });
4664 })?;
4665
4666 // If the project transaction's edits are all contained within this editor, then
4667 // avoid opening a new editor to display them.
4668
4669 if let Some((buffer, transaction)) = entries.first() {
4670 if entries.len() == 1 {
4671 let excerpt = this.update(&mut cx, |editor, cx| {
4672 editor
4673 .buffer()
4674 .read(cx)
4675 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4676 })?;
4677 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4678 if excerpted_buffer == *buffer {
4679 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4680 let excerpt_range = excerpt_range.to_offset(buffer);
4681 buffer
4682 .edited_ranges_for_transaction::<usize>(transaction)
4683 .all(|range| {
4684 excerpt_range.start <= range.start
4685 && excerpt_range.end >= range.end
4686 })
4687 })?;
4688
4689 if all_edits_within_excerpt {
4690 return Ok(());
4691 }
4692 }
4693 }
4694 }
4695 } else {
4696 return Ok(());
4697 }
4698
4699 let mut ranges_to_highlight = Vec::new();
4700 let excerpt_buffer = cx.new_model(|cx| {
4701 let mut multibuffer =
4702 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4703 for (buffer_handle, transaction) in &entries {
4704 let buffer = buffer_handle.read(cx);
4705 ranges_to_highlight.extend(
4706 multibuffer.push_excerpts_with_context_lines(
4707 buffer_handle.clone(),
4708 buffer
4709 .edited_ranges_for_transaction::<usize>(transaction)
4710 .collect(),
4711 DEFAULT_MULTIBUFFER_CONTEXT,
4712 cx,
4713 ),
4714 );
4715 }
4716 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4717 multibuffer
4718 })?;
4719
4720 workspace.update(&mut cx, |workspace, cx| {
4721 let project = workspace.project().clone();
4722 let editor =
4723 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4724 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4725 editor.update(cx, |editor, cx| {
4726 editor.highlight_background::<Self>(
4727 &ranges_to_highlight,
4728 |theme| theme.editor_highlighted_line_background,
4729 cx,
4730 );
4731 });
4732 })?;
4733
4734 Ok(())
4735 }
4736
4737 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4738 let project = self.project.clone()?;
4739 let buffer = self.buffer.read(cx);
4740 let newest_selection = self.selections.newest_anchor().clone();
4741 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4742 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4743 if start_buffer != end_buffer {
4744 return None;
4745 }
4746
4747 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4748 cx.background_executor()
4749 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4750 .await;
4751
4752 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4753 project.code_actions(&start_buffer, start..end, cx)
4754 }) {
4755 code_actions.await
4756 } else {
4757 Vec::new()
4758 };
4759
4760 this.update(&mut cx, |this, cx| {
4761 this.available_code_actions = if actions.is_empty() {
4762 None
4763 } else {
4764 Some((
4765 Location {
4766 buffer: start_buffer,
4767 range: start..end,
4768 },
4769 actions.into(),
4770 ))
4771 };
4772 cx.notify();
4773 })
4774 .log_err();
4775 }));
4776 None
4777 }
4778
4779 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4780 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4781 self.show_git_blame_inline = false;
4782
4783 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4784 cx.background_executor().timer(delay).await;
4785
4786 this.update(&mut cx, |this, cx| {
4787 this.show_git_blame_inline = true;
4788 cx.notify();
4789 })
4790 .log_err();
4791 }));
4792 }
4793 }
4794
4795 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4796 if self.pending_rename.is_some() {
4797 return None;
4798 }
4799
4800 let project = self.project.clone()?;
4801 let buffer = self.buffer.read(cx);
4802 let newest_selection = self.selections.newest_anchor().clone();
4803 let cursor_position = newest_selection.head();
4804 let (cursor_buffer, cursor_buffer_position) =
4805 buffer.text_anchor_for_position(cursor_position, cx)?;
4806 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4807 if cursor_buffer != tail_buffer {
4808 return None;
4809 }
4810
4811 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4812 cx.background_executor()
4813 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4814 .await;
4815
4816 let highlights = if let Some(highlights) = project
4817 .update(&mut cx, |project, cx| {
4818 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4819 })
4820 .log_err()
4821 {
4822 highlights.await.log_err()
4823 } else {
4824 None
4825 };
4826
4827 if let Some(highlights) = highlights {
4828 this.update(&mut cx, |this, cx| {
4829 if this.pending_rename.is_some() {
4830 return;
4831 }
4832
4833 let buffer_id = cursor_position.buffer_id;
4834 let buffer = this.buffer.read(cx);
4835 if !buffer
4836 .text_anchor_for_position(cursor_position, cx)
4837 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4838 {
4839 return;
4840 }
4841
4842 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4843 let mut write_ranges = Vec::new();
4844 let mut read_ranges = Vec::new();
4845 for highlight in highlights {
4846 for (excerpt_id, excerpt_range) in
4847 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4848 {
4849 let start = highlight
4850 .range
4851 .start
4852 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4853 let end = highlight
4854 .range
4855 .end
4856 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4857 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4858 continue;
4859 }
4860
4861 let range = Anchor {
4862 buffer_id,
4863 excerpt_id,
4864 text_anchor: start,
4865 }..Anchor {
4866 buffer_id,
4867 excerpt_id,
4868 text_anchor: end,
4869 };
4870 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4871 write_ranges.push(range);
4872 } else {
4873 read_ranges.push(range);
4874 }
4875 }
4876 }
4877
4878 this.highlight_background::<DocumentHighlightRead>(
4879 &read_ranges,
4880 |theme| theme.editor_document_highlight_read_background,
4881 cx,
4882 );
4883 this.highlight_background::<DocumentHighlightWrite>(
4884 &write_ranges,
4885 |theme| theme.editor_document_highlight_write_background,
4886 cx,
4887 );
4888 cx.notify();
4889 })
4890 .log_err();
4891 }
4892 }));
4893 None
4894 }
4895
4896 fn refresh_inline_completion(
4897 &mut self,
4898 debounce: bool,
4899 cx: &mut ViewContext<Self>,
4900 ) -> Option<()> {
4901 let provider = self.inline_completion_provider()?;
4902 let cursor = self.selections.newest_anchor().head();
4903 let (buffer, cursor_buffer_position) =
4904 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4905 if !self.show_inline_completions
4906 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4907 {
4908 self.discard_inline_completion(false, cx);
4909 return None;
4910 }
4911
4912 self.update_visible_inline_completion(cx);
4913 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4914 Some(())
4915 }
4916
4917 fn cycle_inline_completion(
4918 &mut self,
4919 direction: Direction,
4920 cx: &mut ViewContext<Self>,
4921 ) -> Option<()> {
4922 let provider = self.inline_completion_provider()?;
4923 let cursor = self.selections.newest_anchor().head();
4924 let (buffer, cursor_buffer_position) =
4925 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4926 if !self.show_inline_completions
4927 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4928 {
4929 return None;
4930 }
4931
4932 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4933 self.update_visible_inline_completion(cx);
4934
4935 Some(())
4936 }
4937
4938 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4939 if !self.has_active_inline_completion(cx) {
4940 self.refresh_inline_completion(false, cx);
4941 return;
4942 }
4943
4944 self.update_visible_inline_completion(cx);
4945 }
4946
4947 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4948 self.show_cursor_names(cx);
4949 }
4950
4951 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4952 self.show_cursor_names = true;
4953 cx.notify();
4954 cx.spawn(|this, mut cx| async move {
4955 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4956 this.update(&mut cx, |this, cx| {
4957 this.show_cursor_names = false;
4958 cx.notify()
4959 })
4960 .ok()
4961 })
4962 .detach();
4963 }
4964
4965 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4966 if self.has_active_inline_completion(cx) {
4967 self.cycle_inline_completion(Direction::Next, cx);
4968 } else {
4969 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4970 if is_copilot_disabled {
4971 cx.propagate();
4972 }
4973 }
4974 }
4975
4976 pub fn previous_inline_completion(
4977 &mut self,
4978 _: &PreviousInlineCompletion,
4979 cx: &mut ViewContext<Self>,
4980 ) {
4981 if self.has_active_inline_completion(cx) {
4982 self.cycle_inline_completion(Direction::Prev, cx);
4983 } else {
4984 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4985 if is_copilot_disabled {
4986 cx.propagate();
4987 }
4988 }
4989 }
4990
4991 pub fn accept_inline_completion(
4992 &mut self,
4993 _: &AcceptInlineCompletion,
4994 cx: &mut ViewContext<Self>,
4995 ) {
4996 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
4997 return;
4998 };
4999 if let Some(provider) = self.inline_completion_provider() {
5000 provider.accept(cx);
5001 }
5002
5003 cx.emit(EditorEvent::InputHandled {
5004 utf16_range_to_replace: None,
5005 text: completion.text.to_string().into(),
5006 });
5007
5008 if let Some(range) = delete_range {
5009 self.change_selections(None, cx, |s| s.select_ranges([range]))
5010 }
5011 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5012 self.refresh_inline_completion(true, cx);
5013 cx.notify();
5014 }
5015
5016 pub fn accept_partial_inline_completion(
5017 &mut self,
5018 _: &AcceptPartialInlineCompletion,
5019 cx: &mut ViewContext<Self>,
5020 ) {
5021 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5022 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5023 let mut partial_completion = completion
5024 .text
5025 .chars()
5026 .by_ref()
5027 .take_while(|c| c.is_alphabetic())
5028 .collect::<String>();
5029 if partial_completion.is_empty() {
5030 partial_completion = completion
5031 .text
5032 .chars()
5033 .by_ref()
5034 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5035 .collect::<String>();
5036 }
5037
5038 cx.emit(EditorEvent::InputHandled {
5039 utf16_range_to_replace: None,
5040 text: partial_completion.clone().into(),
5041 });
5042
5043 if let Some(range) = delete_range {
5044 self.change_selections(None, cx, |s| s.select_ranges([range]))
5045 }
5046 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5047
5048 self.refresh_inline_completion(true, cx);
5049 cx.notify();
5050 }
5051 }
5052 }
5053
5054 fn discard_inline_completion(
5055 &mut self,
5056 should_report_inline_completion_event: bool,
5057 cx: &mut ViewContext<Self>,
5058 ) -> bool {
5059 if let Some(provider) = self.inline_completion_provider() {
5060 provider.discard(should_report_inline_completion_event, cx);
5061 }
5062
5063 self.take_active_inline_completion(cx).is_some()
5064 }
5065
5066 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5067 if let Some(completion) = self.active_inline_completion.as_ref() {
5068 let buffer = self.buffer.read(cx).read(cx);
5069 completion.0.position.is_valid(&buffer)
5070 } else {
5071 false
5072 }
5073 }
5074
5075 fn take_active_inline_completion(
5076 &mut self,
5077 cx: &mut ViewContext<Self>,
5078 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5079 let completion = self.active_inline_completion.take()?;
5080 self.display_map.update(cx, |map, cx| {
5081 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5082 });
5083 let buffer = self.buffer.read(cx).read(cx);
5084
5085 if completion.0.position.is_valid(&buffer) {
5086 Some(completion)
5087 } else {
5088 None
5089 }
5090 }
5091
5092 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5093 let selection = self.selections.newest_anchor();
5094 let cursor = selection.head();
5095
5096 let excerpt_id = cursor.excerpt_id;
5097
5098 if self.context_menu.read().is_none()
5099 && self.completion_tasks.is_empty()
5100 && selection.start == selection.end
5101 {
5102 if let Some(provider) = self.inline_completion_provider() {
5103 if let Some((buffer, cursor_buffer_position)) =
5104 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5105 {
5106 if let Some((text, text_anchor_range)) =
5107 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5108 {
5109 let text = Rope::from(text);
5110 let mut to_remove = Vec::new();
5111 if let Some(completion) = self.active_inline_completion.take() {
5112 to_remove.push(completion.0.id);
5113 }
5114
5115 let completion_inlay =
5116 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5117
5118 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5119 let snapshot = self.buffer.read(cx).snapshot(cx);
5120 Some(
5121 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5122 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5123 )
5124 });
5125 self.active_inline_completion =
5126 Some((completion_inlay.clone(), multibuffer_anchor_range));
5127
5128 self.display_map.update(cx, move |map, cx| {
5129 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5130 });
5131 cx.notify();
5132 return;
5133 }
5134 }
5135 }
5136 }
5137
5138 self.discard_inline_completion(false, cx);
5139 }
5140
5141 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5142 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5143 }
5144
5145 fn render_code_actions_indicator(
5146 &self,
5147 _style: &EditorStyle,
5148 row: DisplayRow,
5149 is_active: bool,
5150 cx: &mut ViewContext<Self>,
5151 ) -> Option<IconButton> {
5152 if self.available_code_actions.is_some() {
5153 Some(
5154 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5155 .shape(ui::IconButtonShape::Square)
5156 .icon_size(IconSize::XSmall)
5157 .icon_color(Color::Muted)
5158 .selected(is_active)
5159 .on_click(cx.listener(move |editor, _e, cx| {
5160 editor.focus(cx);
5161 editor.toggle_code_actions(
5162 &ToggleCodeActions {
5163 deployed_from_indicator: Some(row),
5164 },
5165 cx,
5166 );
5167 })),
5168 )
5169 } else {
5170 None
5171 }
5172 }
5173
5174 fn clear_tasks(&mut self) {
5175 self.tasks.clear()
5176 }
5177
5178 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5179 if let Some(_) = self.tasks.insert(key, value) {
5180 // This case should hopefully be rare, but just in case...
5181 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5182 }
5183 }
5184
5185 fn render_run_indicator(
5186 &self,
5187 _style: &EditorStyle,
5188 is_active: bool,
5189 row: DisplayRow,
5190 cx: &mut ViewContext<Self>,
5191 ) -> IconButton {
5192 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5193 .shape(ui::IconButtonShape::Square)
5194 .icon_size(IconSize::XSmall)
5195 .icon_color(Color::Muted)
5196 .selected(is_active)
5197 .on_click(cx.listener(move |editor, _e, cx| {
5198 editor.focus(cx);
5199 editor.toggle_code_actions(
5200 &ToggleCodeActions {
5201 deployed_from_indicator: Some(row),
5202 },
5203 cx,
5204 );
5205 }))
5206 }
5207
5208 fn close_hunk_diff_button(
5209 &self,
5210 hunk: HoveredHunk,
5211 row: DisplayRow,
5212 cx: &mut ViewContext<Self>,
5213 ) -> IconButton {
5214 IconButton::new(
5215 ("close_hunk_diff_indicator", row.0 as usize),
5216 ui::IconName::Close,
5217 )
5218 .shape(ui::IconButtonShape::Square)
5219 .icon_size(IconSize::XSmall)
5220 .icon_color(Color::Muted)
5221 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5222 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5223 }
5224
5225 pub fn context_menu_visible(&self) -> bool {
5226 self.context_menu
5227 .read()
5228 .as_ref()
5229 .map_or(false, |menu| menu.visible())
5230 }
5231
5232 fn render_context_menu(
5233 &self,
5234 cursor_position: DisplayPoint,
5235 style: &EditorStyle,
5236 max_height: Pixels,
5237 cx: &mut ViewContext<Editor>,
5238 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5239 self.context_menu.read().as_ref().map(|menu| {
5240 menu.render(
5241 cursor_position,
5242 style,
5243 max_height,
5244 self.workspace.as_ref().map(|(w, _)| w.clone()),
5245 cx,
5246 )
5247 })
5248 }
5249
5250 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5251 cx.notify();
5252 self.completion_tasks.clear();
5253 let context_menu = self.context_menu.write().take();
5254 if context_menu.is_some() {
5255 self.update_visible_inline_completion(cx);
5256 }
5257 context_menu
5258 }
5259
5260 pub fn insert_snippet(
5261 &mut self,
5262 insertion_ranges: &[Range<usize>],
5263 snippet: Snippet,
5264 cx: &mut ViewContext<Self>,
5265 ) -> Result<()> {
5266 struct Tabstop<T> {
5267 is_end_tabstop: bool,
5268 ranges: Vec<Range<T>>,
5269 }
5270
5271 let tabstops = self.buffer.update(cx, |buffer, cx| {
5272 let snippet_text: Arc<str> = snippet.text.clone().into();
5273 buffer.edit(
5274 insertion_ranges
5275 .iter()
5276 .cloned()
5277 .map(|range| (range, snippet_text.clone())),
5278 Some(AutoindentMode::EachLine),
5279 cx,
5280 );
5281
5282 let snapshot = &*buffer.read(cx);
5283 let snippet = &snippet;
5284 snippet
5285 .tabstops
5286 .iter()
5287 .map(|tabstop| {
5288 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5289 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5290 });
5291 let mut tabstop_ranges = tabstop
5292 .iter()
5293 .flat_map(|tabstop_range| {
5294 let mut delta = 0_isize;
5295 insertion_ranges.iter().map(move |insertion_range| {
5296 let insertion_start = insertion_range.start as isize + delta;
5297 delta +=
5298 snippet.text.len() as isize - insertion_range.len() as isize;
5299
5300 let start = ((insertion_start + tabstop_range.start) as usize)
5301 .min(snapshot.len());
5302 let end = ((insertion_start + tabstop_range.end) as usize)
5303 .min(snapshot.len());
5304 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5305 })
5306 })
5307 .collect::<Vec<_>>();
5308 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5309
5310 Tabstop {
5311 is_end_tabstop,
5312 ranges: tabstop_ranges,
5313 }
5314 })
5315 .collect::<Vec<_>>()
5316 });
5317 if let Some(tabstop) = tabstops.first() {
5318 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5319 s.select_ranges(tabstop.ranges.iter().cloned());
5320 });
5321
5322 // If we're already at the last tabstop and it's at the end of the snippet,
5323 // we're done, we don't need to keep the state around.
5324 if !tabstop.is_end_tabstop {
5325 let ranges = tabstops
5326 .into_iter()
5327 .map(|tabstop| tabstop.ranges)
5328 .collect::<Vec<_>>();
5329 self.snippet_stack.push(SnippetState {
5330 active_index: 0,
5331 ranges,
5332 });
5333 }
5334
5335 // Check whether the just-entered snippet ends with an auto-closable bracket.
5336 if self.autoclose_regions.is_empty() {
5337 let snapshot = self.buffer.read(cx).snapshot(cx);
5338 for selection in &mut self.selections.all::<Point>(cx) {
5339 let selection_head = selection.head();
5340 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5341 continue;
5342 };
5343
5344 let mut bracket_pair = None;
5345 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5346 let prev_chars = snapshot
5347 .reversed_chars_at(selection_head)
5348 .collect::<String>();
5349 for (pair, enabled) in scope.brackets() {
5350 if enabled
5351 && pair.close
5352 && prev_chars.starts_with(pair.start.as_str())
5353 && next_chars.starts_with(pair.end.as_str())
5354 {
5355 bracket_pair = Some(pair.clone());
5356 break;
5357 }
5358 }
5359 if let Some(pair) = bracket_pair {
5360 let start = snapshot.anchor_after(selection_head);
5361 let end = snapshot.anchor_after(selection_head);
5362 self.autoclose_regions.push(AutocloseRegion {
5363 selection_id: selection.id,
5364 range: start..end,
5365 pair,
5366 });
5367 }
5368 }
5369 }
5370 }
5371 Ok(())
5372 }
5373
5374 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5375 self.move_to_snippet_tabstop(Bias::Right, cx)
5376 }
5377
5378 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5379 self.move_to_snippet_tabstop(Bias::Left, cx)
5380 }
5381
5382 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5383 if let Some(mut snippet) = self.snippet_stack.pop() {
5384 match bias {
5385 Bias::Left => {
5386 if snippet.active_index > 0 {
5387 snippet.active_index -= 1;
5388 } else {
5389 self.snippet_stack.push(snippet);
5390 return false;
5391 }
5392 }
5393 Bias::Right => {
5394 if snippet.active_index + 1 < snippet.ranges.len() {
5395 snippet.active_index += 1;
5396 } else {
5397 self.snippet_stack.push(snippet);
5398 return false;
5399 }
5400 }
5401 }
5402 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5403 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5404 s.select_anchor_ranges(current_ranges.iter().cloned())
5405 });
5406 // If snippet state is not at the last tabstop, push it back on the stack
5407 if snippet.active_index + 1 < snippet.ranges.len() {
5408 self.snippet_stack.push(snippet);
5409 }
5410 return true;
5411 }
5412 }
5413
5414 false
5415 }
5416
5417 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5418 self.transact(cx, |this, cx| {
5419 this.select_all(&SelectAll, cx);
5420 this.insert("", cx);
5421 });
5422 }
5423
5424 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5425 self.transact(cx, |this, cx| {
5426 this.select_autoclose_pair(cx);
5427 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5428 if !this.linked_edit_ranges.is_empty() {
5429 let selections = this.selections.all::<MultiBufferPoint>(cx);
5430 let snapshot = this.buffer.read(cx).snapshot(cx);
5431
5432 for selection in selections.iter() {
5433 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5434 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5435 if selection_start.buffer_id != selection_end.buffer_id {
5436 continue;
5437 }
5438 if let Some(ranges) =
5439 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5440 {
5441 for (buffer, entries) in ranges {
5442 linked_ranges.entry(buffer).or_default().extend(entries);
5443 }
5444 }
5445 }
5446 }
5447
5448 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5449 if !this.selections.line_mode {
5450 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5451 for selection in &mut selections {
5452 if selection.is_empty() {
5453 let old_head = selection.head();
5454 let mut new_head =
5455 movement::left(&display_map, old_head.to_display_point(&display_map))
5456 .to_point(&display_map);
5457 if let Some((buffer, line_buffer_range)) = display_map
5458 .buffer_snapshot
5459 .buffer_line_for_row(MultiBufferRow(old_head.row))
5460 {
5461 let indent_size =
5462 buffer.indent_size_for_line(line_buffer_range.start.row);
5463 let indent_len = match indent_size.kind {
5464 IndentKind::Space => {
5465 buffer.settings_at(line_buffer_range.start, cx).tab_size
5466 }
5467 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5468 };
5469 if old_head.column <= indent_size.len && old_head.column > 0 {
5470 let indent_len = indent_len.get();
5471 new_head = cmp::min(
5472 new_head,
5473 MultiBufferPoint::new(
5474 old_head.row,
5475 ((old_head.column - 1) / indent_len) * indent_len,
5476 ),
5477 );
5478 }
5479 }
5480
5481 selection.set_head(new_head, SelectionGoal::None);
5482 }
5483 }
5484 }
5485
5486 this.signature_help_state.set_backspace_pressed(true);
5487 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5488 this.insert("", cx);
5489 let empty_str: Arc<str> = Arc::from("");
5490 for (buffer, edits) in linked_ranges {
5491 let snapshot = buffer.read(cx).snapshot();
5492 use text::ToPoint as TP;
5493
5494 let edits = edits
5495 .into_iter()
5496 .map(|range| {
5497 let end_point = TP::to_point(&range.end, &snapshot);
5498 let mut start_point = TP::to_point(&range.start, &snapshot);
5499
5500 if end_point == start_point {
5501 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5502 .saturating_sub(1);
5503 start_point = TP::to_point(&offset, &snapshot);
5504 };
5505
5506 (start_point..end_point, empty_str.clone())
5507 })
5508 .sorted_by_key(|(range, _)| range.start)
5509 .collect::<Vec<_>>();
5510 buffer.update(cx, |this, cx| {
5511 this.edit(edits, None, cx);
5512 })
5513 }
5514 this.refresh_inline_completion(true, cx);
5515 linked_editing_ranges::refresh_linked_ranges(this, cx);
5516 });
5517 }
5518
5519 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5520 self.transact(cx, |this, cx| {
5521 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5522 let line_mode = s.line_mode;
5523 s.move_with(|map, selection| {
5524 if selection.is_empty() && !line_mode {
5525 let cursor = movement::right(map, selection.head());
5526 selection.end = cursor;
5527 selection.reversed = true;
5528 selection.goal = SelectionGoal::None;
5529 }
5530 })
5531 });
5532 this.insert("", cx);
5533 this.refresh_inline_completion(true, cx);
5534 });
5535 }
5536
5537 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5538 if self.move_to_prev_snippet_tabstop(cx) {
5539 return;
5540 }
5541
5542 self.outdent(&Outdent, cx);
5543 }
5544
5545 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5546 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5547 return;
5548 }
5549
5550 let mut selections = self.selections.all_adjusted(cx);
5551 let buffer = self.buffer.read(cx);
5552 let snapshot = buffer.snapshot(cx);
5553 let rows_iter = selections.iter().map(|s| s.head().row);
5554 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5555
5556 let mut edits = Vec::new();
5557 let mut prev_edited_row = 0;
5558 let mut row_delta = 0;
5559 for selection in &mut selections {
5560 if selection.start.row != prev_edited_row {
5561 row_delta = 0;
5562 }
5563 prev_edited_row = selection.end.row;
5564
5565 // If the selection is non-empty, then increase the indentation of the selected lines.
5566 if !selection.is_empty() {
5567 row_delta =
5568 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5569 continue;
5570 }
5571
5572 // If the selection is empty and the cursor is in the leading whitespace before the
5573 // suggested indentation, then auto-indent the line.
5574 let cursor = selection.head();
5575 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5576 if let Some(suggested_indent) =
5577 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5578 {
5579 if cursor.column < suggested_indent.len
5580 && cursor.column <= current_indent.len
5581 && current_indent.len <= suggested_indent.len
5582 {
5583 selection.start = Point::new(cursor.row, suggested_indent.len);
5584 selection.end = selection.start;
5585 if row_delta == 0 {
5586 edits.extend(Buffer::edit_for_indent_size_adjustment(
5587 cursor.row,
5588 current_indent,
5589 suggested_indent,
5590 ));
5591 row_delta = suggested_indent.len - current_indent.len;
5592 }
5593 continue;
5594 }
5595 }
5596
5597 // Otherwise, insert a hard or soft tab.
5598 let settings = buffer.settings_at(cursor, cx);
5599 let tab_size = if settings.hard_tabs {
5600 IndentSize::tab()
5601 } else {
5602 let tab_size = settings.tab_size.get();
5603 let char_column = snapshot
5604 .text_for_range(Point::new(cursor.row, 0)..cursor)
5605 .flat_map(str::chars)
5606 .count()
5607 + row_delta as usize;
5608 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5609 IndentSize::spaces(chars_to_next_tab_stop)
5610 };
5611 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5612 selection.end = selection.start;
5613 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5614 row_delta += tab_size.len;
5615 }
5616
5617 self.transact(cx, |this, cx| {
5618 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5619 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5620 this.refresh_inline_completion(true, cx);
5621 });
5622 }
5623
5624 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5625 if self.read_only(cx) {
5626 return;
5627 }
5628 let mut selections = self.selections.all::<Point>(cx);
5629 let mut prev_edited_row = 0;
5630 let mut row_delta = 0;
5631 let mut edits = Vec::new();
5632 let buffer = self.buffer.read(cx);
5633 let snapshot = buffer.snapshot(cx);
5634 for selection in &mut selections {
5635 if selection.start.row != prev_edited_row {
5636 row_delta = 0;
5637 }
5638 prev_edited_row = selection.end.row;
5639
5640 row_delta =
5641 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5642 }
5643
5644 self.transact(cx, |this, cx| {
5645 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5646 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5647 });
5648 }
5649
5650 fn indent_selection(
5651 buffer: &MultiBuffer,
5652 snapshot: &MultiBufferSnapshot,
5653 selection: &mut Selection<Point>,
5654 edits: &mut Vec<(Range<Point>, String)>,
5655 delta_for_start_row: u32,
5656 cx: &AppContext,
5657 ) -> u32 {
5658 let settings = buffer.settings_at(selection.start, cx);
5659 let tab_size = settings.tab_size.get();
5660 let indent_kind = if settings.hard_tabs {
5661 IndentKind::Tab
5662 } else {
5663 IndentKind::Space
5664 };
5665 let mut start_row = selection.start.row;
5666 let mut end_row = selection.end.row + 1;
5667
5668 // If a selection ends at the beginning of a line, don't indent
5669 // that last line.
5670 if selection.end.column == 0 && selection.end.row > selection.start.row {
5671 end_row -= 1;
5672 }
5673
5674 // Avoid re-indenting a row that has already been indented by a
5675 // previous selection, but still update this selection's column
5676 // to reflect that indentation.
5677 if delta_for_start_row > 0 {
5678 start_row += 1;
5679 selection.start.column += delta_for_start_row;
5680 if selection.end.row == selection.start.row {
5681 selection.end.column += delta_for_start_row;
5682 }
5683 }
5684
5685 let mut delta_for_end_row = 0;
5686 let has_multiple_rows = start_row + 1 != end_row;
5687 for row in start_row..end_row {
5688 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5689 let indent_delta = match (current_indent.kind, indent_kind) {
5690 (IndentKind::Space, IndentKind::Space) => {
5691 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5692 IndentSize::spaces(columns_to_next_tab_stop)
5693 }
5694 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5695 (_, IndentKind::Tab) => IndentSize::tab(),
5696 };
5697
5698 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5699 0
5700 } else {
5701 selection.start.column
5702 };
5703 let row_start = Point::new(row, start);
5704 edits.push((
5705 row_start..row_start,
5706 indent_delta.chars().collect::<String>(),
5707 ));
5708
5709 // Update this selection's endpoints to reflect the indentation.
5710 if row == selection.start.row {
5711 selection.start.column += indent_delta.len;
5712 }
5713 if row == selection.end.row {
5714 selection.end.column += indent_delta.len;
5715 delta_for_end_row = indent_delta.len;
5716 }
5717 }
5718
5719 if selection.start.row == selection.end.row {
5720 delta_for_start_row + delta_for_end_row
5721 } else {
5722 delta_for_end_row
5723 }
5724 }
5725
5726 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5727 if self.read_only(cx) {
5728 return;
5729 }
5730 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5731 let selections = self.selections.all::<Point>(cx);
5732 let mut deletion_ranges = Vec::new();
5733 let mut last_outdent = None;
5734 {
5735 let buffer = self.buffer.read(cx);
5736 let snapshot = buffer.snapshot(cx);
5737 for selection in &selections {
5738 let settings = buffer.settings_at(selection.start, cx);
5739 let tab_size = settings.tab_size.get();
5740 let mut rows = selection.spanned_rows(false, &display_map);
5741
5742 // Avoid re-outdenting a row that has already been outdented by a
5743 // previous selection.
5744 if let Some(last_row) = last_outdent {
5745 if last_row == rows.start {
5746 rows.start = rows.start.next_row();
5747 }
5748 }
5749 let has_multiple_rows = rows.len() > 1;
5750 for row in rows.iter_rows() {
5751 let indent_size = snapshot.indent_size_for_line(row);
5752 if indent_size.len > 0 {
5753 let deletion_len = match indent_size.kind {
5754 IndentKind::Space => {
5755 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5756 if columns_to_prev_tab_stop == 0 {
5757 tab_size
5758 } else {
5759 columns_to_prev_tab_stop
5760 }
5761 }
5762 IndentKind::Tab => 1,
5763 };
5764 let start = if has_multiple_rows
5765 || deletion_len > selection.start.column
5766 || indent_size.len < selection.start.column
5767 {
5768 0
5769 } else {
5770 selection.start.column - deletion_len
5771 };
5772 deletion_ranges.push(
5773 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5774 );
5775 last_outdent = Some(row);
5776 }
5777 }
5778 }
5779 }
5780
5781 self.transact(cx, |this, cx| {
5782 this.buffer.update(cx, |buffer, cx| {
5783 let empty_str: Arc<str> = Arc::default();
5784 buffer.edit(
5785 deletion_ranges
5786 .into_iter()
5787 .map(|range| (range, empty_str.clone())),
5788 None,
5789 cx,
5790 );
5791 });
5792 let selections = this.selections.all::<usize>(cx);
5793 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5794 });
5795 }
5796
5797 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5798 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5799 let selections = self.selections.all::<Point>(cx);
5800
5801 let mut new_cursors = Vec::new();
5802 let mut edit_ranges = Vec::new();
5803 let mut selections = selections.iter().peekable();
5804 while let Some(selection) = selections.next() {
5805 let mut rows = selection.spanned_rows(false, &display_map);
5806 let goal_display_column = selection.head().to_display_point(&display_map).column();
5807
5808 // Accumulate contiguous regions of rows that we want to delete.
5809 while let Some(next_selection) = selections.peek() {
5810 let next_rows = next_selection.spanned_rows(false, &display_map);
5811 if next_rows.start <= rows.end {
5812 rows.end = next_rows.end;
5813 selections.next().unwrap();
5814 } else {
5815 break;
5816 }
5817 }
5818
5819 let buffer = &display_map.buffer_snapshot;
5820 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5821 let edit_end;
5822 let cursor_buffer_row;
5823 if buffer.max_point().row >= rows.end.0 {
5824 // If there's a line after the range, delete the \n from the end of the row range
5825 // and position the cursor on the next line.
5826 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5827 cursor_buffer_row = rows.end;
5828 } else {
5829 // If there isn't a line after the range, delete the \n from the line before the
5830 // start of the row range and position the cursor there.
5831 edit_start = edit_start.saturating_sub(1);
5832 edit_end = buffer.len();
5833 cursor_buffer_row = rows.start.previous_row();
5834 }
5835
5836 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5837 *cursor.column_mut() =
5838 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5839
5840 new_cursors.push((
5841 selection.id,
5842 buffer.anchor_after(cursor.to_point(&display_map)),
5843 ));
5844 edit_ranges.push(edit_start..edit_end);
5845 }
5846
5847 self.transact(cx, |this, cx| {
5848 let buffer = this.buffer.update(cx, |buffer, cx| {
5849 let empty_str: Arc<str> = Arc::default();
5850 buffer.edit(
5851 edit_ranges
5852 .into_iter()
5853 .map(|range| (range, empty_str.clone())),
5854 None,
5855 cx,
5856 );
5857 buffer.snapshot(cx)
5858 });
5859 let new_selections = new_cursors
5860 .into_iter()
5861 .map(|(id, cursor)| {
5862 let cursor = cursor.to_point(&buffer);
5863 Selection {
5864 id,
5865 start: cursor,
5866 end: cursor,
5867 reversed: false,
5868 goal: SelectionGoal::None,
5869 }
5870 })
5871 .collect();
5872
5873 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5874 s.select(new_selections);
5875 });
5876 });
5877 }
5878
5879 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5880 if self.read_only(cx) {
5881 return;
5882 }
5883 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5884 for selection in self.selections.all::<Point>(cx) {
5885 let start = MultiBufferRow(selection.start.row);
5886 let end = if selection.start.row == selection.end.row {
5887 MultiBufferRow(selection.start.row + 1)
5888 } else {
5889 MultiBufferRow(selection.end.row)
5890 };
5891
5892 if let Some(last_row_range) = row_ranges.last_mut() {
5893 if start <= last_row_range.end {
5894 last_row_range.end = end;
5895 continue;
5896 }
5897 }
5898 row_ranges.push(start..end);
5899 }
5900
5901 let snapshot = self.buffer.read(cx).snapshot(cx);
5902 let mut cursor_positions = Vec::new();
5903 for row_range in &row_ranges {
5904 let anchor = snapshot.anchor_before(Point::new(
5905 row_range.end.previous_row().0,
5906 snapshot.line_len(row_range.end.previous_row()),
5907 ));
5908 cursor_positions.push(anchor..anchor);
5909 }
5910
5911 self.transact(cx, |this, cx| {
5912 for row_range in row_ranges.into_iter().rev() {
5913 for row in row_range.iter_rows().rev() {
5914 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5915 let next_line_row = row.next_row();
5916 let indent = snapshot.indent_size_for_line(next_line_row);
5917 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5918
5919 let replace = if snapshot.line_len(next_line_row) > indent.len {
5920 " "
5921 } else {
5922 ""
5923 };
5924
5925 this.buffer.update(cx, |buffer, cx| {
5926 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5927 });
5928 }
5929 }
5930
5931 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5932 s.select_anchor_ranges(cursor_positions)
5933 });
5934 });
5935 }
5936
5937 pub fn sort_lines_case_sensitive(
5938 &mut self,
5939 _: &SortLinesCaseSensitive,
5940 cx: &mut ViewContext<Self>,
5941 ) {
5942 self.manipulate_lines(cx, |lines| lines.sort())
5943 }
5944
5945 pub fn sort_lines_case_insensitive(
5946 &mut self,
5947 _: &SortLinesCaseInsensitive,
5948 cx: &mut ViewContext<Self>,
5949 ) {
5950 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5951 }
5952
5953 pub fn unique_lines_case_insensitive(
5954 &mut self,
5955 _: &UniqueLinesCaseInsensitive,
5956 cx: &mut ViewContext<Self>,
5957 ) {
5958 self.manipulate_lines(cx, |lines| {
5959 let mut seen = HashSet::default();
5960 lines.retain(|line| seen.insert(line.to_lowercase()));
5961 })
5962 }
5963
5964 pub fn unique_lines_case_sensitive(
5965 &mut self,
5966 _: &UniqueLinesCaseSensitive,
5967 cx: &mut ViewContext<Self>,
5968 ) {
5969 self.manipulate_lines(cx, |lines| {
5970 let mut seen = HashSet::default();
5971 lines.retain(|line| seen.insert(*line));
5972 })
5973 }
5974
5975 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5976 let mut revert_changes = HashMap::default();
5977 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5978 for hunk in hunks_for_rows(
5979 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
5980 &multi_buffer_snapshot,
5981 ) {
5982 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
5983 }
5984 if !revert_changes.is_empty() {
5985 self.transact(cx, |editor, cx| {
5986 editor.revert(revert_changes, cx);
5987 });
5988 }
5989 }
5990
5991 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5992 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5993 if !revert_changes.is_empty() {
5994 self.transact(cx, |editor, cx| {
5995 editor.revert(revert_changes, cx);
5996 });
5997 }
5998 }
5999
6000 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6001 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6002 let project_path = buffer.read(cx).project_path(cx)?;
6003 let project = self.project.as_ref()?.read(cx);
6004 let entry = project.entry_for_path(&project_path, cx)?;
6005 let abs_path = project.absolute_path(&project_path, cx)?;
6006 let parent = if entry.is_symlink {
6007 abs_path.canonicalize().ok()?
6008 } else {
6009 abs_path
6010 }
6011 .parent()?
6012 .to_path_buf();
6013 Some(parent)
6014 }) {
6015 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6016 }
6017 }
6018
6019 fn gather_revert_changes(
6020 &mut self,
6021 selections: &[Selection<Anchor>],
6022 cx: &mut ViewContext<'_, Editor>,
6023 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6024 let mut revert_changes = HashMap::default();
6025 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6026 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6027 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6028 }
6029 revert_changes
6030 }
6031
6032 pub fn prepare_revert_change(
6033 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6034 multi_buffer: &Model<MultiBuffer>,
6035 hunk: &DiffHunk<MultiBufferRow>,
6036 cx: &AppContext,
6037 ) -> Option<()> {
6038 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6039 let buffer = buffer.read(cx);
6040 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6041 let buffer_snapshot = buffer.snapshot();
6042 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6043 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6044 probe
6045 .0
6046 .start
6047 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6048 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6049 }) {
6050 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6051 Some(())
6052 } else {
6053 None
6054 }
6055 }
6056
6057 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6058 self.manipulate_lines(cx, |lines| lines.reverse())
6059 }
6060
6061 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6062 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6063 }
6064
6065 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6066 where
6067 Fn: FnMut(&mut Vec<&str>),
6068 {
6069 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6070 let buffer = self.buffer.read(cx).snapshot(cx);
6071
6072 let mut edits = Vec::new();
6073
6074 let selections = self.selections.all::<Point>(cx);
6075 let mut selections = selections.iter().peekable();
6076 let mut contiguous_row_selections = Vec::new();
6077 let mut new_selections = Vec::new();
6078 let mut added_lines = 0;
6079 let mut removed_lines = 0;
6080
6081 while let Some(selection) = selections.next() {
6082 let (start_row, end_row) = consume_contiguous_rows(
6083 &mut contiguous_row_selections,
6084 selection,
6085 &display_map,
6086 &mut selections,
6087 );
6088
6089 let start_point = Point::new(start_row.0, 0);
6090 let end_point = Point::new(
6091 end_row.previous_row().0,
6092 buffer.line_len(end_row.previous_row()),
6093 );
6094 let text = buffer
6095 .text_for_range(start_point..end_point)
6096 .collect::<String>();
6097
6098 let mut lines = text.split('\n').collect_vec();
6099
6100 let lines_before = lines.len();
6101 callback(&mut lines);
6102 let lines_after = lines.len();
6103
6104 edits.push((start_point..end_point, lines.join("\n")));
6105
6106 // Selections must change based on added and removed line count
6107 let start_row =
6108 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6109 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6110 new_selections.push(Selection {
6111 id: selection.id,
6112 start: start_row,
6113 end: end_row,
6114 goal: SelectionGoal::None,
6115 reversed: selection.reversed,
6116 });
6117
6118 if lines_after > lines_before {
6119 added_lines += lines_after - lines_before;
6120 } else if lines_before > lines_after {
6121 removed_lines += lines_before - lines_after;
6122 }
6123 }
6124
6125 self.transact(cx, |this, cx| {
6126 let buffer = this.buffer.update(cx, |buffer, cx| {
6127 buffer.edit(edits, None, cx);
6128 buffer.snapshot(cx)
6129 });
6130
6131 // Recalculate offsets on newly edited buffer
6132 let new_selections = new_selections
6133 .iter()
6134 .map(|s| {
6135 let start_point = Point::new(s.start.0, 0);
6136 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6137 Selection {
6138 id: s.id,
6139 start: buffer.point_to_offset(start_point),
6140 end: buffer.point_to_offset(end_point),
6141 goal: s.goal,
6142 reversed: s.reversed,
6143 }
6144 })
6145 .collect();
6146
6147 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6148 s.select(new_selections);
6149 });
6150
6151 this.request_autoscroll(Autoscroll::fit(), cx);
6152 });
6153 }
6154
6155 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6156 self.manipulate_text(cx, |text| text.to_uppercase())
6157 }
6158
6159 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6160 self.manipulate_text(cx, |text| text.to_lowercase())
6161 }
6162
6163 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6164 self.manipulate_text(cx, |text| {
6165 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6166 // https://github.com/rutrum/convert-case/issues/16
6167 text.split('\n')
6168 .map(|line| line.to_case(Case::Title))
6169 .join("\n")
6170 })
6171 }
6172
6173 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6174 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6175 }
6176
6177 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6178 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6179 }
6180
6181 pub fn convert_to_upper_camel_case(
6182 &mut self,
6183 _: &ConvertToUpperCamelCase,
6184 cx: &mut ViewContext<Self>,
6185 ) {
6186 self.manipulate_text(cx, |text| {
6187 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6188 // https://github.com/rutrum/convert-case/issues/16
6189 text.split('\n')
6190 .map(|line| line.to_case(Case::UpperCamel))
6191 .join("\n")
6192 })
6193 }
6194
6195 pub fn convert_to_lower_camel_case(
6196 &mut self,
6197 _: &ConvertToLowerCamelCase,
6198 cx: &mut ViewContext<Self>,
6199 ) {
6200 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6201 }
6202
6203 pub fn convert_to_opposite_case(
6204 &mut self,
6205 _: &ConvertToOppositeCase,
6206 cx: &mut ViewContext<Self>,
6207 ) {
6208 self.manipulate_text(cx, |text| {
6209 text.chars()
6210 .fold(String::with_capacity(text.len()), |mut t, c| {
6211 if c.is_uppercase() {
6212 t.extend(c.to_lowercase());
6213 } else {
6214 t.extend(c.to_uppercase());
6215 }
6216 t
6217 })
6218 })
6219 }
6220
6221 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6222 where
6223 Fn: FnMut(&str) -> String,
6224 {
6225 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6226 let buffer = self.buffer.read(cx).snapshot(cx);
6227
6228 let mut new_selections = Vec::new();
6229 let mut edits = Vec::new();
6230 let mut selection_adjustment = 0i32;
6231
6232 for selection in self.selections.all::<usize>(cx) {
6233 let selection_is_empty = selection.is_empty();
6234
6235 let (start, end) = if selection_is_empty {
6236 let word_range = movement::surrounding_word(
6237 &display_map,
6238 selection.start.to_display_point(&display_map),
6239 );
6240 let start = word_range.start.to_offset(&display_map, Bias::Left);
6241 let end = word_range.end.to_offset(&display_map, Bias::Left);
6242 (start, end)
6243 } else {
6244 (selection.start, selection.end)
6245 };
6246
6247 let text = buffer.text_for_range(start..end).collect::<String>();
6248 let old_length = text.len() as i32;
6249 let text = callback(&text);
6250
6251 new_selections.push(Selection {
6252 start: (start as i32 - selection_adjustment) as usize,
6253 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6254 goal: SelectionGoal::None,
6255 ..selection
6256 });
6257
6258 selection_adjustment += old_length - text.len() as i32;
6259
6260 edits.push((start..end, text));
6261 }
6262
6263 self.transact(cx, |this, cx| {
6264 this.buffer.update(cx, |buffer, cx| {
6265 buffer.edit(edits, None, cx);
6266 });
6267
6268 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6269 s.select(new_selections);
6270 });
6271
6272 this.request_autoscroll(Autoscroll::fit(), cx);
6273 });
6274 }
6275
6276 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6277 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6278 let buffer = &display_map.buffer_snapshot;
6279 let selections = self.selections.all::<Point>(cx);
6280
6281 let mut edits = Vec::new();
6282 let mut selections_iter = selections.iter().peekable();
6283 while let Some(selection) = selections_iter.next() {
6284 // Avoid duplicating the same lines twice.
6285 let mut rows = selection.spanned_rows(false, &display_map);
6286
6287 while let Some(next_selection) = selections_iter.peek() {
6288 let next_rows = next_selection.spanned_rows(false, &display_map);
6289 if next_rows.start < rows.end {
6290 rows.end = next_rows.end;
6291 selections_iter.next().unwrap();
6292 } else {
6293 break;
6294 }
6295 }
6296
6297 // Copy the text from the selected row region and splice it either at the start
6298 // or end of the region.
6299 let start = Point::new(rows.start.0, 0);
6300 let end = Point::new(
6301 rows.end.previous_row().0,
6302 buffer.line_len(rows.end.previous_row()),
6303 );
6304 let text = buffer
6305 .text_for_range(start..end)
6306 .chain(Some("\n"))
6307 .collect::<String>();
6308 let insert_location = if upwards {
6309 Point::new(rows.end.0, 0)
6310 } else {
6311 start
6312 };
6313 edits.push((insert_location..insert_location, text));
6314 }
6315
6316 self.transact(cx, |this, cx| {
6317 this.buffer.update(cx, |buffer, cx| {
6318 buffer.edit(edits, None, cx);
6319 });
6320
6321 this.request_autoscroll(Autoscroll::fit(), cx);
6322 });
6323 }
6324
6325 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6326 self.duplicate_line(true, cx);
6327 }
6328
6329 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6330 self.duplicate_line(false, cx);
6331 }
6332
6333 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6334 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6335 let buffer = self.buffer.read(cx).snapshot(cx);
6336
6337 let mut edits = Vec::new();
6338 let mut unfold_ranges = Vec::new();
6339 let mut refold_ranges = Vec::new();
6340
6341 let selections = self.selections.all::<Point>(cx);
6342 let mut selections = selections.iter().peekable();
6343 let mut contiguous_row_selections = Vec::new();
6344 let mut new_selections = Vec::new();
6345
6346 while let Some(selection) = selections.next() {
6347 // Find all the selections that span a contiguous row range
6348 let (start_row, end_row) = consume_contiguous_rows(
6349 &mut contiguous_row_selections,
6350 selection,
6351 &display_map,
6352 &mut selections,
6353 );
6354
6355 // Move the text spanned by the row range to be before the line preceding the row range
6356 if start_row.0 > 0 {
6357 let range_to_move = Point::new(
6358 start_row.previous_row().0,
6359 buffer.line_len(start_row.previous_row()),
6360 )
6361 ..Point::new(
6362 end_row.previous_row().0,
6363 buffer.line_len(end_row.previous_row()),
6364 );
6365 let insertion_point = display_map
6366 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6367 .0;
6368
6369 // Don't move lines across excerpts
6370 if buffer
6371 .excerpt_boundaries_in_range((
6372 Bound::Excluded(insertion_point),
6373 Bound::Included(range_to_move.end),
6374 ))
6375 .next()
6376 .is_none()
6377 {
6378 let text = buffer
6379 .text_for_range(range_to_move.clone())
6380 .flat_map(|s| s.chars())
6381 .skip(1)
6382 .chain(['\n'])
6383 .collect::<String>();
6384
6385 edits.push((
6386 buffer.anchor_after(range_to_move.start)
6387 ..buffer.anchor_before(range_to_move.end),
6388 String::new(),
6389 ));
6390 let insertion_anchor = buffer.anchor_after(insertion_point);
6391 edits.push((insertion_anchor..insertion_anchor, text));
6392
6393 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6394
6395 // Move selections up
6396 new_selections.extend(contiguous_row_selections.drain(..).map(
6397 |mut selection| {
6398 selection.start.row -= row_delta;
6399 selection.end.row -= row_delta;
6400 selection
6401 },
6402 ));
6403
6404 // Move folds up
6405 unfold_ranges.push(range_to_move.clone());
6406 for fold in display_map.folds_in_range(
6407 buffer.anchor_before(range_to_move.start)
6408 ..buffer.anchor_after(range_to_move.end),
6409 ) {
6410 let mut start = fold.range.start.to_point(&buffer);
6411 let mut end = fold.range.end.to_point(&buffer);
6412 start.row -= row_delta;
6413 end.row -= row_delta;
6414 refold_ranges.push((start..end, fold.placeholder.clone()));
6415 }
6416 }
6417 }
6418
6419 // If we didn't move line(s), preserve the existing selections
6420 new_selections.append(&mut contiguous_row_selections);
6421 }
6422
6423 self.transact(cx, |this, cx| {
6424 this.unfold_ranges(unfold_ranges, true, true, cx);
6425 this.buffer.update(cx, |buffer, cx| {
6426 for (range, text) in edits {
6427 buffer.edit([(range, text)], None, cx);
6428 }
6429 });
6430 this.fold_ranges(refold_ranges, true, cx);
6431 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6432 s.select(new_selections);
6433 })
6434 });
6435 }
6436
6437 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6438 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6439 let buffer = self.buffer.read(cx).snapshot(cx);
6440
6441 let mut edits = Vec::new();
6442 let mut unfold_ranges = Vec::new();
6443 let mut refold_ranges = Vec::new();
6444
6445 let selections = self.selections.all::<Point>(cx);
6446 let mut selections = selections.iter().peekable();
6447 let mut contiguous_row_selections = Vec::new();
6448 let mut new_selections = Vec::new();
6449
6450 while let Some(selection) = selections.next() {
6451 // Find all the selections that span a contiguous row range
6452 let (start_row, end_row) = consume_contiguous_rows(
6453 &mut contiguous_row_selections,
6454 selection,
6455 &display_map,
6456 &mut selections,
6457 );
6458
6459 // Move the text spanned by the row range to be after the last line of the row range
6460 if end_row.0 <= buffer.max_point().row {
6461 let range_to_move =
6462 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6463 let insertion_point = display_map
6464 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6465 .0;
6466
6467 // Don't move lines across excerpt boundaries
6468 if buffer
6469 .excerpt_boundaries_in_range((
6470 Bound::Excluded(range_to_move.start),
6471 Bound::Included(insertion_point),
6472 ))
6473 .next()
6474 .is_none()
6475 {
6476 let mut text = String::from("\n");
6477 text.extend(buffer.text_for_range(range_to_move.clone()));
6478 text.pop(); // Drop trailing newline
6479 edits.push((
6480 buffer.anchor_after(range_to_move.start)
6481 ..buffer.anchor_before(range_to_move.end),
6482 String::new(),
6483 ));
6484 let insertion_anchor = buffer.anchor_after(insertion_point);
6485 edits.push((insertion_anchor..insertion_anchor, text));
6486
6487 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6488
6489 // Move selections down
6490 new_selections.extend(contiguous_row_selections.drain(..).map(
6491 |mut selection| {
6492 selection.start.row += row_delta;
6493 selection.end.row += row_delta;
6494 selection
6495 },
6496 ));
6497
6498 // Move folds down
6499 unfold_ranges.push(range_to_move.clone());
6500 for fold in display_map.folds_in_range(
6501 buffer.anchor_before(range_to_move.start)
6502 ..buffer.anchor_after(range_to_move.end),
6503 ) {
6504 let mut start = fold.range.start.to_point(&buffer);
6505 let mut end = fold.range.end.to_point(&buffer);
6506 start.row += row_delta;
6507 end.row += row_delta;
6508 refold_ranges.push((start..end, fold.placeholder.clone()));
6509 }
6510 }
6511 }
6512
6513 // If we didn't move line(s), preserve the existing selections
6514 new_selections.append(&mut contiguous_row_selections);
6515 }
6516
6517 self.transact(cx, |this, cx| {
6518 this.unfold_ranges(unfold_ranges, true, true, cx);
6519 this.buffer.update(cx, |buffer, cx| {
6520 for (range, text) in edits {
6521 buffer.edit([(range, text)], None, cx);
6522 }
6523 });
6524 this.fold_ranges(refold_ranges, true, cx);
6525 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6526 });
6527 }
6528
6529 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6530 let text_layout_details = &self.text_layout_details(cx);
6531 self.transact(cx, |this, cx| {
6532 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6533 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6534 let line_mode = s.line_mode;
6535 s.move_with(|display_map, selection| {
6536 if !selection.is_empty() || line_mode {
6537 return;
6538 }
6539
6540 let mut head = selection.head();
6541 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6542 if head.column() == display_map.line_len(head.row()) {
6543 transpose_offset = display_map
6544 .buffer_snapshot
6545 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6546 }
6547
6548 if transpose_offset == 0 {
6549 return;
6550 }
6551
6552 *head.column_mut() += 1;
6553 head = display_map.clip_point(head, Bias::Right);
6554 let goal = SelectionGoal::HorizontalPosition(
6555 display_map
6556 .x_for_display_point(head, &text_layout_details)
6557 .into(),
6558 );
6559 selection.collapse_to(head, goal);
6560
6561 let transpose_start = display_map
6562 .buffer_snapshot
6563 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6564 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6565 let transpose_end = display_map
6566 .buffer_snapshot
6567 .clip_offset(transpose_offset + 1, Bias::Right);
6568 if let Some(ch) =
6569 display_map.buffer_snapshot.chars_at(transpose_start).next()
6570 {
6571 edits.push((transpose_start..transpose_offset, String::new()));
6572 edits.push((transpose_end..transpose_end, ch.to_string()));
6573 }
6574 }
6575 });
6576 edits
6577 });
6578 this.buffer
6579 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6580 let selections = this.selections.all::<usize>(cx);
6581 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6582 s.select(selections);
6583 });
6584 });
6585 }
6586
6587 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6588 let mut text = String::new();
6589 let buffer = self.buffer.read(cx).snapshot(cx);
6590 let mut selections = self.selections.all::<Point>(cx);
6591 let mut clipboard_selections = Vec::with_capacity(selections.len());
6592 {
6593 let max_point = buffer.max_point();
6594 let mut is_first = true;
6595 for selection in &mut selections {
6596 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6597 if is_entire_line {
6598 selection.start = Point::new(selection.start.row, 0);
6599 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6600 selection.goal = SelectionGoal::None;
6601 }
6602 if is_first {
6603 is_first = false;
6604 } else {
6605 text += "\n";
6606 }
6607 let mut len = 0;
6608 for chunk in buffer.text_for_range(selection.start..selection.end) {
6609 text.push_str(chunk);
6610 len += chunk.len();
6611 }
6612 clipboard_selections.push(ClipboardSelection {
6613 len,
6614 is_entire_line,
6615 first_line_indent: buffer
6616 .indent_size_for_line(MultiBufferRow(selection.start.row))
6617 .len,
6618 });
6619 }
6620 }
6621
6622 self.transact(cx, |this, cx| {
6623 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6624 s.select(selections);
6625 });
6626 this.insert("", cx);
6627 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6628 text,
6629 clipboard_selections,
6630 ));
6631 });
6632 }
6633
6634 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6635 let selections = self.selections.all::<Point>(cx);
6636 let buffer = self.buffer.read(cx).read(cx);
6637 let mut text = String::new();
6638
6639 let mut clipboard_selections = Vec::with_capacity(selections.len());
6640 {
6641 let max_point = buffer.max_point();
6642 let mut is_first = true;
6643 for selection in selections.iter() {
6644 let mut start = selection.start;
6645 let mut end = selection.end;
6646 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6647 if is_entire_line {
6648 start = Point::new(start.row, 0);
6649 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6650 }
6651 if is_first {
6652 is_first = false;
6653 } else {
6654 text += "\n";
6655 }
6656 let mut len = 0;
6657 for chunk in buffer.text_for_range(start..end) {
6658 text.push_str(chunk);
6659 len += chunk.len();
6660 }
6661 clipboard_selections.push(ClipboardSelection {
6662 len,
6663 is_entire_line,
6664 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6665 });
6666 }
6667 }
6668
6669 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6670 text,
6671 clipboard_selections,
6672 ));
6673 }
6674
6675 pub fn do_paste(
6676 &mut self,
6677 text: &String,
6678 clipboard_selections: Option<Vec<ClipboardSelection>>,
6679 handle_entire_lines: bool,
6680 cx: &mut ViewContext<Self>,
6681 ) {
6682 if self.read_only(cx) {
6683 return;
6684 }
6685
6686 let clipboard_text = Cow::Borrowed(text);
6687
6688 self.transact(cx, |this, cx| {
6689 if let Some(mut clipboard_selections) = clipboard_selections {
6690 let old_selections = this.selections.all::<usize>(cx);
6691 let all_selections_were_entire_line =
6692 clipboard_selections.iter().all(|s| s.is_entire_line);
6693 let first_selection_indent_column =
6694 clipboard_selections.first().map(|s| s.first_line_indent);
6695 if clipboard_selections.len() != old_selections.len() {
6696 clipboard_selections.drain(..);
6697 }
6698
6699 this.buffer.update(cx, |buffer, cx| {
6700 let snapshot = buffer.read(cx);
6701 let mut start_offset = 0;
6702 let mut edits = Vec::new();
6703 let mut original_indent_columns = Vec::new();
6704 for (ix, selection) in old_selections.iter().enumerate() {
6705 let to_insert;
6706 let entire_line;
6707 let original_indent_column;
6708 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6709 let end_offset = start_offset + clipboard_selection.len;
6710 to_insert = &clipboard_text[start_offset..end_offset];
6711 entire_line = clipboard_selection.is_entire_line;
6712 start_offset = end_offset + 1;
6713 original_indent_column = Some(clipboard_selection.first_line_indent);
6714 } else {
6715 to_insert = clipboard_text.as_str();
6716 entire_line = all_selections_were_entire_line;
6717 original_indent_column = first_selection_indent_column
6718 }
6719
6720 // If the corresponding selection was empty when this slice of the
6721 // clipboard text was written, then the entire line containing the
6722 // selection was copied. If this selection is also currently empty,
6723 // then paste the line before the current line of the buffer.
6724 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6725 let column = selection.start.to_point(&snapshot).column as usize;
6726 let line_start = selection.start - column;
6727 line_start..line_start
6728 } else {
6729 selection.range()
6730 };
6731
6732 edits.push((range, to_insert));
6733 original_indent_columns.extend(original_indent_column);
6734 }
6735 drop(snapshot);
6736
6737 buffer.edit(
6738 edits,
6739 Some(AutoindentMode::Block {
6740 original_indent_columns,
6741 }),
6742 cx,
6743 );
6744 });
6745
6746 let selections = this.selections.all::<usize>(cx);
6747 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6748 } else {
6749 this.insert(&clipboard_text, cx);
6750 }
6751 });
6752 }
6753
6754 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6755 if let Some(item) = cx.read_from_clipboard() {
6756 let entries = item.entries();
6757
6758 match entries.first() {
6759 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6760 // of all the pasted entries.
6761 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6762 .do_paste(
6763 clipboard_string.text(),
6764 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6765 true,
6766 cx,
6767 ),
6768 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6769 }
6770 }
6771 }
6772
6773 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6774 if self.read_only(cx) {
6775 return;
6776 }
6777
6778 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6779 if let Some((selections, _)) =
6780 self.selection_history.transaction(transaction_id).cloned()
6781 {
6782 self.change_selections(None, cx, |s| {
6783 s.select_anchors(selections.to_vec());
6784 });
6785 }
6786 self.request_autoscroll(Autoscroll::fit(), cx);
6787 self.unmark_text(cx);
6788 self.refresh_inline_completion(true, cx);
6789 cx.emit(EditorEvent::Edited { transaction_id });
6790 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6791 }
6792 }
6793
6794 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6795 if self.read_only(cx) {
6796 return;
6797 }
6798
6799 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6800 if let Some((_, Some(selections))) =
6801 self.selection_history.transaction(transaction_id).cloned()
6802 {
6803 self.change_selections(None, cx, |s| {
6804 s.select_anchors(selections.to_vec());
6805 });
6806 }
6807 self.request_autoscroll(Autoscroll::fit(), cx);
6808 self.unmark_text(cx);
6809 self.refresh_inline_completion(true, cx);
6810 cx.emit(EditorEvent::Edited { transaction_id });
6811 }
6812 }
6813
6814 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6815 self.buffer
6816 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6817 }
6818
6819 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6820 self.buffer
6821 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6822 }
6823
6824 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6825 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6826 let line_mode = s.line_mode;
6827 s.move_with(|map, selection| {
6828 let cursor = if selection.is_empty() && !line_mode {
6829 movement::left(map, selection.start)
6830 } else {
6831 selection.start
6832 };
6833 selection.collapse_to(cursor, SelectionGoal::None);
6834 });
6835 })
6836 }
6837
6838 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6839 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6840 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6841 })
6842 }
6843
6844 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6845 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6846 let line_mode = s.line_mode;
6847 s.move_with(|map, selection| {
6848 let cursor = if selection.is_empty() && !line_mode {
6849 movement::right(map, selection.end)
6850 } else {
6851 selection.end
6852 };
6853 selection.collapse_to(cursor, SelectionGoal::None)
6854 });
6855 })
6856 }
6857
6858 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6859 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6860 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6861 })
6862 }
6863
6864 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6865 if self.take_rename(true, cx).is_some() {
6866 return;
6867 }
6868
6869 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6870 cx.propagate();
6871 return;
6872 }
6873
6874 let text_layout_details = &self.text_layout_details(cx);
6875 let selection_count = self.selections.count();
6876 let first_selection = self.selections.first_anchor();
6877
6878 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6879 let line_mode = s.line_mode;
6880 s.move_with(|map, selection| {
6881 if !selection.is_empty() && !line_mode {
6882 selection.goal = SelectionGoal::None;
6883 }
6884 let (cursor, goal) = movement::up(
6885 map,
6886 selection.start,
6887 selection.goal,
6888 false,
6889 &text_layout_details,
6890 );
6891 selection.collapse_to(cursor, goal);
6892 });
6893 });
6894
6895 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6896 {
6897 cx.propagate();
6898 }
6899 }
6900
6901 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6902 if self.take_rename(true, cx).is_some() {
6903 return;
6904 }
6905
6906 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6907 cx.propagate();
6908 return;
6909 }
6910
6911 let text_layout_details = &self.text_layout_details(cx);
6912
6913 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6914 let line_mode = s.line_mode;
6915 s.move_with(|map, selection| {
6916 if !selection.is_empty() && !line_mode {
6917 selection.goal = SelectionGoal::None;
6918 }
6919 let (cursor, goal) = movement::up_by_rows(
6920 map,
6921 selection.start,
6922 action.lines,
6923 selection.goal,
6924 false,
6925 &text_layout_details,
6926 );
6927 selection.collapse_to(cursor, goal);
6928 });
6929 })
6930 }
6931
6932 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6933 if self.take_rename(true, cx).is_some() {
6934 return;
6935 }
6936
6937 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6938 cx.propagate();
6939 return;
6940 }
6941
6942 let text_layout_details = &self.text_layout_details(cx);
6943
6944 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6945 let line_mode = s.line_mode;
6946 s.move_with(|map, selection| {
6947 if !selection.is_empty() && !line_mode {
6948 selection.goal = SelectionGoal::None;
6949 }
6950 let (cursor, goal) = movement::down_by_rows(
6951 map,
6952 selection.start,
6953 action.lines,
6954 selection.goal,
6955 false,
6956 &text_layout_details,
6957 );
6958 selection.collapse_to(cursor, goal);
6959 });
6960 })
6961 }
6962
6963 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6964 let text_layout_details = &self.text_layout_details(cx);
6965 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6966 s.move_heads_with(|map, head, goal| {
6967 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6968 })
6969 })
6970 }
6971
6972 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6973 let text_layout_details = &self.text_layout_details(cx);
6974 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6975 s.move_heads_with(|map, head, goal| {
6976 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6977 })
6978 })
6979 }
6980
6981 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6982 let Some(row_count) = self.visible_row_count() else {
6983 return;
6984 };
6985
6986 let text_layout_details = &self.text_layout_details(cx);
6987
6988 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6989 s.move_heads_with(|map, head, goal| {
6990 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6991 })
6992 })
6993 }
6994
6995 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6996 if self.take_rename(true, cx).is_some() {
6997 return;
6998 }
6999
7000 if self
7001 .context_menu
7002 .write()
7003 .as_mut()
7004 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7005 .unwrap_or(false)
7006 {
7007 return;
7008 }
7009
7010 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7011 cx.propagate();
7012 return;
7013 }
7014
7015 let Some(row_count) = self.visible_row_count() else {
7016 return;
7017 };
7018
7019 let autoscroll = if action.center_cursor {
7020 Autoscroll::center()
7021 } else {
7022 Autoscroll::fit()
7023 };
7024
7025 let text_layout_details = &self.text_layout_details(cx);
7026
7027 self.change_selections(Some(autoscroll), cx, |s| {
7028 let line_mode = s.line_mode;
7029 s.move_with(|map, selection| {
7030 if !selection.is_empty() && !line_mode {
7031 selection.goal = SelectionGoal::None;
7032 }
7033 let (cursor, goal) = movement::up_by_rows(
7034 map,
7035 selection.end,
7036 row_count,
7037 selection.goal,
7038 false,
7039 &text_layout_details,
7040 );
7041 selection.collapse_to(cursor, goal);
7042 });
7043 });
7044 }
7045
7046 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7047 let text_layout_details = &self.text_layout_details(cx);
7048 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7049 s.move_heads_with(|map, head, goal| {
7050 movement::up(map, head, goal, false, &text_layout_details)
7051 })
7052 })
7053 }
7054
7055 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7056 self.take_rename(true, cx);
7057
7058 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7059 cx.propagate();
7060 return;
7061 }
7062
7063 let text_layout_details = &self.text_layout_details(cx);
7064 let selection_count = self.selections.count();
7065 let first_selection = self.selections.first_anchor();
7066
7067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7068 let line_mode = s.line_mode;
7069 s.move_with(|map, selection| {
7070 if !selection.is_empty() && !line_mode {
7071 selection.goal = SelectionGoal::None;
7072 }
7073 let (cursor, goal) = movement::down(
7074 map,
7075 selection.end,
7076 selection.goal,
7077 false,
7078 &text_layout_details,
7079 );
7080 selection.collapse_to(cursor, goal);
7081 });
7082 });
7083
7084 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7085 {
7086 cx.propagate();
7087 }
7088 }
7089
7090 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7091 let Some(row_count) = self.visible_row_count() else {
7092 return;
7093 };
7094
7095 let text_layout_details = &self.text_layout_details(cx);
7096
7097 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7098 s.move_heads_with(|map, head, goal| {
7099 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7100 })
7101 })
7102 }
7103
7104 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7105 if self.take_rename(true, cx).is_some() {
7106 return;
7107 }
7108
7109 if self
7110 .context_menu
7111 .write()
7112 .as_mut()
7113 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7114 .unwrap_or(false)
7115 {
7116 return;
7117 }
7118
7119 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7120 cx.propagate();
7121 return;
7122 }
7123
7124 let Some(row_count) = self.visible_row_count() else {
7125 return;
7126 };
7127
7128 let autoscroll = if action.center_cursor {
7129 Autoscroll::center()
7130 } else {
7131 Autoscroll::fit()
7132 };
7133
7134 let text_layout_details = &self.text_layout_details(cx);
7135 self.change_selections(Some(autoscroll), cx, |s| {
7136 let line_mode = s.line_mode;
7137 s.move_with(|map, selection| {
7138 if !selection.is_empty() && !line_mode {
7139 selection.goal = SelectionGoal::None;
7140 }
7141 let (cursor, goal) = movement::down_by_rows(
7142 map,
7143 selection.end,
7144 row_count,
7145 selection.goal,
7146 false,
7147 &text_layout_details,
7148 );
7149 selection.collapse_to(cursor, goal);
7150 });
7151 });
7152 }
7153
7154 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7155 let text_layout_details = &self.text_layout_details(cx);
7156 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7157 s.move_heads_with(|map, head, goal| {
7158 movement::down(map, head, goal, false, &text_layout_details)
7159 })
7160 });
7161 }
7162
7163 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7164 if let Some(context_menu) = self.context_menu.write().as_mut() {
7165 context_menu.select_first(self.project.as_ref(), cx);
7166 }
7167 }
7168
7169 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7170 if let Some(context_menu) = self.context_menu.write().as_mut() {
7171 context_menu.select_prev(self.project.as_ref(), cx);
7172 }
7173 }
7174
7175 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7176 if let Some(context_menu) = self.context_menu.write().as_mut() {
7177 context_menu.select_next(self.project.as_ref(), cx);
7178 }
7179 }
7180
7181 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7182 if let Some(context_menu) = self.context_menu.write().as_mut() {
7183 context_menu.select_last(self.project.as_ref(), cx);
7184 }
7185 }
7186
7187 pub fn move_to_previous_word_start(
7188 &mut self,
7189 _: &MoveToPreviousWordStart,
7190 cx: &mut ViewContext<Self>,
7191 ) {
7192 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7193 s.move_cursors_with(|map, head, _| {
7194 (
7195 movement::previous_word_start(map, head),
7196 SelectionGoal::None,
7197 )
7198 });
7199 })
7200 }
7201
7202 pub fn move_to_previous_subword_start(
7203 &mut self,
7204 _: &MoveToPreviousSubwordStart,
7205 cx: &mut ViewContext<Self>,
7206 ) {
7207 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7208 s.move_cursors_with(|map, head, _| {
7209 (
7210 movement::previous_subword_start(map, head),
7211 SelectionGoal::None,
7212 )
7213 });
7214 })
7215 }
7216
7217 pub fn select_to_previous_word_start(
7218 &mut self,
7219 _: &SelectToPreviousWordStart,
7220 cx: &mut ViewContext<Self>,
7221 ) {
7222 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7223 s.move_heads_with(|map, head, _| {
7224 (
7225 movement::previous_word_start(map, head),
7226 SelectionGoal::None,
7227 )
7228 });
7229 })
7230 }
7231
7232 pub fn select_to_previous_subword_start(
7233 &mut self,
7234 _: &SelectToPreviousSubwordStart,
7235 cx: &mut ViewContext<Self>,
7236 ) {
7237 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 s.move_heads_with(|map, head, _| {
7239 (
7240 movement::previous_subword_start(map, head),
7241 SelectionGoal::None,
7242 )
7243 });
7244 })
7245 }
7246
7247 pub fn delete_to_previous_word_start(
7248 &mut self,
7249 _: &DeleteToPreviousWordStart,
7250 cx: &mut ViewContext<Self>,
7251 ) {
7252 self.transact(cx, |this, cx| {
7253 this.select_autoclose_pair(cx);
7254 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7255 let line_mode = s.line_mode;
7256 s.move_with(|map, selection| {
7257 if selection.is_empty() && !line_mode {
7258 let cursor = movement::previous_word_start(map, selection.head());
7259 selection.set_head(cursor, SelectionGoal::None);
7260 }
7261 });
7262 });
7263 this.insert("", cx);
7264 });
7265 }
7266
7267 pub fn delete_to_previous_subword_start(
7268 &mut self,
7269 _: &DeleteToPreviousSubwordStart,
7270 cx: &mut ViewContext<Self>,
7271 ) {
7272 self.transact(cx, |this, cx| {
7273 this.select_autoclose_pair(cx);
7274 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7275 let line_mode = s.line_mode;
7276 s.move_with(|map, selection| {
7277 if selection.is_empty() && !line_mode {
7278 let cursor = movement::previous_subword_start(map, selection.head());
7279 selection.set_head(cursor, SelectionGoal::None);
7280 }
7281 });
7282 });
7283 this.insert("", cx);
7284 });
7285 }
7286
7287 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7289 s.move_cursors_with(|map, head, _| {
7290 (movement::next_word_end(map, head), SelectionGoal::None)
7291 });
7292 })
7293 }
7294
7295 pub fn move_to_next_subword_end(
7296 &mut self,
7297 _: &MoveToNextSubwordEnd,
7298 cx: &mut ViewContext<Self>,
7299 ) {
7300 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7301 s.move_cursors_with(|map, head, _| {
7302 (movement::next_subword_end(map, head), SelectionGoal::None)
7303 });
7304 })
7305 }
7306
7307 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7308 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7309 s.move_heads_with(|map, head, _| {
7310 (movement::next_word_end(map, head), SelectionGoal::None)
7311 });
7312 })
7313 }
7314
7315 pub fn select_to_next_subword_end(
7316 &mut self,
7317 _: &SelectToNextSubwordEnd,
7318 cx: &mut ViewContext<Self>,
7319 ) {
7320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7321 s.move_heads_with(|map, head, _| {
7322 (movement::next_subword_end(map, head), SelectionGoal::None)
7323 });
7324 })
7325 }
7326
7327 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7328 self.transact(cx, |this, cx| {
7329 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7330 let line_mode = s.line_mode;
7331 s.move_with(|map, selection| {
7332 if selection.is_empty() && !line_mode {
7333 let cursor = movement::next_word_end(map, selection.head());
7334 selection.set_head(cursor, SelectionGoal::None);
7335 }
7336 });
7337 });
7338 this.insert("", cx);
7339 });
7340 }
7341
7342 pub fn delete_to_next_subword_end(
7343 &mut self,
7344 _: &DeleteToNextSubwordEnd,
7345 cx: &mut ViewContext<Self>,
7346 ) {
7347 self.transact(cx, |this, cx| {
7348 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7349 s.move_with(|map, selection| {
7350 if selection.is_empty() {
7351 let cursor = movement::next_subword_end(map, selection.head());
7352 selection.set_head(cursor, SelectionGoal::None);
7353 }
7354 });
7355 });
7356 this.insert("", cx);
7357 });
7358 }
7359
7360 pub fn move_to_beginning_of_line(
7361 &mut self,
7362 action: &MoveToBeginningOfLine,
7363 cx: &mut ViewContext<Self>,
7364 ) {
7365 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7366 s.move_cursors_with(|map, head, _| {
7367 (
7368 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7369 SelectionGoal::None,
7370 )
7371 });
7372 })
7373 }
7374
7375 pub fn select_to_beginning_of_line(
7376 &mut self,
7377 action: &SelectToBeginningOfLine,
7378 cx: &mut ViewContext<Self>,
7379 ) {
7380 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7381 s.move_heads_with(|map, head, _| {
7382 (
7383 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7384 SelectionGoal::None,
7385 )
7386 });
7387 });
7388 }
7389
7390 pub fn delete_to_beginning_of_line(
7391 &mut self,
7392 _: &DeleteToBeginningOfLine,
7393 cx: &mut ViewContext<Self>,
7394 ) {
7395 self.transact(cx, |this, cx| {
7396 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7397 s.move_with(|_, selection| {
7398 selection.reversed = true;
7399 });
7400 });
7401
7402 this.select_to_beginning_of_line(
7403 &SelectToBeginningOfLine {
7404 stop_at_soft_wraps: false,
7405 },
7406 cx,
7407 );
7408 this.backspace(&Backspace, cx);
7409 });
7410 }
7411
7412 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7413 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7414 s.move_cursors_with(|map, head, _| {
7415 (
7416 movement::line_end(map, head, action.stop_at_soft_wraps),
7417 SelectionGoal::None,
7418 )
7419 });
7420 })
7421 }
7422
7423 pub fn select_to_end_of_line(
7424 &mut self,
7425 action: &SelectToEndOfLine,
7426 cx: &mut ViewContext<Self>,
7427 ) {
7428 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7429 s.move_heads_with(|map, head, _| {
7430 (
7431 movement::line_end(map, head, action.stop_at_soft_wraps),
7432 SelectionGoal::None,
7433 )
7434 });
7435 })
7436 }
7437
7438 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7439 self.transact(cx, |this, cx| {
7440 this.select_to_end_of_line(
7441 &SelectToEndOfLine {
7442 stop_at_soft_wraps: false,
7443 },
7444 cx,
7445 );
7446 this.delete(&Delete, cx);
7447 });
7448 }
7449
7450 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7451 self.transact(cx, |this, cx| {
7452 this.select_to_end_of_line(
7453 &SelectToEndOfLine {
7454 stop_at_soft_wraps: false,
7455 },
7456 cx,
7457 );
7458 this.cut(&Cut, cx);
7459 });
7460 }
7461
7462 pub fn move_to_start_of_paragraph(
7463 &mut self,
7464 _: &MoveToStartOfParagraph,
7465 cx: &mut ViewContext<Self>,
7466 ) {
7467 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7468 cx.propagate();
7469 return;
7470 }
7471
7472 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7473 s.move_with(|map, selection| {
7474 selection.collapse_to(
7475 movement::start_of_paragraph(map, selection.head(), 1),
7476 SelectionGoal::None,
7477 )
7478 });
7479 })
7480 }
7481
7482 pub fn move_to_end_of_paragraph(
7483 &mut self,
7484 _: &MoveToEndOfParagraph,
7485 cx: &mut ViewContext<Self>,
7486 ) {
7487 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7488 cx.propagate();
7489 return;
7490 }
7491
7492 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7493 s.move_with(|map, selection| {
7494 selection.collapse_to(
7495 movement::end_of_paragraph(map, selection.head(), 1),
7496 SelectionGoal::None,
7497 )
7498 });
7499 })
7500 }
7501
7502 pub fn select_to_start_of_paragraph(
7503 &mut self,
7504 _: &SelectToStartOfParagraph,
7505 cx: &mut ViewContext<Self>,
7506 ) {
7507 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7508 cx.propagate();
7509 return;
7510 }
7511
7512 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7513 s.move_heads_with(|map, head, _| {
7514 (
7515 movement::start_of_paragraph(map, head, 1),
7516 SelectionGoal::None,
7517 )
7518 });
7519 })
7520 }
7521
7522 pub fn select_to_end_of_paragraph(
7523 &mut self,
7524 _: &SelectToEndOfParagraph,
7525 cx: &mut ViewContext<Self>,
7526 ) {
7527 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7528 cx.propagate();
7529 return;
7530 }
7531
7532 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7533 s.move_heads_with(|map, head, _| {
7534 (
7535 movement::end_of_paragraph(map, head, 1),
7536 SelectionGoal::None,
7537 )
7538 });
7539 })
7540 }
7541
7542 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7543 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7544 cx.propagate();
7545 return;
7546 }
7547
7548 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7549 s.select_ranges(vec![0..0]);
7550 });
7551 }
7552
7553 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7554 let mut selection = self.selections.last::<Point>(cx);
7555 selection.set_head(Point::zero(), SelectionGoal::None);
7556
7557 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7558 s.select(vec![selection]);
7559 });
7560 }
7561
7562 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7563 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7564 cx.propagate();
7565 return;
7566 }
7567
7568 let cursor = self.buffer.read(cx).read(cx).len();
7569 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7570 s.select_ranges(vec![cursor..cursor])
7571 });
7572 }
7573
7574 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7575 self.nav_history = nav_history;
7576 }
7577
7578 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7579 self.nav_history.as_ref()
7580 }
7581
7582 fn push_to_nav_history(
7583 &mut self,
7584 cursor_anchor: Anchor,
7585 new_position: Option<Point>,
7586 cx: &mut ViewContext<Self>,
7587 ) {
7588 if let Some(nav_history) = self.nav_history.as_mut() {
7589 let buffer = self.buffer.read(cx).read(cx);
7590 let cursor_position = cursor_anchor.to_point(&buffer);
7591 let scroll_state = self.scroll_manager.anchor();
7592 let scroll_top_row = scroll_state.top_row(&buffer);
7593 drop(buffer);
7594
7595 if let Some(new_position) = new_position {
7596 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7597 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7598 return;
7599 }
7600 }
7601
7602 nav_history.push(
7603 Some(NavigationData {
7604 cursor_anchor,
7605 cursor_position,
7606 scroll_anchor: scroll_state,
7607 scroll_top_row,
7608 }),
7609 cx,
7610 );
7611 }
7612 }
7613
7614 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7615 let buffer = self.buffer.read(cx).snapshot(cx);
7616 let mut selection = self.selections.first::<usize>(cx);
7617 selection.set_head(buffer.len(), SelectionGoal::None);
7618 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7619 s.select(vec![selection]);
7620 });
7621 }
7622
7623 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7624 let end = self.buffer.read(cx).read(cx).len();
7625 self.change_selections(None, cx, |s| {
7626 s.select_ranges(vec![0..end]);
7627 });
7628 }
7629
7630 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7632 let mut selections = self.selections.all::<Point>(cx);
7633 let max_point = display_map.buffer_snapshot.max_point();
7634 for selection in &mut selections {
7635 let rows = selection.spanned_rows(true, &display_map);
7636 selection.start = Point::new(rows.start.0, 0);
7637 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7638 selection.reversed = false;
7639 }
7640 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7641 s.select(selections);
7642 });
7643 }
7644
7645 pub fn split_selection_into_lines(
7646 &mut self,
7647 _: &SplitSelectionIntoLines,
7648 cx: &mut ViewContext<Self>,
7649 ) {
7650 let mut to_unfold = Vec::new();
7651 let mut new_selection_ranges = Vec::new();
7652 {
7653 let selections = self.selections.all::<Point>(cx);
7654 let buffer = self.buffer.read(cx).read(cx);
7655 for selection in selections {
7656 for row in selection.start.row..selection.end.row {
7657 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7658 new_selection_ranges.push(cursor..cursor);
7659 }
7660 new_selection_ranges.push(selection.end..selection.end);
7661 to_unfold.push(selection.start..selection.end);
7662 }
7663 }
7664 self.unfold_ranges(to_unfold, true, true, cx);
7665 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7666 s.select_ranges(new_selection_ranges);
7667 });
7668 }
7669
7670 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7671 self.add_selection(true, cx);
7672 }
7673
7674 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7675 self.add_selection(false, cx);
7676 }
7677
7678 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7679 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7680 let mut selections = self.selections.all::<Point>(cx);
7681 let text_layout_details = self.text_layout_details(cx);
7682 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7683 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7684 let range = oldest_selection.display_range(&display_map).sorted();
7685
7686 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7687 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7688 let positions = start_x.min(end_x)..start_x.max(end_x);
7689
7690 selections.clear();
7691 let mut stack = Vec::new();
7692 for row in range.start.row().0..=range.end.row().0 {
7693 if let Some(selection) = self.selections.build_columnar_selection(
7694 &display_map,
7695 DisplayRow(row),
7696 &positions,
7697 oldest_selection.reversed,
7698 &text_layout_details,
7699 ) {
7700 stack.push(selection.id);
7701 selections.push(selection);
7702 }
7703 }
7704
7705 if above {
7706 stack.reverse();
7707 }
7708
7709 AddSelectionsState { above, stack }
7710 });
7711
7712 let last_added_selection = *state.stack.last().unwrap();
7713 let mut new_selections = Vec::new();
7714 if above == state.above {
7715 let end_row = if above {
7716 DisplayRow(0)
7717 } else {
7718 display_map.max_point().row()
7719 };
7720
7721 'outer: for selection in selections {
7722 if selection.id == last_added_selection {
7723 let range = selection.display_range(&display_map).sorted();
7724 debug_assert_eq!(range.start.row(), range.end.row());
7725 let mut row = range.start.row();
7726 let positions =
7727 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7728 px(start)..px(end)
7729 } else {
7730 let start_x =
7731 display_map.x_for_display_point(range.start, &text_layout_details);
7732 let end_x =
7733 display_map.x_for_display_point(range.end, &text_layout_details);
7734 start_x.min(end_x)..start_x.max(end_x)
7735 };
7736
7737 while row != end_row {
7738 if above {
7739 row.0 -= 1;
7740 } else {
7741 row.0 += 1;
7742 }
7743
7744 if let Some(new_selection) = self.selections.build_columnar_selection(
7745 &display_map,
7746 row,
7747 &positions,
7748 selection.reversed,
7749 &text_layout_details,
7750 ) {
7751 state.stack.push(new_selection.id);
7752 if above {
7753 new_selections.push(new_selection);
7754 new_selections.push(selection);
7755 } else {
7756 new_selections.push(selection);
7757 new_selections.push(new_selection);
7758 }
7759
7760 continue 'outer;
7761 }
7762 }
7763 }
7764
7765 new_selections.push(selection);
7766 }
7767 } else {
7768 new_selections = selections;
7769 new_selections.retain(|s| s.id != last_added_selection);
7770 state.stack.pop();
7771 }
7772
7773 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7774 s.select(new_selections);
7775 });
7776 if state.stack.len() > 1 {
7777 self.add_selections_state = Some(state);
7778 }
7779 }
7780
7781 pub fn select_next_match_internal(
7782 &mut self,
7783 display_map: &DisplaySnapshot,
7784 replace_newest: bool,
7785 autoscroll: Option<Autoscroll>,
7786 cx: &mut ViewContext<Self>,
7787 ) -> Result<()> {
7788 fn select_next_match_ranges(
7789 this: &mut Editor,
7790 range: Range<usize>,
7791 replace_newest: bool,
7792 auto_scroll: Option<Autoscroll>,
7793 cx: &mut ViewContext<Editor>,
7794 ) {
7795 this.unfold_ranges([range.clone()], false, true, cx);
7796 this.change_selections(auto_scroll, cx, |s| {
7797 if replace_newest {
7798 s.delete(s.newest_anchor().id);
7799 }
7800 s.insert_range(range.clone());
7801 });
7802 }
7803
7804 let buffer = &display_map.buffer_snapshot;
7805 let mut selections = self.selections.all::<usize>(cx);
7806 if let Some(mut select_next_state) = self.select_next_state.take() {
7807 let query = &select_next_state.query;
7808 if !select_next_state.done {
7809 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7810 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7811 let mut next_selected_range = None;
7812
7813 let bytes_after_last_selection =
7814 buffer.bytes_in_range(last_selection.end..buffer.len());
7815 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7816 let query_matches = query
7817 .stream_find_iter(bytes_after_last_selection)
7818 .map(|result| (last_selection.end, result))
7819 .chain(
7820 query
7821 .stream_find_iter(bytes_before_first_selection)
7822 .map(|result| (0, result)),
7823 );
7824
7825 for (start_offset, query_match) in query_matches {
7826 let query_match = query_match.unwrap(); // can only fail due to I/O
7827 let offset_range =
7828 start_offset + query_match.start()..start_offset + query_match.end();
7829 let display_range = offset_range.start.to_display_point(&display_map)
7830 ..offset_range.end.to_display_point(&display_map);
7831
7832 if !select_next_state.wordwise
7833 || (!movement::is_inside_word(&display_map, display_range.start)
7834 && !movement::is_inside_word(&display_map, display_range.end))
7835 {
7836 // TODO: This is n^2, because we might check all the selections
7837 if !selections
7838 .iter()
7839 .any(|selection| selection.range().overlaps(&offset_range))
7840 {
7841 next_selected_range = Some(offset_range);
7842 break;
7843 }
7844 }
7845 }
7846
7847 if let Some(next_selected_range) = next_selected_range {
7848 select_next_match_ranges(
7849 self,
7850 next_selected_range,
7851 replace_newest,
7852 autoscroll,
7853 cx,
7854 );
7855 } else {
7856 select_next_state.done = true;
7857 }
7858 }
7859
7860 self.select_next_state = Some(select_next_state);
7861 } else {
7862 let mut only_carets = true;
7863 let mut same_text_selected = true;
7864 let mut selected_text = None;
7865
7866 let mut selections_iter = selections.iter().peekable();
7867 while let Some(selection) = selections_iter.next() {
7868 if selection.start != selection.end {
7869 only_carets = false;
7870 }
7871
7872 if same_text_selected {
7873 if selected_text.is_none() {
7874 selected_text =
7875 Some(buffer.text_for_range(selection.range()).collect::<String>());
7876 }
7877
7878 if let Some(next_selection) = selections_iter.peek() {
7879 if next_selection.range().len() == selection.range().len() {
7880 let next_selected_text = buffer
7881 .text_for_range(next_selection.range())
7882 .collect::<String>();
7883 if Some(next_selected_text) != selected_text {
7884 same_text_selected = false;
7885 selected_text = None;
7886 }
7887 } else {
7888 same_text_selected = false;
7889 selected_text = None;
7890 }
7891 }
7892 }
7893 }
7894
7895 if only_carets {
7896 for selection in &mut selections {
7897 let word_range = movement::surrounding_word(
7898 &display_map,
7899 selection.start.to_display_point(&display_map),
7900 );
7901 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7902 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7903 selection.goal = SelectionGoal::None;
7904 selection.reversed = false;
7905 select_next_match_ranges(
7906 self,
7907 selection.start..selection.end,
7908 replace_newest,
7909 autoscroll,
7910 cx,
7911 );
7912 }
7913
7914 if selections.len() == 1 {
7915 let selection = selections
7916 .last()
7917 .expect("ensured that there's only one selection");
7918 let query = buffer
7919 .text_for_range(selection.start..selection.end)
7920 .collect::<String>();
7921 let is_empty = query.is_empty();
7922 let select_state = SelectNextState {
7923 query: AhoCorasick::new(&[query])?,
7924 wordwise: true,
7925 done: is_empty,
7926 };
7927 self.select_next_state = Some(select_state);
7928 } else {
7929 self.select_next_state = None;
7930 }
7931 } else if let Some(selected_text) = selected_text {
7932 self.select_next_state = Some(SelectNextState {
7933 query: AhoCorasick::new(&[selected_text])?,
7934 wordwise: false,
7935 done: false,
7936 });
7937 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7938 }
7939 }
7940 Ok(())
7941 }
7942
7943 pub fn select_all_matches(
7944 &mut self,
7945 _action: &SelectAllMatches,
7946 cx: &mut ViewContext<Self>,
7947 ) -> Result<()> {
7948 self.push_to_selection_history();
7949 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7950
7951 self.select_next_match_internal(&display_map, false, None, cx)?;
7952 let Some(select_next_state) = self.select_next_state.as_mut() else {
7953 return Ok(());
7954 };
7955 if select_next_state.done {
7956 return Ok(());
7957 }
7958
7959 let mut new_selections = self.selections.all::<usize>(cx);
7960
7961 let buffer = &display_map.buffer_snapshot;
7962 let query_matches = select_next_state
7963 .query
7964 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7965
7966 for query_match in query_matches {
7967 let query_match = query_match.unwrap(); // can only fail due to I/O
7968 let offset_range = query_match.start()..query_match.end();
7969 let display_range = offset_range.start.to_display_point(&display_map)
7970 ..offset_range.end.to_display_point(&display_map);
7971
7972 if !select_next_state.wordwise
7973 || (!movement::is_inside_word(&display_map, display_range.start)
7974 && !movement::is_inside_word(&display_map, display_range.end))
7975 {
7976 self.selections.change_with(cx, |selections| {
7977 new_selections.push(Selection {
7978 id: selections.new_selection_id(),
7979 start: offset_range.start,
7980 end: offset_range.end,
7981 reversed: false,
7982 goal: SelectionGoal::None,
7983 });
7984 });
7985 }
7986 }
7987
7988 new_selections.sort_by_key(|selection| selection.start);
7989 let mut ix = 0;
7990 while ix + 1 < new_selections.len() {
7991 let current_selection = &new_selections[ix];
7992 let next_selection = &new_selections[ix + 1];
7993 if current_selection.range().overlaps(&next_selection.range()) {
7994 if current_selection.id < next_selection.id {
7995 new_selections.remove(ix + 1);
7996 } else {
7997 new_selections.remove(ix);
7998 }
7999 } else {
8000 ix += 1;
8001 }
8002 }
8003
8004 select_next_state.done = true;
8005 self.unfold_ranges(
8006 new_selections.iter().map(|selection| selection.range()),
8007 false,
8008 false,
8009 cx,
8010 );
8011 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8012 selections.select(new_selections)
8013 });
8014
8015 Ok(())
8016 }
8017
8018 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8019 self.push_to_selection_history();
8020 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8021 self.select_next_match_internal(
8022 &display_map,
8023 action.replace_newest,
8024 Some(Autoscroll::newest()),
8025 cx,
8026 )?;
8027 Ok(())
8028 }
8029
8030 pub fn select_previous(
8031 &mut self,
8032 action: &SelectPrevious,
8033 cx: &mut ViewContext<Self>,
8034 ) -> Result<()> {
8035 self.push_to_selection_history();
8036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8037 let buffer = &display_map.buffer_snapshot;
8038 let mut selections = self.selections.all::<usize>(cx);
8039 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8040 let query = &select_prev_state.query;
8041 if !select_prev_state.done {
8042 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8043 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8044 let mut next_selected_range = None;
8045 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8046 let bytes_before_last_selection =
8047 buffer.reversed_bytes_in_range(0..last_selection.start);
8048 let bytes_after_first_selection =
8049 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8050 let query_matches = query
8051 .stream_find_iter(bytes_before_last_selection)
8052 .map(|result| (last_selection.start, result))
8053 .chain(
8054 query
8055 .stream_find_iter(bytes_after_first_selection)
8056 .map(|result| (buffer.len(), result)),
8057 );
8058 for (end_offset, query_match) in query_matches {
8059 let query_match = query_match.unwrap(); // can only fail due to I/O
8060 let offset_range =
8061 end_offset - query_match.end()..end_offset - query_match.start();
8062 let display_range = offset_range.start.to_display_point(&display_map)
8063 ..offset_range.end.to_display_point(&display_map);
8064
8065 if !select_prev_state.wordwise
8066 || (!movement::is_inside_word(&display_map, display_range.start)
8067 && !movement::is_inside_word(&display_map, display_range.end))
8068 {
8069 next_selected_range = Some(offset_range);
8070 break;
8071 }
8072 }
8073
8074 if let Some(next_selected_range) = next_selected_range {
8075 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8076 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8077 if action.replace_newest {
8078 s.delete(s.newest_anchor().id);
8079 }
8080 s.insert_range(next_selected_range);
8081 });
8082 } else {
8083 select_prev_state.done = true;
8084 }
8085 }
8086
8087 self.select_prev_state = Some(select_prev_state);
8088 } else {
8089 let mut only_carets = true;
8090 let mut same_text_selected = true;
8091 let mut selected_text = None;
8092
8093 let mut selections_iter = selections.iter().peekable();
8094 while let Some(selection) = selections_iter.next() {
8095 if selection.start != selection.end {
8096 only_carets = false;
8097 }
8098
8099 if same_text_selected {
8100 if selected_text.is_none() {
8101 selected_text =
8102 Some(buffer.text_for_range(selection.range()).collect::<String>());
8103 }
8104
8105 if let Some(next_selection) = selections_iter.peek() {
8106 if next_selection.range().len() == selection.range().len() {
8107 let next_selected_text = buffer
8108 .text_for_range(next_selection.range())
8109 .collect::<String>();
8110 if Some(next_selected_text) != selected_text {
8111 same_text_selected = false;
8112 selected_text = None;
8113 }
8114 } else {
8115 same_text_selected = false;
8116 selected_text = None;
8117 }
8118 }
8119 }
8120 }
8121
8122 if only_carets {
8123 for selection in &mut selections {
8124 let word_range = movement::surrounding_word(
8125 &display_map,
8126 selection.start.to_display_point(&display_map),
8127 );
8128 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8129 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8130 selection.goal = SelectionGoal::None;
8131 selection.reversed = false;
8132 }
8133 if selections.len() == 1 {
8134 let selection = selections
8135 .last()
8136 .expect("ensured that there's only one selection");
8137 let query = buffer
8138 .text_for_range(selection.start..selection.end)
8139 .collect::<String>();
8140 let is_empty = query.is_empty();
8141 let select_state = SelectNextState {
8142 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8143 wordwise: true,
8144 done: is_empty,
8145 };
8146 self.select_prev_state = Some(select_state);
8147 } else {
8148 self.select_prev_state = None;
8149 }
8150
8151 self.unfold_ranges(
8152 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8153 false,
8154 true,
8155 cx,
8156 );
8157 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8158 s.select(selections);
8159 });
8160 } else if let Some(selected_text) = selected_text {
8161 self.select_prev_state = Some(SelectNextState {
8162 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8163 wordwise: false,
8164 done: false,
8165 });
8166 self.select_previous(action, cx)?;
8167 }
8168 }
8169 Ok(())
8170 }
8171
8172 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8173 let text_layout_details = &self.text_layout_details(cx);
8174 self.transact(cx, |this, cx| {
8175 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8176 let mut edits = Vec::new();
8177 let mut selection_edit_ranges = Vec::new();
8178 let mut last_toggled_row = None;
8179 let snapshot = this.buffer.read(cx).read(cx);
8180 let empty_str: Arc<str> = Arc::default();
8181 let mut suffixes_inserted = Vec::new();
8182
8183 fn comment_prefix_range(
8184 snapshot: &MultiBufferSnapshot,
8185 row: MultiBufferRow,
8186 comment_prefix: &str,
8187 comment_prefix_whitespace: &str,
8188 ) -> Range<Point> {
8189 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8190
8191 let mut line_bytes = snapshot
8192 .bytes_in_range(start..snapshot.max_point())
8193 .flatten()
8194 .copied();
8195
8196 // If this line currently begins with the line comment prefix, then record
8197 // the range containing the prefix.
8198 if line_bytes
8199 .by_ref()
8200 .take(comment_prefix.len())
8201 .eq(comment_prefix.bytes())
8202 {
8203 // Include any whitespace that matches the comment prefix.
8204 let matching_whitespace_len = line_bytes
8205 .zip(comment_prefix_whitespace.bytes())
8206 .take_while(|(a, b)| a == b)
8207 .count() as u32;
8208 let end = Point::new(
8209 start.row,
8210 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8211 );
8212 start..end
8213 } else {
8214 start..start
8215 }
8216 }
8217
8218 fn comment_suffix_range(
8219 snapshot: &MultiBufferSnapshot,
8220 row: MultiBufferRow,
8221 comment_suffix: &str,
8222 comment_suffix_has_leading_space: bool,
8223 ) -> Range<Point> {
8224 let end = Point::new(row.0, snapshot.line_len(row));
8225 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8226
8227 let mut line_end_bytes = snapshot
8228 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8229 .flatten()
8230 .copied();
8231
8232 let leading_space_len = if suffix_start_column > 0
8233 && line_end_bytes.next() == Some(b' ')
8234 && comment_suffix_has_leading_space
8235 {
8236 1
8237 } else {
8238 0
8239 };
8240
8241 // If this line currently begins with the line comment prefix, then record
8242 // the range containing the prefix.
8243 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8244 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8245 start..end
8246 } else {
8247 end..end
8248 }
8249 }
8250
8251 // TODO: Handle selections that cross excerpts
8252 for selection in &mut selections {
8253 let start_column = snapshot
8254 .indent_size_for_line(MultiBufferRow(selection.start.row))
8255 .len;
8256 let language = if let Some(language) =
8257 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8258 {
8259 language
8260 } else {
8261 continue;
8262 };
8263
8264 selection_edit_ranges.clear();
8265
8266 // If multiple selections contain a given row, avoid processing that
8267 // row more than once.
8268 let mut start_row = MultiBufferRow(selection.start.row);
8269 if last_toggled_row == Some(start_row) {
8270 start_row = start_row.next_row();
8271 }
8272 let end_row =
8273 if selection.end.row > selection.start.row && selection.end.column == 0 {
8274 MultiBufferRow(selection.end.row - 1)
8275 } else {
8276 MultiBufferRow(selection.end.row)
8277 };
8278 last_toggled_row = Some(end_row);
8279
8280 if start_row > end_row {
8281 continue;
8282 }
8283
8284 // If the language has line comments, toggle those.
8285 let full_comment_prefixes = language.line_comment_prefixes();
8286 if !full_comment_prefixes.is_empty() {
8287 let first_prefix = full_comment_prefixes
8288 .first()
8289 .expect("prefixes is non-empty");
8290 let prefix_trimmed_lengths = full_comment_prefixes
8291 .iter()
8292 .map(|p| p.trim_end_matches(' ').len())
8293 .collect::<SmallVec<[usize; 4]>>();
8294
8295 let mut all_selection_lines_are_comments = true;
8296
8297 for row in start_row.0..=end_row.0 {
8298 let row = MultiBufferRow(row);
8299 if start_row < end_row && snapshot.is_line_blank(row) {
8300 continue;
8301 }
8302
8303 let prefix_range = full_comment_prefixes
8304 .iter()
8305 .zip(prefix_trimmed_lengths.iter().copied())
8306 .map(|(prefix, trimmed_prefix_len)| {
8307 comment_prefix_range(
8308 snapshot.deref(),
8309 row,
8310 &prefix[..trimmed_prefix_len],
8311 &prefix[trimmed_prefix_len..],
8312 )
8313 })
8314 .max_by_key(|range| range.end.column - range.start.column)
8315 .expect("prefixes is non-empty");
8316
8317 if prefix_range.is_empty() {
8318 all_selection_lines_are_comments = false;
8319 }
8320
8321 selection_edit_ranges.push(prefix_range);
8322 }
8323
8324 if all_selection_lines_are_comments {
8325 edits.extend(
8326 selection_edit_ranges
8327 .iter()
8328 .cloned()
8329 .map(|range| (range, empty_str.clone())),
8330 );
8331 } else {
8332 let min_column = selection_edit_ranges
8333 .iter()
8334 .map(|range| range.start.column)
8335 .min()
8336 .unwrap_or(0);
8337 edits.extend(selection_edit_ranges.iter().map(|range| {
8338 let position = Point::new(range.start.row, min_column);
8339 (position..position, first_prefix.clone())
8340 }));
8341 }
8342 } else if let Some((full_comment_prefix, comment_suffix)) =
8343 language.block_comment_delimiters()
8344 {
8345 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8346 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8347 let prefix_range = comment_prefix_range(
8348 snapshot.deref(),
8349 start_row,
8350 comment_prefix,
8351 comment_prefix_whitespace,
8352 );
8353 let suffix_range = comment_suffix_range(
8354 snapshot.deref(),
8355 end_row,
8356 comment_suffix.trim_start_matches(' '),
8357 comment_suffix.starts_with(' '),
8358 );
8359
8360 if prefix_range.is_empty() || suffix_range.is_empty() {
8361 edits.push((
8362 prefix_range.start..prefix_range.start,
8363 full_comment_prefix.clone(),
8364 ));
8365 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8366 suffixes_inserted.push((end_row, comment_suffix.len()));
8367 } else {
8368 edits.push((prefix_range, empty_str.clone()));
8369 edits.push((suffix_range, empty_str.clone()));
8370 }
8371 } else {
8372 continue;
8373 }
8374 }
8375
8376 drop(snapshot);
8377 this.buffer.update(cx, |buffer, cx| {
8378 buffer.edit(edits, None, cx);
8379 });
8380
8381 // Adjust selections so that they end before any comment suffixes that
8382 // were inserted.
8383 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8384 let mut selections = this.selections.all::<Point>(cx);
8385 let snapshot = this.buffer.read(cx).read(cx);
8386 for selection in &mut selections {
8387 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8388 match row.cmp(&MultiBufferRow(selection.end.row)) {
8389 Ordering::Less => {
8390 suffixes_inserted.next();
8391 continue;
8392 }
8393 Ordering::Greater => break,
8394 Ordering::Equal => {
8395 if selection.end.column == snapshot.line_len(row) {
8396 if selection.is_empty() {
8397 selection.start.column -= suffix_len as u32;
8398 }
8399 selection.end.column -= suffix_len as u32;
8400 }
8401 break;
8402 }
8403 }
8404 }
8405 }
8406
8407 drop(snapshot);
8408 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8409
8410 let selections = this.selections.all::<Point>(cx);
8411 let selections_on_single_row = selections.windows(2).all(|selections| {
8412 selections[0].start.row == selections[1].start.row
8413 && selections[0].end.row == selections[1].end.row
8414 && selections[0].start.row == selections[0].end.row
8415 });
8416 let selections_selecting = selections
8417 .iter()
8418 .any(|selection| selection.start != selection.end);
8419 let advance_downwards = action.advance_downwards
8420 && selections_on_single_row
8421 && !selections_selecting
8422 && !matches!(this.mode, EditorMode::SingleLine { .. });
8423
8424 if advance_downwards {
8425 let snapshot = this.buffer.read(cx).snapshot(cx);
8426
8427 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8428 s.move_cursors_with(|display_snapshot, display_point, _| {
8429 let mut point = display_point.to_point(display_snapshot);
8430 point.row += 1;
8431 point = snapshot.clip_point(point, Bias::Left);
8432 let display_point = point.to_display_point(display_snapshot);
8433 let goal = SelectionGoal::HorizontalPosition(
8434 display_snapshot
8435 .x_for_display_point(display_point, &text_layout_details)
8436 .into(),
8437 );
8438 (display_point, goal)
8439 })
8440 });
8441 }
8442 });
8443 }
8444
8445 pub fn select_enclosing_symbol(
8446 &mut self,
8447 _: &SelectEnclosingSymbol,
8448 cx: &mut ViewContext<Self>,
8449 ) {
8450 let buffer = self.buffer.read(cx).snapshot(cx);
8451 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8452
8453 fn update_selection(
8454 selection: &Selection<usize>,
8455 buffer_snap: &MultiBufferSnapshot,
8456 ) -> Option<Selection<usize>> {
8457 let cursor = selection.head();
8458 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8459 for symbol in symbols.iter().rev() {
8460 let start = symbol.range.start.to_offset(&buffer_snap);
8461 let end = symbol.range.end.to_offset(&buffer_snap);
8462 let new_range = start..end;
8463 if start < selection.start || end > selection.end {
8464 return Some(Selection {
8465 id: selection.id,
8466 start: new_range.start,
8467 end: new_range.end,
8468 goal: SelectionGoal::None,
8469 reversed: selection.reversed,
8470 });
8471 }
8472 }
8473 None
8474 }
8475
8476 let mut selected_larger_symbol = false;
8477 let new_selections = old_selections
8478 .iter()
8479 .map(|selection| match update_selection(selection, &buffer) {
8480 Some(new_selection) => {
8481 if new_selection.range() != selection.range() {
8482 selected_larger_symbol = true;
8483 }
8484 new_selection
8485 }
8486 None => selection.clone(),
8487 })
8488 .collect::<Vec<_>>();
8489
8490 if selected_larger_symbol {
8491 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8492 s.select(new_selections);
8493 });
8494 }
8495 }
8496
8497 pub fn select_larger_syntax_node(
8498 &mut self,
8499 _: &SelectLargerSyntaxNode,
8500 cx: &mut ViewContext<Self>,
8501 ) {
8502 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8503 let buffer = self.buffer.read(cx).snapshot(cx);
8504 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8505
8506 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8507 let mut selected_larger_node = false;
8508 let new_selections = old_selections
8509 .iter()
8510 .map(|selection| {
8511 let old_range = selection.start..selection.end;
8512 let mut new_range = old_range.clone();
8513 while let Some(containing_range) =
8514 buffer.range_for_syntax_ancestor(new_range.clone())
8515 {
8516 new_range = containing_range;
8517 if !display_map.intersects_fold(new_range.start)
8518 && !display_map.intersects_fold(new_range.end)
8519 {
8520 break;
8521 }
8522 }
8523
8524 selected_larger_node |= new_range != old_range;
8525 Selection {
8526 id: selection.id,
8527 start: new_range.start,
8528 end: new_range.end,
8529 goal: SelectionGoal::None,
8530 reversed: selection.reversed,
8531 }
8532 })
8533 .collect::<Vec<_>>();
8534
8535 if selected_larger_node {
8536 stack.push(old_selections);
8537 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8538 s.select(new_selections);
8539 });
8540 }
8541 self.select_larger_syntax_node_stack = stack;
8542 }
8543
8544 pub fn select_smaller_syntax_node(
8545 &mut self,
8546 _: &SelectSmallerSyntaxNode,
8547 cx: &mut ViewContext<Self>,
8548 ) {
8549 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8550 if let Some(selections) = stack.pop() {
8551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8552 s.select(selections.to_vec());
8553 });
8554 }
8555 self.select_larger_syntax_node_stack = stack;
8556 }
8557
8558 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8559 if !EditorSettings::get_global(cx).gutter.runnables {
8560 self.clear_tasks();
8561 return Task::ready(());
8562 }
8563 let project = self.project.clone();
8564 cx.spawn(|this, mut cx| async move {
8565 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8566 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8567 }) else {
8568 return;
8569 };
8570
8571 let Some(project) = project else {
8572 return;
8573 };
8574
8575 let hide_runnables = project
8576 .update(&mut cx, |project, cx| {
8577 // Do not display any test indicators in non-dev server remote projects.
8578 project.is_remote() && project.ssh_connection_string(cx).is_none()
8579 })
8580 .unwrap_or(true);
8581 if hide_runnables {
8582 return;
8583 }
8584 let new_rows =
8585 cx.background_executor()
8586 .spawn({
8587 let snapshot = display_snapshot.clone();
8588 async move {
8589 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8590 }
8591 })
8592 .await;
8593 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8594
8595 this.update(&mut cx, |this, _| {
8596 this.clear_tasks();
8597 for (key, value) in rows {
8598 this.insert_tasks(key, value);
8599 }
8600 })
8601 .ok();
8602 })
8603 }
8604 fn fetch_runnable_ranges(
8605 snapshot: &DisplaySnapshot,
8606 range: Range<Anchor>,
8607 ) -> Vec<language::RunnableRange> {
8608 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8609 }
8610
8611 fn runnable_rows(
8612 project: Model<Project>,
8613 snapshot: DisplaySnapshot,
8614 runnable_ranges: Vec<RunnableRange>,
8615 mut cx: AsyncWindowContext,
8616 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8617 runnable_ranges
8618 .into_iter()
8619 .filter_map(|mut runnable| {
8620 let tasks = cx
8621 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8622 .ok()?;
8623 if tasks.is_empty() {
8624 return None;
8625 }
8626
8627 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8628
8629 let row = snapshot
8630 .buffer_snapshot
8631 .buffer_line_for_row(MultiBufferRow(point.row))?
8632 .1
8633 .start
8634 .row;
8635
8636 let context_range =
8637 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8638 Some((
8639 (runnable.buffer_id, row),
8640 RunnableTasks {
8641 templates: tasks,
8642 offset: MultiBufferOffset(runnable.run_range.start),
8643 context_range,
8644 column: point.column,
8645 extra_variables: runnable.extra_captures,
8646 },
8647 ))
8648 })
8649 .collect()
8650 }
8651
8652 fn templates_with_tags(
8653 project: &Model<Project>,
8654 runnable: &mut Runnable,
8655 cx: &WindowContext<'_>,
8656 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8657 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8658 let (worktree_id, file) = project
8659 .buffer_for_id(runnable.buffer, cx)
8660 .and_then(|buffer| buffer.read(cx).file())
8661 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8662 .unzip();
8663
8664 (project.task_inventory().clone(), worktree_id, file)
8665 });
8666
8667 let inventory = inventory.read(cx);
8668 let tags = mem::take(&mut runnable.tags);
8669 let mut tags: Vec<_> = tags
8670 .into_iter()
8671 .flat_map(|tag| {
8672 let tag = tag.0.clone();
8673 inventory
8674 .list_tasks(
8675 file.clone(),
8676 Some(runnable.language.clone()),
8677 worktree_id,
8678 cx,
8679 )
8680 .into_iter()
8681 .filter(move |(_, template)| {
8682 template.tags.iter().any(|source_tag| source_tag == &tag)
8683 })
8684 })
8685 .sorted_by_key(|(kind, _)| kind.to_owned())
8686 .collect();
8687 if let Some((leading_tag_source, _)) = tags.first() {
8688 // Strongest source wins; if we have worktree tag binding, prefer that to
8689 // global and language bindings;
8690 // if we have a global binding, prefer that to language binding.
8691 let first_mismatch = tags
8692 .iter()
8693 .position(|(tag_source, _)| tag_source != leading_tag_source);
8694 if let Some(index) = first_mismatch {
8695 tags.truncate(index);
8696 }
8697 }
8698
8699 tags
8700 }
8701
8702 pub fn move_to_enclosing_bracket(
8703 &mut self,
8704 _: &MoveToEnclosingBracket,
8705 cx: &mut ViewContext<Self>,
8706 ) {
8707 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8708 s.move_offsets_with(|snapshot, selection| {
8709 let Some(enclosing_bracket_ranges) =
8710 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8711 else {
8712 return;
8713 };
8714
8715 let mut best_length = usize::MAX;
8716 let mut best_inside = false;
8717 let mut best_in_bracket_range = false;
8718 let mut best_destination = None;
8719 for (open, close) in enclosing_bracket_ranges {
8720 let close = close.to_inclusive();
8721 let length = close.end() - open.start;
8722 let inside = selection.start >= open.end && selection.end <= *close.start();
8723 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8724 || close.contains(&selection.head());
8725
8726 // If best is next to a bracket and current isn't, skip
8727 if !in_bracket_range && best_in_bracket_range {
8728 continue;
8729 }
8730
8731 // Prefer smaller lengths unless best is inside and current isn't
8732 if length > best_length && (best_inside || !inside) {
8733 continue;
8734 }
8735
8736 best_length = length;
8737 best_inside = inside;
8738 best_in_bracket_range = in_bracket_range;
8739 best_destination = Some(
8740 if close.contains(&selection.start) && close.contains(&selection.end) {
8741 if inside {
8742 open.end
8743 } else {
8744 open.start
8745 }
8746 } else {
8747 if inside {
8748 *close.start()
8749 } else {
8750 *close.end()
8751 }
8752 },
8753 );
8754 }
8755
8756 if let Some(destination) = best_destination {
8757 selection.collapse_to(destination, SelectionGoal::None);
8758 }
8759 })
8760 });
8761 }
8762
8763 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8764 self.end_selection(cx);
8765 self.selection_history.mode = SelectionHistoryMode::Undoing;
8766 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8767 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8768 self.select_next_state = entry.select_next_state;
8769 self.select_prev_state = entry.select_prev_state;
8770 self.add_selections_state = entry.add_selections_state;
8771 self.request_autoscroll(Autoscroll::newest(), cx);
8772 }
8773 self.selection_history.mode = SelectionHistoryMode::Normal;
8774 }
8775
8776 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8777 self.end_selection(cx);
8778 self.selection_history.mode = SelectionHistoryMode::Redoing;
8779 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8780 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8781 self.select_next_state = entry.select_next_state;
8782 self.select_prev_state = entry.select_prev_state;
8783 self.add_selections_state = entry.add_selections_state;
8784 self.request_autoscroll(Autoscroll::newest(), cx);
8785 }
8786 self.selection_history.mode = SelectionHistoryMode::Normal;
8787 }
8788
8789 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8790 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8791 }
8792
8793 pub fn expand_excerpts_down(
8794 &mut self,
8795 action: &ExpandExcerptsDown,
8796 cx: &mut ViewContext<Self>,
8797 ) {
8798 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8799 }
8800
8801 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8802 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8803 }
8804
8805 pub fn expand_excerpts_for_direction(
8806 &mut self,
8807 lines: u32,
8808 direction: ExpandExcerptDirection,
8809 cx: &mut ViewContext<Self>,
8810 ) {
8811 let selections = self.selections.disjoint_anchors();
8812
8813 let lines = if lines == 0 {
8814 EditorSettings::get_global(cx).expand_excerpt_lines
8815 } else {
8816 lines
8817 };
8818
8819 self.buffer.update(cx, |buffer, cx| {
8820 buffer.expand_excerpts(
8821 selections
8822 .into_iter()
8823 .map(|selection| selection.head().excerpt_id)
8824 .dedup(),
8825 lines,
8826 direction,
8827 cx,
8828 )
8829 })
8830 }
8831
8832 pub fn expand_excerpt(
8833 &mut self,
8834 excerpt: ExcerptId,
8835 direction: ExpandExcerptDirection,
8836 cx: &mut ViewContext<Self>,
8837 ) {
8838 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8839 self.buffer.update(cx, |buffer, cx| {
8840 buffer.expand_excerpts([excerpt], lines, direction, cx)
8841 })
8842 }
8843
8844 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8845 self.go_to_diagnostic_impl(Direction::Next, cx)
8846 }
8847
8848 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8849 self.go_to_diagnostic_impl(Direction::Prev, cx)
8850 }
8851
8852 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8853 let buffer = self.buffer.read(cx).snapshot(cx);
8854 let selection = self.selections.newest::<usize>(cx);
8855
8856 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8857 if direction == Direction::Next {
8858 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8859 let (group_id, jump_to) = popover.activation_info();
8860 if self.activate_diagnostics(group_id, cx) {
8861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8862 let mut new_selection = s.newest_anchor().clone();
8863 new_selection.collapse_to(jump_to, SelectionGoal::None);
8864 s.select_anchors(vec![new_selection.clone()]);
8865 });
8866 }
8867 return;
8868 }
8869 }
8870
8871 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8872 active_diagnostics
8873 .primary_range
8874 .to_offset(&buffer)
8875 .to_inclusive()
8876 });
8877 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8878 if active_primary_range.contains(&selection.head()) {
8879 *active_primary_range.start()
8880 } else {
8881 selection.head()
8882 }
8883 } else {
8884 selection.head()
8885 };
8886 let snapshot = self.snapshot(cx);
8887 loop {
8888 let diagnostics = if direction == Direction::Prev {
8889 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8890 } else {
8891 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8892 }
8893 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8894 let group = diagnostics
8895 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8896 // be sorted in a stable way
8897 // skip until we are at current active diagnostic, if it exists
8898 .skip_while(|entry| {
8899 (match direction {
8900 Direction::Prev => entry.range.start >= search_start,
8901 Direction::Next => entry.range.start <= search_start,
8902 }) && self
8903 .active_diagnostics
8904 .as_ref()
8905 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8906 })
8907 .find_map(|entry| {
8908 if entry.diagnostic.is_primary
8909 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8910 && !entry.range.is_empty()
8911 // if we match with the active diagnostic, skip it
8912 && Some(entry.diagnostic.group_id)
8913 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8914 {
8915 Some((entry.range, entry.diagnostic.group_id))
8916 } else {
8917 None
8918 }
8919 });
8920
8921 if let Some((primary_range, group_id)) = group {
8922 if self.activate_diagnostics(group_id, cx) {
8923 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8924 s.select(vec![Selection {
8925 id: selection.id,
8926 start: primary_range.start,
8927 end: primary_range.start,
8928 reversed: false,
8929 goal: SelectionGoal::None,
8930 }]);
8931 });
8932 }
8933 break;
8934 } else {
8935 // Cycle around to the start of the buffer, potentially moving back to the start of
8936 // the currently active diagnostic.
8937 active_primary_range.take();
8938 if direction == Direction::Prev {
8939 if search_start == buffer.len() {
8940 break;
8941 } else {
8942 search_start = buffer.len();
8943 }
8944 } else if search_start == 0 {
8945 break;
8946 } else {
8947 search_start = 0;
8948 }
8949 }
8950 }
8951 }
8952
8953 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8954 let snapshot = self
8955 .display_map
8956 .update(cx, |display_map, cx| display_map.snapshot(cx));
8957 let selection = self.selections.newest::<Point>(cx);
8958
8959 if !self.seek_in_direction(
8960 &snapshot,
8961 selection.head(),
8962 false,
8963 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8964 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8965 ),
8966 cx,
8967 ) {
8968 let wrapped_point = Point::zero();
8969 self.seek_in_direction(
8970 &snapshot,
8971 wrapped_point,
8972 true,
8973 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8974 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8975 ),
8976 cx,
8977 );
8978 }
8979 }
8980
8981 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8982 let snapshot = self
8983 .display_map
8984 .update(cx, |display_map, cx| display_map.snapshot(cx));
8985 let selection = self.selections.newest::<Point>(cx);
8986
8987 if !self.seek_in_direction(
8988 &snapshot,
8989 selection.head(),
8990 false,
8991 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8992 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8993 ),
8994 cx,
8995 ) {
8996 let wrapped_point = snapshot.buffer_snapshot.max_point();
8997 self.seek_in_direction(
8998 &snapshot,
8999 wrapped_point,
9000 true,
9001 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9002 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9003 ),
9004 cx,
9005 );
9006 }
9007 }
9008
9009 fn seek_in_direction(
9010 &mut self,
9011 snapshot: &DisplaySnapshot,
9012 initial_point: Point,
9013 is_wrapped: bool,
9014 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9015 cx: &mut ViewContext<Editor>,
9016 ) -> bool {
9017 let display_point = initial_point.to_display_point(snapshot);
9018 let mut hunks = hunks
9019 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9020 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9021 .dedup();
9022
9023 if let Some(hunk) = hunks.next() {
9024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9025 let row = hunk.start_display_row();
9026 let point = DisplayPoint::new(row, 0);
9027 s.select_display_ranges([point..point]);
9028 });
9029
9030 true
9031 } else {
9032 false
9033 }
9034 }
9035
9036 pub fn go_to_definition(
9037 &mut self,
9038 _: &GoToDefinition,
9039 cx: &mut ViewContext<Self>,
9040 ) -> Task<Result<Navigated>> {
9041 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9042 let references = self.find_all_references(&FindAllReferences, cx);
9043 cx.background_executor().spawn(async move {
9044 if definition.await? == Navigated::Yes {
9045 return Ok(Navigated::Yes);
9046 }
9047 if let Some(references) = references {
9048 if references.await? == Navigated::Yes {
9049 return Ok(Navigated::Yes);
9050 }
9051 }
9052
9053 Ok(Navigated::No)
9054 })
9055 }
9056
9057 pub fn go_to_declaration(
9058 &mut self,
9059 _: &GoToDeclaration,
9060 cx: &mut ViewContext<Self>,
9061 ) -> Task<Result<Navigated>> {
9062 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9063 }
9064
9065 pub fn go_to_declaration_split(
9066 &mut self,
9067 _: &GoToDeclaration,
9068 cx: &mut ViewContext<Self>,
9069 ) -> Task<Result<Navigated>> {
9070 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9071 }
9072
9073 pub fn go_to_implementation(
9074 &mut self,
9075 _: &GoToImplementation,
9076 cx: &mut ViewContext<Self>,
9077 ) -> Task<Result<Navigated>> {
9078 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9079 }
9080
9081 pub fn go_to_implementation_split(
9082 &mut self,
9083 _: &GoToImplementationSplit,
9084 cx: &mut ViewContext<Self>,
9085 ) -> Task<Result<Navigated>> {
9086 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9087 }
9088
9089 pub fn go_to_type_definition(
9090 &mut self,
9091 _: &GoToTypeDefinition,
9092 cx: &mut ViewContext<Self>,
9093 ) -> Task<Result<Navigated>> {
9094 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9095 }
9096
9097 pub fn go_to_definition_split(
9098 &mut self,
9099 _: &GoToDefinitionSplit,
9100 cx: &mut ViewContext<Self>,
9101 ) -> Task<Result<Navigated>> {
9102 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9103 }
9104
9105 pub fn go_to_type_definition_split(
9106 &mut self,
9107 _: &GoToTypeDefinitionSplit,
9108 cx: &mut ViewContext<Self>,
9109 ) -> Task<Result<Navigated>> {
9110 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9111 }
9112
9113 fn go_to_definition_of_kind(
9114 &mut self,
9115 kind: GotoDefinitionKind,
9116 split: bool,
9117 cx: &mut ViewContext<Self>,
9118 ) -> Task<Result<Navigated>> {
9119 let Some(workspace) = self.workspace() else {
9120 return Task::ready(Ok(Navigated::No));
9121 };
9122 let buffer = self.buffer.read(cx);
9123 let head = self.selections.newest::<usize>(cx).head();
9124 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9125 text_anchor
9126 } else {
9127 return Task::ready(Ok(Navigated::No));
9128 };
9129
9130 let project = workspace.read(cx).project().clone();
9131 let definitions = project.update(cx, |project, cx| match kind {
9132 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9133 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9134 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9135 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9136 });
9137
9138 cx.spawn(|editor, mut cx| async move {
9139 let definitions = definitions.await?;
9140 let navigated = editor
9141 .update(&mut cx, |editor, cx| {
9142 editor.navigate_to_hover_links(
9143 Some(kind),
9144 definitions
9145 .into_iter()
9146 .filter(|location| {
9147 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9148 })
9149 .map(HoverLink::Text)
9150 .collect::<Vec<_>>(),
9151 split,
9152 cx,
9153 )
9154 })?
9155 .await?;
9156 anyhow::Ok(navigated)
9157 })
9158 }
9159
9160 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9161 let position = self.selections.newest_anchor().head();
9162 let Some((buffer, buffer_position)) =
9163 self.buffer.read(cx).text_anchor_for_position(position, cx)
9164 else {
9165 return;
9166 };
9167
9168 cx.spawn(|editor, mut cx| async move {
9169 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9170 editor.update(&mut cx, |_, cx| {
9171 cx.open_url(&url);
9172 })
9173 } else {
9174 Ok(())
9175 }
9176 })
9177 .detach();
9178 }
9179
9180 pub(crate) fn navigate_to_hover_links(
9181 &mut self,
9182 kind: Option<GotoDefinitionKind>,
9183 mut definitions: Vec<HoverLink>,
9184 split: bool,
9185 cx: &mut ViewContext<Editor>,
9186 ) -> Task<Result<Navigated>> {
9187 // If there is one definition, just open it directly
9188 if definitions.len() == 1 {
9189 let definition = definitions.pop().unwrap();
9190 let target_task = match definition {
9191 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9192 HoverLink::InlayHint(lsp_location, server_id) => {
9193 self.compute_target_location(lsp_location, server_id, cx)
9194 }
9195 HoverLink::Url(url) => {
9196 cx.open_url(&url);
9197 Task::ready(Ok(None))
9198 }
9199 };
9200 cx.spawn(|editor, mut cx| async move {
9201 let target = target_task.await.context("target resolution task")?;
9202 let Some(target) = target else {
9203 return Ok(Navigated::No);
9204 };
9205 editor.update(&mut cx, |editor, cx| {
9206 let Some(workspace) = editor.workspace() else {
9207 return Navigated::No;
9208 };
9209 let pane = workspace.read(cx).active_pane().clone();
9210
9211 let range = target.range.to_offset(target.buffer.read(cx));
9212 let range = editor.range_for_match(&range);
9213
9214 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9215 let buffer = target.buffer.read(cx);
9216 let range = check_multiline_range(buffer, range);
9217 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9218 s.select_ranges([range]);
9219 });
9220 } else {
9221 cx.window_context().defer(move |cx| {
9222 let target_editor: View<Self> =
9223 workspace.update(cx, |workspace, cx| {
9224 let pane = if split {
9225 workspace.adjacent_pane(cx)
9226 } else {
9227 workspace.active_pane().clone()
9228 };
9229
9230 workspace.open_project_item(
9231 pane,
9232 target.buffer.clone(),
9233 true,
9234 true,
9235 cx,
9236 )
9237 });
9238 target_editor.update(cx, |target_editor, cx| {
9239 // When selecting a definition in a different buffer, disable the nav history
9240 // to avoid creating a history entry at the previous cursor location.
9241 pane.update(cx, |pane, _| pane.disable_history());
9242 let buffer = target.buffer.read(cx);
9243 let range = check_multiline_range(buffer, range);
9244 target_editor.change_selections(
9245 Some(Autoscroll::focused()),
9246 cx,
9247 |s| {
9248 s.select_ranges([range]);
9249 },
9250 );
9251 pane.update(cx, |pane, _| pane.enable_history());
9252 });
9253 });
9254 }
9255 Navigated::Yes
9256 })
9257 })
9258 } else if !definitions.is_empty() {
9259 let replica_id = self.replica_id(cx);
9260 cx.spawn(|editor, mut cx| async move {
9261 let (title, location_tasks, workspace) = editor
9262 .update(&mut cx, |editor, cx| {
9263 let tab_kind = match kind {
9264 Some(GotoDefinitionKind::Implementation) => "Implementations",
9265 _ => "Definitions",
9266 };
9267 let title = definitions
9268 .iter()
9269 .find_map(|definition| match definition {
9270 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9271 let buffer = origin.buffer.read(cx);
9272 format!(
9273 "{} for {}",
9274 tab_kind,
9275 buffer
9276 .text_for_range(origin.range.clone())
9277 .collect::<String>()
9278 )
9279 }),
9280 HoverLink::InlayHint(_, _) => None,
9281 HoverLink::Url(_) => None,
9282 })
9283 .unwrap_or(tab_kind.to_string());
9284 let location_tasks = definitions
9285 .into_iter()
9286 .map(|definition| match definition {
9287 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9288 HoverLink::InlayHint(lsp_location, server_id) => {
9289 editor.compute_target_location(lsp_location, server_id, cx)
9290 }
9291 HoverLink::Url(_) => Task::ready(Ok(None)),
9292 })
9293 .collect::<Vec<_>>();
9294 (title, location_tasks, editor.workspace().clone())
9295 })
9296 .context("location tasks preparation")?;
9297
9298 let locations = futures::future::join_all(location_tasks)
9299 .await
9300 .into_iter()
9301 .filter_map(|location| location.transpose())
9302 .collect::<Result<_>>()
9303 .context("location tasks")?;
9304
9305 let Some(workspace) = workspace else {
9306 return Ok(Navigated::No);
9307 };
9308 let opened = workspace
9309 .update(&mut cx, |workspace, cx| {
9310 Self::open_locations_in_multibuffer(
9311 workspace, locations, replica_id, title, split, cx,
9312 )
9313 })
9314 .ok();
9315
9316 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9317 })
9318 } else {
9319 Task::ready(Ok(Navigated::No))
9320 }
9321 }
9322
9323 fn compute_target_location(
9324 &self,
9325 lsp_location: lsp::Location,
9326 server_id: LanguageServerId,
9327 cx: &mut ViewContext<Editor>,
9328 ) -> Task<anyhow::Result<Option<Location>>> {
9329 let Some(project) = self.project.clone() else {
9330 return Task::Ready(Some(Ok(None)));
9331 };
9332
9333 cx.spawn(move |editor, mut cx| async move {
9334 let location_task = editor.update(&mut cx, |editor, cx| {
9335 project.update(cx, |project, cx| {
9336 let language_server_name =
9337 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9338 project
9339 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9340 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9341 });
9342 language_server_name.map(|language_server_name| {
9343 project.open_local_buffer_via_lsp(
9344 lsp_location.uri.clone(),
9345 server_id,
9346 language_server_name,
9347 cx,
9348 )
9349 })
9350 })
9351 })?;
9352 let location = match location_task {
9353 Some(task) => Some({
9354 let target_buffer_handle = task.await.context("open local buffer")?;
9355 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9356 let target_start = target_buffer
9357 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9358 let target_end = target_buffer
9359 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9360 target_buffer.anchor_after(target_start)
9361 ..target_buffer.anchor_before(target_end)
9362 })?;
9363 Location {
9364 buffer: target_buffer_handle,
9365 range,
9366 }
9367 }),
9368 None => None,
9369 };
9370 Ok(location)
9371 })
9372 }
9373
9374 pub fn find_all_references(
9375 &mut self,
9376 _: &FindAllReferences,
9377 cx: &mut ViewContext<Self>,
9378 ) -> Option<Task<Result<Navigated>>> {
9379 let multi_buffer = self.buffer.read(cx);
9380 let selection = self.selections.newest::<usize>(cx);
9381 let head = selection.head();
9382
9383 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9384 let head_anchor = multi_buffer_snapshot.anchor_at(
9385 head,
9386 if head < selection.tail() {
9387 Bias::Right
9388 } else {
9389 Bias::Left
9390 },
9391 );
9392
9393 match self
9394 .find_all_references_task_sources
9395 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9396 {
9397 Ok(_) => {
9398 log::info!(
9399 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9400 );
9401 return None;
9402 }
9403 Err(i) => {
9404 self.find_all_references_task_sources.insert(i, head_anchor);
9405 }
9406 }
9407
9408 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9409 let replica_id = self.replica_id(cx);
9410 let workspace = self.workspace()?;
9411 let project = workspace.read(cx).project().clone();
9412 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9413 Some(cx.spawn(|editor, mut cx| async move {
9414 let _cleanup = defer({
9415 let mut cx = cx.clone();
9416 move || {
9417 let _ = editor.update(&mut cx, |editor, _| {
9418 if let Ok(i) =
9419 editor
9420 .find_all_references_task_sources
9421 .binary_search_by(|anchor| {
9422 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9423 })
9424 {
9425 editor.find_all_references_task_sources.remove(i);
9426 }
9427 });
9428 }
9429 });
9430
9431 let locations = references.await?;
9432 if locations.is_empty() {
9433 return anyhow::Ok(Navigated::No);
9434 }
9435
9436 workspace.update(&mut cx, |workspace, cx| {
9437 let title = locations
9438 .first()
9439 .as_ref()
9440 .map(|location| {
9441 let buffer = location.buffer.read(cx);
9442 format!(
9443 "References to `{}`",
9444 buffer
9445 .text_for_range(location.range.clone())
9446 .collect::<String>()
9447 )
9448 })
9449 .unwrap();
9450 Self::open_locations_in_multibuffer(
9451 workspace, locations, replica_id, title, false, cx,
9452 );
9453 Navigated::Yes
9454 })
9455 }))
9456 }
9457
9458 /// Opens a multibuffer with the given project locations in it
9459 pub fn open_locations_in_multibuffer(
9460 workspace: &mut Workspace,
9461 mut locations: Vec<Location>,
9462 replica_id: ReplicaId,
9463 title: String,
9464 split: bool,
9465 cx: &mut ViewContext<Workspace>,
9466 ) {
9467 // If there are multiple definitions, open them in a multibuffer
9468 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9469 let mut locations = locations.into_iter().peekable();
9470 let mut ranges_to_highlight = Vec::new();
9471 let capability = workspace.project().read(cx).capability();
9472
9473 let excerpt_buffer = cx.new_model(|cx| {
9474 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9475 while let Some(location) = locations.next() {
9476 let buffer = location.buffer.read(cx);
9477 let mut ranges_for_buffer = Vec::new();
9478 let range = location.range.to_offset(buffer);
9479 ranges_for_buffer.push(range.clone());
9480
9481 while let Some(next_location) = locations.peek() {
9482 if next_location.buffer == location.buffer {
9483 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9484 locations.next();
9485 } else {
9486 break;
9487 }
9488 }
9489
9490 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9491 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9492 location.buffer.clone(),
9493 ranges_for_buffer,
9494 DEFAULT_MULTIBUFFER_CONTEXT,
9495 cx,
9496 ))
9497 }
9498
9499 multibuffer.with_title(title)
9500 });
9501
9502 let editor = cx.new_view(|cx| {
9503 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9504 });
9505 editor.update(cx, |editor, cx| {
9506 if let Some(first_range) = ranges_to_highlight.first() {
9507 editor.change_selections(None, cx, |selections| {
9508 selections.clear_disjoint();
9509 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9510 });
9511 }
9512 editor.highlight_background::<Self>(
9513 &ranges_to_highlight,
9514 |theme| theme.editor_highlighted_line_background,
9515 cx,
9516 );
9517 });
9518
9519 let item = Box::new(editor);
9520 let item_id = item.item_id();
9521
9522 if split {
9523 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9524 } else {
9525 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9526 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9527 pane.close_current_preview_item(cx)
9528 } else {
9529 None
9530 }
9531 });
9532 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9533 }
9534 workspace.active_pane().update(cx, |pane, cx| {
9535 pane.set_preview_item_id(Some(item_id), cx);
9536 });
9537 }
9538
9539 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9540 use language::ToOffset as _;
9541
9542 let project = self.project.clone()?;
9543 let selection = self.selections.newest_anchor().clone();
9544 let (cursor_buffer, cursor_buffer_position) = self
9545 .buffer
9546 .read(cx)
9547 .text_anchor_for_position(selection.head(), cx)?;
9548 let (tail_buffer, cursor_buffer_position_end) = self
9549 .buffer
9550 .read(cx)
9551 .text_anchor_for_position(selection.tail(), cx)?;
9552 if tail_buffer != cursor_buffer {
9553 return None;
9554 }
9555
9556 let snapshot = cursor_buffer.read(cx).snapshot();
9557 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9558 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9559 let prepare_rename = project.update(cx, |project, cx| {
9560 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9561 });
9562 drop(snapshot);
9563
9564 Some(cx.spawn(|this, mut cx| async move {
9565 let rename_range = if let Some(range) = prepare_rename.await? {
9566 Some(range)
9567 } else {
9568 this.update(&mut cx, |this, cx| {
9569 let buffer = this.buffer.read(cx).snapshot(cx);
9570 let mut buffer_highlights = this
9571 .document_highlights_for_position(selection.head(), &buffer)
9572 .filter(|highlight| {
9573 highlight.start.excerpt_id == selection.head().excerpt_id
9574 && highlight.end.excerpt_id == selection.head().excerpt_id
9575 });
9576 buffer_highlights
9577 .next()
9578 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9579 })?
9580 };
9581 if let Some(rename_range) = rename_range {
9582 this.update(&mut cx, |this, cx| {
9583 let snapshot = cursor_buffer.read(cx).snapshot();
9584 let rename_buffer_range = rename_range.to_offset(&snapshot);
9585 let cursor_offset_in_rename_range =
9586 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9587 let cursor_offset_in_rename_range_end =
9588 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9589
9590 this.take_rename(false, cx);
9591 let buffer = this.buffer.read(cx).read(cx);
9592 let cursor_offset = selection.head().to_offset(&buffer);
9593 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9594 let rename_end = rename_start + rename_buffer_range.len();
9595 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9596 let mut old_highlight_id = None;
9597 let old_name: Arc<str> = buffer
9598 .chunks(rename_start..rename_end, true)
9599 .map(|chunk| {
9600 if old_highlight_id.is_none() {
9601 old_highlight_id = chunk.syntax_highlight_id;
9602 }
9603 chunk.text
9604 })
9605 .collect::<String>()
9606 .into();
9607
9608 drop(buffer);
9609
9610 // Position the selection in the rename editor so that it matches the current selection.
9611 this.show_local_selections = false;
9612 let rename_editor = cx.new_view(|cx| {
9613 let mut editor = Editor::single_line(cx);
9614 editor.buffer.update(cx, |buffer, cx| {
9615 buffer.edit([(0..0, old_name.clone())], None, cx)
9616 });
9617 let rename_selection_range = match cursor_offset_in_rename_range
9618 .cmp(&cursor_offset_in_rename_range_end)
9619 {
9620 Ordering::Equal => {
9621 editor.select_all(&SelectAll, cx);
9622 return editor;
9623 }
9624 Ordering::Less => {
9625 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9626 }
9627 Ordering::Greater => {
9628 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9629 }
9630 };
9631 if rename_selection_range.end > old_name.len() {
9632 editor.select_all(&SelectAll, cx);
9633 } else {
9634 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9635 s.select_ranges([rename_selection_range]);
9636 });
9637 }
9638 editor
9639 });
9640 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9641 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9642 _ => {}
9643 })
9644 .detach();
9645
9646 let write_highlights =
9647 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9648 let read_highlights =
9649 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9650 let ranges = write_highlights
9651 .iter()
9652 .flat_map(|(_, ranges)| ranges.iter())
9653 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9654 .cloned()
9655 .collect();
9656
9657 this.highlight_text::<Rename>(
9658 ranges,
9659 HighlightStyle {
9660 fade_out: Some(0.6),
9661 ..Default::default()
9662 },
9663 cx,
9664 );
9665 let rename_focus_handle = rename_editor.focus_handle(cx);
9666 cx.focus(&rename_focus_handle);
9667 let block_id = this.insert_blocks(
9668 [BlockProperties {
9669 style: BlockStyle::Flex,
9670 position: range.start,
9671 height: 1,
9672 render: Box::new({
9673 let rename_editor = rename_editor.clone();
9674 move |cx: &mut BlockContext| {
9675 let mut text_style = cx.editor_style.text.clone();
9676 if let Some(highlight_style) = old_highlight_id
9677 .and_then(|h| h.style(&cx.editor_style.syntax))
9678 {
9679 text_style = text_style.highlight(highlight_style);
9680 }
9681 div()
9682 .pl(cx.anchor_x)
9683 .child(EditorElement::new(
9684 &rename_editor,
9685 EditorStyle {
9686 background: cx.theme().system().transparent,
9687 local_player: cx.editor_style.local_player,
9688 text: text_style,
9689 scrollbar_width: cx.editor_style.scrollbar_width,
9690 syntax: cx.editor_style.syntax.clone(),
9691 status: cx.editor_style.status.clone(),
9692 inlay_hints_style: HighlightStyle {
9693 color: Some(cx.theme().status().hint),
9694 font_weight: Some(FontWeight::BOLD),
9695 ..HighlightStyle::default()
9696 },
9697 suggestions_style: HighlightStyle {
9698 color: Some(cx.theme().status().predictive),
9699 ..HighlightStyle::default()
9700 },
9701 ..EditorStyle::default()
9702 },
9703 ))
9704 .into_any_element()
9705 }
9706 }),
9707 disposition: BlockDisposition::Below,
9708 priority: 0,
9709 }],
9710 Some(Autoscroll::fit()),
9711 cx,
9712 )[0];
9713 this.pending_rename = Some(RenameState {
9714 range,
9715 old_name,
9716 editor: rename_editor,
9717 block_id,
9718 });
9719 })?;
9720 }
9721
9722 Ok(())
9723 }))
9724 }
9725
9726 pub fn confirm_rename(
9727 &mut self,
9728 _: &ConfirmRename,
9729 cx: &mut ViewContext<Self>,
9730 ) -> Option<Task<Result<()>>> {
9731 let rename = self.take_rename(false, cx)?;
9732 let workspace = self.workspace()?;
9733 let (start_buffer, start) = self
9734 .buffer
9735 .read(cx)
9736 .text_anchor_for_position(rename.range.start, cx)?;
9737 let (end_buffer, end) = self
9738 .buffer
9739 .read(cx)
9740 .text_anchor_for_position(rename.range.end, cx)?;
9741 if start_buffer != end_buffer {
9742 return None;
9743 }
9744
9745 let buffer = start_buffer;
9746 let range = start..end;
9747 let old_name = rename.old_name;
9748 let new_name = rename.editor.read(cx).text(cx);
9749
9750 let rename = workspace
9751 .read(cx)
9752 .project()
9753 .clone()
9754 .update(cx, |project, cx| {
9755 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9756 });
9757 let workspace = workspace.downgrade();
9758
9759 Some(cx.spawn(|editor, mut cx| async move {
9760 let project_transaction = rename.await?;
9761 Self::open_project_transaction(
9762 &editor,
9763 workspace,
9764 project_transaction,
9765 format!("Rename: {} → {}", old_name, new_name),
9766 cx.clone(),
9767 )
9768 .await?;
9769
9770 editor.update(&mut cx, |editor, cx| {
9771 editor.refresh_document_highlights(cx);
9772 })?;
9773 Ok(())
9774 }))
9775 }
9776
9777 fn take_rename(
9778 &mut self,
9779 moving_cursor: bool,
9780 cx: &mut ViewContext<Self>,
9781 ) -> Option<RenameState> {
9782 let rename = self.pending_rename.take()?;
9783 if rename.editor.focus_handle(cx).is_focused(cx) {
9784 cx.focus(&self.focus_handle);
9785 }
9786
9787 self.remove_blocks(
9788 [rename.block_id].into_iter().collect(),
9789 Some(Autoscroll::fit()),
9790 cx,
9791 );
9792 self.clear_highlights::<Rename>(cx);
9793 self.show_local_selections = true;
9794
9795 if moving_cursor {
9796 let rename_editor = rename.editor.read(cx);
9797 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9798
9799 // Update the selection to match the position of the selection inside
9800 // the rename editor.
9801 let snapshot = self.buffer.read(cx).read(cx);
9802 let rename_range = rename.range.to_offset(&snapshot);
9803 let cursor_in_editor = snapshot
9804 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9805 .min(rename_range.end);
9806 drop(snapshot);
9807
9808 self.change_selections(None, cx, |s| {
9809 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9810 });
9811 } else {
9812 self.refresh_document_highlights(cx);
9813 }
9814
9815 Some(rename)
9816 }
9817
9818 pub fn pending_rename(&self) -> Option<&RenameState> {
9819 self.pending_rename.as_ref()
9820 }
9821
9822 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9823 let project = match &self.project {
9824 Some(project) => project.clone(),
9825 None => return None,
9826 };
9827
9828 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9829 }
9830
9831 fn perform_format(
9832 &mut self,
9833 project: Model<Project>,
9834 trigger: FormatTrigger,
9835 cx: &mut ViewContext<Self>,
9836 ) -> Task<Result<()>> {
9837 let buffer = self.buffer().clone();
9838 let mut buffers = buffer.read(cx).all_buffers();
9839 if trigger == FormatTrigger::Save {
9840 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9841 }
9842
9843 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9844 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9845
9846 cx.spawn(|_, mut cx| async move {
9847 let transaction = futures::select_biased! {
9848 () = timeout => {
9849 log::warn!("timed out waiting for formatting");
9850 None
9851 }
9852 transaction = format.log_err().fuse() => transaction,
9853 };
9854
9855 buffer
9856 .update(&mut cx, |buffer, cx| {
9857 if let Some(transaction) = transaction {
9858 if !buffer.is_singleton() {
9859 buffer.push_transaction(&transaction.0, cx);
9860 }
9861 }
9862
9863 cx.notify();
9864 })
9865 .ok();
9866
9867 Ok(())
9868 })
9869 }
9870
9871 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9872 if let Some(project) = self.project.clone() {
9873 self.buffer.update(cx, |multi_buffer, cx| {
9874 project.update(cx, |project, cx| {
9875 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9876 });
9877 })
9878 }
9879 }
9880
9881 fn cancel_language_server_work(
9882 &mut self,
9883 _: &CancelLanguageServerWork,
9884 cx: &mut ViewContext<Self>,
9885 ) {
9886 if let Some(project) = self.project.clone() {
9887 self.buffer.update(cx, |multi_buffer, cx| {
9888 project.update(cx, |project, cx| {
9889 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9890 });
9891 })
9892 }
9893 }
9894
9895 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9896 cx.show_character_palette();
9897 }
9898
9899 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9900 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9901 let buffer = self.buffer.read(cx).snapshot(cx);
9902 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9903 let is_valid = buffer
9904 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9905 .any(|entry| {
9906 entry.diagnostic.is_primary
9907 && !entry.range.is_empty()
9908 && entry.range.start == primary_range_start
9909 && entry.diagnostic.message == active_diagnostics.primary_message
9910 });
9911
9912 if is_valid != active_diagnostics.is_valid {
9913 active_diagnostics.is_valid = is_valid;
9914 let mut new_styles = HashMap::default();
9915 for (block_id, diagnostic) in &active_diagnostics.blocks {
9916 new_styles.insert(
9917 *block_id,
9918 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9919 );
9920 }
9921 self.display_map.update(cx, |display_map, _cx| {
9922 display_map.replace_blocks(new_styles)
9923 });
9924 }
9925 }
9926 }
9927
9928 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9929 self.dismiss_diagnostics(cx);
9930 let snapshot = self.snapshot(cx);
9931 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9932 let buffer = self.buffer.read(cx).snapshot(cx);
9933
9934 let mut primary_range = None;
9935 let mut primary_message = None;
9936 let mut group_end = Point::zero();
9937 let diagnostic_group = buffer
9938 .diagnostic_group::<MultiBufferPoint>(group_id)
9939 .filter_map(|entry| {
9940 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9941 && (entry.range.start.row == entry.range.end.row
9942 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9943 {
9944 return None;
9945 }
9946 if entry.range.end > group_end {
9947 group_end = entry.range.end;
9948 }
9949 if entry.diagnostic.is_primary {
9950 primary_range = Some(entry.range.clone());
9951 primary_message = Some(entry.diagnostic.message.clone());
9952 }
9953 Some(entry)
9954 })
9955 .collect::<Vec<_>>();
9956 let primary_range = primary_range?;
9957 let primary_message = primary_message?;
9958 let primary_range =
9959 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9960
9961 let blocks = display_map
9962 .insert_blocks(
9963 diagnostic_group.iter().map(|entry| {
9964 let diagnostic = entry.diagnostic.clone();
9965 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
9966 BlockProperties {
9967 style: BlockStyle::Fixed,
9968 position: buffer.anchor_after(entry.range.start),
9969 height: message_height,
9970 render: diagnostic_block_renderer(diagnostic, None, true, true),
9971 disposition: BlockDisposition::Below,
9972 priority: 0,
9973 }
9974 }),
9975 cx,
9976 )
9977 .into_iter()
9978 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9979 .collect();
9980
9981 Some(ActiveDiagnosticGroup {
9982 primary_range,
9983 primary_message,
9984 group_id,
9985 blocks,
9986 is_valid: true,
9987 })
9988 });
9989 self.active_diagnostics.is_some()
9990 }
9991
9992 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9993 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9994 self.display_map.update(cx, |display_map, cx| {
9995 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9996 });
9997 cx.notify();
9998 }
9999 }
10000
10001 pub fn set_selections_from_remote(
10002 &mut self,
10003 selections: Vec<Selection<Anchor>>,
10004 pending_selection: Option<Selection<Anchor>>,
10005 cx: &mut ViewContext<Self>,
10006 ) {
10007 let old_cursor_position = self.selections.newest_anchor().head();
10008 self.selections.change_with(cx, |s| {
10009 s.select_anchors(selections);
10010 if let Some(pending_selection) = pending_selection {
10011 s.set_pending(pending_selection, SelectMode::Character);
10012 } else {
10013 s.clear_pending();
10014 }
10015 });
10016 self.selections_did_change(false, &old_cursor_position, true, cx);
10017 }
10018
10019 fn push_to_selection_history(&mut self) {
10020 self.selection_history.push(SelectionHistoryEntry {
10021 selections: self.selections.disjoint_anchors(),
10022 select_next_state: self.select_next_state.clone(),
10023 select_prev_state: self.select_prev_state.clone(),
10024 add_selections_state: self.add_selections_state.clone(),
10025 });
10026 }
10027
10028 pub fn transact(
10029 &mut self,
10030 cx: &mut ViewContext<Self>,
10031 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10032 ) -> Option<TransactionId> {
10033 self.start_transaction_at(Instant::now(), cx);
10034 update(self, cx);
10035 self.end_transaction_at(Instant::now(), cx)
10036 }
10037
10038 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10039 self.end_selection(cx);
10040 if let Some(tx_id) = self
10041 .buffer
10042 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10043 {
10044 self.selection_history
10045 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10046 cx.emit(EditorEvent::TransactionBegun {
10047 transaction_id: tx_id,
10048 })
10049 }
10050 }
10051
10052 fn end_transaction_at(
10053 &mut self,
10054 now: Instant,
10055 cx: &mut ViewContext<Self>,
10056 ) -> Option<TransactionId> {
10057 if let Some(transaction_id) = self
10058 .buffer
10059 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10060 {
10061 if let Some((_, end_selections)) =
10062 self.selection_history.transaction_mut(transaction_id)
10063 {
10064 *end_selections = Some(self.selections.disjoint_anchors());
10065 } else {
10066 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10067 }
10068
10069 cx.emit(EditorEvent::Edited { transaction_id });
10070 Some(transaction_id)
10071 } else {
10072 None
10073 }
10074 }
10075
10076 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10077 let mut fold_ranges = Vec::new();
10078
10079 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10080
10081 let selections = self.selections.all_adjusted(cx);
10082 for selection in selections {
10083 let range = selection.range().sorted();
10084 let buffer_start_row = range.start.row;
10085
10086 for row in (0..=range.end.row).rev() {
10087 if let Some((foldable_range, fold_text)) =
10088 display_map.foldable_range(MultiBufferRow(row))
10089 {
10090 if foldable_range.end.row >= buffer_start_row {
10091 fold_ranges.push((foldable_range, fold_text));
10092 if row <= range.start.row {
10093 break;
10094 }
10095 }
10096 }
10097 }
10098 }
10099
10100 self.fold_ranges(fold_ranges, true, cx);
10101 }
10102
10103 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10104 let buffer_row = fold_at.buffer_row;
10105 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10106
10107 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10108 let autoscroll = self
10109 .selections
10110 .all::<Point>(cx)
10111 .iter()
10112 .any(|selection| fold_range.overlaps(&selection.range()));
10113
10114 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10115 }
10116 }
10117
10118 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10119 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10120 let buffer = &display_map.buffer_snapshot;
10121 let selections = self.selections.all::<Point>(cx);
10122 let ranges = selections
10123 .iter()
10124 .map(|s| {
10125 let range = s.display_range(&display_map).sorted();
10126 let mut start = range.start.to_point(&display_map);
10127 let mut end = range.end.to_point(&display_map);
10128 start.column = 0;
10129 end.column = buffer.line_len(MultiBufferRow(end.row));
10130 start..end
10131 })
10132 .collect::<Vec<_>>();
10133
10134 self.unfold_ranges(ranges, true, true, cx);
10135 }
10136
10137 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10138 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10139
10140 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10141 ..Point::new(
10142 unfold_at.buffer_row.0,
10143 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10144 );
10145
10146 let autoscroll = self
10147 .selections
10148 .all::<Point>(cx)
10149 .iter()
10150 .any(|selection| selection.range().overlaps(&intersection_range));
10151
10152 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10153 }
10154
10155 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10156 let selections = self.selections.all::<Point>(cx);
10157 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10158 let line_mode = self.selections.line_mode;
10159 let ranges = selections.into_iter().map(|s| {
10160 if line_mode {
10161 let start = Point::new(s.start.row, 0);
10162 let end = Point::new(
10163 s.end.row,
10164 display_map
10165 .buffer_snapshot
10166 .line_len(MultiBufferRow(s.end.row)),
10167 );
10168 (start..end, display_map.fold_placeholder.clone())
10169 } else {
10170 (s.start..s.end, display_map.fold_placeholder.clone())
10171 }
10172 });
10173 self.fold_ranges(ranges, true, cx);
10174 }
10175
10176 pub fn fold_ranges<T: ToOffset + Clone>(
10177 &mut self,
10178 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10179 auto_scroll: bool,
10180 cx: &mut ViewContext<Self>,
10181 ) {
10182 let mut fold_ranges = Vec::new();
10183 let mut buffers_affected = HashMap::default();
10184 let multi_buffer = self.buffer().read(cx);
10185 for (fold_range, fold_text) in ranges {
10186 if let Some((_, buffer, _)) =
10187 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10188 {
10189 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10190 };
10191 fold_ranges.push((fold_range, fold_text));
10192 }
10193
10194 let mut ranges = fold_ranges.into_iter().peekable();
10195 if ranges.peek().is_some() {
10196 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10197
10198 if auto_scroll {
10199 self.request_autoscroll(Autoscroll::fit(), cx);
10200 }
10201
10202 for buffer in buffers_affected.into_values() {
10203 self.sync_expanded_diff_hunks(buffer, cx);
10204 }
10205
10206 cx.notify();
10207
10208 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10209 // Clear diagnostics block when folding a range that contains it.
10210 let snapshot = self.snapshot(cx);
10211 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10212 drop(snapshot);
10213 self.active_diagnostics = Some(active_diagnostics);
10214 self.dismiss_diagnostics(cx);
10215 } else {
10216 self.active_diagnostics = Some(active_diagnostics);
10217 }
10218 }
10219
10220 self.scrollbar_marker_state.dirty = true;
10221 }
10222 }
10223
10224 pub fn unfold_ranges<T: ToOffset + Clone>(
10225 &mut self,
10226 ranges: impl IntoIterator<Item = Range<T>>,
10227 inclusive: bool,
10228 auto_scroll: bool,
10229 cx: &mut ViewContext<Self>,
10230 ) {
10231 let mut unfold_ranges = Vec::new();
10232 let mut buffers_affected = HashMap::default();
10233 let multi_buffer = self.buffer().read(cx);
10234 for range in ranges {
10235 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10236 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10237 };
10238 unfold_ranges.push(range);
10239 }
10240
10241 let mut ranges = unfold_ranges.into_iter().peekable();
10242 if ranges.peek().is_some() {
10243 self.display_map
10244 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10245 if auto_scroll {
10246 self.request_autoscroll(Autoscroll::fit(), cx);
10247 }
10248
10249 for buffer in buffers_affected.into_values() {
10250 self.sync_expanded_diff_hunks(buffer, cx);
10251 }
10252
10253 cx.notify();
10254 self.scrollbar_marker_state.dirty = true;
10255 self.active_indent_guides_state.dirty = true;
10256 }
10257 }
10258
10259 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10260 if hovered != self.gutter_hovered {
10261 self.gutter_hovered = hovered;
10262 cx.notify();
10263 }
10264 }
10265
10266 pub fn insert_blocks(
10267 &mut self,
10268 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10269 autoscroll: Option<Autoscroll>,
10270 cx: &mut ViewContext<Self>,
10271 ) -> Vec<CustomBlockId> {
10272 let blocks = self
10273 .display_map
10274 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10275 if let Some(autoscroll) = autoscroll {
10276 self.request_autoscroll(autoscroll, cx);
10277 }
10278 cx.notify();
10279 blocks
10280 }
10281
10282 pub fn resize_blocks(
10283 &mut self,
10284 heights: HashMap<CustomBlockId, u32>,
10285 autoscroll: Option<Autoscroll>,
10286 cx: &mut ViewContext<Self>,
10287 ) {
10288 self.display_map
10289 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10290 if let Some(autoscroll) = autoscroll {
10291 self.request_autoscroll(autoscroll, cx);
10292 }
10293 cx.notify();
10294 }
10295
10296 pub fn replace_blocks(
10297 &mut self,
10298 renderers: HashMap<CustomBlockId, RenderBlock>,
10299 autoscroll: Option<Autoscroll>,
10300 cx: &mut ViewContext<Self>,
10301 ) {
10302 self.display_map
10303 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10304 if let Some(autoscroll) = autoscroll {
10305 self.request_autoscroll(autoscroll, cx);
10306 }
10307 cx.notify();
10308 }
10309
10310 pub fn remove_blocks(
10311 &mut self,
10312 block_ids: HashSet<CustomBlockId>,
10313 autoscroll: Option<Autoscroll>,
10314 cx: &mut ViewContext<Self>,
10315 ) {
10316 self.display_map.update(cx, |display_map, cx| {
10317 display_map.remove_blocks(block_ids, cx)
10318 });
10319 if let Some(autoscroll) = autoscroll {
10320 self.request_autoscroll(autoscroll, cx);
10321 }
10322 cx.notify();
10323 }
10324
10325 pub fn row_for_block(
10326 &self,
10327 block_id: CustomBlockId,
10328 cx: &mut ViewContext<Self>,
10329 ) -> Option<DisplayRow> {
10330 self.display_map
10331 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10332 }
10333
10334 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10335 self.focused_block = Some(focused_block);
10336 }
10337
10338 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10339 self.focused_block.take()
10340 }
10341
10342 pub fn insert_creases(
10343 &mut self,
10344 creases: impl IntoIterator<Item = Crease>,
10345 cx: &mut ViewContext<Self>,
10346 ) -> Vec<CreaseId> {
10347 self.display_map
10348 .update(cx, |map, cx| map.insert_creases(creases, cx))
10349 }
10350
10351 pub fn remove_creases(
10352 &mut self,
10353 ids: impl IntoIterator<Item = CreaseId>,
10354 cx: &mut ViewContext<Self>,
10355 ) {
10356 self.display_map
10357 .update(cx, |map, cx| map.remove_creases(ids, cx));
10358 }
10359
10360 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10361 self.display_map
10362 .update(cx, |map, cx| map.snapshot(cx))
10363 .longest_row()
10364 }
10365
10366 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10367 self.display_map
10368 .update(cx, |map, cx| map.snapshot(cx))
10369 .max_point()
10370 }
10371
10372 pub fn text(&self, cx: &AppContext) -> String {
10373 self.buffer.read(cx).read(cx).text()
10374 }
10375
10376 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10377 let text = self.text(cx);
10378 let text = text.trim();
10379
10380 if text.is_empty() {
10381 return None;
10382 }
10383
10384 Some(text.to_string())
10385 }
10386
10387 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10388 self.transact(cx, |this, cx| {
10389 this.buffer
10390 .read(cx)
10391 .as_singleton()
10392 .expect("you can only call set_text on editors for singleton buffers")
10393 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10394 });
10395 }
10396
10397 pub fn display_text(&self, cx: &mut AppContext) -> String {
10398 self.display_map
10399 .update(cx, |map, cx| map.snapshot(cx))
10400 .text()
10401 }
10402
10403 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10404 let mut wrap_guides = smallvec::smallvec![];
10405
10406 if self.show_wrap_guides == Some(false) {
10407 return wrap_guides;
10408 }
10409
10410 let settings = self.buffer.read(cx).settings_at(0, cx);
10411 if settings.show_wrap_guides {
10412 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10413 wrap_guides.push((soft_wrap as usize, true));
10414 }
10415 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10416 }
10417
10418 wrap_guides
10419 }
10420
10421 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10422 let settings = self.buffer.read(cx).settings_at(0, cx);
10423 let mode = self
10424 .soft_wrap_mode_override
10425 .unwrap_or_else(|| settings.soft_wrap);
10426 match mode {
10427 language_settings::SoftWrap::None => SoftWrap::None,
10428 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10429 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10430 language_settings::SoftWrap::PreferredLineLength => {
10431 SoftWrap::Column(settings.preferred_line_length)
10432 }
10433 }
10434 }
10435
10436 pub fn set_soft_wrap_mode(
10437 &mut self,
10438 mode: language_settings::SoftWrap,
10439 cx: &mut ViewContext<Self>,
10440 ) {
10441 self.soft_wrap_mode_override = Some(mode);
10442 cx.notify();
10443 }
10444
10445 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10446 let rem_size = cx.rem_size();
10447 self.display_map.update(cx, |map, cx| {
10448 map.set_font(
10449 style.text.font(),
10450 style.text.font_size.to_pixels(rem_size),
10451 cx,
10452 )
10453 });
10454 self.style = Some(style);
10455 }
10456
10457 pub fn style(&self) -> Option<&EditorStyle> {
10458 self.style.as_ref()
10459 }
10460
10461 // Called by the element. This method is not designed to be called outside of the editor
10462 // element's layout code because it does not notify when rewrapping is computed synchronously.
10463 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10464 self.display_map
10465 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10466 }
10467
10468 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10469 if self.soft_wrap_mode_override.is_some() {
10470 self.soft_wrap_mode_override.take();
10471 } else {
10472 let soft_wrap = match self.soft_wrap_mode(cx) {
10473 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10474 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10475 language_settings::SoftWrap::PreferLine
10476 }
10477 };
10478 self.soft_wrap_mode_override = Some(soft_wrap);
10479 }
10480 cx.notify();
10481 }
10482
10483 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10484 let Some(workspace) = self.workspace() else {
10485 return;
10486 };
10487 let fs = workspace.read(cx).app_state().fs.clone();
10488 let current_show = TabBarSettings::get_global(cx).show;
10489 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10490 setting.show = Some(!current_show);
10491 });
10492 }
10493
10494 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10495 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10496 self.buffer
10497 .read(cx)
10498 .settings_at(0, cx)
10499 .indent_guides
10500 .enabled
10501 });
10502 self.show_indent_guides = Some(!currently_enabled);
10503 cx.notify();
10504 }
10505
10506 fn should_show_indent_guides(&self) -> Option<bool> {
10507 self.show_indent_guides
10508 }
10509
10510 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10511 let mut editor_settings = EditorSettings::get_global(cx).clone();
10512 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10513 EditorSettings::override_global(editor_settings, cx);
10514 }
10515
10516 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10517 self.show_gutter = show_gutter;
10518 cx.notify();
10519 }
10520
10521 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10522 self.show_line_numbers = Some(show_line_numbers);
10523 cx.notify();
10524 }
10525
10526 pub fn set_show_git_diff_gutter(
10527 &mut self,
10528 show_git_diff_gutter: bool,
10529 cx: &mut ViewContext<Self>,
10530 ) {
10531 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10532 cx.notify();
10533 }
10534
10535 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10536 self.show_code_actions = Some(show_code_actions);
10537 cx.notify();
10538 }
10539
10540 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10541 self.show_runnables = Some(show_runnables);
10542 cx.notify();
10543 }
10544
10545 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10546 if self.display_map.read(cx).masked != masked {
10547 self.display_map.update(cx, |map, _| map.masked = masked);
10548 }
10549 cx.notify()
10550 }
10551
10552 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10553 self.show_wrap_guides = Some(show_wrap_guides);
10554 cx.notify();
10555 }
10556
10557 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10558 self.show_indent_guides = Some(show_indent_guides);
10559 cx.notify();
10560 }
10561
10562 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10563 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10564 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10565 if let Some(dir) = file.abs_path(cx).parent() {
10566 return Some(dir.to_owned());
10567 }
10568 }
10569
10570 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10571 return Some(project_path.path.to_path_buf());
10572 }
10573 }
10574
10575 None
10576 }
10577
10578 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10579 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10580 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10581 cx.reveal_path(&file.abs_path(cx));
10582 }
10583 }
10584 }
10585
10586 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10587 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10588 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10589 if let Some(path) = file.abs_path(cx).to_str() {
10590 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10591 }
10592 }
10593 }
10594 }
10595
10596 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10597 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10598 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10599 if let Some(path) = file.path().to_str() {
10600 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10601 }
10602 }
10603 }
10604 }
10605
10606 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10607 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10608
10609 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10610 self.start_git_blame(true, cx);
10611 }
10612
10613 cx.notify();
10614 }
10615
10616 pub fn toggle_git_blame_inline(
10617 &mut self,
10618 _: &ToggleGitBlameInline,
10619 cx: &mut ViewContext<Self>,
10620 ) {
10621 self.toggle_git_blame_inline_internal(true, cx);
10622 cx.notify();
10623 }
10624
10625 pub fn git_blame_inline_enabled(&self) -> bool {
10626 self.git_blame_inline_enabled
10627 }
10628
10629 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10630 self.show_selection_menu = self
10631 .show_selection_menu
10632 .map(|show_selections_menu| !show_selections_menu)
10633 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10634
10635 cx.notify();
10636 }
10637
10638 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10639 self.show_selection_menu
10640 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10641 }
10642
10643 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10644 if let Some(project) = self.project.as_ref() {
10645 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10646 return;
10647 };
10648
10649 if buffer.read(cx).file().is_none() {
10650 return;
10651 }
10652
10653 let focused = self.focus_handle(cx).contains_focused(cx);
10654
10655 let project = project.clone();
10656 let blame =
10657 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10658 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10659 self.blame = Some(blame);
10660 }
10661 }
10662
10663 fn toggle_git_blame_inline_internal(
10664 &mut self,
10665 user_triggered: bool,
10666 cx: &mut ViewContext<Self>,
10667 ) {
10668 if self.git_blame_inline_enabled {
10669 self.git_blame_inline_enabled = false;
10670 self.show_git_blame_inline = false;
10671 self.show_git_blame_inline_delay_task.take();
10672 } else {
10673 self.git_blame_inline_enabled = true;
10674 self.start_git_blame_inline(user_triggered, cx);
10675 }
10676
10677 cx.notify();
10678 }
10679
10680 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10681 self.start_git_blame(user_triggered, cx);
10682
10683 if ProjectSettings::get_global(cx)
10684 .git
10685 .inline_blame_delay()
10686 .is_some()
10687 {
10688 self.start_inline_blame_timer(cx);
10689 } else {
10690 self.show_git_blame_inline = true
10691 }
10692 }
10693
10694 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10695 self.blame.as_ref()
10696 }
10697
10698 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10699 self.show_git_blame_gutter && self.has_blame_entries(cx)
10700 }
10701
10702 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10703 self.show_git_blame_inline
10704 && self.focus_handle.is_focused(cx)
10705 && !self.newest_selection_head_on_empty_line(cx)
10706 && self.has_blame_entries(cx)
10707 }
10708
10709 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10710 self.blame()
10711 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10712 }
10713
10714 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10715 let cursor_anchor = self.selections.newest_anchor().head();
10716
10717 let snapshot = self.buffer.read(cx).snapshot(cx);
10718 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10719
10720 snapshot.line_len(buffer_row) == 0
10721 }
10722
10723 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10724 let (path, selection, repo) = maybe!({
10725 let project_handle = self.project.as_ref()?.clone();
10726 let project = project_handle.read(cx);
10727
10728 let selection = self.selections.newest::<Point>(cx);
10729 let selection_range = selection.range();
10730
10731 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10732 (buffer, selection_range.start.row..selection_range.end.row)
10733 } else {
10734 let buffer_ranges = self
10735 .buffer()
10736 .read(cx)
10737 .range_to_buffer_ranges(selection_range, cx);
10738
10739 let (buffer, range, _) = if selection.reversed {
10740 buffer_ranges.first()
10741 } else {
10742 buffer_ranges.last()
10743 }?;
10744
10745 let snapshot = buffer.read(cx).snapshot();
10746 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10747 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10748 (buffer.clone(), selection)
10749 };
10750
10751 let path = buffer
10752 .read(cx)
10753 .file()?
10754 .as_local()?
10755 .path()
10756 .to_str()?
10757 .to_string();
10758 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10759 Some((path, selection, repo))
10760 })
10761 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10762
10763 const REMOTE_NAME: &str = "origin";
10764 let origin_url = repo
10765 .remote_url(REMOTE_NAME)
10766 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10767 let sha = repo
10768 .head_sha()
10769 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10770
10771 let (provider, remote) =
10772 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10773 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10774
10775 Ok(provider.build_permalink(
10776 remote,
10777 BuildPermalinkParams {
10778 sha: &sha,
10779 path: &path,
10780 selection: Some(selection),
10781 },
10782 ))
10783 }
10784
10785 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10786 let permalink = self.get_permalink_to_line(cx);
10787
10788 match permalink {
10789 Ok(permalink) => {
10790 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10791 }
10792 Err(err) => {
10793 let message = format!("Failed to copy permalink: {err}");
10794
10795 Err::<(), anyhow::Error>(err).log_err();
10796
10797 if let Some(workspace) = self.workspace() {
10798 workspace.update(cx, |workspace, cx| {
10799 struct CopyPermalinkToLine;
10800
10801 workspace.show_toast(
10802 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10803 cx,
10804 )
10805 })
10806 }
10807 }
10808 }
10809 }
10810
10811 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10812 let permalink = self.get_permalink_to_line(cx);
10813
10814 match permalink {
10815 Ok(permalink) => {
10816 cx.open_url(permalink.as_ref());
10817 }
10818 Err(err) => {
10819 let message = format!("Failed to open permalink: {err}");
10820
10821 Err::<(), anyhow::Error>(err).log_err();
10822
10823 if let Some(workspace) = self.workspace() {
10824 workspace.update(cx, |workspace, cx| {
10825 struct OpenPermalinkToLine;
10826
10827 workspace.show_toast(
10828 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10829 cx,
10830 )
10831 })
10832 }
10833 }
10834 }
10835 }
10836
10837 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10838 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10839 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10840 pub fn highlight_rows<T: 'static>(
10841 &mut self,
10842 rows: RangeInclusive<Anchor>,
10843 color: Option<Hsla>,
10844 should_autoscroll: bool,
10845 cx: &mut ViewContext<Self>,
10846 ) {
10847 let snapshot = self.buffer().read(cx).snapshot(cx);
10848 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10849 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10850 highlight
10851 .range
10852 .start()
10853 .cmp(&rows.start(), &snapshot)
10854 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10855 });
10856 match (color, existing_highlight_index) {
10857 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10858 ix,
10859 RowHighlight {
10860 index: post_inc(&mut self.highlight_order),
10861 range: rows,
10862 should_autoscroll,
10863 color,
10864 },
10865 ),
10866 (None, Ok(i)) => {
10867 row_highlights.remove(i);
10868 }
10869 }
10870 }
10871
10872 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10873 pub fn clear_row_highlights<T: 'static>(&mut self) {
10874 self.highlighted_rows.remove(&TypeId::of::<T>());
10875 }
10876
10877 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10878 pub fn highlighted_rows<T: 'static>(
10879 &self,
10880 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10881 Some(
10882 self.highlighted_rows
10883 .get(&TypeId::of::<T>())?
10884 .iter()
10885 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10886 )
10887 }
10888
10889 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10890 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10891 /// Allows to ignore certain kinds of highlights.
10892 pub fn highlighted_display_rows(
10893 &mut self,
10894 cx: &mut WindowContext,
10895 ) -> BTreeMap<DisplayRow, Hsla> {
10896 let snapshot = self.snapshot(cx);
10897 let mut used_highlight_orders = HashMap::default();
10898 self.highlighted_rows
10899 .iter()
10900 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10901 .fold(
10902 BTreeMap::<DisplayRow, Hsla>::new(),
10903 |mut unique_rows, highlight| {
10904 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10905 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10906 for row in start_row.0..=end_row.0 {
10907 let used_index =
10908 used_highlight_orders.entry(row).or_insert(highlight.index);
10909 if highlight.index >= *used_index {
10910 *used_index = highlight.index;
10911 match highlight.color {
10912 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10913 None => unique_rows.remove(&DisplayRow(row)),
10914 };
10915 }
10916 }
10917 unique_rows
10918 },
10919 )
10920 }
10921
10922 pub fn highlighted_display_row_for_autoscroll(
10923 &self,
10924 snapshot: &DisplaySnapshot,
10925 ) -> Option<DisplayRow> {
10926 self.highlighted_rows
10927 .values()
10928 .flat_map(|highlighted_rows| highlighted_rows.iter())
10929 .filter_map(|highlight| {
10930 if highlight.color.is_none() || !highlight.should_autoscroll {
10931 return None;
10932 }
10933 Some(highlight.range.start().to_display_point(&snapshot).row())
10934 })
10935 .min()
10936 }
10937
10938 pub fn set_search_within_ranges(
10939 &mut self,
10940 ranges: &[Range<Anchor>],
10941 cx: &mut ViewContext<Self>,
10942 ) {
10943 self.highlight_background::<SearchWithinRange>(
10944 ranges,
10945 |colors| colors.editor_document_highlight_read_background,
10946 cx,
10947 )
10948 }
10949
10950 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10951 self.breadcrumb_header = Some(new_header);
10952 }
10953
10954 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10955 self.clear_background_highlights::<SearchWithinRange>(cx);
10956 }
10957
10958 pub fn highlight_background<T: 'static>(
10959 &mut self,
10960 ranges: &[Range<Anchor>],
10961 color_fetcher: fn(&ThemeColors) -> Hsla,
10962 cx: &mut ViewContext<Self>,
10963 ) {
10964 self.background_highlights
10965 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10966 self.scrollbar_marker_state.dirty = true;
10967 cx.notify();
10968 }
10969
10970 pub fn clear_background_highlights<T: 'static>(
10971 &mut self,
10972 cx: &mut ViewContext<Self>,
10973 ) -> Option<BackgroundHighlight> {
10974 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10975 if !text_highlights.1.is_empty() {
10976 self.scrollbar_marker_state.dirty = true;
10977 cx.notify();
10978 }
10979 Some(text_highlights)
10980 }
10981
10982 pub fn highlight_gutter<T: 'static>(
10983 &mut self,
10984 ranges: &[Range<Anchor>],
10985 color_fetcher: fn(&AppContext) -> Hsla,
10986 cx: &mut ViewContext<Self>,
10987 ) {
10988 self.gutter_highlights
10989 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10990 cx.notify();
10991 }
10992
10993 pub fn clear_gutter_highlights<T: 'static>(
10994 &mut self,
10995 cx: &mut ViewContext<Self>,
10996 ) -> Option<GutterHighlight> {
10997 cx.notify();
10998 self.gutter_highlights.remove(&TypeId::of::<T>())
10999 }
11000
11001 #[cfg(feature = "test-support")]
11002 pub fn all_text_background_highlights(
11003 &mut self,
11004 cx: &mut ViewContext<Self>,
11005 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11006 let snapshot = self.snapshot(cx);
11007 let buffer = &snapshot.buffer_snapshot;
11008 let start = buffer.anchor_before(0);
11009 let end = buffer.anchor_after(buffer.len());
11010 let theme = cx.theme().colors();
11011 self.background_highlights_in_range(start..end, &snapshot, theme)
11012 }
11013
11014 #[cfg(feature = "test-support")]
11015 pub fn search_background_highlights(
11016 &mut self,
11017 cx: &mut ViewContext<Self>,
11018 ) -> Vec<Range<Point>> {
11019 let snapshot = self.buffer().read(cx).snapshot(cx);
11020
11021 let highlights = self
11022 .background_highlights
11023 .get(&TypeId::of::<items::BufferSearchHighlights>());
11024
11025 if let Some((_color, ranges)) = highlights {
11026 ranges
11027 .iter()
11028 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11029 .collect_vec()
11030 } else {
11031 vec![]
11032 }
11033 }
11034
11035 fn document_highlights_for_position<'a>(
11036 &'a self,
11037 position: Anchor,
11038 buffer: &'a MultiBufferSnapshot,
11039 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11040 let read_highlights = self
11041 .background_highlights
11042 .get(&TypeId::of::<DocumentHighlightRead>())
11043 .map(|h| &h.1);
11044 let write_highlights = self
11045 .background_highlights
11046 .get(&TypeId::of::<DocumentHighlightWrite>())
11047 .map(|h| &h.1);
11048 let left_position = position.bias_left(buffer);
11049 let right_position = position.bias_right(buffer);
11050 read_highlights
11051 .into_iter()
11052 .chain(write_highlights)
11053 .flat_map(move |ranges| {
11054 let start_ix = match ranges.binary_search_by(|probe| {
11055 let cmp = probe.end.cmp(&left_position, buffer);
11056 if cmp.is_ge() {
11057 Ordering::Greater
11058 } else {
11059 Ordering::Less
11060 }
11061 }) {
11062 Ok(i) | Err(i) => i,
11063 };
11064
11065 ranges[start_ix..]
11066 .iter()
11067 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11068 })
11069 }
11070
11071 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11072 self.background_highlights
11073 .get(&TypeId::of::<T>())
11074 .map_or(false, |(_, highlights)| !highlights.is_empty())
11075 }
11076
11077 pub fn background_highlights_in_range(
11078 &self,
11079 search_range: Range<Anchor>,
11080 display_snapshot: &DisplaySnapshot,
11081 theme: &ThemeColors,
11082 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11083 let mut results = Vec::new();
11084 for (color_fetcher, ranges) in self.background_highlights.values() {
11085 let color = color_fetcher(theme);
11086 let start_ix = match ranges.binary_search_by(|probe| {
11087 let cmp = probe
11088 .end
11089 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11090 if cmp.is_gt() {
11091 Ordering::Greater
11092 } else {
11093 Ordering::Less
11094 }
11095 }) {
11096 Ok(i) | Err(i) => i,
11097 };
11098 for range in &ranges[start_ix..] {
11099 if range
11100 .start
11101 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11102 .is_ge()
11103 {
11104 break;
11105 }
11106
11107 let start = range.start.to_display_point(&display_snapshot);
11108 let end = range.end.to_display_point(&display_snapshot);
11109 results.push((start..end, color))
11110 }
11111 }
11112 results
11113 }
11114
11115 pub fn background_highlight_row_ranges<T: 'static>(
11116 &self,
11117 search_range: Range<Anchor>,
11118 display_snapshot: &DisplaySnapshot,
11119 count: usize,
11120 ) -> Vec<RangeInclusive<DisplayPoint>> {
11121 let mut results = Vec::new();
11122 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11123 return vec![];
11124 };
11125
11126 let start_ix = match ranges.binary_search_by(|probe| {
11127 let cmp = probe
11128 .end
11129 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11130 if cmp.is_gt() {
11131 Ordering::Greater
11132 } else {
11133 Ordering::Less
11134 }
11135 }) {
11136 Ok(i) | Err(i) => i,
11137 };
11138 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11139 if let (Some(start_display), Some(end_display)) = (start, end) {
11140 results.push(
11141 start_display.to_display_point(display_snapshot)
11142 ..=end_display.to_display_point(display_snapshot),
11143 );
11144 }
11145 };
11146 let mut start_row: Option<Point> = None;
11147 let mut end_row: Option<Point> = None;
11148 if ranges.len() > count {
11149 return Vec::new();
11150 }
11151 for range in &ranges[start_ix..] {
11152 if range
11153 .start
11154 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11155 .is_ge()
11156 {
11157 break;
11158 }
11159 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11160 if let Some(current_row) = &end_row {
11161 if end.row == current_row.row {
11162 continue;
11163 }
11164 }
11165 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11166 if start_row.is_none() {
11167 assert_eq!(end_row, None);
11168 start_row = Some(start);
11169 end_row = Some(end);
11170 continue;
11171 }
11172 if let Some(current_end) = end_row.as_mut() {
11173 if start.row > current_end.row + 1 {
11174 push_region(start_row, end_row);
11175 start_row = Some(start);
11176 end_row = Some(end);
11177 } else {
11178 // Merge two hunks.
11179 *current_end = end;
11180 }
11181 } else {
11182 unreachable!();
11183 }
11184 }
11185 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11186 push_region(start_row, end_row);
11187 results
11188 }
11189
11190 pub fn gutter_highlights_in_range(
11191 &self,
11192 search_range: Range<Anchor>,
11193 display_snapshot: &DisplaySnapshot,
11194 cx: &AppContext,
11195 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11196 let mut results = Vec::new();
11197 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11198 let color = color_fetcher(cx);
11199 let start_ix = match ranges.binary_search_by(|probe| {
11200 let cmp = probe
11201 .end
11202 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11203 if cmp.is_gt() {
11204 Ordering::Greater
11205 } else {
11206 Ordering::Less
11207 }
11208 }) {
11209 Ok(i) | Err(i) => i,
11210 };
11211 for range in &ranges[start_ix..] {
11212 if range
11213 .start
11214 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11215 .is_ge()
11216 {
11217 break;
11218 }
11219
11220 let start = range.start.to_display_point(&display_snapshot);
11221 let end = range.end.to_display_point(&display_snapshot);
11222 results.push((start..end, color))
11223 }
11224 }
11225 results
11226 }
11227
11228 /// Get the text ranges corresponding to the redaction query
11229 pub fn redacted_ranges(
11230 &self,
11231 search_range: Range<Anchor>,
11232 display_snapshot: &DisplaySnapshot,
11233 cx: &WindowContext,
11234 ) -> Vec<Range<DisplayPoint>> {
11235 display_snapshot
11236 .buffer_snapshot
11237 .redacted_ranges(search_range, |file| {
11238 if let Some(file) = file {
11239 file.is_private()
11240 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11241 } else {
11242 false
11243 }
11244 })
11245 .map(|range| {
11246 range.start.to_display_point(display_snapshot)
11247 ..range.end.to_display_point(display_snapshot)
11248 })
11249 .collect()
11250 }
11251
11252 pub fn highlight_text<T: 'static>(
11253 &mut self,
11254 ranges: Vec<Range<Anchor>>,
11255 style: HighlightStyle,
11256 cx: &mut ViewContext<Self>,
11257 ) {
11258 self.display_map.update(cx, |map, _| {
11259 map.highlight_text(TypeId::of::<T>(), ranges, style)
11260 });
11261 cx.notify();
11262 }
11263
11264 pub(crate) fn highlight_inlays<T: 'static>(
11265 &mut self,
11266 highlights: Vec<InlayHighlight>,
11267 style: HighlightStyle,
11268 cx: &mut ViewContext<Self>,
11269 ) {
11270 self.display_map.update(cx, |map, _| {
11271 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11272 });
11273 cx.notify();
11274 }
11275
11276 pub fn text_highlights<'a, T: 'static>(
11277 &'a self,
11278 cx: &'a AppContext,
11279 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11280 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11281 }
11282
11283 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11284 let cleared = self
11285 .display_map
11286 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11287 if cleared {
11288 cx.notify();
11289 }
11290 }
11291
11292 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11293 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11294 && self.focus_handle.is_focused(cx)
11295 }
11296
11297 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11298 self.show_cursor_when_unfocused = is_enabled;
11299 cx.notify();
11300 }
11301
11302 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11303 cx.notify();
11304 }
11305
11306 fn on_buffer_event(
11307 &mut self,
11308 multibuffer: Model<MultiBuffer>,
11309 event: &multi_buffer::Event,
11310 cx: &mut ViewContext<Self>,
11311 ) {
11312 match event {
11313 multi_buffer::Event::Edited {
11314 singleton_buffer_edited,
11315 } => {
11316 self.scrollbar_marker_state.dirty = true;
11317 self.active_indent_guides_state.dirty = true;
11318 self.refresh_active_diagnostics(cx);
11319 self.refresh_code_actions(cx);
11320 if self.has_active_inline_completion(cx) {
11321 self.update_visible_inline_completion(cx);
11322 }
11323 cx.emit(EditorEvent::BufferEdited);
11324 cx.emit(SearchEvent::MatchesInvalidated);
11325 if *singleton_buffer_edited {
11326 if let Some(project) = &self.project {
11327 let project = project.read(cx);
11328 #[allow(clippy::mutable_key_type)]
11329 let languages_affected = multibuffer
11330 .read(cx)
11331 .all_buffers()
11332 .into_iter()
11333 .filter_map(|buffer| {
11334 let buffer = buffer.read(cx);
11335 let language = buffer.language()?;
11336 if project.is_local()
11337 && project.language_servers_for_buffer(buffer, cx).count() == 0
11338 {
11339 None
11340 } else {
11341 Some(language)
11342 }
11343 })
11344 .cloned()
11345 .collect::<HashSet<_>>();
11346 if !languages_affected.is_empty() {
11347 self.refresh_inlay_hints(
11348 InlayHintRefreshReason::BufferEdited(languages_affected),
11349 cx,
11350 );
11351 }
11352 }
11353 }
11354
11355 let Some(project) = &self.project else { return };
11356 let telemetry = project.read(cx).client().telemetry().clone();
11357 refresh_linked_ranges(self, cx);
11358 telemetry.log_edit_event("editor");
11359 }
11360 multi_buffer::Event::ExcerptsAdded {
11361 buffer,
11362 predecessor,
11363 excerpts,
11364 } => {
11365 self.tasks_update_task = Some(self.refresh_runnables(cx));
11366 cx.emit(EditorEvent::ExcerptsAdded {
11367 buffer: buffer.clone(),
11368 predecessor: *predecessor,
11369 excerpts: excerpts.clone(),
11370 });
11371 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11372 }
11373 multi_buffer::Event::ExcerptsRemoved { ids } => {
11374 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11375 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11376 }
11377 multi_buffer::Event::ExcerptsEdited { ids } => {
11378 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11379 }
11380 multi_buffer::Event::ExcerptsExpanded { ids } => {
11381 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11382 }
11383 multi_buffer::Event::Reparsed(buffer_id) => {
11384 self.tasks_update_task = Some(self.refresh_runnables(cx));
11385
11386 cx.emit(EditorEvent::Reparsed(*buffer_id));
11387 }
11388 multi_buffer::Event::LanguageChanged(buffer_id) => {
11389 linked_editing_ranges::refresh_linked_ranges(self, cx);
11390 cx.emit(EditorEvent::Reparsed(*buffer_id));
11391 cx.notify();
11392 }
11393 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11394 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11395 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11396 cx.emit(EditorEvent::TitleChanged)
11397 }
11398 multi_buffer::Event::DiffBaseChanged => {
11399 self.scrollbar_marker_state.dirty = true;
11400 cx.emit(EditorEvent::DiffBaseChanged);
11401 cx.notify();
11402 }
11403 multi_buffer::Event::DiffUpdated { buffer } => {
11404 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11405 cx.notify();
11406 }
11407 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11408 multi_buffer::Event::DiagnosticsUpdated => {
11409 self.refresh_active_diagnostics(cx);
11410 self.scrollbar_marker_state.dirty = true;
11411 cx.notify();
11412 }
11413 _ => {}
11414 };
11415 }
11416
11417 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11418 cx.notify();
11419 }
11420
11421 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11422 self.tasks_update_task = Some(self.refresh_runnables(cx));
11423 self.refresh_inline_completion(true, cx);
11424 self.refresh_inlay_hints(
11425 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11426 self.selections.newest_anchor().head(),
11427 &self.buffer.read(cx).snapshot(cx),
11428 cx,
11429 )),
11430 cx,
11431 );
11432 let editor_settings = EditorSettings::get_global(cx);
11433 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11434 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11435
11436 let project_settings = ProjectSettings::get_global(cx);
11437 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11438
11439 if self.mode == EditorMode::Full {
11440 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11441 if self.git_blame_inline_enabled != inline_blame_enabled {
11442 self.toggle_git_blame_inline_internal(false, cx);
11443 }
11444 }
11445
11446 cx.notify();
11447 }
11448
11449 pub fn set_searchable(&mut self, searchable: bool) {
11450 self.searchable = searchable;
11451 }
11452
11453 pub fn searchable(&self) -> bool {
11454 self.searchable
11455 }
11456
11457 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11458 self.open_excerpts_common(true, cx)
11459 }
11460
11461 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11462 self.open_excerpts_common(false, cx)
11463 }
11464
11465 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11466 let buffer = self.buffer.read(cx);
11467 if buffer.is_singleton() {
11468 cx.propagate();
11469 return;
11470 }
11471
11472 let Some(workspace) = self.workspace() else {
11473 cx.propagate();
11474 return;
11475 };
11476
11477 let mut new_selections_by_buffer = HashMap::default();
11478 for selection in self.selections.all::<usize>(cx) {
11479 for (buffer, mut range, _) in
11480 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11481 {
11482 if selection.reversed {
11483 mem::swap(&mut range.start, &mut range.end);
11484 }
11485 new_selections_by_buffer
11486 .entry(buffer)
11487 .or_insert(Vec::new())
11488 .push(range)
11489 }
11490 }
11491
11492 // We defer the pane interaction because we ourselves are a workspace item
11493 // and activating a new item causes the pane to call a method on us reentrantly,
11494 // which panics if we're on the stack.
11495 cx.window_context().defer(move |cx| {
11496 workspace.update(cx, |workspace, cx| {
11497 let pane = if split {
11498 workspace.adjacent_pane(cx)
11499 } else {
11500 workspace.active_pane().clone()
11501 };
11502
11503 for (buffer, ranges) in new_selections_by_buffer {
11504 let editor =
11505 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11506 editor.update(cx, |editor, cx| {
11507 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11508 s.select_ranges(ranges);
11509 });
11510 });
11511 }
11512 })
11513 });
11514 }
11515
11516 fn jump(
11517 &mut self,
11518 path: ProjectPath,
11519 position: Point,
11520 anchor: language::Anchor,
11521 offset_from_top: u32,
11522 cx: &mut ViewContext<Self>,
11523 ) {
11524 let workspace = self.workspace();
11525 cx.spawn(|_, mut cx| async move {
11526 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11527 let editor = workspace.update(&mut cx, |workspace, cx| {
11528 // Reset the preview item id before opening the new item
11529 workspace.active_pane().update(cx, |pane, cx| {
11530 pane.set_preview_item_id(None, cx);
11531 });
11532 workspace.open_path_preview(path, None, true, true, cx)
11533 })?;
11534 let editor = editor
11535 .await?
11536 .downcast::<Editor>()
11537 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11538 .downgrade();
11539 editor.update(&mut cx, |editor, cx| {
11540 let buffer = editor
11541 .buffer()
11542 .read(cx)
11543 .as_singleton()
11544 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11545 let buffer = buffer.read(cx);
11546 let cursor = if buffer.can_resolve(&anchor) {
11547 language::ToPoint::to_point(&anchor, buffer)
11548 } else {
11549 buffer.clip_point(position, Bias::Left)
11550 };
11551
11552 let nav_history = editor.nav_history.take();
11553 editor.change_selections(
11554 Some(Autoscroll::top_relative(offset_from_top as usize)),
11555 cx,
11556 |s| {
11557 s.select_ranges([cursor..cursor]);
11558 },
11559 );
11560 editor.nav_history = nav_history;
11561
11562 anyhow::Ok(())
11563 })??;
11564
11565 anyhow::Ok(())
11566 })
11567 .detach_and_log_err(cx);
11568 }
11569
11570 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11571 let snapshot = self.buffer.read(cx).read(cx);
11572 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11573 Some(
11574 ranges
11575 .iter()
11576 .map(move |range| {
11577 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11578 })
11579 .collect(),
11580 )
11581 }
11582
11583 fn selection_replacement_ranges(
11584 &self,
11585 range: Range<OffsetUtf16>,
11586 cx: &AppContext,
11587 ) -> Vec<Range<OffsetUtf16>> {
11588 let selections = self.selections.all::<OffsetUtf16>(cx);
11589 let newest_selection = selections
11590 .iter()
11591 .max_by_key(|selection| selection.id)
11592 .unwrap();
11593 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11594 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11595 let snapshot = self.buffer.read(cx).read(cx);
11596 selections
11597 .into_iter()
11598 .map(|mut selection| {
11599 selection.start.0 =
11600 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11601 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11602 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11603 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11604 })
11605 .collect()
11606 }
11607
11608 fn report_editor_event(
11609 &self,
11610 operation: &'static str,
11611 file_extension: Option<String>,
11612 cx: &AppContext,
11613 ) {
11614 if cfg!(any(test, feature = "test-support")) {
11615 return;
11616 }
11617
11618 let Some(project) = &self.project else { return };
11619
11620 // If None, we are in a file without an extension
11621 let file = self
11622 .buffer
11623 .read(cx)
11624 .as_singleton()
11625 .and_then(|b| b.read(cx).file());
11626 let file_extension = file_extension.or(file
11627 .as_ref()
11628 .and_then(|file| Path::new(file.file_name(cx)).extension())
11629 .and_then(|e| e.to_str())
11630 .map(|a| a.to_string()));
11631
11632 let vim_mode = cx
11633 .global::<SettingsStore>()
11634 .raw_user_settings()
11635 .get("vim_mode")
11636 == Some(&serde_json::Value::Bool(true));
11637
11638 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11639 == language::language_settings::InlineCompletionProvider::Copilot;
11640 let copilot_enabled_for_language = self
11641 .buffer
11642 .read(cx)
11643 .settings_at(0, cx)
11644 .show_inline_completions;
11645
11646 let telemetry = project.read(cx).client().telemetry().clone();
11647 telemetry.report_editor_event(
11648 file_extension,
11649 vim_mode,
11650 operation,
11651 copilot_enabled,
11652 copilot_enabled_for_language,
11653 )
11654 }
11655
11656 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11657 /// with each line being an array of {text, highlight} objects.
11658 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11659 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11660 return;
11661 };
11662
11663 #[derive(Serialize)]
11664 struct Chunk<'a> {
11665 text: String,
11666 highlight: Option<&'a str>,
11667 }
11668
11669 let snapshot = buffer.read(cx).snapshot();
11670 let range = self
11671 .selected_text_range(cx)
11672 .and_then(|selected_range| {
11673 if selected_range.is_empty() {
11674 None
11675 } else {
11676 Some(selected_range)
11677 }
11678 })
11679 .unwrap_or_else(|| 0..snapshot.len());
11680
11681 let chunks = snapshot.chunks(range, true);
11682 let mut lines = Vec::new();
11683 let mut line: VecDeque<Chunk> = VecDeque::new();
11684
11685 let Some(style) = self.style.as_ref() else {
11686 return;
11687 };
11688
11689 for chunk in chunks {
11690 let highlight = chunk
11691 .syntax_highlight_id
11692 .and_then(|id| id.name(&style.syntax));
11693 let mut chunk_lines = chunk.text.split('\n').peekable();
11694 while let Some(text) = chunk_lines.next() {
11695 let mut merged_with_last_token = false;
11696 if let Some(last_token) = line.back_mut() {
11697 if last_token.highlight == highlight {
11698 last_token.text.push_str(text);
11699 merged_with_last_token = true;
11700 }
11701 }
11702
11703 if !merged_with_last_token {
11704 line.push_back(Chunk {
11705 text: text.into(),
11706 highlight,
11707 });
11708 }
11709
11710 if chunk_lines.peek().is_some() {
11711 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11712 line.pop_front();
11713 }
11714 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11715 line.pop_back();
11716 }
11717
11718 lines.push(mem::take(&mut line));
11719 }
11720 }
11721 }
11722
11723 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11724 return;
11725 };
11726 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11727 }
11728
11729 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11730 &self.inlay_hint_cache
11731 }
11732
11733 pub fn replay_insert_event(
11734 &mut self,
11735 text: &str,
11736 relative_utf16_range: Option<Range<isize>>,
11737 cx: &mut ViewContext<Self>,
11738 ) {
11739 if !self.input_enabled {
11740 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11741 return;
11742 }
11743 if let Some(relative_utf16_range) = relative_utf16_range {
11744 let selections = self.selections.all::<OffsetUtf16>(cx);
11745 self.change_selections(None, cx, |s| {
11746 let new_ranges = selections.into_iter().map(|range| {
11747 let start = OffsetUtf16(
11748 range
11749 .head()
11750 .0
11751 .saturating_add_signed(relative_utf16_range.start),
11752 );
11753 let end = OffsetUtf16(
11754 range
11755 .head()
11756 .0
11757 .saturating_add_signed(relative_utf16_range.end),
11758 );
11759 start..end
11760 });
11761 s.select_ranges(new_ranges);
11762 });
11763 }
11764
11765 self.handle_input(text, cx);
11766 }
11767
11768 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11769 let Some(project) = self.project.as_ref() else {
11770 return false;
11771 };
11772 let project = project.read(cx);
11773
11774 let mut supports = false;
11775 self.buffer().read(cx).for_each_buffer(|buffer| {
11776 if !supports {
11777 supports = project
11778 .language_servers_for_buffer(buffer.read(cx), cx)
11779 .any(
11780 |(_, server)| match server.capabilities().inlay_hint_provider {
11781 Some(lsp::OneOf::Left(enabled)) => enabled,
11782 Some(lsp::OneOf::Right(_)) => true,
11783 None => false,
11784 },
11785 )
11786 }
11787 });
11788 supports
11789 }
11790
11791 pub fn focus(&self, cx: &mut WindowContext) {
11792 cx.focus(&self.focus_handle)
11793 }
11794
11795 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11796 self.focus_handle.is_focused(cx)
11797 }
11798
11799 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11800 cx.emit(EditorEvent::Focused);
11801
11802 if let Some(descendant) = self
11803 .last_focused_descendant
11804 .take()
11805 .and_then(|descendant| descendant.upgrade())
11806 {
11807 cx.focus(&descendant);
11808 } else {
11809 if let Some(blame) = self.blame.as_ref() {
11810 blame.update(cx, GitBlame::focus)
11811 }
11812
11813 self.blink_manager.update(cx, BlinkManager::enable);
11814 self.show_cursor_names(cx);
11815 self.buffer.update(cx, |buffer, cx| {
11816 buffer.finalize_last_transaction(cx);
11817 if self.leader_peer_id.is_none() {
11818 buffer.set_active_selections(
11819 &self.selections.disjoint_anchors(),
11820 self.selections.line_mode,
11821 self.cursor_shape,
11822 cx,
11823 );
11824 }
11825 });
11826 }
11827 }
11828
11829 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11830 cx.emit(EditorEvent::FocusedIn)
11831 }
11832
11833 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11834 if event.blurred != self.focus_handle {
11835 self.last_focused_descendant = Some(event.blurred);
11836 }
11837 }
11838
11839 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11840 self.blink_manager.update(cx, BlinkManager::disable);
11841 self.buffer
11842 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11843
11844 if let Some(blame) = self.blame.as_ref() {
11845 blame.update(cx, GitBlame::blur)
11846 }
11847 if !self.hover_state.focused(cx) {
11848 hide_hover(self, cx);
11849 }
11850
11851 self.hide_context_menu(cx);
11852 cx.emit(EditorEvent::Blurred);
11853 cx.notify();
11854 }
11855
11856 pub fn register_action<A: Action>(
11857 &mut self,
11858 listener: impl Fn(&A, &mut WindowContext) + 'static,
11859 ) -> Subscription {
11860 let id = self.next_editor_action_id.post_inc();
11861 let listener = Arc::new(listener);
11862 self.editor_actions.borrow_mut().insert(
11863 id,
11864 Box::new(move |cx| {
11865 let cx = cx.window_context();
11866 let listener = listener.clone();
11867 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11868 let action = action.downcast_ref().unwrap();
11869 if phase == DispatchPhase::Bubble {
11870 listener(action, cx)
11871 }
11872 })
11873 }),
11874 );
11875
11876 let editor_actions = self.editor_actions.clone();
11877 Subscription::new(move || {
11878 editor_actions.borrow_mut().remove(&id);
11879 })
11880 }
11881
11882 pub fn file_header_size(&self) -> u32 {
11883 self.file_header_size
11884 }
11885
11886 pub fn revert(
11887 &mut self,
11888 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11889 cx: &mut ViewContext<Self>,
11890 ) {
11891 self.buffer().update(cx, |multi_buffer, cx| {
11892 for (buffer_id, changes) in revert_changes {
11893 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11894 buffer.update(cx, |buffer, cx| {
11895 buffer.edit(
11896 changes.into_iter().map(|(range, text)| {
11897 (range, text.to_string().map(Arc::<str>::from))
11898 }),
11899 None,
11900 cx,
11901 );
11902 });
11903 }
11904 }
11905 });
11906 self.change_selections(None, cx, |selections| selections.refresh());
11907 }
11908
11909 pub fn to_pixel_point(
11910 &mut self,
11911 source: multi_buffer::Anchor,
11912 editor_snapshot: &EditorSnapshot,
11913 cx: &mut ViewContext<Self>,
11914 ) -> Option<gpui::Point<Pixels>> {
11915 let source_point = source.to_display_point(editor_snapshot);
11916 self.display_to_pixel_point(source_point, editor_snapshot, cx)
11917 }
11918
11919 pub fn display_to_pixel_point(
11920 &mut self,
11921 source: DisplayPoint,
11922 editor_snapshot: &EditorSnapshot,
11923 cx: &mut ViewContext<Self>,
11924 ) -> Option<gpui::Point<Pixels>> {
11925 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11926 let text_layout_details = self.text_layout_details(cx);
11927 let scroll_top = text_layout_details
11928 .scroll_anchor
11929 .scroll_position(editor_snapshot)
11930 .y;
11931
11932 if source.row().as_f32() < scroll_top.floor() {
11933 return None;
11934 }
11935 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11936 let source_y = line_height * (source.row().as_f32() - scroll_top);
11937 Some(gpui::Point::new(source_x, source_y))
11938 }
11939
11940 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
11941 let bounds = self.last_bounds?;
11942 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
11943 }
11944
11945 pub fn has_active_completions_menu(&self) -> bool {
11946 self.context_menu.read().as_ref().map_or(false, |menu| {
11947 menu.visible() && matches!(menu, ContextMenu::Completions(_))
11948 })
11949 }
11950
11951 pub fn register_addon<T: Addon>(&mut self, instance: T) {
11952 self.addons
11953 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
11954 }
11955
11956 pub fn unregister_addon<T: Addon>(&mut self) {
11957 self.addons.remove(&std::any::TypeId::of::<T>());
11958 }
11959
11960 pub fn addon<T: Addon>(&self) -> Option<&T> {
11961 let type_id = std::any::TypeId::of::<T>();
11962 self.addons
11963 .get(&type_id)
11964 .and_then(|item| item.to_any().downcast_ref::<T>())
11965 }
11966}
11967
11968fn hunks_for_selections(
11969 multi_buffer_snapshot: &MultiBufferSnapshot,
11970 selections: &[Selection<Anchor>],
11971) -> Vec<DiffHunk<MultiBufferRow>> {
11972 let buffer_rows_for_selections = selections.iter().map(|selection| {
11973 let head = selection.head();
11974 let tail = selection.tail();
11975 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11976 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11977 if start > end {
11978 end..start
11979 } else {
11980 start..end
11981 }
11982 });
11983
11984 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11985}
11986
11987pub fn hunks_for_rows(
11988 rows: impl Iterator<Item = Range<MultiBufferRow>>,
11989 multi_buffer_snapshot: &MultiBufferSnapshot,
11990) -> Vec<DiffHunk<MultiBufferRow>> {
11991 let mut hunks = Vec::new();
11992 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11993 HashMap::default();
11994 for selected_multi_buffer_rows in rows {
11995 let query_rows =
11996 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11997 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11998 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11999 // when the caret is just above or just below the deleted hunk.
12000 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12001 let related_to_selection = if allow_adjacent {
12002 hunk.associated_range.overlaps(&query_rows)
12003 || hunk.associated_range.start == query_rows.end
12004 || hunk.associated_range.end == query_rows.start
12005 } else {
12006 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12007 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12008 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12009 || selected_multi_buffer_rows.end == hunk.associated_range.start
12010 };
12011 if related_to_selection {
12012 if !processed_buffer_rows
12013 .entry(hunk.buffer_id)
12014 .or_default()
12015 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12016 {
12017 continue;
12018 }
12019 hunks.push(hunk);
12020 }
12021 }
12022 }
12023
12024 hunks
12025}
12026
12027pub trait CollaborationHub {
12028 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12029 fn user_participant_indices<'a>(
12030 &self,
12031 cx: &'a AppContext,
12032 ) -> &'a HashMap<u64, ParticipantIndex>;
12033 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12034}
12035
12036impl CollaborationHub for Model<Project> {
12037 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12038 self.read(cx).collaborators()
12039 }
12040
12041 fn user_participant_indices<'a>(
12042 &self,
12043 cx: &'a AppContext,
12044 ) -> &'a HashMap<u64, ParticipantIndex> {
12045 self.read(cx).user_store().read(cx).participant_indices()
12046 }
12047
12048 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12049 let this = self.read(cx);
12050 let user_ids = this.collaborators().values().map(|c| c.user_id);
12051 this.user_store().read_with(cx, |user_store, cx| {
12052 user_store.participant_names(user_ids, cx)
12053 })
12054 }
12055}
12056
12057pub trait CompletionProvider {
12058 fn completions(
12059 &self,
12060 buffer: &Model<Buffer>,
12061 buffer_position: text::Anchor,
12062 trigger: CompletionContext,
12063 cx: &mut ViewContext<Editor>,
12064 ) -> Task<Result<Vec<Completion>>>;
12065
12066 fn resolve_completions(
12067 &self,
12068 buffer: Model<Buffer>,
12069 completion_indices: Vec<usize>,
12070 completions: Arc<RwLock<Box<[Completion]>>>,
12071 cx: &mut ViewContext<Editor>,
12072 ) -> Task<Result<bool>>;
12073
12074 fn apply_additional_edits_for_completion(
12075 &self,
12076 buffer: Model<Buffer>,
12077 completion: Completion,
12078 push_to_history: bool,
12079 cx: &mut ViewContext<Editor>,
12080 ) -> Task<Result<Option<language::Transaction>>>;
12081
12082 fn is_completion_trigger(
12083 &self,
12084 buffer: &Model<Buffer>,
12085 position: language::Anchor,
12086 text: &str,
12087 trigger_in_words: bool,
12088 cx: &mut ViewContext<Editor>,
12089 ) -> bool;
12090
12091 fn sort_completions(&self) -> bool {
12092 true
12093 }
12094}
12095
12096fn snippet_completions(
12097 project: &Project,
12098 buffer: &Model<Buffer>,
12099 buffer_position: text::Anchor,
12100 cx: &mut AppContext,
12101) -> Vec<Completion> {
12102 let language = buffer.read(cx).language_at(buffer_position);
12103 let language_name = language.as_ref().map(|language| language.lsp_id());
12104 let snippet_store = project.snippets().read(cx);
12105 let snippets = snippet_store.snippets_for(language_name, cx);
12106
12107 if snippets.is_empty() {
12108 return vec![];
12109 }
12110 let snapshot = buffer.read(cx).text_snapshot();
12111 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12112
12113 let mut lines = chunks.lines();
12114 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12115 return vec![];
12116 };
12117
12118 let scope = language.map(|language| language.default_scope());
12119 let mut last_word = line_at
12120 .chars()
12121 .rev()
12122 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12123 .collect::<String>();
12124 last_word = last_word.chars().rev().collect();
12125 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12126 let to_lsp = |point: &text::Anchor| {
12127 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12128 point_to_lsp(end)
12129 };
12130 let lsp_end = to_lsp(&buffer_position);
12131 snippets
12132 .into_iter()
12133 .filter_map(|snippet| {
12134 let matching_prefix = snippet
12135 .prefix
12136 .iter()
12137 .find(|prefix| prefix.starts_with(&last_word))?;
12138 let start = as_offset - last_word.len();
12139 let start = snapshot.anchor_before(start);
12140 let range = start..buffer_position;
12141 let lsp_start = to_lsp(&start);
12142 let lsp_range = lsp::Range {
12143 start: lsp_start,
12144 end: lsp_end,
12145 };
12146 Some(Completion {
12147 old_range: range,
12148 new_text: snippet.body.clone(),
12149 label: CodeLabel {
12150 text: matching_prefix.clone(),
12151 runs: vec![],
12152 filter_range: 0..matching_prefix.len(),
12153 },
12154 server_id: LanguageServerId(usize::MAX),
12155 documentation: snippet
12156 .description
12157 .clone()
12158 .map(|description| Documentation::SingleLine(description)),
12159 lsp_completion: lsp::CompletionItem {
12160 label: snippet.prefix.first().unwrap().clone(),
12161 kind: Some(CompletionItemKind::SNIPPET),
12162 label_details: snippet.description.as_ref().map(|description| {
12163 lsp::CompletionItemLabelDetails {
12164 detail: Some(description.clone()),
12165 description: None,
12166 }
12167 }),
12168 insert_text_format: Some(InsertTextFormat::SNIPPET),
12169 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12170 lsp::InsertReplaceEdit {
12171 new_text: snippet.body.clone(),
12172 insert: lsp_range,
12173 replace: lsp_range,
12174 },
12175 )),
12176 filter_text: Some(snippet.body.clone()),
12177 sort_text: Some(char::MAX.to_string()),
12178 ..Default::default()
12179 },
12180 confirm: None,
12181 })
12182 })
12183 .collect()
12184}
12185
12186impl CompletionProvider for Model<Project> {
12187 fn completions(
12188 &self,
12189 buffer: &Model<Buffer>,
12190 buffer_position: text::Anchor,
12191 options: CompletionContext,
12192 cx: &mut ViewContext<Editor>,
12193 ) -> Task<Result<Vec<Completion>>> {
12194 self.update(cx, |project, cx| {
12195 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12196 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12197 cx.background_executor().spawn(async move {
12198 let mut completions = project_completions.await?;
12199 //let snippets = snippets.into_iter().;
12200 completions.extend(snippets);
12201 Ok(completions)
12202 })
12203 })
12204 }
12205
12206 fn resolve_completions(
12207 &self,
12208 buffer: Model<Buffer>,
12209 completion_indices: Vec<usize>,
12210 completions: Arc<RwLock<Box<[Completion]>>>,
12211 cx: &mut ViewContext<Editor>,
12212 ) -> Task<Result<bool>> {
12213 self.update(cx, |project, cx| {
12214 project.resolve_completions(buffer, completion_indices, completions, cx)
12215 })
12216 }
12217
12218 fn apply_additional_edits_for_completion(
12219 &self,
12220 buffer: Model<Buffer>,
12221 completion: Completion,
12222 push_to_history: bool,
12223 cx: &mut ViewContext<Editor>,
12224 ) -> Task<Result<Option<language::Transaction>>> {
12225 self.update(cx, |project, cx| {
12226 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12227 })
12228 }
12229
12230 fn is_completion_trigger(
12231 &self,
12232 buffer: &Model<Buffer>,
12233 position: language::Anchor,
12234 text: &str,
12235 trigger_in_words: bool,
12236 cx: &mut ViewContext<Editor>,
12237 ) -> bool {
12238 if !EditorSettings::get_global(cx).show_completions_on_input {
12239 return false;
12240 }
12241
12242 let mut chars = text.chars();
12243 let char = if let Some(char) = chars.next() {
12244 char
12245 } else {
12246 return false;
12247 };
12248 if chars.next().is_some() {
12249 return false;
12250 }
12251
12252 let buffer = buffer.read(cx);
12253 let scope = buffer.snapshot().language_scope_at(position);
12254 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12255 return true;
12256 }
12257
12258 buffer
12259 .completion_triggers()
12260 .iter()
12261 .any(|string| string == text)
12262 }
12263}
12264
12265fn inlay_hint_settings(
12266 location: Anchor,
12267 snapshot: &MultiBufferSnapshot,
12268 cx: &mut ViewContext<'_, Editor>,
12269) -> InlayHintSettings {
12270 let file = snapshot.file_at(location);
12271 let language = snapshot.language_at(location);
12272 let settings = all_language_settings(file, cx);
12273 settings
12274 .language(language.map(|l| l.name()).as_deref())
12275 .inlay_hints
12276}
12277
12278fn consume_contiguous_rows(
12279 contiguous_row_selections: &mut Vec<Selection<Point>>,
12280 selection: &Selection<Point>,
12281 display_map: &DisplaySnapshot,
12282 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12283) -> (MultiBufferRow, MultiBufferRow) {
12284 contiguous_row_selections.push(selection.clone());
12285 let start_row = MultiBufferRow(selection.start.row);
12286 let mut end_row = ending_row(selection, display_map);
12287
12288 while let Some(next_selection) = selections.peek() {
12289 if next_selection.start.row <= end_row.0 {
12290 end_row = ending_row(next_selection, display_map);
12291 contiguous_row_selections.push(selections.next().unwrap().clone());
12292 } else {
12293 break;
12294 }
12295 }
12296 (start_row, end_row)
12297}
12298
12299fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12300 if next_selection.end.column > 0 || next_selection.is_empty() {
12301 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12302 } else {
12303 MultiBufferRow(next_selection.end.row)
12304 }
12305}
12306
12307impl EditorSnapshot {
12308 pub fn remote_selections_in_range<'a>(
12309 &'a self,
12310 range: &'a Range<Anchor>,
12311 collaboration_hub: &dyn CollaborationHub,
12312 cx: &'a AppContext,
12313 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12314 let participant_names = collaboration_hub.user_names(cx);
12315 let participant_indices = collaboration_hub.user_participant_indices(cx);
12316 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12317 let collaborators_by_replica_id = collaborators_by_peer_id
12318 .iter()
12319 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12320 .collect::<HashMap<_, _>>();
12321 self.buffer_snapshot
12322 .selections_in_range(range, false)
12323 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12324 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12325 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12326 let user_name = participant_names.get(&collaborator.user_id).cloned();
12327 Some(RemoteSelection {
12328 replica_id,
12329 selection,
12330 cursor_shape,
12331 line_mode,
12332 participant_index,
12333 peer_id: collaborator.peer_id,
12334 user_name,
12335 })
12336 })
12337 }
12338
12339 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12340 self.display_snapshot.buffer_snapshot.language_at(position)
12341 }
12342
12343 pub fn is_focused(&self) -> bool {
12344 self.is_focused
12345 }
12346
12347 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12348 self.placeholder_text.as_ref()
12349 }
12350
12351 pub fn scroll_position(&self) -> gpui::Point<f32> {
12352 self.scroll_anchor.scroll_position(&self.display_snapshot)
12353 }
12354
12355 fn gutter_dimensions(
12356 &self,
12357 font_id: FontId,
12358 font_size: Pixels,
12359 em_width: Pixels,
12360 max_line_number_width: Pixels,
12361 cx: &AppContext,
12362 ) -> GutterDimensions {
12363 if !self.show_gutter {
12364 return GutterDimensions::default();
12365 }
12366 let descent = cx.text_system().descent(font_id, font_size);
12367
12368 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12369 matches!(
12370 ProjectSettings::get_global(cx).git.git_gutter,
12371 Some(GitGutterSetting::TrackedFiles)
12372 )
12373 });
12374 let gutter_settings = EditorSettings::get_global(cx).gutter;
12375 let show_line_numbers = self
12376 .show_line_numbers
12377 .unwrap_or(gutter_settings.line_numbers);
12378 let line_gutter_width = if show_line_numbers {
12379 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12380 let min_width_for_number_on_gutter = em_width * 4.0;
12381 max_line_number_width.max(min_width_for_number_on_gutter)
12382 } else {
12383 0.0.into()
12384 };
12385
12386 let show_code_actions = self
12387 .show_code_actions
12388 .unwrap_or(gutter_settings.code_actions);
12389
12390 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12391
12392 let git_blame_entries_width = self
12393 .render_git_blame_gutter
12394 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12395
12396 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12397 left_padding += if show_code_actions || show_runnables {
12398 em_width * 3.0
12399 } else if show_git_gutter && show_line_numbers {
12400 em_width * 2.0
12401 } else if show_git_gutter || show_line_numbers {
12402 em_width
12403 } else {
12404 px(0.)
12405 };
12406
12407 let right_padding = if gutter_settings.folds && show_line_numbers {
12408 em_width * 4.0
12409 } else if gutter_settings.folds {
12410 em_width * 3.0
12411 } else if show_line_numbers {
12412 em_width
12413 } else {
12414 px(0.)
12415 };
12416
12417 GutterDimensions {
12418 left_padding,
12419 right_padding,
12420 width: line_gutter_width + left_padding + right_padding,
12421 margin: -descent,
12422 git_blame_entries_width,
12423 }
12424 }
12425
12426 pub fn render_fold_toggle(
12427 &self,
12428 buffer_row: MultiBufferRow,
12429 row_contains_cursor: bool,
12430 editor: View<Editor>,
12431 cx: &mut WindowContext,
12432 ) -> Option<AnyElement> {
12433 let folded = self.is_line_folded(buffer_row);
12434
12435 if let Some(crease) = self
12436 .crease_snapshot
12437 .query_row(buffer_row, &self.buffer_snapshot)
12438 {
12439 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12440 if folded {
12441 editor.update(cx, |editor, cx| {
12442 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12443 });
12444 } else {
12445 editor.update(cx, |editor, cx| {
12446 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12447 });
12448 }
12449 });
12450
12451 Some((crease.render_toggle)(
12452 buffer_row,
12453 folded,
12454 toggle_callback,
12455 cx,
12456 ))
12457 } else if folded
12458 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12459 {
12460 Some(
12461 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12462 .selected(folded)
12463 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12464 if folded {
12465 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12466 } else {
12467 this.fold_at(&FoldAt { buffer_row }, cx);
12468 }
12469 }))
12470 .into_any_element(),
12471 )
12472 } else {
12473 None
12474 }
12475 }
12476
12477 pub fn render_crease_trailer(
12478 &self,
12479 buffer_row: MultiBufferRow,
12480 cx: &mut WindowContext,
12481 ) -> Option<AnyElement> {
12482 let folded = self.is_line_folded(buffer_row);
12483 let crease = self
12484 .crease_snapshot
12485 .query_row(buffer_row, &self.buffer_snapshot)?;
12486 Some((crease.render_trailer)(buffer_row, folded, cx))
12487 }
12488}
12489
12490impl Deref for EditorSnapshot {
12491 type Target = DisplaySnapshot;
12492
12493 fn deref(&self) -> &Self::Target {
12494 &self.display_snapshot
12495 }
12496}
12497
12498#[derive(Clone, Debug, PartialEq, Eq)]
12499pub enum EditorEvent {
12500 InputIgnored {
12501 text: Arc<str>,
12502 },
12503 InputHandled {
12504 utf16_range_to_replace: Option<Range<isize>>,
12505 text: Arc<str>,
12506 },
12507 ExcerptsAdded {
12508 buffer: Model<Buffer>,
12509 predecessor: ExcerptId,
12510 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12511 },
12512 ExcerptsRemoved {
12513 ids: Vec<ExcerptId>,
12514 },
12515 ExcerptsEdited {
12516 ids: Vec<ExcerptId>,
12517 },
12518 ExcerptsExpanded {
12519 ids: Vec<ExcerptId>,
12520 },
12521 BufferEdited,
12522 Edited {
12523 transaction_id: clock::Lamport,
12524 },
12525 Reparsed(BufferId),
12526 Focused,
12527 FocusedIn,
12528 Blurred,
12529 DirtyChanged,
12530 Saved,
12531 TitleChanged,
12532 DiffBaseChanged,
12533 SelectionsChanged {
12534 local: bool,
12535 },
12536 ScrollPositionChanged {
12537 local: bool,
12538 autoscroll: bool,
12539 },
12540 Closed,
12541 TransactionUndone {
12542 transaction_id: clock::Lamport,
12543 },
12544 TransactionBegun {
12545 transaction_id: clock::Lamport,
12546 },
12547}
12548
12549impl EventEmitter<EditorEvent> for Editor {}
12550
12551impl FocusableView for Editor {
12552 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12553 self.focus_handle.clone()
12554 }
12555}
12556
12557impl Render for Editor {
12558 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12559 let settings = ThemeSettings::get_global(cx);
12560
12561 let text_style = match self.mode {
12562 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12563 color: cx.theme().colors().editor_foreground,
12564 font_family: settings.ui_font.family.clone(),
12565 font_features: settings.ui_font.features.clone(),
12566 font_fallbacks: settings.ui_font.fallbacks.clone(),
12567 font_size: rems(0.875).into(),
12568 font_weight: settings.ui_font.weight,
12569 line_height: relative(settings.buffer_line_height.value()),
12570 ..Default::default()
12571 },
12572 EditorMode::Full => TextStyle {
12573 color: cx.theme().colors().editor_foreground,
12574 font_family: settings.buffer_font.family.clone(),
12575 font_features: settings.buffer_font.features.clone(),
12576 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12577 font_size: settings.buffer_font_size(cx).into(),
12578 font_weight: settings.buffer_font.weight,
12579 line_height: relative(settings.buffer_line_height.value()),
12580 ..Default::default()
12581 },
12582 };
12583
12584 let background = match self.mode {
12585 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12586 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12587 EditorMode::Full => cx.theme().colors().editor_background,
12588 };
12589
12590 EditorElement::new(
12591 cx.view(),
12592 EditorStyle {
12593 background,
12594 local_player: cx.theme().players().local(),
12595 text: text_style,
12596 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12597 syntax: cx.theme().syntax().clone(),
12598 status: cx.theme().status().clone(),
12599 inlay_hints_style: HighlightStyle {
12600 color: Some(cx.theme().status().hint),
12601 ..HighlightStyle::default()
12602 },
12603 suggestions_style: HighlightStyle {
12604 color: Some(cx.theme().status().predictive),
12605 ..HighlightStyle::default()
12606 },
12607 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12608 },
12609 )
12610 }
12611}
12612
12613impl ViewInputHandler for Editor {
12614 fn text_for_range(
12615 &mut self,
12616 range_utf16: Range<usize>,
12617 cx: &mut ViewContext<Self>,
12618 ) -> Option<String> {
12619 Some(
12620 self.buffer
12621 .read(cx)
12622 .read(cx)
12623 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12624 .collect(),
12625 )
12626 }
12627
12628 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12629 // Prevent the IME menu from appearing when holding down an alphabetic key
12630 // while input is disabled.
12631 if !self.input_enabled {
12632 return None;
12633 }
12634
12635 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12636 Some(range.start.0..range.end.0)
12637 }
12638
12639 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12640 let snapshot = self.buffer.read(cx).read(cx);
12641 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12642 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12643 }
12644
12645 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12646 self.clear_highlights::<InputComposition>(cx);
12647 self.ime_transaction.take();
12648 }
12649
12650 fn replace_text_in_range(
12651 &mut self,
12652 range_utf16: Option<Range<usize>>,
12653 text: &str,
12654 cx: &mut ViewContext<Self>,
12655 ) {
12656 if !self.input_enabled {
12657 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12658 return;
12659 }
12660
12661 self.transact(cx, |this, cx| {
12662 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12663 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12664 Some(this.selection_replacement_ranges(range_utf16, cx))
12665 } else {
12666 this.marked_text_ranges(cx)
12667 };
12668
12669 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12670 let newest_selection_id = this.selections.newest_anchor().id;
12671 this.selections
12672 .all::<OffsetUtf16>(cx)
12673 .iter()
12674 .zip(ranges_to_replace.iter())
12675 .find_map(|(selection, range)| {
12676 if selection.id == newest_selection_id {
12677 Some(
12678 (range.start.0 as isize - selection.head().0 as isize)
12679 ..(range.end.0 as isize - selection.head().0 as isize),
12680 )
12681 } else {
12682 None
12683 }
12684 })
12685 });
12686
12687 cx.emit(EditorEvent::InputHandled {
12688 utf16_range_to_replace: range_to_replace,
12689 text: text.into(),
12690 });
12691
12692 if let Some(new_selected_ranges) = new_selected_ranges {
12693 this.change_selections(None, cx, |selections| {
12694 selections.select_ranges(new_selected_ranges)
12695 });
12696 this.backspace(&Default::default(), cx);
12697 }
12698
12699 this.handle_input(text, cx);
12700 });
12701
12702 if let Some(transaction) = self.ime_transaction {
12703 self.buffer.update(cx, |buffer, cx| {
12704 buffer.group_until_transaction(transaction, cx);
12705 });
12706 }
12707
12708 self.unmark_text(cx);
12709 }
12710
12711 fn replace_and_mark_text_in_range(
12712 &mut self,
12713 range_utf16: Option<Range<usize>>,
12714 text: &str,
12715 new_selected_range_utf16: Option<Range<usize>>,
12716 cx: &mut ViewContext<Self>,
12717 ) {
12718 if !self.input_enabled {
12719 return;
12720 }
12721
12722 let transaction = self.transact(cx, |this, cx| {
12723 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12724 let snapshot = this.buffer.read(cx).read(cx);
12725 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12726 for marked_range in &mut marked_ranges {
12727 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12728 marked_range.start.0 += relative_range_utf16.start;
12729 marked_range.start =
12730 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12731 marked_range.end =
12732 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12733 }
12734 }
12735 Some(marked_ranges)
12736 } else if let Some(range_utf16) = range_utf16 {
12737 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12738 Some(this.selection_replacement_ranges(range_utf16, cx))
12739 } else {
12740 None
12741 };
12742
12743 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12744 let newest_selection_id = this.selections.newest_anchor().id;
12745 this.selections
12746 .all::<OffsetUtf16>(cx)
12747 .iter()
12748 .zip(ranges_to_replace.iter())
12749 .find_map(|(selection, range)| {
12750 if selection.id == newest_selection_id {
12751 Some(
12752 (range.start.0 as isize - selection.head().0 as isize)
12753 ..(range.end.0 as isize - selection.head().0 as isize),
12754 )
12755 } else {
12756 None
12757 }
12758 })
12759 });
12760
12761 cx.emit(EditorEvent::InputHandled {
12762 utf16_range_to_replace: range_to_replace,
12763 text: text.into(),
12764 });
12765
12766 if let Some(ranges) = ranges_to_replace {
12767 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12768 }
12769
12770 let marked_ranges = {
12771 let snapshot = this.buffer.read(cx).read(cx);
12772 this.selections
12773 .disjoint_anchors()
12774 .iter()
12775 .map(|selection| {
12776 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12777 })
12778 .collect::<Vec<_>>()
12779 };
12780
12781 if text.is_empty() {
12782 this.unmark_text(cx);
12783 } else {
12784 this.highlight_text::<InputComposition>(
12785 marked_ranges.clone(),
12786 HighlightStyle {
12787 underline: Some(UnderlineStyle {
12788 thickness: px(1.),
12789 color: None,
12790 wavy: false,
12791 }),
12792 ..Default::default()
12793 },
12794 cx,
12795 );
12796 }
12797
12798 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12799 let use_autoclose = this.use_autoclose;
12800 let use_auto_surround = this.use_auto_surround;
12801 this.set_use_autoclose(false);
12802 this.set_use_auto_surround(false);
12803 this.handle_input(text, cx);
12804 this.set_use_autoclose(use_autoclose);
12805 this.set_use_auto_surround(use_auto_surround);
12806
12807 if let Some(new_selected_range) = new_selected_range_utf16 {
12808 let snapshot = this.buffer.read(cx).read(cx);
12809 let new_selected_ranges = marked_ranges
12810 .into_iter()
12811 .map(|marked_range| {
12812 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12813 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12814 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12815 snapshot.clip_offset_utf16(new_start, Bias::Left)
12816 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12817 })
12818 .collect::<Vec<_>>();
12819
12820 drop(snapshot);
12821 this.change_selections(None, cx, |selections| {
12822 selections.select_ranges(new_selected_ranges)
12823 });
12824 }
12825 });
12826
12827 self.ime_transaction = self.ime_transaction.or(transaction);
12828 if let Some(transaction) = self.ime_transaction {
12829 self.buffer.update(cx, |buffer, cx| {
12830 buffer.group_until_transaction(transaction, cx);
12831 });
12832 }
12833
12834 if self.text_highlights::<InputComposition>(cx).is_none() {
12835 self.ime_transaction.take();
12836 }
12837 }
12838
12839 fn bounds_for_range(
12840 &mut self,
12841 range_utf16: Range<usize>,
12842 element_bounds: gpui::Bounds<Pixels>,
12843 cx: &mut ViewContext<Self>,
12844 ) -> Option<gpui::Bounds<Pixels>> {
12845 let text_layout_details = self.text_layout_details(cx);
12846 let style = &text_layout_details.editor_style;
12847 let font_id = cx.text_system().resolve_font(&style.text.font());
12848 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12849 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12850
12851 let em_width = cx
12852 .text_system()
12853 .typographic_bounds(font_id, font_size, 'm')
12854 .unwrap()
12855 .size
12856 .width;
12857
12858 let snapshot = self.snapshot(cx);
12859 let scroll_position = snapshot.scroll_position();
12860 let scroll_left = scroll_position.x * em_width;
12861
12862 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12863 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12864 + self.gutter_dimensions.width;
12865 let y = line_height * (start.row().as_f32() - scroll_position.y);
12866
12867 Some(Bounds {
12868 origin: element_bounds.origin + point(x, y),
12869 size: size(em_width, line_height),
12870 })
12871 }
12872}
12873
12874trait SelectionExt {
12875 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12876 fn spanned_rows(
12877 &self,
12878 include_end_if_at_line_start: bool,
12879 map: &DisplaySnapshot,
12880 ) -> Range<MultiBufferRow>;
12881}
12882
12883impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12884 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12885 let start = self
12886 .start
12887 .to_point(&map.buffer_snapshot)
12888 .to_display_point(map);
12889 let end = self
12890 .end
12891 .to_point(&map.buffer_snapshot)
12892 .to_display_point(map);
12893 if self.reversed {
12894 end..start
12895 } else {
12896 start..end
12897 }
12898 }
12899
12900 fn spanned_rows(
12901 &self,
12902 include_end_if_at_line_start: bool,
12903 map: &DisplaySnapshot,
12904 ) -> Range<MultiBufferRow> {
12905 let start = self.start.to_point(&map.buffer_snapshot);
12906 let mut end = self.end.to_point(&map.buffer_snapshot);
12907 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12908 end.row -= 1;
12909 }
12910
12911 let buffer_start = map.prev_line_boundary(start).0;
12912 let buffer_end = map.next_line_boundary(end).0;
12913 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12914 }
12915}
12916
12917impl<T: InvalidationRegion> InvalidationStack<T> {
12918 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12919 where
12920 S: Clone + ToOffset,
12921 {
12922 while let Some(region) = self.last() {
12923 let all_selections_inside_invalidation_ranges =
12924 if selections.len() == region.ranges().len() {
12925 selections
12926 .iter()
12927 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12928 .all(|(selection, invalidation_range)| {
12929 let head = selection.head().to_offset(buffer);
12930 invalidation_range.start <= head && invalidation_range.end >= head
12931 })
12932 } else {
12933 false
12934 };
12935
12936 if all_selections_inside_invalidation_ranges {
12937 break;
12938 } else {
12939 self.pop();
12940 }
12941 }
12942 }
12943}
12944
12945impl<T> Default for InvalidationStack<T> {
12946 fn default() -> Self {
12947 Self(Default::default())
12948 }
12949}
12950
12951impl<T> Deref for InvalidationStack<T> {
12952 type Target = Vec<T>;
12953
12954 fn deref(&self) -> &Self::Target {
12955 &self.0
12956 }
12957}
12958
12959impl<T> DerefMut for InvalidationStack<T> {
12960 fn deref_mut(&mut self) -> &mut Self::Target {
12961 &mut self.0
12962 }
12963}
12964
12965impl InvalidationRegion for SnippetState {
12966 fn ranges(&self) -> &[Range<Anchor>] {
12967 &self.ranges[self.active_index]
12968 }
12969}
12970
12971pub fn diagnostic_block_renderer(
12972 diagnostic: Diagnostic,
12973 max_message_rows: Option<u8>,
12974 allow_closing: bool,
12975 _is_valid: bool,
12976) -> RenderBlock {
12977 let (text_without_backticks, code_ranges) =
12978 highlight_diagnostic_message(&diagnostic, max_message_rows);
12979
12980 Box::new(move |cx: &mut BlockContext| {
12981 let group_id: SharedString = cx.block_id.to_string().into();
12982
12983 let mut text_style = cx.text_style().clone();
12984 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12985 let theme_settings = ThemeSettings::get_global(cx);
12986 text_style.font_family = theme_settings.buffer_font.family.clone();
12987 text_style.font_style = theme_settings.buffer_font.style;
12988 text_style.font_features = theme_settings.buffer_font.features.clone();
12989 text_style.font_weight = theme_settings.buffer_font.weight;
12990
12991 let multi_line_diagnostic = diagnostic.message.contains('\n');
12992
12993 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12994 if multi_line_diagnostic {
12995 v_flex()
12996 } else {
12997 h_flex()
12998 }
12999 .when(allow_closing, |div| {
13000 div.children(diagnostic.is_primary.then(|| {
13001 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13002 .icon_color(Color::Muted)
13003 .size(ButtonSize::Compact)
13004 .style(ButtonStyle::Transparent)
13005 .visible_on_hover(group_id.clone())
13006 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13007 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13008 }))
13009 })
13010 .child(
13011 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13012 .icon_color(Color::Muted)
13013 .size(ButtonSize::Compact)
13014 .style(ButtonStyle::Transparent)
13015 .visible_on_hover(group_id.clone())
13016 .on_click({
13017 let message = diagnostic.message.clone();
13018 move |_click, cx| {
13019 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13020 }
13021 })
13022 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13023 )
13024 };
13025
13026 let icon_size = buttons(&diagnostic, cx.block_id)
13027 .into_any_element()
13028 .layout_as_root(AvailableSpace::min_size(), cx);
13029
13030 h_flex()
13031 .id(cx.block_id)
13032 .group(group_id.clone())
13033 .relative()
13034 .size_full()
13035 .pl(cx.gutter_dimensions.width)
13036 .w(cx.max_width + cx.gutter_dimensions.width)
13037 .child(
13038 div()
13039 .flex()
13040 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13041 .flex_shrink(),
13042 )
13043 .child(buttons(&diagnostic, cx.block_id))
13044 .child(div().flex().flex_shrink_0().child(
13045 StyledText::new(text_without_backticks.clone()).with_highlights(
13046 &text_style,
13047 code_ranges.iter().map(|range| {
13048 (
13049 range.clone(),
13050 HighlightStyle {
13051 font_weight: Some(FontWeight::BOLD),
13052 ..Default::default()
13053 },
13054 )
13055 }),
13056 ),
13057 ))
13058 .into_any_element()
13059 })
13060}
13061
13062pub fn highlight_diagnostic_message(
13063 diagnostic: &Diagnostic,
13064 mut max_message_rows: Option<u8>,
13065) -> (SharedString, Vec<Range<usize>>) {
13066 let mut text_without_backticks = String::new();
13067 let mut code_ranges = Vec::new();
13068
13069 if let Some(source) = &diagnostic.source {
13070 text_without_backticks.push_str(&source);
13071 code_ranges.push(0..source.len());
13072 text_without_backticks.push_str(": ");
13073 }
13074
13075 let mut prev_offset = 0;
13076 let mut in_code_block = false;
13077 let has_row_limit = max_message_rows.is_some();
13078 let mut newline_indices = diagnostic
13079 .message
13080 .match_indices('\n')
13081 .filter(|_| has_row_limit)
13082 .map(|(ix, _)| ix)
13083 .fuse()
13084 .peekable();
13085
13086 for (quote_ix, _) in diagnostic
13087 .message
13088 .match_indices('`')
13089 .chain([(diagnostic.message.len(), "")])
13090 {
13091 let mut first_newline_ix = None;
13092 let mut last_newline_ix = None;
13093 while let Some(newline_ix) = newline_indices.peek() {
13094 if *newline_ix < quote_ix {
13095 if first_newline_ix.is_none() {
13096 first_newline_ix = Some(*newline_ix);
13097 }
13098 last_newline_ix = Some(*newline_ix);
13099
13100 if let Some(rows_left) = &mut max_message_rows {
13101 if *rows_left == 0 {
13102 break;
13103 } else {
13104 *rows_left -= 1;
13105 }
13106 }
13107 let _ = newline_indices.next();
13108 } else {
13109 break;
13110 }
13111 }
13112 let prev_len = text_without_backticks.len();
13113 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13114 text_without_backticks.push_str(new_text);
13115 if in_code_block {
13116 code_ranges.push(prev_len..text_without_backticks.len());
13117 }
13118 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13119 in_code_block = !in_code_block;
13120 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13121 text_without_backticks.push_str("...");
13122 break;
13123 }
13124 }
13125
13126 (text_without_backticks.into(), code_ranges)
13127}
13128
13129fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13130 match severity {
13131 DiagnosticSeverity::ERROR => colors.error,
13132 DiagnosticSeverity::WARNING => colors.warning,
13133 DiagnosticSeverity::INFORMATION => colors.info,
13134 DiagnosticSeverity::HINT => colors.info,
13135 _ => colors.ignored,
13136 }
13137}
13138
13139pub fn styled_runs_for_code_label<'a>(
13140 label: &'a CodeLabel,
13141 syntax_theme: &'a theme::SyntaxTheme,
13142) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13143 let fade_out = HighlightStyle {
13144 fade_out: Some(0.35),
13145 ..Default::default()
13146 };
13147
13148 let mut prev_end = label.filter_range.end;
13149 label
13150 .runs
13151 .iter()
13152 .enumerate()
13153 .flat_map(move |(ix, (range, highlight_id))| {
13154 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13155 style
13156 } else {
13157 return Default::default();
13158 };
13159 let mut muted_style = style;
13160 muted_style.highlight(fade_out);
13161
13162 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13163 if range.start >= label.filter_range.end {
13164 if range.start > prev_end {
13165 runs.push((prev_end..range.start, fade_out));
13166 }
13167 runs.push((range.clone(), muted_style));
13168 } else if range.end <= label.filter_range.end {
13169 runs.push((range.clone(), style));
13170 } else {
13171 runs.push((range.start..label.filter_range.end, style));
13172 runs.push((label.filter_range.end..range.end, muted_style));
13173 }
13174 prev_end = cmp::max(prev_end, range.end);
13175
13176 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13177 runs.push((prev_end..label.text.len(), fade_out));
13178 }
13179
13180 runs
13181 })
13182}
13183
13184pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13185 let mut prev_index = 0;
13186 let mut prev_codepoint: Option<char> = None;
13187 text.char_indices()
13188 .chain([(text.len(), '\0')])
13189 .filter_map(move |(index, codepoint)| {
13190 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13191 let is_boundary = index == text.len()
13192 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13193 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13194 if is_boundary {
13195 let chunk = &text[prev_index..index];
13196 prev_index = index;
13197 Some(chunk)
13198 } else {
13199 None
13200 }
13201 })
13202}
13203
13204pub trait RangeToAnchorExt: Sized {
13205 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13206
13207 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13208 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13209 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13210 }
13211}
13212
13213impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13214 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13215 let start_offset = self.start.to_offset(snapshot);
13216 let end_offset = self.end.to_offset(snapshot);
13217 if start_offset == end_offset {
13218 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13219 } else {
13220 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13221 }
13222 }
13223}
13224
13225pub trait RowExt {
13226 fn as_f32(&self) -> f32;
13227
13228 fn next_row(&self) -> Self;
13229
13230 fn previous_row(&self) -> Self;
13231
13232 fn minus(&self, other: Self) -> u32;
13233}
13234
13235impl RowExt for DisplayRow {
13236 fn as_f32(&self) -> f32 {
13237 self.0 as f32
13238 }
13239
13240 fn next_row(&self) -> Self {
13241 Self(self.0 + 1)
13242 }
13243
13244 fn previous_row(&self) -> Self {
13245 Self(self.0.saturating_sub(1))
13246 }
13247
13248 fn minus(&self, other: Self) -> u32 {
13249 self.0 - other.0
13250 }
13251}
13252
13253impl RowExt for MultiBufferRow {
13254 fn as_f32(&self) -> f32 {
13255 self.0 as f32
13256 }
13257
13258 fn next_row(&self) -> Self {
13259 Self(self.0 + 1)
13260 }
13261
13262 fn previous_row(&self) -> Self {
13263 Self(self.0.saturating_sub(1))
13264 }
13265
13266 fn minus(&self, other: Self) -> u32 {
13267 self.0 - other.0
13268 }
13269}
13270
13271trait RowRangeExt {
13272 type Row;
13273
13274 fn len(&self) -> usize;
13275
13276 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13277}
13278
13279impl RowRangeExt for Range<MultiBufferRow> {
13280 type Row = MultiBufferRow;
13281
13282 fn len(&self) -> usize {
13283 (self.end.0 - self.start.0) as usize
13284 }
13285
13286 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13287 (self.start.0..self.end.0).map(MultiBufferRow)
13288 }
13289}
13290
13291impl RowRangeExt for Range<DisplayRow> {
13292 type Row = DisplayRow;
13293
13294 fn len(&self) -> usize {
13295 (self.end.0 - self.start.0) as usize
13296 }
13297
13298 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13299 (self.start.0..self.end.0).map(DisplayRow)
13300 }
13301}
13302
13303fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13304 if hunk.diff_base_byte_range.is_empty() {
13305 DiffHunkStatus::Added
13306 } else if hunk.associated_range.is_empty() {
13307 DiffHunkStatus::Removed
13308 } else {
13309 DiffHunkStatus::Modified
13310 }
13311}
13312
13313/// If select range has more than one line, we
13314/// just point the cursor to range.start.
13315fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13316 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13317 range
13318 } else {
13319 range.start..range.start
13320 }
13321}