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::{find_file, 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_vertical);
302 workspace.register_action(Editor::new_file_horizontal);
303 },
304 )
305 .detach();
306
307 cx.on_action(move |_: &workspace::NewFile, cx| {
308 let app_state = workspace::AppState::global(cx);
309 if let Some(app_state) = app_state.upgrade() {
310 workspace::open_new(app_state, cx, |workspace, cx| {
311 Editor::new_file(workspace, &Default::default(), cx)
312 })
313 .detach();
314 }
315 });
316 cx.on_action(move |_: &workspace::NewWindow, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325}
326
327pub struct SearchWithinRange;
328
329trait InvalidationRegion {
330 fn ranges(&self) -> &[Range<Anchor>];
331}
332
333#[derive(Clone, Debug, PartialEq)]
334pub enum SelectPhase {
335 Begin {
336 position: DisplayPoint,
337 add: bool,
338 click_count: usize,
339 },
340 BeginColumnar {
341 position: DisplayPoint,
342 reset: bool,
343 goal_column: u32,
344 },
345 Extend {
346 position: DisplayPoint,
347 click_count: usize,
348 },
349 Update {
350 position: DisplayPoint,
351 goal_column: u32,
352 scroll_delta: gpui::Point<f32>,
353 },
354 End,
355}
356
357#[derive(Clone, Debug)]
358pub enum SelectMode {
359 Character,
360 Word(Range<Anchor>),
361 Line(Range<Anchor>),
362 All,
363}
364
365#[derive(Copy, Clone, PartialEq, Eq, Debug)]
366pub enum EditorMode {
367 SingleLine { auto_width: bool },
368 AutoHeight { max_lines: usize },
369 Full,
370}
371
372#[derive(Clone, Debug)]
373pub enum SoftWrap {
374 None,
375 PreferLine,
376 EditorWidth,
377 Column(u32),
378 Bounded(u32),
379}
380
381#[derive(Clone)]
382pub struct EditorStyle {
383 pub background: Hsla,
384 pub local_player: PlayerColor,
385 pub text: TextStyle,
386 pub scrollbar_width: Pixels,
387 pub syntax: Arc<SyntaxTheme>,
388 pub status: StatusColors,
389 pub inlay_hints_style: HighlightStyle,
390 pub suggestions_style: HighlightStyle,
391 pub unnecessary_code_fade: f32,
392}
393
394impl Default for EditorStyle {
395 fn default() -> Self {
396 Self {
397 background: Hsla::default(),
398 local_player: PlayerColor::default(),
399 text: TextStyle::default(),
400 scrollbar_width: Pixels::default(),
401 syntax: Default::default(),
402 // HACK: Status colors don't have a real default.
403 // We should look into removing the status colors from the editor
404 // style and retrieve them directly from the theme.
405 status: StatusColors::dark(),
406 inlay_hints_style: HighlightStyle::default(),
407 suggestions_style: HighlightStyle::default(),
408 unnecessary_code_fade: Default::default(),
409 }
410 }
411}
412
413type CompletionId = usize;
414
415#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
416struct EditorActionId(usize);
417
418impl EditorActionId {
419 pub fn post_inc(&mut self) -> Self {
420 let answer = self.0;
421
422 *self = Self(answer + 1);
423
424 Self(answer)
425 }
426}
427
428// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
429// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
430
431type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
432type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
433
434#[derive(Default)]
435struct ScrollbarMarkerState {
436 scrollbar_size: Size<Pixels>,
437 dirty: bool,
438 markers: Arc<[PaintQuad]>,
439 pending_refresh: Option<Task<Result<()>>>,
440}
441
442impl ScrollbarMarkerState {
443 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
444 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
445 }
446}
447
448#[derive(Clone, Debug)]
449struct RunnableTasks {
450 templates: Vec<(TaskSourceKind, TaskTemplate)>,
451 offset: MultiBufferOffset,
452 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
453 column: u32,
454 // Values of all named captures, including those starting with '_'
455 extra_variables: HashMap<String, String>,
456 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
457 context_range: Range<BufferOffset>,
458}
459
460#[derive(Clone)]
461struct ResolvedTasks {
462 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
463 position: Anchor,
464}
465#[derive(Copy, Clone, Debug)]
466struct MultiBufferOffset(usize);
467#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
468struct BufferOffset(usize);
469
470// Addons allow storing per-editor state in other crates (e.g. Vim)
471pub trait Addon: 'static {
472 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
473
474 fn to_any(&self) -> &dyn std::any::Any;
475}
476
477/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
478///
479/// See the [module level documentation](self) for more information.
480pub struct Editor {
481 focus_handle: FocusHandle,
482 last_focused_descendant: Option<WeakFocusHandle>,
483 /// The text buffer being edited
484 buffer: Model<MultiBuffer>,
485 /// Map of how text in the buffer should be displayed.
486 /// Handles soft wraps, folds, fake inlay text insertions, etc.
487 pub display_map: Model<DisplayMap>,
488 pub selections: SelectionsCollection,
489 pub scroll_manager: ScrollManager,
490 /// When inline assist editors are linked, they all render cursors because
491 /// typing enters text into each of them, even the ones that aren't focused.
492 pub(crate) show_cursor_when_unfocused: bool,
493 columnar_selection_tail: Option<Anchor>,
494 add_selections_state: Option<AddSelectionsState>,
495 select_next_state: Option<SelectNextState>,
496 select_prev_state: Option<SelectNextState>,
497 selection_history: SelectionHistory,
498 autoclose_regions: Vec<AutocloseRegion>,
499 snippet_stack: InvalidationStack<SnippetState>,
500 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
501 ime_transaction: Option<TransactionId>,
502 active_diagnostics: Option<ActiveDiagnosticGroup>,
503 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
504 project: Option<Model<Project>>,
505 completion_provider: Option<Box<dyn CompletionProvider>>,
506 collaboration_hub: Option<Box<dyn CollaborationHub>>,
507 blink_manager: Model<BlinkManager>,
508 show_cursor_names: bool,
509 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
510 pub show_local_selections: bool,
511 mode: EditorMode,
512 show_breadcrumbs: bool,
513 show_gutter: bool,
514 show_line_numbers: Option<bool>,
515 show_git_diff_gutter: Option<bool>,
516 show_code_actions: Option<bool>,
517 show_runnables: Option<bool>,
518 show_wrap_guides: Option<bool>,
519 show_indent_guides: Option<bool>,
520 placeholder_text: Option<Arc<str>>,
521 highlight_order: usize,
522 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
523 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
524 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
525 scrollbar_marker_state: ScrollbarMarkerState,
526 active_indent_guides_state: ActiveIndentGuidesState,
527 nav_history: Option<ItemNavHistory>,
528 context_menu: RwLock<Option<ContextMenu>>,
529 mouse_context_menu: Option<MouseContextMenu>,
530 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
531 signature_help_state: SignatureHelpState,
532 auto_signature_help: Option<bool>,
533 find_all_references_task_sources: Vec<Anchor>,
534 next_completion_id: CompletionId,
535 completion_documentation_pre_resolve_debounce: DebouncedDelay,
536 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
537 code_actions_task: Option<Task<()>>,
538 document_highlights_task: Option<Task<()>>,
539 linked_editing_range_task: Option<Task<Option<()>>>,
540 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
541 pending_rename: Option<RenameState>,
542 searchable: bool,
543 cursor_shape: CursorShape,
544 current_line_highlight: Option<CurrentLineHighlight>,
545 collapse_matches: bool,
546 autoindent_mode: Option<AutoindentMode>,
547 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
548 input_enabled: bool,
549 use_modal_editing: bool,
550 read_only: bool,
551 leader_peer_id: Option<PeerId>,
552 remote_id: Option<ViewId>,
553 hover_state: HoverState,
554 gutter_hovered: bool,
555 hovered_link_state: Option<HoveredLinkState>,
556 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
557 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
558 show_inline_completions: bool,
559 inlay_hint_cache: InlayHintCache,
560 expanded_hunks: ExpandedHunks,
561 next_inlay_id: usize,
562 _subscriptions: Vec<Subscription>,
563 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
564 gutter_dimensions: GutterDimensions,
565 style: Option<EditorStyle>,
566 next_editor_action_id: EditorActionId,
567 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
568 use_autoclose: bool,
569 use_auto_surround: bool,
570 auto_replace_emoji_shortcode: bool,
571 show_git_blame_gutter: bool,
572 show_git_blame_inline: bool,
573 show_git_blame_inline_delay_task: Option<Task<()>>,
574 git_blame_inline_enabled: bool,
575 serialize_dirty_buffers: bool,
576 show_selection_menu: Option<bool>,
577 blame: Option<Model<GitBlame>>,
578 blame_subscription: Option<Subscription>,
579 custom_context_menu: Option<
580 Box<
581 dyn 'static
582 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
583 >,
584 >,
585 last_bounds: Option<Bounds<Pixels>>,
586 expect_bounds_change: Option<Bounds<Pixels>>,
587 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
588 tasks_update_task: Option<Task<()>>,
589 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
590 file_header_size: u32,
591 breadcrumb_header: Option<String>,
592 focused_block: Option<FocusedBlock>,
593 next_scroll_position: NextScrollCursorCenterTopBottom,
594 addons: HashMap<TypeId, Box<dyn Addon>>,
595 _scroll_cursor_center_top_bottom_task: Task<()>,
596}
597
598#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
599enum NextScrollCursorCenterTopBottom {
600 #[default]
601 Center,
602 Top,
603 Bottom,
604}
605
606impl NextScrollCursorCenterTopBottom {
607 fn next(&self) -> Self {
608 match self {
609 Self::Center => Self::Top,
610 Self::Top => Self::Bottom,
611 Self::Bottom => Self::Center,
612 }
613 }
614}
615
616#[derive(Clone)]
617pub struct EditorSnapshot {
618 pub mode: EditorMode,
619 show_gutter: bool,
620 show_line_numbers: Option<bool>,
621 show_git_diff_gutter: Option<bool>,
622 show_code_actions: Option<bool>,
623 show_runnables: Option<bool>,
624 render_git_blame_gutter: bool,
625 pub display_snapshot: DisplaySnapshot,
626 pub placeholder_text: Option<Arc<str>>,
627 is_focused: bool,
628 scroll_anchor: ScrollAnchor,
629 ongoing_scroll: OngoingScroll,
630 current_line_highlight: CurrentLineHighlight,
631 gutter_hovered: bool,
632}
633
634const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
635
636#[derive(Default, Debug, Clone, Copy)]
637pub struct GutterDimensions {
638 pub left_padding: Pixels,
639 pub right_padding: Pixels,
640 pub width: Pixels,
641 pub margin: Pixels,
642 pub git_blame_entries_width: Option<Pixels>,
643}
644
645impl GutterDimensions {
646 /// The full width of the space taken up by the gutter.
647 pub fn full_width(&self) -> Pixels {
648 self.margin + self.width
649 }
650
651 /// The width of the space reserved for the fold indicators,
652 /// use alongside 'justify_end' and `gutter_width` to
653 /// right align content with the line numbers
654 pub fn fold_area_width(&self) -> Pixels {
655 self.margin + self.right_padding
656 }
657}
658
659#[derive(Debug)]
660pub struct RemoteSelection {
661 pub replica_id: ReplicaId,
662 pub selection: Selection<Anchor>,
663 pub cursor_shape: CursorShape,
664 pub peer_id: PeerId,
665 pub line_mode: bool,
666 pub participant_index: Option<ParticipantIndex>,
667 pub user_name: Option<SharedString>,
668}
669
670#[derive(Clone, Debug)]
671struct SelectionHistoryEntry {
672 selections: Arc<[Selection<Anchor>]>,
673 select_next_state: Option<SelectNextState>,
674 select_prev_state: Option<SelectNextState>,
675 add_selections_state: Option<AddSelectionsState>,
676}
677
678enum SelectionHistoryMode {
679 Normal,
680 Undoing,
681 Redoing,
682}
683
684#[derive(Clone, PartialEq, Eq, Hash)]
685struct HoveredCursor {
686 replica_id: u16,
687 selection_id: usize,
688}
689
690impl Default for SelectionHistoryMode {
691 fn default() -> Self {
692 Self::Normal
693 }
694}
695
696#[derive(Default)]
697struct SelectionHistory {
698 #[allow(clippy::type_complexity)]
699 selections_by_transaction:
700 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
701 mode: SelectionHistoryMode,
702 undo_stack: VecDeque<SelectionHistoryEntry>,
703 redo_stack: VecDeque<SelectionHistoryEntry>,
704}
705
706impl SelectionHistory {
707 fn insert_transaction(
708 &mut self,
709 transaction_id: TransactionId,
710 selections: Arc<[Selection<Anchor>]>,
711 ) {
712 self.selections_by_transaction
713 .insert(transaction_id, (selections, None));
714 }
715
716 #[allow(clippy::type_complexity)]
717 fn transaction(
718 &self,
719 transaction_id: TransactionId,
720 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
721 self.selections_by_transaction.get(&transaction_id)
722 }
723
724 #[allow(clippy::type_complexity)]
725 fn transaction_mut(
726 &mut self,
727 transaction_id: TransactionId,
728 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
729 self.selections_by_transaction.get_mut(&transaction_id)
730 }
731
732 fn push(&mut self, entry: SelectionHistoryEntry) {
733 if !entry.selections.is_empty() {
734 match self.mode {
735 SelectionHistoryMode::Normal => {
736 self.push_undo(entry);
737 self.redo_stack.clear();
738 }
739 SelectionHistoryMode::Undoing => self.push_redo(entry),
740 SelectionHistoryMode::Redoing => self.push_undo(entry),
741 }
742 }
743 }
744
745 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
746 if self
747 .undo_stack
748 .back()
749 .map_or(true, |e| e.selections != entry.selections)
750 {
751 self.undo_stack.push_back(entry);
752 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
753 self.undo_stack.pop_front();
754 }
755 }
756 }
757
758 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
759 if self
760 .redo_stack
761 .back()
762 .map_or(true, |e| e.selections != entry.selections)
763 {
764 self.redo_stack.push_back(entry);
765 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
766 self.redo_stack.pop_front();
767 }
768 }
769 }
770}
771
772struct RowHighlight {
773 index: usize,
774 range: RangeInclusive<Anchor>,
775 color: Option<Hsla>,
776 should_autoscroll: bool,
777}
778
779#[derive(Clone, Debug)]
780struct AddSelectionsState {
781 above: bool,
782 stack: Vec<usize>,
783}
784
785#[derive(Clone)]
786struct SelectNextState {
787 query: AhoCorasick,
788 wordwise: bool,
789 done: bool,
790}
791
792impl std::fmt::Debug for SelectNextState {
793 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
794 f.debug_struct(std::any::type_name::<Self>())
795 .field("wordwise", &self.wordwise)
796 .field("done", &self.done)
797 .finish()
798 }
799}
800
801#[derive(Debug)]
802struct AutocloseRegion {
803 selection_id: usize,
804 range: Range<Anchor>,
805 pair: BracketPair,
806}
807
808#[derive(Debug)]
809struct SnippetState {
810 ranges: Vec<Vec<Range<Anchor>>>,
811 active_index: usize,
812}
813
814#[doc(hidden)]
815pub struct RenameState {
816 pub range: Range<Anchor>,
817 pub old_name: Arc<str>,
818 pub editor: View<Editor>,
819 block_id: CustomBlockId,
820}
821
822struct InvalidationStack<T>(Vec<T>);
823
824struct RegisteredInlineCompletionProvider {
825 provider: Arc<dyn InlineCompletionProviderHandle>,
826 _subscription: Subscription,
827}
828
829enum ContextMenu {
830 Completions(CompletionsMenu),
831 CodeActions(CodeActionsMenu),
832}
833
834impl ContextMenu {
835 fn select_first(
836 &mut self,
837 project: Option<&Model<Project>>,
838 cx: &mut ViewContext<Editor>,
839 ) -> bool {
840 if self.visible() {
841 match self {
842 ContextMenu::Completions(menu) => menu.select_first(project, cx),
843 ContextMenu::CodeActions(menu) => menu.select_first(cx),
844 }
845 true
846 } else {
847 false
848 }
849 }
850
851 fn select_prev(
852 &mut self,
853 project: Option<&Model<Project>>,
854 cx: &mut ViewContext<Editor>,
855 ) -> bool {
856 if self.visible() {
857 match self {
858 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
859 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
860 }
861 true
862 } else {
863 false
864 }
865 }
866
867 fn select_next(
868 &mut self,
869 project: Option<&Model<Project>>,
870 cx: &mut ViewContext<Editor>,
871 ) -> bool {
872 if self.visible() {
873 match self {
874 ContextMenu::Completions(menu) => menu.select_next(project, cx),
875 ContextMenu::CodeActions(menu) => menu.select_next(cx),
876 }
877 true
878 } else {
879 false
880 }
881 }
882
883 fn select_last(
884 &mut self,
885 project: Option<&Model<Project>>,
886 cx: &mut ViewContext<Editor>,
887 ) -> bool {
888 if self.visible() {
889 match self {
890 ContextMenu::Completions(menu) => menu.select_last(project, cx),
891 ContextMenu::CodeActions(menu) => menu.select_last(cx),
892 }
893 true
894 } else {
895 false
896 }
897 }
898
899 fn visible(&self) -> bool {
900 match self {
901 ContextMenu::Completions(menu) => menu.visible(),
902 ContextMenu::CodeActions(menu) => menu.visible(),
903 }
904 }
905
906 fn render(
907 &self,
908 cursor_position: DisplayPoint,
909 style: &EditorStyle,
910 max_height: Pixels,
911 workspace: Option<WeakView<Workspace>>,
912 cx: &mut ViewContext<Editor>,
913 ) -> (ContextMenuOrigin, AnyElement) {
914 match self {
915 ContextMenu::Completions(menu) => (
916 ContextMenuOrigin::EditorPoint(cursor_position),
917 menu.render(style, max_height, workspace, cx),
918 ),
919 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
920 }
921 }
922}
923
924enum ContextMenuOrigin {
925 EditorPoint(DisplayPoint),
926 GutterIndicator(DisplayRow),
927}
928
929#[derive(Clone)]
930struct CompletionsMenu {
931 id: CompletionId,
932 sort_completions: bool,
933 initial_position: Anchor,
934 buffer: Model<Buffer>,
935 completions: Arc<RwLock<Box<[Completion]>>>,
936 match_candidates: Arc<[StringMatchCandidate]>,
937 matches: Arc<[StringMatch]>,
938 selected_item: usize,
939 scroll_handle: UniformListScrollHandle,
940 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
941}
942
943impl CompletionsMenu {
944 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
945 self.selected_item = 0;
946 self.scroll_handle.scroll_to_item(self.selected_item);
947 self.attempt_resolve_selected_completion_documentation(project, cx);
948 cx.notify();
949 }
950
951 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
952 if self.selected_item > 0 {
953 self.selected_item -= 1;
954 } else {
955 self.selected_item = self.matches.len() - 1;
956 }
957 self.scroll_handle.scroll_to_item(self.selected_item);
958 self.attempt_resolve_selected_completion_documentation(project, cx);
959 cx.notify();
960 }
961
962 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
963 if self.selected_item + 1 < self.matches.len() {
964 self.selected_item += 1;
965 } else {
966 self.selected_item = 0;
967 }
968 self.scroll_handle.scroll_to_item(self.selected_item);
969 self.attempt_resolve_selected_completion_documentation(project, cx);
970 cx.notify();
971 }
972
973 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
974 self.selected_item = self.matches.len() - 1;
975 self.scroll_handle.scroll_to_item(self.selected_item);
976 self.attempt_resolve_selected_completion_documentation(project, cx);
977 cx.notify();
978 }
979
980 fn pre_resolve_completion_documentation(
981 buffer: Model<Buffer>,
982 completions: Arc<RwLock<Box<[Completion]>>>,
983 matches: Arc<[StringMatch]>,
984 editor: &Editor,
985 cx: &mut ViewContext<Editor>,
986 ) -> Task<()> {
987 let settings = EditorSettings::get_global(cx);
988 if !settings.show_completion_documentation {
989 return Task::ready(());
990 }
991
992 let Some(provider) = editor.completion_provider.as_ref() else {
993 return Task::ready(());
994 };
995
996 let resolve_task = provider.resolve_completions(
997 buffer,
998 matches.iter().map(|m| m.candidate_id).collect(),
999 completions.clone(),
1000 cx,
1001 );
1002
1003 return cx.spawn(move |this, mut cx| async move {
1004 if let Some(true) = resolve_task.await.log_err() {
1005 this.update(&mut cx, |_, cx| cx.notify()).ok();
1006 }
1007 });
1008 }
1009
1010 fn attempt_resolve_selected_completion_documentation(
1011 &mut self,
1012 project: Option<&Model<Project>>,
1013 cx: &mut ViewContext<Editor>,
1014 ) {
1015 let settings = EditorSettings::get_global(cx);
1016 if !settings.show_completion_documentation {
1017 return;
1018 }
1019
1020 let completion_index = self.matches[self.selected_item].candidate_id;
1021 let Some(project) = project else {
1022 return;
1023 };
1024
1025 let resolve_task = project.update(cx, |project, cx| {
1026 project.resolve_completions(
1027 self.buffer.clone(),
1028 vec![completion_index],
1029 self.completions.clone(),
1030 cx,
1031 )
1032 });
1033
1034 let delay_ms =
1035 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1036 let delay = Duration::from_millis(delay_ms);
1037
1038 self.selected_completion_documentation_resolve_debounce
1039 .lock()
1040 .fire_new(delay, cx, |_, cx| {
1041 cx.spawn(move |this, mut cx| async move {
1042 if let Some(true) = resolve_task.await.log_err() {
1043 this.update(&mut cx, |_, cx| cx.notify()).ok();
1044 }
1045 })
1046 });
1047 }
1048
1049 fn visible(&self) -> bool {
1050 !self.matches.is_empty()
1051 }
1052
1053 fn render(
1054 &self,
1055 style: &EditorStyle,
1056 max_height: Pixels,
1057 workspace: Option<WeakView<Workspace>>,
1058 cx: &mut ViewContext<Editor>,
1059 ) -> AnyElement {
1060 let settings = EditorSettings::get_global(cx);
1061 let show_completion_documentation = settings.show_completion_documentation;
1062
1063 let widest_completion_ix = self
1064 .matches
1065 .iter()
1066 .enumerate()
1067 .max_by_key(|(_, mat)| {
1068 let completions = self.completions.read();
1069 let completion = &completions[mat.candidate_id];
1070 let documentation = &completion.documentation;
1071
1072 let mut len = completion.label.text.chars().count();
1073 if let Some(Documentation::SingleLine(text)) = documentation {
1074 if show_completion_documentation {
1075 len += text.chars().count();
1076 }
1077 }
1078
1079 len
1080 })
1081 .map(|(ix, _)| ix);
1082
1083 let completions = self.completions.clone();
1084 let matches = self.matches.clone();
1085 let selected_item = self.selected_item;
1086 let style = style.clone();
1087
1088 let multiline_docs = if show_completion_documentation {
1089 let mat = &self.matches[selected_item];
1090 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1091 Some(Documentation::MultiLinePlainText(text)) => {
1092 Some(div().child(SharedString::from(text.clone())))
1093 }
1094 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1095 Some(div().child(render_parsed_markdown(
1096 "completions_markdown",
1097 parsed,
1098 &style,
1099 workspace,
1100 cx,
1101 )))
1102 }
1103 _ => None,
1104 };
1105 multiline_docs.map(|div| {
1106 div.id("multiline_docs")
1107 .max_h(max_height)
1108 .flex_1()
1109 .px_1p5()
1110 .py_1()
1111 .min_w(px(260.))
1112 .max_w(px(640.))
1113 .w(px(500.))
1114 .overflow_y_scroll()
1115 .occlude()
1116 })
1117 } else {
1118 None
1119 };
1120
1121 let list = uniform_list(
1122 cx.view().clone(),
1123 "completions",
1124 matches.len(),
1125 move |_editor, range, cx| {
1126 let start_ix = range.start;
1127 let completions_guard = completions.read();
1128
1129 matches[range]
1130 .iter()
1131 .enumerate()
1132 .map(|(ix, mat)| {
1133 let item_ix = start_ix + ix;
1134 let candidate_id = mat.candidate_id;
1135 let completion = &completions_guard[candidate_id];
1136
1137 let documentation = if show_completion_documentation {
1138 &completion.documentation
1139 } else {
1140 &None
1141 };
1142
1143 let highlights = gpui::combine_highlights(
1144 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1145 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1146 |(range, mut highlight)| {
1147 // Ignore font weight for syntax highlighting, as we'll use it
1148 // for fuzzy matches.
1149 highlight.font_weight = None;
1150
1151 if completion.lsp_completion.deprecated.unwrap_or(false) {
1152 highlight.strikethrough = Some(StrikethroughStyle {
1153 thickness: 1.0.into(),
1154 ..Default::default()
1155 });
1156 highlight.color = Some(cx.theme().colors().text_muted);
1157 }
1158
1159 (range, highlight)
1160 },
1161 ),
1162 );
1163 let completion_label = StyledText::new(completion.label.text.clone())
1164 .with_highlights(&style.text, highlights);
1165 let documentation_label =
1166 if let Some(Documentation::SingleLine(text)) = documentation {
1167 if text.trim().is_empty() {
1168 None
1169 } else {
1170 Some(
1171 Label::new(text.clone())
1172 .ml_4()
1173 .size(LabelSize::Small)
1174 .color(Color::Muted),
1175 )
1176 }
1177 } else {
1178 None
1179 };
1180
1181 div().min_w(px(220.)).max_w(px(540.)).child(
1182 ListItem::new(mat.candidate_id)
1183 .inset(true)
1184 .selected(item_ix == selected_item)
1185 .on_click(cx.listener(move |editor, _event, cx| {
1186 cx.stop_propagation();
1187 if let Some(task) = editor.confirm_completion(
1188 &ConfirmCompletion {
1189 item_ix: Some(item_ix),
1190 },
1191 cx,
1192 ) {
1193 task.detach_and_log_err(cx)
1194 }
1195 }))
1196 .child(h_flex().overflow_hidden().child(completion_label))
1197 .end_slot::<Label>(documentation_label),
1198 )
1199 })
1200 .collect()
1201 },
1202 )
1203 .occlude()
1204 .max_h(max_height)
1205 .track_scroll(self.scroll_handle.clone())
1206 .with_width_from_item(widest_completion_ix)
1207 .with_sizing_behavior(ListSizingBehavior::Infer);
1208
1209 Popover::new()
1210 .child(list)
1211 .when_some(multiline_docs, |popover, multiline_docs| {
1212 popover.aside(multiline_docs)
1213 })
1214 .into_any_element()
1215 }
1216
1217 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1218 let mut matches = if let Some(query) = query {
1219 fuzzy::match_strings(
1220 &self.match_candidates,
1221 query,
1222 query.chars().any(|c| c.is_uppercase()),
1223 100,
1224 &Default::default(),
1225 executor,
1226 )
1227 .await
1228 } else {
1229 self.match_candidates
1230 .iter()
1231 .enumerate()
1232 .map(|(candidate_id, candidate)| StringMatch {
1233 candidate_id,
1234 score: Default::default(),
1235 positions: Default::default(),
1236 string: candidate.string.clone(),
1237 })
1238 .collect()
1239 };
1240
1241 // Remove all candidates where the query's start does not match the start of any word in the candidate
1242 if let Some(query) = query {
1243 if let Some(query_start) = query.chars().next() {
1244 matches.retain(|string_match| {
1245 split_words(&string_match.string).any(|word| {
1246 // Check that the first codepoint of the word as lowercase matches the first
1247 // codepoint of the query as lowercase
1248 word.chars()
1249 .flat_map(|codepoint| codepoint.to_lowercase())
1250 .zip(query_start.to_lowercase())
1251 .all(|(word_cp, query_cp)| word_cp == query_cp)
1252 })
1253 });
1254 }
1255 }
1256
1257 let completions = self.completions.read();
1258 if self.sort_completions {
1259 matches.sort_unstable_by_key(|mat| {
1260 // We do want to strike a balance here between what the language server tells us
1261 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1262 // `Creat` and there is a local variable called `CreateComponent`).
1263 // So what we do is: we bucket all matches into two buckets
1264 // - Strong matches
1265 // - Weak matches
1266 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1267 // and the Weak matches are the rest.
1268 //
1269 // For the strong matches, we sort by the language-servers score first and for the weak
1270 // matches, we prefer our fuzzy finder first.
1271 //
1272 // The thinking behind that: it's useless to take the sort_text the language-server gives
1273 // us into account when it's obviously a bad match.
1274
1275 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1276 enum MatchScore<'a> {
1277 Strong {
1278 sort_text: Option<&'a str>,
1279 score: Reverse<OrderedFloat<f64>>,
1280 sort_key: (usize, &'a str),
1281 },
1282 Weak {
1283 score: Reverse<OrderedFloat<f64>>,
1284 sort_text: Option<&'a str>,
1285 sort_key: (usize, &'a str),
1286 },
1287 }
1288
1289 let completion = &completions[mat.candidate_id];
1290 let sort_key = completion.sort_key();
1291 let sort_text = completion.lsp_completion.sort_text.as_deref();
1292 let score = Reverse(OrderedFloat(mat.score));
1293
1294 if mat.score >= 0.2 {
1295 MatchScore::Strong {
1296 sort_text,
1297 score,
1298 sort_key,
1299 }
1300 } else {
1301 MatchScore::Weak {
1302 score,
1303 sort_text,
1304 sort_key,
1305 }
1306 }
1307 });
1308 }
1309
1310 for mat in &mut matches {
1311 let completion = &completions[mat.candidate_id];
1312 mat.string.clone_from(&completion.label.text);
1313 for position in &mut mat.positions {
1314 *position += completion.label.filter_range.start;
1315 }
1316 }
1317 drop(completions);
1318
1319 self.matches = matches.into();
1320 self.selected_item = 0;
1321 }
1322}
1323
1324#[derive(Clone)]
1325struct CodeActionContents {
1326 tasks: Option<Arc<ResolvedTasks>>,
1327 actions: Option<Arc<[CodeAction]>>,
1328}
1329
1330impl CodeActionContents {
1331 fn len(&self) -> usize {
1332 match (&self.tasks, &self.actions) {
1333 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1334 (Some(tasks), None) => tasks.templates.len(),
1335 (None, Some(actions)) => actions.len(),
1336 (None, None) => 0,
1337 }
1338 }
1339
1340 fn is_empty(&self) -> bool {
1341 match (&self.tasks, &self.actions) {
1342 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1343 (Some(tasks), None) => tasks.templates.is_empty(),
1344 (None, Some(actions)) => actions.is_empty(),
1345 (None, None) => true,
1346 }
1347 }
1348
1349 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1350 self.tasks
1351 .iter()
1352 .flat_map(|tasks| {
1353 tasks
1354 .templates
1355 .iter()
1356 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1357 })
1358 .chain(self.actions.iter().flat_map(|actions| {
1359 actions
1360 .iter()
1361 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1362 }))
1363 }
1364 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1365 match (&self.tasks, &self.actions) {
1366 (Some(tasks), Some(actions)) => {
1367 if index < tasks.templates.len() {
1368 tasks
1369 .templates
1370 .get(index)
1371 .cloned()
1372 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1373 } else {
1374 actions
1375 .get(index - tasks.templates.len())
1376 .cloned()
1377 .map(CodeActionsItem::CodeAction)
1378 }
1379 }
1380 (Some(tasks), None) => tasks
1381 .templates
1382 .get(index)
1383 .cloned()
1384 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1385 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1386 (None, None) => None,
1387 }
1388 }
1389}
1390
1391#[allow(clippy::large_enum_variant)]
1392#[derive(Clone)]
1393enum CodeActionsItem {
1394 Task(TaskSourceKind, ResolvedTask),
1395 CodeAction(CodeAction),
1396}
1397
1398impl CodeActionsItem {
1399 fn as_task(&self) -> Option<&ResolvedTask> {
1400 let Self::Task(_, task) = self else {
1401 return None;
1402 };
1403 Some(task)
1404 }
1405 fn as_code_action(&self) -> Option<&CodeAction> {
1406 let Self::CodeAction(action) = self else {
1407 return None;
1408 };
1409 Some(action)
1410 }
1411 fn label(&self) -> String {
1412 match self {
1413 Self::CodeAction(action) => action.lsp_action.title.clone(),
1414 Self::Task(_, task) => task.resolved_label.clone(),
1415 }
1416 }
1417}
1418
1419struct CodeActionsMenu {
1420 actions: CodeActionContents,
1421 buffer: Model<Buffer>,
1422 selected_item: usize,
1423 scroll_handle: UniformListScrollHandle,
1424 deployed_from_indicator: Option<DisplayRow>,
1425}
1426
1427impl CodeActionsMenu {
1428 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1429 self.selected_item = 0;
1430 self.scroll_handle.scroll_to_item(self.selected_item);
1431 cx.notify()
1432 }
1433
1434 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1435 if self.selected_item > 0 {
1436 self.selected_item -= 1;
1437 } else {
1438 self.selected_item = self.actions.len() - 1;
1439 }
1440 self.scroll_handle.scroll_to_item(self.selected_item);
1441 cx.notify();
1442 }
1443
1444 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1445 if self.selected_item + 1 < self.actions.len() {
1446 self.selected_item += 1;
1447 } else {
1448 self.selected_item = 0;
1449 }
1450 self.scroll_handle.scroll_to_item(self.selected_item);
1451 cx.notify();
1452 }
1453
1454 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1455 self.selected_item = self.actions.len() - 1;
1456 self.scroll_handle.scroll_to_item(self.selected_item);
1457 cx.notify()
1458 }
1459
1460 fn visible(&self) -> bool {
1461 !self.actions.is_empty()
1462 }
1463
1464 fn render(
1465 &self,
1466 cursor_position: DisplayPoint,
1467 _style: &EditorStyle,
1468 max_height: Pixels,
1469 cx: &mut ViewContext<Editor>,
1470 ) -> (ContextMenuOrigin, AnyElement) {
1471 let actions = self.actions.clone();
1472 let selected_item = self.selected_item;
1473 let element = uniform_list(
1474 cx.view().clone(),
1475 "code_actions_menu",
1476 self.actions.len(),
1477 move |_this, range, cx| {
1478 actions
1479 .iter()
1480 .skip(range.start)
1481 .take(range.end - range.start)
1482 .enumerate()
1483 .map(|(ix, action)| {
1484 let item_ix = range.start + ix;
1485 let selected = selected_item == item_ix;
1486 let colors = cx.theme().colors();
1487 div()
1488 .px_2()
1489 .text_color(colors.text)
1490 .when(selected, |style| {
1491 style
1492 .bg(colors.element_active)
1493 .text_color(colors.text_accent)
1494 })
1495 .hover(|style| {
1496 style
1497 .bg(colors.element_hover)
1498 .text_color(colors.text_accent)
1499 })
1500 .whitespace_nowrap()
1501 .when_some(action.as_code_action(), |this, action| {
1502 this.on_mouse_down(
1503 MouseButton::Left,
1504 cx.listener(move |editor, _, cx| {
1505 cx.stop_propagation();
1506 if let Some(task) = editor.confirm_code_action(
1507 &ConfirmCodeAction {
1508 item_ix: Some(item_ix),
1509 },
1510 cx,
1511 ) {
1512 task.detach_and_log_err(cx)
1513 }
1514 }),
1515 )
1516 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1517 .child(SharedString::from(action.lsp_action.title.clone()))
1518 })
1519 .when_some(action.as_task(), |this, task| {
1520 this.on_mouse_down(
1521 MouseButton::Left,
1522 cx.listener(move |editor, _, cx| {
1523 cx.stop_propagation();
1524 if let Some(task) = editor.confirm_code_action(
1525 &ConfirmCodeAction {
1526 item_ix: Some(item_ix),
1527 },
1528 cx,
1529 ) {
1530 task.detach_and_log_err(cx)
1531 }
1532 }),
1533 )
1534 .child(SharedString::from(task.resolved_label.clone()))
1535 })
1536 })
1537 .collect()
1538 },
1539 )
1540 .elevation_1(cx)
1541 .px_2()
1542 .py_1()
1543 .max_h(max_height)
1544 .occlude()
1545 .track_scroll(self.scroll_handle.clone())
1546 .with_width_from_item(
1547 self.actions
1548 .iter()
1549 .enumerate()
1550 .max_by_key(|(_, action)| match action {
1551 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1552 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1553 })
1554 .map(|(ix, _)| ix),
1555 )
1556 .with_sizing_behavior(ListSizingBehavior::Infer)
1557 .into_any_element();
1558
1559 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1560 ContextMenuOrigin::GutterIndicator(row)
1561 } else {
1562 ContextMenuOrigin::EditorPoint(cursor_position)
1563 };
1564
1565 (cursor_position, element)
1566 }
1567}
1568
1569#[derive(Debug)]
1570struct ActiveDiagnosticGroup {
1571 primary_range: Range<Anchor>,
1572 primary_message: String,
1573 group_id: usize,
1574 blocks: HashMap<CustomBlockId, Diagnostic>,
1575 is_valid: bool,
1576}
1577
1578#[derive(Serialize, Deserialize, Clone, Debug)]
1579pub struct ClipboardSelection {
1580 pub len: usize,
1581 pub is_entire_line: bool,
1582 pub first_line_indent: u32,
1583}
1584
1585#[derive(Debug)]
1586pub(crate) struct NavigationData {
1587 cursor_anchor: Anchor,
1588 cursor_position: Point,
1589 scroll_anchor: ScrollAnchor,
1590 scroll_top_row: u32,
1591}
1592
1593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1594enum GotoDefinitionKind {
1595 Symbol,
1596 Declaration,
1597 Type,
1598 Implementation,
1599}
1600
1601#[derive(Debug, Clone)]
1602enum InlayHintRefreshReason {
1603 Toggle(bool),
1604 SettingsChange(InlayHintSettings),
1605 NewLinesShown,
1606 BufferEdited(HashSet<Arc<Language>>),
1607 RefreshRequested,
1608 ExcerptsRemoved(Vec<ExcerptId>),
1609}
1610
1611impl InlayHintRefreshReason {
1612 fn description(&self) -> &'static str {
1613 match self {
1614 Self::Toggle(_) => "toggle",
1615 Self::SettingsChange(_) => "settings change",
1616 Self::NewLinesShown => "new lines shown",
1617 Self::BufferEdited(_) => "buffer edited",
1618 Self::RefreshRequested => "refresh requested",
1619 Self::ExcerptsRemoved(_) => "excerpts removed",
1620 }
1621 }
1622}
1623
1624pub(crate) struct FocusedBlock {
1625 id: BlockId,
1626 focus_handle: WeakFocusHandle,
1627}
1628
1629impl Editor {
1630 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1631 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1632 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1633 Self::new(
1634 EditorMode::SingleLine { auto_width: false },
1635 buffer,
1636 None,
1637 false,
1638 cx,
1639 )
1640 }
1641
1642 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1643 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1644 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1645 Self::new(EditorMode::Full, buffer, None, false, cx)
1646 }
1647
1648 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1649 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1650 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1651 Self::new(
1652 EditorMode::SingleLine { auto_width: true },
1653 buffer,
1654 None,
1655 false,
1656 cx,
1657 )
1658 }
1659
1660 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1661 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1662 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1663 Self::new(
1664 EditorMode::AutoHeight { max_lines },
1665 buffer,
1666 None,
1667 false,
1668 cx,
1669 )
1670 }
1671
1672 pub fn for_buffer(
1673 buffer: Model<Buffer>,
1674 project: Option<Model<Project>>,
1675 cx: &mut ViewContext<Self>,
1676 ) -> Self {
1677 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1678 Self::new(EditorMode::Full, buffer, project, false, cx)
1679 }
1680
1681 pub fn for_multibuffer(
1682 buffer: Model<MultiBuffer>,
1683 project: Option<Model<Project>>,
1684 show_excerpt_controls: bool,
1685 cx: &mut ViewContext<Self>,
1686 ) -> Self {
1687 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1688 }
1689
1690 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1691 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1692 let mut clone = Self::new(
1693 self.mode,
1694 self.buffer.clone(),
1695 self.project.clone(),
1696 show_excerpt_controls,
1697 cx,
1698 );
1699 self.display_map.update(cx, |display_map, cx| {
1700 let snapshot = display_map.snapshot(cx);
1701 clone.display_map.update(cx, |display_map, cx| {
1702 display_map.set_state(&snapshot, cx);
1703 });
1704 });
1705 clone.selections.clone_state(&self.selections);
1706 clone.scroll_manager.clone_state(&self.scroll_manager);
1707 clone.searchable = self.searchable;
1708 clone
1709 }
1710
1711 pub fn new(
1712 mode: EditorMode,
1713 buffer: Model<MultiBuffer>,
1714 project: Option<Model<Project>>,
1715 show_excerpt_controls: bool,
1716 cx: &mut ViewContext<Self>,
1717 ) -> Self {
1718 let style = cx.text_style();
1719 let font_size = style.font_size.to_pixels(cx.rem_size());
1720 let editor = cx.view().downgrade();
1721 let fold_placeholder = FoldPlaceholder {
1722 constrain_width: true,
1723 render: Arc::new(move |fold_id, fold_range, cx| {
1724 let editor = editor.clone();
1725 div()
1726 .id(fold_id)
1727 .bg(cx.theme().colors().ghost_element_background)
1728 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1729 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1730 .rounded_sm()
1731 .size_full()
1732 .cursor_pointer()
1733 .child("⋯")
1734 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1735 .on_click(move |_, cx| {
1736 editor
1737 .update(cx, |editor, cx| {
1738 editor.unfold_ranges(
1739 [fold_range.start..fold_range.end],
1740 true,
1741 false,
1742 cx,
1743 );
1744 cx.stop_propagation();
1745 })
1746 .ok();
1747 })
1748 .into_any()
1749 }),
1750 merge_adjacent: true,
1751 };
1752 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1753 let display_map = cx.new_model(|cx| {
1754 DisplayMap::new(
1755 buffer.clone(),
1756 style.font(),
1757 font_size,
1758 None,
1759 show_excerpt_controls,
1760 file_header_size,
1761 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1762 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1763 fold_placeholder,
1764 cx,
1765 )
1766 });
1767
1768 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1769
1770 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1771
1772 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1773 .then(|| language_settings::SoftWrap::PreferLine);
1774
1775 let mut project_subscriptions = Vec::new();
1776 if mode == EditorMode::Full {
1777 if let Some(project) = project.as_ref() {
1778 if buffer.read(cx).is_singleton() {
1779 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1780 cx.emit(EditorEvent::TitleChanged);
1781 }));
1782 }
1783 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1784 if let project::Event::RefreshInlayHints = event {
1785 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1786 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1787 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1788 let focus_handle = editor.focus_handle(cx);
1789 if focus_handle.is_focused(cx) {
1790 let snapshot = buffer.read(cx).snapshot();
1791 for (range, snippet) in snippet_edits {
1792 let editor_range =
1793 language::range_from_lsp(*range).to_offset(&snapshot);
1794 editor
1795 .insert_snippet(&[editor_range], snippet.clone(), cx)
1796 .ok();
1797 }
1798 }
1799 }
1800 }
1801 }));
1802 let task_inventory = project.read(cx).task_inventory().clone();
1803 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1804 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1805 }));
1806 }
1807 }
1808
1809 let inlay_hint_settings = inlay_hint_settings(
1810 selections.newest_anchor().head(),
1811 &buffer.read(cx).snapshot(cx),
1812 cx,
1813 );
1814 let focus_handle = cx.focus_handle();
1815 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1816 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1817 .detach();
1818 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1819 .detach();
1820 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1821
1822 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1823 Some(false)
1824 } else {
1825 None
1826 };
1827
1828 let mut this = Self {
1829 focus_handle,
1830 show_cursor_when_unfocused: false,
1831 last_focused_descendant: None,
1832 buffer: buffer.clone(),
1833 display_map: display_map.clone(),
1834 selections,
1835 scroll_manager: ScrollManager::new(cx),
1836 columnar_selection_tail: None,
1837 add_selections_state: None,
1838 select_next_state: None,
1839 select_prev_state: None,
1840 selection_history: Default::default(),
1841 autoclose_regions: Default::default(),
1842 snippet_stack: Default::default(),
1843 select_larger_syntax_node_stack: Vec::new(),
1844 ime_transaction: Default::default(),
1845 active_diagnostics: None,
1846 soft_wrap_mode_override,
1847 completion_provider: project.clone().map(|project| Box::new(project) as _),
1848 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1849 project,
1850 blink_manager: blink_manager.clone(),
1851 show_local_selections: true,
1852 mode,
1853 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1854 show_gutter: mode == EditorMode::Full,
1855 show_line_numbers: None,
1856 show_git_diff_gutter: None,
1857 show_code_actions: None,
1858 show_runnables: None,
1859 show_wrap_guides: None,
1860 show_indent_guides,
1861 placeholder_text: None,
1862 highlight_order: 0,
1863 highlighted_rows: HashMap::default(),
1864 background_highlights: Default::default(),
1865 gutter_highlights: TreeMap::default(),
1866 scrollbar_marker_state: ScrollbarMarkerState::default(),
1867 active_indent_guides_state: ActiveIndentGuidesState::default(),
1868 nav_history: None,
1869 context_menu: RwLock::new(None),
1870 mouse_context_menu: None,
1871 completion_tasks: Default::default(),
1872 signature_help_state: SignatureHelpState::default(),
1873 auto_signature_help: None,
1874 find_all_references_task_sources: Vec::new(),
1875 next_completion_id: 0,
1876 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1877 next_inlay_id: 0,
1878 available_code_actions: Default::default(),
1879 code_actions_task: Default::default(),
1880 document_highlights_task: Default::default(),
1881 linked_editing_range_task: Default::default(),
1882 pending_rename: Default::default(),
1883 searchable: true,
1884 cursor_shape: Default::default(),
1885 current_line_highlight: None,
1886 autoindent_mode: Some(AutoindentMode::EachLine),
1887 collapse_matches: false,
1888 workspace: None,
1889 input_enabled: true,
1890 use_modal_editing: mode == EditorMode::Full,
1891 read_only: false,
1892 use_autoclose: true,
1893 use_auto_surround: true,
1894 auto_replace_emoji_shortcode: false,
1895 leader_peer_id: None,
1896 remote_id: None,
1897 hover_state: Default::default(),
1898 hovered_link_state: Default::default(),
1899 inline_completion_provider: None,
1900 active_inline_completion: None,
1901 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1902 expanded_hunks: ExpandedHunks::default(),
1903 gutter_hovered: false,
1904 pixel_position_of_newest_cursor: None,
1905 last_bounds: None,
1906 expect_bounds_change: None,
1907 gutter_dimensions: GutterDimensions::default(),
1908 style: None,
1909 show_cursor_names: false,
1910 hovered_cursors: Default::default(),
1911 next_editor_action_id: EditorActionId::default(),
1912 editor_actions: Rc::default(),
1913 show_inline_completions: mode == EditorMode::Full,
1914 custom_context_menu: None,
1915 show_git_blame_gutter: false,
1916 show_git_blame_inline: false,
1917 show_selection_menu: None,
1918 show_git_blame_inline_delay_task: None,
1919 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1920 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1921 .session
1922 .restore_unsaved_buffers,
1923 blame: None,
1924 blame_subscription: None,
1925 file_header_size,
1926 tasks: Default::default(),
1927 _subscriptions: vec![
1928 cx.observe(&buffer, Self::on_buffer_changed),
1929 cx.subscribe(&buffer, Self::on_buffer_event),
1930 cx.observe(&display_map, Self::on_display_map_changed),
1931 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1932 cx.observe_global::<SettingsStore>(Self::settings_changed),
1933 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1934 cx.observe_window_activation(|editor, cx| {
1935 let active = cx.is_window_active();
1936 editor.blink_manager.update(cx, |blink_manager, cx| {
1937 if active {
1938 blink_manager.enable(cx);
1939 } else {
1940 blink_manager.disable(cx);
1941 }
1942 });
1943 }),
1944 ],
1945 tasks_update_task: None,
1946 linked_edit_ranges: Default::default(),
1947 previous_search_ranges: None,
1948 breadcrumb_header: None,
1949 focused_block: None,
1950 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1951 addons: HashMap::default(),
1952 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1953 };
1954 this.tasks_update_task = Some(this.refresh_runnables(cx));
1955 this._subscriptions.extend(project_subscriptions);
1956
1957 this.end_selection(cx);
1958 this.scroll_manager.show_scrollbar(cx);
1959
1960 if mode == EditorMode::Full {
1961 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1962 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1963
1964 if this.git_blame_inline_enabled {
1965 this.git_blame_inline_enabled = true;
1966 this.start_git_blame_inline(false, cx);
1967 }
1968 }
1969
1970 this.report_editor_event("open", None, cx);
1971 this
1972 }
1973
1974 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1975 self.mouse_context_menu
1976 .as_ref()
1977 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1978 }
1979
1980 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1981 let mut key_context = KeyContext::new_with_defaults();
1982 key_context.add("Editor");
1983 let mode = match self.mode {
1984 EditorMode::SingleLine { .. } => "single_line",
1985 EditorMode::AutoHeight { .. } => "auto_height",
1986 EditorMode::Full => "full",
1987 };
1988
1989 if EditorSettings::jupyter_enabled(cx) {
1990 key_context.add("jupyter");
1991 }
1992
1993 key_context.set("mode", mode);
1994 if self.pending_rename.is_some() {
1995 key_context.add("renaming");
1996 }
1997 if self.context_menu_visible() {
1998 match self.context_menu.read().as_ref() {
1999 Some(ContextMenu::Completions(_)) => {
2000 key_context.add("menu");
2001 key_context.add("showing_completions")
2002 }
2003 Some(ContextMenu::CodeActions(_)) => {
2004 key_context.add("menu");
2005 key_context.add("showing_code_actions")
2006 }
2007 None => {}
2008 }
2009 }
2010
2011 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2012 if !self.focus_handle(cx).contains_focused(cx)
2013 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2014 {
2015 for addon in self.addons.values() {
2016 addon.extend_key_context(&mut key_context, cx)
2017 }
2018 }
2019
2020 if let Some(extension) = self
2021 .buffer
2022 .read(cx)
2023 .as_singleton()
2024 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2025 {
2026 key_context.set("extension", extension.to_string());
2027 }
2028
2029 if self.has_active_inline_completion(cx) {
2030 key_context.add("copilot_suggestion");
2031 key_context.add("inline_completion");
2032 }
2033
2034 key_context
2035 }
2036
2037 pub fn new_file(
2038 workspace: &mut Workspace,
2039 _: &workspace::NewFile,
2040 cx: &mut ViewContext<Workspace>,
2041 ) {
2042 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2043 "Failed to create buffer",
2044 cx,
2045 |e, _| match e.error_code() {
2046 ErrorCode::RemoteUpgradeRequired => Some(format!(
2047 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2048 e.error_tag("required").unwrap_or("the latest version")
2049 )),
2050 _ => None,
2051 },
2052 );
2053 }
2054
2055 pub fn new_in_workspace(
2056 workspace: &mut Workspace,
2057 cx: &mut ViewContext<Workspace>,
2058 ) -> Task<Result<View<Editor>>> {
2059 let project = workspace.project().clone();
2060 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2061
2062 cx.spawn(|workspace, mut cx| async move {
2063 let buffer = create.await?;
2064 workspace.update(&mut cx, |workspace, cx| {
2065 let editor =
2066 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2067 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2068 editor
2069 })
2070 })
2071 }
2072
2073 fn new_file_vertical(
2074 workspace: &mut Workspace,
2075 _: &workspace::NewFileSplitVertical,
2076 cx: &mut ViewContext<Workspace>,
2077 ) {
2078 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2079 }
2080
2081 fn new_file_horizontal(
2082 workspace: &mut Workspace,
2083 _: &workspace::NewFileSplitHorizontal,
2084 cx: &mut ViewContext<Workspace>,
2085 ) {
2086 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2087 }
2088
2089 fn new_file_in_direction(
2090 workspace: &mut Workspace,
2091 direction: SplitDirection,
2092 cx: &mut ViewContext<Workspace>,
2093 ) {
2094 let project = workspace.project().clone();
2095 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2096
2097 cx.spawn(|workspace, mut cx| async move {
2098 let buffer = create.await?;
2099 workspace.update(&mut cx, move |workspace, cx| {
2100 workspace.split_item(
2101 direction,
2102 Box::new(
2103 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2104 ),
2105 cx,
2106 )
2107 })?;
2108 anyhow::Ok(())
2109 })
2110 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2111 ErrorCode::RemoteUpgradeRequired => Some(format!(
2112 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2113 e.error_tag("required").unwrap_or("the latest version")
2114 )),
2115 _ => None,
2116 });
2117 }
2118
2119 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2120 self.buffer.read(cx).replica_id()
2121 }
2122
2123 pub fn leader_peer_id(&self) -> Option<PeerId> {
2124 self.leader_peer_id
2125 }
2126
2127 pub fn buffer(&self) -> &Model<MultiBuffer> {
2128 &self.buffer
2129 }
2130
2131 pub fn workspace(&self) -> Option<View<Workspace>> {
2132 self.workspace.as_ref()?.0.upgrade()
2133 }
2134
2135 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2136 self.buffer().read(cx).title(cx)
2137 }
2138
2139 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2140 EditorSnapshot {
2141 mode: self.mode,
2142 show_gutter: self.show_gutter,
2143 show_line_numbers: self.show_line_numbers,
2144 show_git_diff_gutter: self.show_git_diff_gutter,
2145 show_code_actions: self.show_code_actions,
2146 show_runnables: self.show_runnables,
2147 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2148 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2149 scroll_anchor: self.scroll_manager.anchor(),
2150 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2151 placeholder_text: self.placeholder_text.clone(),
2152 is_focused: self.focus_handle.is_focused(cx),
2153 current_line_highlight: self
2154 .current_line_highlight
2155 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2156 gutter_hovered: self.gutter_hovered,
2157 }
2158 }
2159
2160 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2161 self.buffer.read(cx).language_at(point, cx)
2162 }
2163
2164 pub fn file_at<T: ToOffset>(
2165 &self,
2166 point: T,
2167 cx: &AppContext,
2168 ) -> Option<Arc<dyn language::File>> {
2169 self.buffer.read(cx).read(cx).file_at(point).cloned()
2170 }
2171
2172 pub fn active_excerpt(
2173 &self,
2174 cx: &AppContext,
2175 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2176 self.buffer
2177 .read(cx)
2178 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2179 }
2180
2181 pub fn mode(&self) -> EditorMode {
2182 self.mode
2183 }
2184
2185 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2186 self.collaboration_hub.as_deref()
2187 }
2188
2189 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2190 self.collaboration_hub = Some(hub);
2191 }
2192
2193 pub fn set_custom_context_menu(
2194 &mut self,
2195 f: impl 'static
2196 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2197 ) {
2198 self.custom_context_menu = Some(Box::new(f))
2199 }
2200
2201 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2202 self.completion_provider = Some(provider);
2203 }
2204
2205 pub fn set_inline_completion_provider<T>(
2206 &mut self,
2207 provider: Option<Model<T>>,
2208 cx: &mut ViewContext<Self>,
2209 ) where
2210 T: InlineCompletionProvider,
2211 {
2212 self.inline_completion_provider =
2213 provider.map(|provider| RegisteredInlineCompletionProvider {
2214 _subscription: cx.observe(&provider, |this, _, cx| {
2215 if this.focus_handle.is_focused(cx) {
2216 this.update_visible_inline_completion(cx);
2217 }
2218 }),
2219 provider: Arc::new(provider),
2220 });
2221 self.refresh_inline_completion(false, false, cx);
2222 }
2223
2224 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2225 self.placeholder_text.as_deref()
2226 }
2227
2228 pub fn set_placeholder_text(
2229 &mut self,
2230 placeholder_text: impl Into<Arc<str>>,
2231 cx: &mut ViewContext<Self>,
2232 ) {
2233 let placeholder_text = Some(placeholder_text.into());
2234 if self.placeholder_text != placeholder_text {
2235 self.placeholder_text = placeholder_text;
2236 cx.notify();
2237 }
2238 }
2239
2240 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2241 self.cursor_shape = cursor_shape;
2242
2243 // Disrupt blink for immediate user feedback that the cursor shape has changed
2244 self.blink_manager.update(cx, BlinkManager::show_cursor);
2245
2246 cx.notify();
2247 }
2248
2249 pub fn set_current_line_highlight(
2250 &mut self,
2251 current_line_highlight: Option<CurrentLineHighlight>,
2252 ) {
2253 self.current_line_highlight = current_line_highlight;
2254 }
2255
2256 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2257 self.collapse_matches = collapse_matches;
2258 }
2259
2260 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2261 if self.collapse_matches {
2262 return range.start..range.start;
2263 }
2264 range.clone()
2265 }
2266
2267 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2268 if self.display_map.read(cx).clip_at_line_ends != clip {
2269 self.display_map
2270 .update(cx, |map, _| map.clip_at_line_ends = clip);
2271 }
2272 }
2273
2274 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2275 self.input_enabled = input_enabled;
2276 }
2277
2278 pub fn set_autoindent(&mut self, autoindent: bool) {
2279 if autoindent {
2280 self.autoindent_mode = Some(AutoindentMode::EachLine);
2281 } else {
2282 self.autoindent_mode = None;
2283 }
2284 }
2285
2286 pub fn read_only(&self, cx: &AppContext) -> bool {
2287 self.read_only || self.buffer.read(cx).read_only()
2288 }
2289
2290 pub fn set_read_only(&mut self, read_only: bool) {
2291 self.read_only = read_only;
2292 }
2293
2294 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2295 self.use_autoclose = autoclose;
2296 }
2297
2298 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2299 self.use_auto_surround = auto_surround;
2300 }
2301
2302 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2303 self.auto_replace_emoji_shortcode = auto_replace;
2304 }
2305
2306 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2307 self.show_inline_completions = show_inline_completions;
2308 }
2309
2310 pub fn set_use_modal_editing(&mut self, to: bool) {
2311 self.use_modal_editing = to;
2312 }
2313
2314 pub fn use_modal_editing(&self) -> bool {
2315 self.use_modal_editing
2316 }
2317
2318 fn selections_did_change(
2319 &mut self,
2320 local: bool,
2321 old_cursor_position: &Anchor,
2322 show_completions: bool,
2323 cx: &mut ViewContext<Self>,
2324 ) {
2325 // Copy selections to primary selection buffer
2326 #[cfg(target_os = "linux")]
2327 if local {
2328 let selections = self.selections.all::<usize>(cx);
2329 let buffer_handle = self.buffer.read(cx).read(cx);
2330
2331 let mut text = String::new();
2332 for (index, selection) in selections.iter().enumerate() {
2333 let text_for_selection = buffer_handle
2334 .text_for_range(selection.start..selection.end)
2335 .collect::<String>();
2336
2337 text.push_str(&text_for_selection);
2338 if index != selections.len() - 1 {
2339 text.push('\n');
2340 }
2341 }
2342
2343 if !text.is_empty() {
2344 cx.write_to_primary(ClipboardItem::new_string(text));
2345 }
2346 }
2347
2348 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2349 self.buffer.update(cx, |buffer, cx| {
2350 buffer.set_active_selections(
2351 &self.selections.disjoint_anchors(),
2352 self.selections.line_mode,
2353 self.cursor_shape,
2354 cx,
2355 )
2356 });
2357 }
2358 let display_map = self
2359 .display_map
2360 .update(cx, |display_map, cx| display_map.snapshot(cx));
2361 let buffer = &display_map.buffer_snapshot;
2362 self.add_selections_state = None;
2363 self.select_next_state = None;
2364 self.select_prev_state = None;
2365 self.select_larger_syntax_node_stack.clear();
2366 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2367 self.snippet_stack
2368 .invalidate(&self.selections.disjoint_anchors(), buffer);
2369 self.take_rename(false, cx);
2370
2371 let new_cursor_position = self.selections.newest_anchor().head();
2372
2373 self.push_to_nav_history(
2374 *old_cursor_position,
2375 Some(new_cursor_position.to_point(buffer)),
2376 cx,
2377 );
2378
2379 if local {
2380 let new_cursor_position = self.selections.newest_anchor().head();
2381 let mut context_menu = self.context_menu.write();
2382 let completion_menu = match context_menu.as_ref() {
2383 Some(ContextMenu::Completions(menu)) => Some(menu),
2384
2385 _ => {
2386 *context_menu = None;
2387 None
2388 }
2389 };
2390
2391 if let Some(completion_menu) = completion_menu {
2392 let cursor_position = new_cursor_position.to_offset(buffer);
2393 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2394 if kind == Some(CharKind::Word)
2395 && word_range.to_inclusive().contains(&cursor_position)
2396 {
2397 let mut completion_menu = completion_menu.clone();
2398 drop(context_menu);
2399
2400 let query = Self::completion_query(buffer, cursor_position);
2401 cx.spawn(move |this, mut cx| async move {
2402 completion_menu
2403 .filter(query.as_deref(), cx.background_executor().clone())
2404 .await;
2405
2406 this.update(&mut cx, |this, cx| {
2407 let mut context_menu = this.context_menu.write();
2408 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2409 return;
2410 };
2411
2412 if menu.id > completion_menu.id {
2413 return;
2414 }
2415
2416 *context_menu = Some(ContextMenu::Completions(completion_menu));
2417 drop(context_menu);
2418 cx.notify();
2419 })
2420 })
2421 .detach();
2422
2423 if show_completions {
2424 self.show_completions(&ShowCompletions { trigger: None }, cx);
2425 }
2426 } else {
2427 drop(context_menu);
2428 self.hide_context_menu(cx);
2429 }
2430 } else {
2431 drop(context_menu);
2432 }
2433
2434 hide_hover(self, cx);
2435
2436 if old_cursor_position.to_display_point(&display_map).row()
2437 != new_cursor_position.to_display_point(&display_map).row()
2438 {
2439 self.available_code_actions.take();
2440 }
2441 self.refresh_code_actions(cx);
2442 self.refresh_document_highlights(cx);
2443 refresh_matching_bracket_highlights(self, cx);
2444 self.discard_inline_completion(false, cx);
2445 linked_editing_ranges::refresh_linked_ranges(self, cx);
2446 if self.git_blame_inline_enabled {
2447 self.start_inline_blame_timer(cx);
2448 }
2449 }
2450
2451 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2452 cx.emit(EditorEvent::SelectionsChanged { local });
2453
2454 if self.selections.disjoint_anchors().len() == 1 {
2455 cx.emit(SearchEvent::ActiveMatchChanged)
2456 }
2457 cx.notify();
2458 }
2459
2460 pub fn change_selections<R>(
2461 &mut self,
2462 autoscroll: Option<Autoscroll>,
2463 cx: &mut ViewContext<Self>,
2464 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2465 ) -> R {
2466 self.change_selections_inner(autoscroll, true, cx, change)
2467 }
2468
2469 pub fn change_selections_inner<R>(
2470 &mut self,
2471 autoscroll: Option<Autoscroll>,
2472 request_completions: bool,
2473 cx: &mut ViewContext<Self>,
2474 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2475 ) -> R {
2476 let old_cursor_position = self.selections.newest_anchor().head();
2477 self.push_to_selection_history();
2478
2479 let (changed, result) = self.selections.change_with(cx, change);
2480
2481 if changed {
2482 if let Some(autoscroll) = autoscroll {
2483 self.request_autoscroll(autoscroll, cx);
2484 }
2485 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2486
2487 if self.should_open_signature_help_automatically(
2488 &old_cursor_position,
2489 self.signature_help_state.backspace_pressed(),
2490 cx,
2491 ) {
2492 self.show_signature_help(&ShowSignatureHelp, cx);
2493 }
2494 self.signature_help_state.set_backspace_pressed(false);
2495 }
2496
2497 result
2498 }
2499
2500 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2501 where
2502 I: IntoIterator<Item = (Range<S>, T)>,
2503 S: ToOffset,
2504 T: Into<Arc<str>>,
2505 {
2506 if self.read_only(cx) {
2507 return;
2508 }
2509
2510 self.buffer
2511 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2512 }
2513
2514 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2515 where
2516 I: IntoIterator<Item = (Range<S>, T)>,
2517 S: ToOffset,
2518 T: Into<Arc<str>>,
2519 {
2520 if self.read_only(cx) {
2521 return;
2522 }
2523
2524 self.buffer.update(cx, |buffer, cx| {
2525 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2526 });
2527 }
2528
2529 pub fn edit_with_block_indent<I, S, T>(
2530 &mut self,
2531 edits: I,
2532 original_indent_columns: Vec<u32>,
2533 cx: &mut ViewContext<Self>,
2534 ) where
2535 I: IntoIterator<Item = (Range<S>, T)>,
2536 S: ToOffset,
2537 T: Into<Arc<str>>,
2538 {
2539 if self.read_only(cx) {
2540 return;
2541 }
2542
2543 self.buffer.update(cx, |buffer, cx| {
2544 buffer.edit(
2545 edits,
2546 Some(AutoindentMode::Block {
2547 original_indent_columns,
2548 }),
2549 cx,
2550 )
2551 });
2552 }
2553
2554 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2555 self.hide_context_menu(cx);
2556
2557 match phase {
2558 SelectPhase::Begin {
2559 position,
2560 add,
2561 click_count,
2562 } => self.begin_selection(position, add, click_count, cx),
2563 SelectPhase::BeginColumnar {
2564 position,
2565 goal_column,
2566 reset,
2567 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2568 SelectPhase::Extend {
2569 position,
2570 click_count,
2571 } => self.extend_selection(position, click_count, cx),
2572 SelectPhase::Update {
2573 position,
2574 goal_column,
2575 scroll_delta,
2576 } => self.update_selection(position, goal_column, scroll_delta, cx),
2577 SelectPhase::End => self.end_selection(cx),
2578 }
2579 }
2580
2581 fn extend_selection(
2582 &mut self,
2583 position: DisplayPoint,
2584 click_count: usize,
2585 cx: &mut ViewContext<Self>,
2586 ) {
2587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2588 let tail = self.selections.newest::<usize>(cx).tail();
2589 self.begin_selection(position, false, click_count, cx);
2590
2591 let position = position.to_offset(&display_map, Bias::Left);
2592 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2593
2594 let mut pending_selection = self
2595 .selections
2596 .pending_anchor()
2597 .expect("extend_selection not called with pending selection");
2598 if position >= tail {
2599 pending_selection.start = tail_anchor;
2600 } else {
2601 pending_selection.end = tail_anchor;
2602 pending_selection.reversed = true;
2603 }
2604
2605 let mut pending_mode = self.selections.pending_mode().unwrap();
2606 match &mut pending_mode {
2607 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2608 _ => {}
2609 }
2610
2611 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2612 s.set_pending(pending_selection, pending_mode)
2613 });
2614 }
2615
2616 fn begin_selection(
2617 &mut self,
2618 position: DisplayPoint,
2619 add: bool,
2620 click_count: usize,
2621 cx: &mut ViewContext<Self>,
2622 ) {
2623 if !self.focus_handle.is_focused(cx) {
2624 self.last_focused_descendant = None;
2625 cx.focus(&self.focus_handle);
2626 }
2627
2628 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2629 let buffer = &display_map.buffer_snapshot;
2630 let newest_selection = self.selections.newest_anchor().clone();
2631 let position = display_map.clip_point(position, Bias::Left);
2632
2633 let start;
2634 let end;
2635 let mode;
2636 let auto_scroll;
2637 match click_count {
2638 1 => {
2639 start = buffer.anchor_before(position.to_point(&display_map));
2640 end = start;
2641 mode = SelectMode::Character;
2642 auto_scroll = true;
2643 }
2644 2 => {
2645 let range = movement::surrounding_word(&display_map, position);
2646 start = buffer.anchor_before(range.start.to_point(&display_map));
2647 end = buffer.anchor_before(range.end.to_point(&display_map));
2648 mode = SelectMode::Word(start..end);
2649 auto_scroll = true;
2650 }
2651 3 => {
2652 let position = display_map
2653 .clip_point(position, Bias::Left)
2654 .to_point(&display_map);
2655 let line_start = display_map.prev_line_boundary(position).0;
2656 let next_line_start = buffer.clip_point(
2657 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2658 Bias::Left,
2659 );
2660 start = buffer.anchor_before(line_start);
2661 end = buffer.anchor_before(next_line_start);
2662 mode = SelectMode::Line(start..end);
2663 auto_scroll = true;
2664 }
2665 _ => {
2666 start = buffer.anchor_before(0);
2667 end = buffer.anchor_before(buffer.len());
2668 mode = SelectMode::All;
2669 auto_scroll = false;
2670 }
2671 }
2672
2673 let point_to_delete: Option<usize> = {
2674 let selected_points: Vec<Selection<Point>> =
2675 self.selections.disjoint_in_range(start..end, cx);
2676
2677 if !add || click_count > 1 {
2678 None
2679 } else if selected_points.len() > 0 {
2680 Some(selected_points[0].id)
2681 } else {
2682 let clicked_point_already_selected =
2683 self.selections.disjoint.iter().find(|selection| {
2684 selection.start.to_point(buffer) == start.to_point(buffer)
2685 || selection.end.to_point(buffer) == end.to_point(buffer)
2686 });
2687
2688 if let Some(selection) = clicked_point_already_selected {
2689 Some(selection.id)
2690 } else {
2691 None
2692 }
2693 }
2694 };
2695
2696 let selections_count = self.selections.count();
2697
2698 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2699 if let Some(point_to_delete) = point_to_delete {
2700 s.delete(point_to_delete);
2701
2702 if selections_count == 1 {
2703 s.set_pending_anchor_range(start..end, mode);
2704 }
2705 } else {
2706 if !add {
2707 s.clear_disjoint();
2708 } else if click_count > 1 {
2709 s.delete(newest_selection.id)
2710 }
2711
2712 s.set_pending_anchor_range(start..end, mode);
2713 }
2714 });
2715 }
2716
2717 fn begin_columnar_selection(
2718 &mut self,
2719 position: DisplayPoint,
2720 goal_column: u32,
2721 reset: bool,
2722 cx: &mut ViewContext<Self>,
2723 ) {
2724 if !self.focus_handle.is_focused(cx) {
2725 self.last_focused_descendant = None;
2726 cx.focus(&self.focus_handle);
2727 }
2728
2729 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2730
2731 if reset {
2732 let pointer_position = display_map
2733 .buffer_snapshot
2734 .anchor_before(position.to_point(&display_map));
2735
2736 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2737 s.clear_disjoint();
2738 s.set_pending_anchor_range(
2739 pointer_position..pointer_position,
2740 SelectMode::Character,
2741 );
2742 });
2743 }
2744
2745 let tail = self.selections.newest::<Point>(cx).tail();
2746 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2747
2748 if !reset {
2749 self.select_columns(
2750 tail.to_display_point(&display_map),
2751 position,
2752 goal_column,
2753 &display_map,
2754 cx,
2755 );
2756 }
2757 }
2758
2759 fn update_selection(
2760 &mut self,
2761 position: DisplayPoint,
2762 goal_column: u32,
2763 scroll_delta: gpui::Point<f32>,
2764 cx: &mut ViewContext<Self>,
2765 ) {
2766 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2767
2768 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2769 let tail = tail.to_display_point(&display_map);
2770 self.select_columns(tail, position, goal_column, &display_map, cx);
2771 } else if let Some(mut pending) = self.selections.pending_anchor() {
2772 let buffer = self.buffer.read(cx).snapshot(cx);
2773 let head;
2774 let tail;
2775 let mode = self.selections.pending_mode().unwrap();
2776 match &mode {
2777 SelectMode::Character => {
2778 head = position.to_point(&display_map);
2779 tail = pending.tail().to_point(&buffer);
2780 }
2781 SelectMode::Word(original_range) => {
2782 let original_display_range = original_range.start.to_display_point(&display_map)
2783 ..original_range.end.to_display_point(&display_map);
2784 let original_buffer_range = original_display_range.start.to_point(&display_map)
2785 ..original_display_range.end.to_point(&display_map);
2786 if movement::is_inside_word(&display_map, position)
2787 || original_display_range.contains(&position)
2788 {
2789 let word_range = movement::surrounding_word(&display_map, position);
2790 if word_range.start < original_display_range.start {
2791 head = word_range.start.to_point(&display_map);
2792 } else {
2793 head = word_range.end.to_point(&display_map);
2794 }
2795 } else {
2796 head = position.to_point(&display_map);
2797 }
2798
2799 if head <= original_buffer_range.start {
2800 tail = original_buffer_range.end;
2801 } else {
2802 tail = original_buffer_range.start;
2803 }
2804 }
2805 SelectMode::Line(original_range) => {
2806 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2807
2808 let position = display_map
2809 .clip_point(position, Bias::Left)
2810 .to_point(&display_map);
2811 let line_start = display_map.prev_line_boundary(position).0;
2812 let next_line_start = buffer.clip_point(
2813 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2814 Bias::Left,
2815 );
2816
2817 if line_start < original_range.start {
2818 head = line_start
2819 } else {
2820 head = next_line_start
2821 }
2822
2823 if head <= original_range.start {
2824 tail = original_range.end;
2825 } else {
2826 tail = original_range.start;
2827 }
2828 }
2829 SelectMode::All => {
2830 return;
2831 }
2832 };
2833
2834 if head < tail {
2835 pending.start = buffer.anchor_before(head);
2836 pending.end = buffer.anchor_before(tail);
2837 pending.reversed = true;
2838 } else {
2839 pending.start = buffer.anchor_before(tail);
2840 pending.end = buffer.anchor_before(head);
2841 pending.reversed = false;
2842 }
2843
2844 self.change_selections(None, cx, |s| {
2845 s.set_pending(pending, mode);
2846 });
2847 } else {
2848 log::error!("update_selection dispatched with no pending selection");
2849 return;
2850 }
2851
2852 self.apply_scroll_delta(scroll_delta, cx);
2853 cx.notify();
2854 }
2855
2856 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2857 self.columnar_selection_tail.take();
2858 if self.selections.pending_anchor().is_some() {
2859 let selections = self.selections.all::<usize>(cx);
2860 self.change_selections(None, cx, |s| {
2861 s.select(selections);
2862 s.clear_pending();
2863 });
2864 }
2865 }
2866
2867 fn select_columns(
2868 &mut self,
2869 tail: DisplayPoint,
2870 head: DisplayPoint,
2871 goal_column: u32,
2872 display_map: &DisplaySnapshot,
2873 cx: &mut ViewContext<Self>,
2874 ) {
2875 let start_row = cmp::min(tail.row(), head.row());
2876 let end_row = cmp::max(tail.row(), head.row());
2877 let start_column = cmp::min(tail.column(), goal_column);
2878 let end_column = cmp::max(tail.column(), goal_column);
2879 let reversed = start_column < tail.column();
2880
2881 let selection_ranges = (start_row.0..=end_row.0)
2882 .map(DisplayRow)
2883 .filter_map(|row| {
2884 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2885 let start = display_map
2886 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2887 .to_point(display_map);
2888 let end = display_map
2889 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2890 .to_point(display_map);
2891 if reversed {
2892 Some(end..start)
2893 } else {
2894 Some(start..end)
2895 }
2896 } else {
2897 None
2898 }
2899 })
2900 .collect::<Vec<_>>();
2901
2902 self.change_selections(None, cx, |s| {
2903 s.select_ranges(selection_ranges);
2904 });
2905 cx.notify();
2906 }
2907
2908 pub fn has_pending_nonempty_selection(&self) -> bool {
2909 let pending_nonempty_selection = match self.selections.pending_anchor() {
2910 Some(Selection { start, end, .. }) => start != end,
2911 None => false,
2912 };
2913
2914 pending_nonempty_selection
2915 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2916 }
2917
2918 pub fn has_pending_selection(&self) -> bool {
2919 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2920 }
2921
2922 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2923 if self.clear_clicked_diff_hunks(cx) {
2924 cx.notify();
2925 return;
2926 }
2927 if self.dismiss_menus_and_popups(true, cx) {
2928 return;
2929 }
2930
2931 if self.mode == EditorMode::Full {
2932 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2933 return;
2934 }
2935 }
2936
2937 cx.propagate();
2938 }
2939
2940 pub fn dismiss_menus_and_popups(
2941 &mut self,
2942 should_report_inline_completion_event: bool,
2943 cx: &mut ViewContext<Self>,
2944 ) -> bool {
2945 if self.take_rename(false, cx).is_some() {
2946 return true;
2947 }
2948
2949 if hide_hover(self, cx) {
2950 return true;
2951 }
2952
2953 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2954 return true;
2955 }
2956
2957 if self.hide_context_menu(cx).is_some() {
2958 return true;
2959 }
2960
2961 if self.mouse_context_menu.take().is_some() {
2962 return true;
2963 }
2964
2965 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2966 return true;
2967 }
2968
2969 if self.snippet_stack.pop().is_some() {
2970 return true;
2971 }
2972
2973 if self.mode == EditorMode::Full {
2974 if self.active_diagnostics.is_some() {
2975 self.dismiss_diagnostics(cx);
2976 return true;
2977 }
2978 }
2979
2980 false
2981 }
2982
2983 fn linked_editing_ranges_for(
2984 &self,
2985 selection: Range<text::Anchor>,
2986 cx: &AppContext,
2987 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2988 if self.linked_edit_ranges.is_empty() {
2989 return None;
2990 }
2991 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2992 selection.end.buffer_id.and_then(|end_buffer_id| {
2993 if selection.start.buffer_id != Some(end_buffer_id) {
2994 return None;
2995 }
2996 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2997 let snapshot = buffer.read(cx).snapshot();
2998 self.linked_edit_ranges
2999 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3000 .map(|ranges| (ranges, snapshot, buffer))
3001 })?;
3002 use text::ToOffset as TO;
3003 // find offset from the start of current range to current cursor position
3004 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3005
3006 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3007 let start_difference = start_offset - start_byte_offset;
3008 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3009 let end_difference = end_offset - start_byte_offset;
3010 // Current range has associated linked ranges.
3011 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3012 for range in linked_ranges.iter() {
3013 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3014 let end_offset = start_offset + end_difference;
3015 let start_offset = start_offset + start_difference;
3016 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3017 continue;
3018 }
3019 let start = buffer_snapshot.anchor_after(start_offset);
3020 let end = buffer_snapshot.anchor_after(end_offset);
3021 linked_edits
3022 .entry(buffer.clone())
3023 .or_default()
3024 .push(start..end);
3025 }
3026 Some(linked_edits)
3027 }
3028
3029 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3030 let text: Arc<str> = text.into();
3031
3032 if self.read_only(cx) {
3033 return;
3034 }
3035
3036 let selections = self.selections.all_adjusted(cx);
3037 let mut bracket_inserted = false;
3038 let mut edits = Vec::new();
3039 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3040 let mut new_selections = Vec::with_capacity(selections.len());
3041 let mut new_autoclose_regions = Vec::new();
3042 let snapshot = self.buffer.read(cx).read(cx);
3043
3044 for (selection, autoclose_region) in
3045 self.selections_with_autoclose_regions(selections, &snapshot)
3046 {
3047 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3048 // Determine if the inserted text matches the opening or closing
3049 // bracket of any of this language's bracket pairs.
3050 let mut bracket_pair = None;
3051 let mut is_bracket_pair_start = false;
3052 let mut is_bracket_pair_end = false;
3053 if !text.is_empty() {
3054 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3055 // and they are removing the character that triggered IME popup.
3056 for (pair, enabled) in scope.brackets() {
3057 if !pair.close && !pair.surround {
3058 continue;
3059 }
3060
3061 if enabled && pair.start.ends_with(text.as_ref()) {
3062 bracket_pair = Some(pair.clone());
3063 is_bracket_pair_start = true;
3064 break;
3065 }
3066 if pair.end.as_str() == text.as_ref() {
3067 bracket_pair = Some(pair.clone());
3068 is_bracket_pair_end = true;
3069 break;
3070 }
3071 }
3072 }
3073
3074 if let Some(bracket_pair) = bracket_pair {
3075 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3076 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3077 let auto_surround =
3078 self.use_auto_surround && snapshot_settings.use_auto_surround;
3079 if selection.is_empty() {
3080 if is_bracket_pair_start {
3081 let prefix_len = bracket_pair.start.len() - text.len();
3082
3083 // If the inserted text is a suffix of an opening bracket and the
3084 // selection is preceded by the rest of the opening bracket, then
3085 // insert the closing bracket.
3086 let following_text_allows_autoclose = snapshot
3087 .chars_at(selection.start)
3088 .next()
3089 .map_or(true, |c| scope.should_autoclose_before(c));
3090 let preceding_text_matches_prefix = prefix_len == 0
3091 || (selection.start.column >= (prefix_len as u32)
3092 && snapshot.contains_str_at(
3093 Point::new(
3094 selection.start.row,
3095 selection.start.column - (prefix_len as u32),
3096 ),
3097 &bracket_pair.start[..prefix_len],
3098 ));
3099
3100 if autoclose
3101 && bracket_pair.close
3102 && following_text_allows_autoclose
3103 && preceding_text_matches_prefix
3104 {
3105 let anchor = snapshot.anchor_before(selection.end);
3106 new_selections.push((selection.map(|_| anchor), text.len()));
3107 new_autoclose_regions.push((
3108 anchor,
3109 text.len(),
3110 selection.id,
3111 bracket_pair.clone(),
3112 ));
3113 edits.push((
3114 selection.range(),
3115 format!("{}{}", text, bracket_pair.end).into(),
3116 ));
3117 bracket_inserted = true;
3118 continue;
3119 }
3120 }
3121
3122 if let Some(region) = autoclose_region {
3123 // If the selection is followed by an auto-inserted closing bracket,
3124 // then don't insert that closing bracket again; just move the selection
3125 // past the closing bracket.
3126 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3127 && text.as_ref() == region.pair.end.as_str();
3128 if should_skip {
3129 let anchor = snapshot.anchor_after(selection.end);
3130 new_selections
3131 .push((selection.map(|_| anchor), region.pair.end.len()));
3132 continue;
3133 }
3134 }
3135
3136 let always_treat_brackets_as_autoclosed = snapshot
3137 .settings_at(selection.start, cx)
3138 .always_treat_brackets_as_autoclosed;
3139 if always_treat_brackets_as_autoclosed
3140 && is_bracket_pair_end
3141 && snapshot.contains_str_at(selection.end, text.as_ref())
3142 {
3143 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3144 // and the inserted text is a closing bracket and the selection is followed
3145 // by the closing bracket then move the selection past the closing bracket.
3146 let anchor = snapshot.anchor_after(selection.end);
3147 new_selections.push((selection.map(|_| anchor), text.len()));
3148 continue;
3149 }
3150 }
3151 // If an opening bracket is 1 character long and is typed while
3152 // text is selected, then surround that text with the bracket pair.
3153 else if auto_surround
3154 && bracket_pair.surround
3155 && is_bracket_pair_start
3156 && bracket_pair.start.chars().count() == 1
3157 {
3158 edits.push((selection.start..selection.start, text.clone()));
3159 edits.push((
3160 selection.end..selection.end,
3161 bracket_pair.end.as_str().into(),
3162 ));
3163 bracket_inserted = true;
3164 new_selections.push((
3165 Selection {
3166 id: selection.id,
3167 start: snapshot.anchor_after(selection.start),
3168 end: snapshot.anchor_before(selection.end),
3169 reversed: selection.reversed,
3170 goal: selection.goal,
3171 },
3172 0,
3173 ));
3174 continue;
3175 }
3176 }
3177 }
3178
3179 if self.auto_replace_emoji_shortcode
3180 && selection.is_empty()
3181 && text.as_ref().ends_with(':')
3182 {
3183 if let Some(possible_emoji_short_code) =
3184 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3185 {
3186 if !possible_emoji_short_code.is_empty() {
3187 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3188 let emoji_shortcode_start = Point::new(
3189 selection.start.row,
3190 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3191 );
3192
3193 // Remove shortcode from buffer
3194 edits.push((
3195 emoji_shortcode_start..selection.start,
3196 "".to_string().into(),
3197 ));
3198 new_selections.push((
3199 Selection {
3200 id: selection.id,
3201 start: snapshot.anchor_after(emoji_shortcode_start),
3202 end: snapshot.anchor_before(selection.start),
3203 reversed: selection.reversed,
3204 goal: selection.goal,
3205 },
3206 0,
3207 ));
3208
3209 // Insert emoji
3210 let selection_start_anchor = snapshot.anchor_after(selection.start);
3211 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3212 edits.push((selection.start..selection.end, emoji.to_string().into()));
3213
3214 continue;
3215 }
3216 }
3217 }
3218 }
3219
3220 // If not handling any auto-close operation, then just replace the selected
3221 // text with the given input and move the selection to the end of the
3222 // newly inserted text.
3223 let anchor = snapshot.anchor_after(selection.end);
3224 if !self.linked_edit_ranges.is_empty() {
3225 let start_anchor = snapshot.anchor_before(selection.start);
3226
3227 let is_word_char = text.chars().next().map_or(true, |char| {
3228 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3229 let kind = char_kind(&scope, char);
3230
3231 kind == CharKind::Word
3232 });
3233
3234 if is_word_char {
3235 if let Some(ranges) = self
3236 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3237 {
3238 for (buffer, edits) in ranges {
3239 linked_edits
3240 .entry(buffer.clone())
3241 .or_default()
3242 .extend(edits.into_iter().map(|range| (range, text.clone())));
3243 }
3244 }
3245 }
3246 }
3247
3248 new_selections.push((selection.map(|_| anchor), 0));
3249 edits.push((selection.start..selection.end, text.clone()));
3250 }
3251
3252 drop(snapshot);
3253
3254 self.transact(cx, |this, cx| {
3255 this.buffer.update(cx, |buffer, cx| {
3256 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3257 });
3258 for (buffer, edits) in linked_edits {
3259 buffer.update(cx, |buffer, cx| {
3260 let snapshot = buffer.snapshot();
3261 let edits = edits
3262 .into_iter()
3263 .map(|(range, text)| {
3264 use text::ToPoint as TP;
3265 let end_point = TP::to_point(&range.end, &snapshot);
3266 let start_point = TP::to_point(&range.start, &snapshot);
3267 (start_point..end_point, text)
3268 })
3269 .sorted_by_key(|(range, _)| range.start)
3270 .collect::<Vec<_>>();
3271 buffer.edit(edits, None, cx);
3272 })
3273 }
3274 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3275 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3276 let snapshot = this.buffer.read(cx).read(cx);
3277 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3278 .zip(new_selection_deltas)
3279 .map(|(selection, delta)| Selection {
3280 id: selection.id,
3281 start: selection.start + delta,
3282 end: selection.end + delta,
3283 reversed: selection.reversed,
3284 goal: SelectionGoal::None,
3285 })
3286 .collect::<Vec<_>>();
3287
3288 let mut i = 0;
3289 for (position, delta, selection_id, pair) in new_autoclose_regions {
3290 let position = position.to_offset(&snapshot) + delta;
3291 let start = snapshot.anchor_before(position);
3292 let end = snapshot.anchor_after(position);
3293 while let Some(existing_state) = this.autoclose_regions.get(i) {
3294 match existing_state.range.start.cmp(&start, &snapshot) {
3295 Ordering::Less => i += 1,
3296 Ordering::Greater => break,
3297 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3298 Ordering::Less => i += 1,
3299 Ordering::Equal => break,
3300 Ordering::Greater => break,
3301 },
3302 }
3303 }
3304 this.autoclose_regions.insert(
3305 i,
3306 AutocloseRegion {
3307 selection_id,
3308 range: start..end,
3309 pair,
3310 },
3311 );
3312 }
3313
3314 drop(snapshot);
3315 let had_active_inline_completion = this.has_active_inline_completion(cx);
3316 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3317 s.select(new_selections)
3318 });
3319
3320 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3321 if let Some(on_type_format_task) =
3322 this.trigger_on_type_formatting(text.to_string(), cx)
3323 {
3324 on_type_format_task.detach_and_log_err(cx);
3325 }
3326 }
3327
3328 let editor_settings = EditorSettings::get_global(cx);
3329 if bracket_inserted
3330 && (editor_settings.auto_signature_help
3331 || editor_settings.show_signature_help_after_edits)
3332 {
3333 this.show_signature_help(&ShowSignatureHelp, cx);
3334 }
3335
3336 let trigger_in_words = !had_active_inline_completion;
3337 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3338 linked_editing_ranges::refresh_linked_ranges(this, cx);
3339 this.refresh_inline_completion(true, false, cx);
3340 });
3341 }
3342
3343 fn find_possible_emoji_shortcode_at_position(
3344 snapshot: &MultiBufferSnapshot,
3345 position: Point,
3346 ) -> Option<String> {
3347 let mut chars = Vec::new();
3348 let mut found_colon = false;
3349 for char in snapshot.reversed_chars_at(position).take(100) {
3350 // Found a possible emoji shortcode in the middle of the buffer
3351 if found_colon {
3352 if char.is_whitespace() {
3353 chars.reverse();
3354 return Some(chars.iter().collect());
3355 }
3356 // If the previous character is not a whitespace, we are in the middle of a word
3357 // and we only want to complete the shortcode if the word is made up of other emojis
3358 let mut containing_word = String::new();
3359 for ch in snapshot
3360 .reversed_chars_at(position)
3361 .skip(chars.len() + 1)
3362 .take(100)
3363 {
3364 if ch.is_whitespace() {
3365 break;
3366 }
3367 containing_word.push(ch);
3368 }
3369 let containing_word = containing_word.chars().rev().collect::<String>();
3370 if util::word_consists_of_emojis(containing_word.as_str()) {
3371 chars.reverse();
3372 return Some(chars.iter().collect());
3373 }
3374 }
3375
3376 if char.is_whitespace() || !char.is_ascii() {
3377 return None;
3378 }
3379 if char == ':' {
3380 found_colon = true;
3381 } else {
3382 chars.push(char);
3383 }
3384 }
3385 // Found a possible emoji shortcode at the beginning of the buffer
3386 chars.reverse();
3387 Some(chars.iter().collect())
3388 }
3389
3390 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3391 self.transact(cx, |this, cx| {
3392 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3393 let selections = this.selections.all::<usize>(cx);
3394 let multi_buffer = this.buffer.read(cx);
3395 let buffer = multi_buffer.snapshot(cx);
3396 selections
3397 .iter()
3398 .map(|selection| {
3399 let start_point = selection.start.to_point(&buffer);
3400 let mut indent =
3401 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3402 indent.len = cmp::min(indent.len, start_point.column);
3403 let start = selection.start;
3404 let end = selection.end;
3405 let selection_is_empty = start == end;
3406 let language_scope = buffer.language_scope_at(start);
3407 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3408 &language_scope
3409 {
3410 let leading_whitespace_len = buffer
3411 .reversed_chars_at(start)
3412 .take_while(|c| c.is_whitespace() && *c != '\n')
3413 .map(|c| c.len_utf8())
3414 .sum::<usize>();
3415
3416 let trailing_whitespace_len = buffer
3417 .chars_at(end)
3418 .take_while(|c| c.is_whitespace() && *c != '\n')
3419 .map(|c| c.len_utf8())
3420 .sum::<usize>();
3421
3422 let insert_extra_newline =
3423 language.brackets().any(|(pair, enabled)| {
3424 let pair_start = pair.start.trim_end();
3425 let pair_end = pair.end.trim_start();
3426
3427 enabled
3428 && pair.newline
3429 && buffer.contains_str_at(
3430 end + trailing_whitespace_len,
3431 pair_end,
3432 )
3433 && buffer.contains_str_at(
3434 (start - leading_whitespace_len)
3435 .saturating_sub(pair_start.len()),
3436 pair_start,
3437 )
3438 });
3439
3440 // Comment extension on newline is allowed only for cursor selections
3441 let comment_delimiter = maybe!({
3442 if !selection_is_empty {
3443 return None;
3444 }
3445
3446 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3447 return None;
3448 }
3449
3450 let delimiters = language.line_comment_prefixes();
3451 let max_len_of_delimiter =
3452 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3453 let (snapshot, range) =
3454 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3455
3456 let mut index_of_first_non_whitespace = 0;
3457 let comment_candidate = snapshot
3458 .chars_for_range(range)
3459 .skip_while(|c| {
3460 let should_skip = c.is_whitespace();
3461 if should_skip {
3462 index_of_first_non_whitespace += 1;
3463 }
3464 should_skip
3465 })
3466 .take(max_len_of_delimiter)
3467 .collect::<String>();
3468 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3469 comment_candidate.starts_with(comment_prefix.as_ref())
3470 })?;
3471 let cursor_is_placed_after_comment_marker =
3472 index_of_first_non_whitespace + comment_prefix.len()
3473 <= start_point.column as usize;
3474 if cursor_is_placed_after_comment_marker {
3475 Some(comment_prefix.clone())
3476 } else {
3477 None
3478 }
3479 });
3480 (comment_delimiter, insert_extra_newline)
3481 } else {
3482 (None, false)
3483 };
3484
3485 let capacity_for_delimiter = comment_delimiter
3486 .as_deref()
3487 .map(str::len)
3488 .unwrap_or_default();
3489 let mut new_text =
3490 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3491 new_text.push_str("\n");
3492 new_text.extend(indent.chars());
3493 if let Some(delimiter) = &comment_delimiter {
3494 new_text.push_str(&delimiter);
3495 }
3496 if insert_extra_newline {
3497 new_text = new_text.repeat(2);
3498 }
3499
3500 let anchor = buffer.anchor_after(end);
3501 let new_selection = selection.map(|_| anchor);
3502 (
3503 (start..end, new_text),
3504 (insert_extra_newline, new_selection),
3505 )
3506 })
3507 .unzip()
3508 };
3509
3510 this.edit_with_autoindent(edits, cx);
3511 let buffer = this.buffer.read(cx).snapshot(cx);
3512 let new_selections = selection_fixup_info
3513 .into_iter()
3514 .map(|(extra_newline_inserted, new_selection)| {
3515 let mut cursor = new_selection.end.to_point(&buffer);
3516 if extra_newline_inserted {
3517 cursor.row -= 1;
3518 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3519 }
3520 new_selection.map(|_| cursor)
3521 })
3522 .collect();
3523
3524 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3525 this.refresh_inline_completion(true, false, cx);
3526 });
3527 }
3528
3529 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3530 let buffer = self.buffer.read(cx);
3531 let snapshot = buffer.snapshot(cx);
3532
3533 let mut edits = Vec::new();
3534 let mut rows = Vec::new();
3535
3536 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3537 let cursor = selection.head();
3538 let row = cursor.row;
3539
3540 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3541
3542 let newline = "\n".to_string();
3543 edits.push((start_of_line..start_of_line, newline));
3544
3545 rows.push(row + rows_inserted as u32);
3546 }
3547
3548 self.transact(cx, |editor, cx| {
3549 editor.edit(edits, cx);
3550
3551 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3552 let mut index = 0;
3553 s.move_cursors_with(|map, _, _| {
3554 let row = rows[index];
3555 index += 1;
3556
3557 let point = Point::new(row, 0);
3558 let boundary = map.next_line_boundary(point).1;
3559 let clipped = map.clip_point(boundary, Bias::Left);
3560
3561 (clipped, SelectionGoal::None)
3562 });
3563 });
3564
3565 let mut indent_edits = Vec::new();
3566 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3567 for row in rows {
3568 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3569 for (row, indent) in indents {
3570 if indent.len == 0 {
3571 continue;
3572 }
3573
3574 let text = match indent.kind {
3575 IndentKind::Space => " ".repeat(indent.len as usize),
3576 IndentKind::Tab => "\t".repeat(indent.len as usize),
3577 };
3578 let point = Point::new(row.0, 0);
3579 indent_edits.push((point..point, text));
3580 }
3581 }
3582 editor.edit(indent_edits, cx);
3583 });
3584 }
3585
3586 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3587 let buffer = self.buffer.read(cx);
3588 let snapshot = buffer.snapshot(cx);
3589
3590 let mut edits = Vec::new();
3591 let mut rows = Vec::new();
3592 let mut rows_inserted = 0;
3593
3594 for selection in self.selections.all_adjusted(cx) {
3595 let cursor = selection.head();
3596 let row = cursor.row;
3597
3598 let point = Point::new(row + 1, 0);
3599 let start_of_line = snapshot.clip_point(point, Bias::Left);
3600
3601 let newline = "\n".to_string();
3602 edits.push((start_of_line..start_of_line, newline));
3603
3604 rows_inserted += 1;
3605 rows.push(row + rows_inserted);
3606 }
3607
3608 self.transact(cx, |editor, cx| {
3609 editor.edit(edits, cx);
3610
3611 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3612 let mut index = 0;
3613 s.move_cursors_with(|map, _, _| {
3614 let row = rows[index];
3615 index += 1;
3616
3617 let point = Point::new(row, 0);
3618 let boundary = map.next_line_boundary(point).1;
3619 let clipped = map.clip_point(boundary, Bias::Left);
3620
3621 (clipped, SelectionGoal::None)
3622 });
3623 });
3624
3625 let mut indent_edits = Vec::new();
3626 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3627 for row in rows {
3628 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3629 for (row, indent) in indents {
3630 if indent.len == 0 {
3631 continue;
3632 }
3633
3634 let text = match indent.kind {
3635 IndentKind::Space => " ".repeat(indent.len as usize),
3636 IndentKind::Tab => "\t".repeat(indent.len as usize),
3637 };
3638 let point = Point::new(row.0, 0);
3639 indent_edits.push((point..point, text));
3640 }
3641 }
3642 editor.edit(indent_edits, cx);
3643 });
3644 }
3645
3646 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3647 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3648 original_indent_columns: Vec::new(),
3649 });
3650 self.insert_with_autoindent_mode(text, autoindent, cx);
3651 }
3652
3653 fn insert_with_autoindent_mode(
3654 &mut self,
3655 text: &str,
3656 autoindent_mode: Option<AutoindentMode>,
3657 cx: &mut ViewContext<Self>,
3658 ) {
3659 if self.read_only(cx) {
3660 return;
3661 }
3662
3663 let text: Arc<str> = text.into();
3664 self.transact(cx, |this, cx| {
3665 let old_selections = this.selections.all_adjusted(cx);
3666 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3667 let anchors = {
3668 let snapshot = buffer.read(cx);
3669 old_selections
3670 .iter()
3671 .map(|s| {
3672 let anchor = snapshot.anchor_after(s.head());
3673 s.map(|_| anchor)
3674 })
3675 .collect::<Vec<_>>()
3676 };
3677 buffer.edit(
3678 old_selections
3679 .iter()
3680 .map(|s| (s.start..s.end, text.clone())),
3681 autoindent_mode,
3682 cx,
3683 );
3684 anchors
3685 });
3686
3687 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3688 s.select_anchors(selection_anchors);
3689 })
3690 });
3691 }
3692
3693 fn trigger_completion_on_input(
3694 &mut self,
3695 text: &str,
3696 trigger_in_words: bool,
3697 cx: &mut ViewContext<Self>,
3698 ) {
3699 if self.is_completion_trigger(text, trigger_in_words, cx) {
3700 self.show_completions(
3701 &ShowCompletions {
3702 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3703 },
3704 cx,
3705 );
3706 } else {
3707 self.hide_context_menu(cx);
3708 }
3709 }
3710
3711 fn is_completion_trigger(
3712 &self,
3713 text: &str,
3714 trigger_in_words: bool,
3715 cx: &mut ViewContext<Self>,
3716 ) -> bool {
3717 let position = self.selections.newest_anchor().head();
3718 let multibuffer = self.buffer.read(cx);
3719 let Some(buffer) = position
3720 .buffer_id
3721 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3722 else {
3723 return false;
3724 };
3725
3726 if let Some(completion_provider) = &self.completion_provider {
3727 completion_provider.is_completion_trigger(
3728 &buffer,
3729 position.text_anchor,
3730 text,
3731 trigger_in_words,
3732 cx,
3733 )
3734 } else {
3735 false
3736 }
3737 }
3738
3739 /// If any empty selections is touching the start of its innermost containing autoclose
3740 /// region, expand it to select the brackets.
3741 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3742 let selections = self.selections.all::<usize>(cx);
3743 let buffer = self.buffer.read(cx).read(cx);
3744 let new_selections = self
3745 .selections_with_autoclose_regions(selections, &buffer)
3746 .map(|(mut selection, region)| {
3747 if !selection.is_empty() {
3748 return selection;
3749 }
3750
3751 if let Some(region) = region {
3752 let mut range = region.range.to_offset(&buffer);
3753 if selection.start == range.start && range.start >= region.pair.start.len() {
3754 range.start -= region.pair.start.len();
3755 if buffer.contains_str_at(range.start, ®ion.pair.start)
3756 && buffer.contains_str_at(range.end, ®ion.pair.end)
3757 {
3758 range.end += region.pair.end.len();
3759 selection.start = range.start;
3760 selection.end = range.end;
3761
3762 return selection;
3763 }
3764 }
3765 }
3766
3767 let always_treat_brackets_as_autoclosed = buffer
3768 .settings_at(selection.start, cx)
3769 .always_treat_brackets_as_autoclosed;
3770
3771 if !always_treat_brackets_as_autoclosed {
3772 return selection;
3773 }
3774
3775 if let Some(scope) = buffer.language_scope_at(selection.start) {
3776 for (pair, enabled) in scope.brackets() {
3777 if !enabled || !pair.close {
3778 continue;
3779 }
3780
3781 if buffer.contains_str_at(selection.start, &pair.end) {
3782 let pair_start_len = pair.start.len();
3783 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3784 {
3785 selection.start -= pair_start_len;
3786 selection.end += pair.end.len();
3787
3788 return selection;
3789 }
3790 }
3791 }
3792 }
3793
3794 selection
3795 })
3796 .collect();
3797
3798 drop(buffer);
3799 self.change_selections(None, cx, |selections| selections.select(new_selections));
3800 }
3801
3802 /// Iterate the given selections, and for each one, find the smallest surrounding
3803 /// autoclose region. This uses the ordering of the selections and the autoclose
3804 /// regions to avoid repeated comparisons.
3805 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3806 &'a self,
3807 selections: impl IntoIterator<Item = Selection<D>>,
3808 buffer: &'a MultiBufferSnapshot,
3809 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3810 let mut i = 0;
3811 let mut regions = self.autoclose_regions.as_slice();
3812 selections.into_iter().map(move |selection| {
3813 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3814
3815 let mut enclosing = None;
3816 while let Some(pair_state) = regions.get(i) {
3817 if pair_state.range.end.to_offset(buffer) < range.start {
3818 regions = ®ions[i + 1..];
3819 i = 0;
3820 } else if pair_state.range.start.to_offset(buffer) > range.end {
3821 break;
3822 } else {
3823 if pair_state.selection_id == selection.id {
3824 enclosing = Some(pair_state);
3825 }
3826 i += 1;
3827 }
3828 }
3829
3830 (selection.clone(), enclosing)
3831 })
3832 }
3833
3834 /// Remove any autoclose regions that no longer contain their selection.
3835 fn invalidate_autoclose_regions(
3836 &mut self,
3837 mut selections: &[Selection<Anchor>],
3838 buffer: &MultiBufferSnapshot,
3839 ) {
3840 self.autoclose_regions.retain(|state| {
3841 let mut i = 0;
3842 while let Some(selection) = selections.get(i) {
3843 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3844 selections = &selections[1..];
3845 continue;
3846 }
3847 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3848 break;
3849 }
3850 if selection.id == state.selection_id {
3851 return true;
3852 } else {
3853 i += 1;
3854 }
3855 }
3856 false
3857 });
3858 }
3859
3860 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3861 let offset = position.to_offset(buffer);
3862 let (word_range, kind) = buffer.surrounding_word(offset);
3863 if offset > word_range.start && kind == Some(CharKind::Word) {
3864 Some(
3865 buffer
3866 .text_for_range(word_range.start..offset)
3867 .collect::<String>(),
3868 )
3869 } else {
3870 None
3871 }
3872 }
3873
3874 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3875 self.refresh_inlay_hints(
3876 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3877 cx,
3878 );
3879 }
3880
3881 pub fn inlay_hints_enabled(&self) -> bool {
3882 self.inlay_hint_cache.enabled
3883 }
3884
3885 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3886 if self.project.is_none() || self.mode != EditorMode::Full {
3887 return;
3888 }
3889
3890 let reason_description = reason.description();
3891 let ignore_debounce = matches!(
3892 reason,
3893 InlayHintRefreshReason::SettingsChange(_)
3894 | InlayHintRefreshReason::Toggle(_)
3895 | InlayHintRefreshReason::ExcerptsRemoved(_)
3896 );
3897 let (invalidate_cache, required_languages) = match reason {
3898 InlayHintRefreshReason::Toggle(enabled) => {
3899 self.inlay_hint_cache.enabled = enabled;
3900 if enabled {
3901 (InvalidationStrategy::RefreshRequested, None)
3902 } else {
3903 self.inlay_hint_cache.clear();
3904 self.splice_inlays(
3905 self.visible_inlay_hints(cx)
3906 .iter()
3907 .map(|inlay| inlay.id)
3908 .collect(),
3909 Vec::new(),
3910 cx,
3911 );
3912 return;
3913 }
3914 }
3915 InlayHintRefreshReason::SettingsChange(new_settings) => {
3916 match self.inlay_hint_cache.update_settings(
3917 &self.buffer,
3918 new_settings,
3919 self.visible_inlay_hints(cx),
3920 cx,
3921 ) {
3922 ControlFlow::Break(Some(InlaySplice {
3923 to_remove,
3924 to_insert,
3925 })) => {
3926 self.splice_inlays(to_remove, to_insert, cx);
3927 return;
3928 }
3929 ControlFlow::Break(None) => return,
3930 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3931 }
3932 }
3933 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3934 if let Some(InlaySplice {
3935 to_remove,
3936 to_insert,
3937 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3938 {
3939 self.splice_inlays(to_remove, to_insert, cx);
3940 }
3941 return;
3942 }
3943 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3944 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3945 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3946 }
3947 InlayHintRefreshReason::RefreshRequested => {
3948 (InvalidationStrategy::RefreshRequested, None)
3949 }
3950 };
3951
3952 if let Some(InlaySplice {
3953 to_remove,
3954 to_insert,
3955 }) = self.inlay_hint_cache.spawn_hint_refresh(
3956 reason_description,
3957 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3958 invalidate_cache,
3959 ignore_debounce,
3960 cx,
3961 ) {
3962 self.splice_inlays(to_remove, to_insert, cx);
3963 }
3964 }
3965
3966 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3967 self.display_map
3968 .read(cx)
3969 .current_inlays()
3970 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3971 .cloned()
3972 .collect()
3973 }
3974
3975 pub fn excerpts_for_inlay_hints_query(
3976 &self,
3977 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3978 cx: &mut ViewContext<Editor>,
3979 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3980 let Some(project) = self.project.as_ref() else {
3981 return HashMap::default();
3982 };
3983 let project = project.read(cx);
3984 let multi_buffer = self.buffer().read(cx);
3985 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3986 let multi_buffer_visible_start = self
3987 .scroll_manager
3988 .anchor()
3989 .anchor
3990 .to_point(&multi_buffer_snapshot);
3991 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3992 multi_buffer_visible_start
3993 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3994 Bias::Left,
3995 );
3996 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3997 multi_buffer
3998 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3999 .into_iter()
4000 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4001 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4002 let buffer = buffer_handle.read(cx);
4003 let buffer_file = project::File::from_dyn(buffer.file())?;
4004 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4005 let worktree_entry = buffer_worktree
4006 .read(cx)
4007 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4008 if worktree_entry.is_ignored {
4009 return None;
4010 }
4011
4012 let language = buffer.language()?;
4013 if let Some(restrict_to_languages) = restrict_to_languages {
4014 if !restrict_to_languages.contains(language) {
4015 return None;
4016 }
4017 }
4018 Some((
4019 excerpt_id,
4020 (
4021 buffer_handle,
4022 buffer.version().clone(),
4023 excerpt_visible_range,
4024 ),
4025 ))
4026 })
4027 .collect()
4028 }
4029
4030 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4031 TextLayoutDetails {
4032 text_system: cx.text_system().clone(),
4033 editor_style: self.style.clone().unwrap(),
4034 rem_size: cx.rem_size(),
4035 scroll_anchor: self.scroll_manager.anchor(),
4036 visible_rows: self.visible_line_count(),
4037 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4038 }
4039 }
4040
4041 fn splice_inlays(
4042 &self,
4043 to_remove: Vec<InlayId>,
4044 to_insert: Vec<Inlay>,
4045 cx: &mut ViewContext<Self>,
4046 ) {
4047 self.display_map.update(cx, |display_map, cx| {
4048 display_map.splice_inlays(to_remove, to_insert, cx);
4049 });
4050 cx.notify();
4051 }
4052
4053 fn trigger_on_type_formatting(
4054 &self,
4055 input: String,
4056 cx: &mut ViewContext<Self>,
4057 ) -> Option<Task<Result<()>>> {
4058 if input.len() != 1 {
4059 return None;
4060 }
4061
4062 let project = self.project.as_ref()?;
4063 let position = self.selections.newest_anchor().head();
4064 let (buffer, buffer_position) = self
4065 .buffer
4066 .read(cx)
4067 .text_anchor_for_position(position, cx)?;
4068
4069 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4070 // hence we do LSP request & edit on host side only — add formats to host's history.
4071 let push_to_lsp_host_history = true;
4072 // If this is not the host, append its history with new edits.
4073 let push_to_client_history = project.read(cx).is_remote();
4074
4075 let on_type_formatting = project.update(cx, |project, cx| {
4076 project.on_type_format(
4077 buffer.clone(),
4078 buffer_position,
4079 input,
4080 push_to_lsp_host_history,
4081 cx,
4082 )
4083 });
4084 Some(cx.spawn(|editor, mut cx| async move {
4085 if let Some(transaction) = on_type_formatting.await? {
4086 if push_to_client_history {
4087 buffer
4088 .update(&mut cx, |buffer, _| {
4089 buffer.push_transaction(transaction, Instant::now());
4090 })
4091 .ok();
4092 }
4093 editor.update(&mut cx, |editor, cx| {
4094 editor.refresh_document_highlights(cx);
4095 })?;
4096 }
4097 Ok(())
4098 }))
4099 }
4100
4101 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4102 if self.pending_rename.is_some() {
4103 return;
4104 }
4105
4106 let Some(provider) = self.completion_provider.as_ref() else {
4107 return;
4108 };
4109
4110 let position = self.selections.newest_anchor().head();
4111 let (buffer, buffer_position) =
4112 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4113 output
4114 } else {
4115 return;
4116 };
4117
4118 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4119 let is_followup_invoke = {
4120 let context_menu_state = self.context_menu.read();
4121 matches!(
4122 context_menu_state.deref(),
4123 Some(ContextMenu::Completions(_))
4124 )
4125 };
4126 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4127 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4128 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4129 CompletionTriggerKind::TRIGGER_CHARACTER
4130 }
4131
4132 _ => CompletionTriggerKind::INVOKED,
4133 };
4134 let completion_context = CompletionContext {
4135 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4136 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4137 Some(String::from(trigger))
4138 } else {
4139 None
4140 }
4141 }),
4142 trigger_kind,
4143 };
4144 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4145 let sort_completions = provider.sort_completions();
4146
4147 let id = post_inc(&mut self.next_completion_id);
4148 let task = cx.spawn(|this, mut cx| {
4149 async move {
4150 this.update(&mut cx, |this, _| {
4151 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4152 })?;
4153 let completions = completions.await.log_err();
4154 let menu = if let Some(completions) = completions {
4155 let mut menu = CompletionsMenu {
4156 id,
4157 sort_completions,
4158 initial_position: position,
4159 match_candidates: completions
4160 .iter()
4161 .enumerate()
4162 .map(|(id, completion)| {
4163 StringMatchCandidate::new(
4164 id,
4165 completion.label.text[completion.label.filter_range.clone()]
4166 .into(),
4167 )
4168 })
4169 .collect(),
4170 buffer: buffer.clone(),
4171 completions: Arc::new(RwLock::new(completions.into())),
4172 matches: Vec::new().into(),
4173 selected_item: 0,
4174 scroll_handle: UniformListScrollHandle::new(),
4175 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4176 DebouncedDelay::new(),
4177 )),
4178 };
4179 menu.filter(query.as_deref(), cx.background_executor().clone())
4180 .await;
4181
4182 if menu.matches.is_empty() {
4183 None
4184 } else {
4185 this.update(&mut cx, |editor, cx| {
4186 let completions = menu.completions.clone();
4187 let matches = menu.matches.clone();
4188
4189 let delay_ms = EditorSettings::get_global(cx)
4190 .completion_documentation_secondary_query_debounce;
4191 let delay = Duration::from_millis(delay_ms);
4192 editor
4193 .completion_documentation_pre_resolve_debounce
4194 .fire_new(delay, cx, |editor, cx| {
4195 CompletionsMenu::pre_resolve_completion_documentation(
4196 buffer,
4197 completions,
4198 matches,
4199 editor,
4200 cx,
4201 )
4202 });
4203 })
4204 .ok();
4205 Some(menu)
4206 }
4207 } else {
4208 None
4209 };
4210
4211 this.update(&mut cx, |this, cx| {
4212 let mut context_menu = this.context_menu.write();
4213 match context_menu.as_ref() {
4214 None => {}
4215
4216 Some(ContextMenu::Completions(prev_menu)) => {
4217 if prev_menu.id > id {
4218 return;
4219 }
4220 }
4221
4222 _ => return,
4223 }
4224
4225 if this.focus_handle.is_focused(cx) && menu.is_some() {
4226 let menu = menu.unwrap();
4227 *context_menu = Some(ContextMenu::Completions(menu));
4228 drop(context_menu);
4229 this.discard_inline_completion(false, cx);
4230 cx.notify();
4231 } else if this.completion_tasks.len() <= 1 {
4232 // If there are no more completion tasks and the last menu was
4233 // empty, we should hide it. If it was already hidden, we should
4234 // also show the copilot completion when available.
4235 drop(context_menu);
4236 if this.hide_context_menu(cx).is_none() {
4237 this.update_visible_inline_completion(cx);
4238 }
4239 }
4240 })?;
4241
4242 Ok::<_, anyhow::Error>(())
4243 }
4244 .log_err()
4245 });
4246
4247 self.completion_tasks.push((id, task));
4248 }
4249
4250 pub fn confirm_completion(
4251 &mut self,
4252 action: &ConfirmCompletion,
4253 cx: &mut ViewContext<Self>,
4254 ) -> Option<Task<Result<()>>> {
4255 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4256 }
4257
4258 pub fn compose_completion(
4259 &mut self,
4260 action: &ComposeCompletion,
4261 cx: &mut ViewContext<Self>,
4262 ) -> Option<Task<Result<()>>> {
4263 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4264 }
4265
4266 fn do_completion(
4267 &mut self,
4268 item_ix: Option<usize>,
4269 intent: CompletionIntent,
4270 cx: &mut ViewContext<Editor>,
4271 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4272 use language::ToOffset as _;
4273
4274 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4275 menu
4276 } else {
4277 return None;
4278 };
4279
4280 let mat = completions_menu
4281 .matches
4282 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4283 let buffer_handle = completions_menu.buffer;
4284 let completions = completions_menu.completions.read();
4285 let completion = completions.get(mat.candidate_id)?;
4286 cx.stop_propagation();
4287
4288 let snippet;
4289 let text;
4290
4291 if completion.is_snippet() {
4292 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4293 text = snippet.as_ref().unwrap().text.clone();
4294 } else {
4295 snippet = None;
4296 text = completion.new_text.clone();
4297 };
4298 let selections = self.selections.all::<usize>(cx);
4299 let buffer = buffer_handle.read(cx);
4300 let old_range = completion.old_range.to_offset(buffer);
4301 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4302
4303 let newest_selection = self.selections.newest_anchor();
4304 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4305 return None;
4306 }
4307
4308 let lookbehind = newest_selection
4309 .start
4310 .text_anchor
4311 .to_offset(buffer)
4312 .saturating_sub(old_range.start);
4313 let lookahead = old_range
4314 .end
4315 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4316 let mut common_prefix_len = old_text
4317 .bytes()
4318 .zip(text.bytes())
4319 .take_while(|(a, b)| a == b)
4320 .count();
4321
4322 let snapshot = self.buffer.read(cx).snapshot(cx);
4323 let mut range_to_replace: Option<Range<isize>> = None;
4324 let mut ranges = Vec::new();
4325 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4326 for selection in &selections {
4327 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4328 let start = selection.start.saturating_sub(lookbehind);
4329 let end = selection.end + lookahead;
4330 if selection.id == newest_selection.id {
4331 range_to_replace = Some(
4332 ((start + common_prefix_len) as isize - selection.start as isize)
4333 ..(end as isize - selection.start as isize),
4334 );
4335 }
4336 ranges.push(start + common_prefix_len..end);
4337 } else {
4338 common_prefix_len = 0;
4339 ranges.clear();
4340 ranges.extend(selections.iter().map(|s| {
4341 if s.id == newest_selection.id {
4342 range_to_replace = Some(
4343 old_range.start.to_offset_utf16(&snapshot).0 as isize
4344 - selection.start as isize
4345 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4346 - selection.start as isize,
4347 );
4348 old_range.clone()
4349 } else {
4350 s.start..s.end
4351 }
4352 }));
4353 break;
4354 }
4355 if !self.linked_edit_ranges.is_empty() {
4356 let start_anchor = snapshot.anchor_before(selection.head());
4357 let end_anchor = snapshot.anchor_after(selection.tail());
4358 if let Some(ranges) = self
4359 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4360 {
4361 for (buffer, edits) in ranges {
4362 linked_edits.entry(buffer.clone()).or_default().extend(
4363 edits
4364 .into_iter()
4365 .map(|range| (range, text[common_prefix_len..].to_owned())),
4366 );
4367 }
4368 }
4369 }
4370 }
4371 let text = &text[common_prefix_len..];
4372
4373 cx.emit(EditorEvent::InputHandled {
4374 utf16_range_to_replace: range_to_replace,
4375 text: text.into(),
4376 });
4377
4378 self.transact(cx, |this, cx| {
4379 if let Some(mut snippet) = snippet {
4380 snippet.text = text.to_string();
4381 for tabstop in snippet.tabstops.iter_mut().flatten() {
4382 tabstop.start -= common_prefix_len as isize;
4383 tabstop.end -= common_prefix_len as isize;
4384 }
4385
4386 this.insert_snippet(&ranges, snippet, cx).log_err();
4387 } else {
4388 this.buffer.update(cx, |buffer, cx| {
4389 buffer.edit(
4390 ranges.iter().map(|range| (range.clone(), text)),
4391 this.autoindent_mode.clone(),
4392 cx,
4393 );
4394 });
4395 }
4396 for (buffer, edits) in linked_edits {
4397 buffer.update(cx, |buffer, cx| {
4398 let snapshot = buffer.snapshot();
4399 let edits = edits
4400 .into_iter()
4401 .map(|(range, text)| {
4402 use text::ToPoint as TP;
4403 let end_point = TP::to_point(&range.end, &snapshot);
4404 let start_point = TP::to_point(&range.start, &snapshot);
4405 (start_point..end_point, text)
4406 })
4407 .sorted_by_key(|(range, _)| range.start)
4408 .collect::<Vec<_>>();
4409 buffer.edit(edits, None, cx);
4410 })
4411 }
4412
4413 this.refresh_inline_completion(true, false, cx);
4414 });
4415
4416 let show_new_completions_on_confirm = completion
4417 .confirm
4418 .as_ref()
4419 .map_or(false, |confirm| confirm(intent, cx));
4420 if show_new_completions_on_confirm {
4421 self.show_completions(&ShowCompletions { trigger: None }, cx);
4422 }
4423
4424 let provider = self.completion_provider.as_ref()?;
4425 let apply_edits = provider.apply_additional_edits_for_completion(
4426 buffer_handle,
4427 completion.clone(),
4428 true,
4429 cx,
4430 );
4431
4432 let editor_settings = EditorSettings::get_global(cx);
4433 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4434 // After the code completion is finished, users often want to know what signatures are needed.
4435 // so we should automatically call signature_help
4436 self.show_signature_help(&ShowSignatureHelp, cx);
4437 }
4438
4439 Some(cx.foreground_executor().spawn(async move {
4440 apply_edits.await?;
4441 Ok(())
4442 }))
4443 }
4444
4445 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4446 let mut context_menu = self.context_menu.write();
4447 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4448 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4449 // Toggle if we're selecting the same one
4450 *context_menu = None;
4451 cx.notify();
4452 return;
4453 } else {
4454 // Otherwise, clear it and start a new one
4455 *context_menu = None;
4456 cx.notify();
4457 }
4458 }
4459 drop(context_menu);
4460 let snapshot = self.snapshot(cx);
4461 let deployed_from_indicator = action.deployed_from_indicator;
4462 let mut task = self.code_actions_task.take();
4463 let action = action.clone();
4464 cx.spawn(|editor, mut cx| async move {
4465 while let Some(prev_task) = task {
4466 prev_task.await;
4467 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4468 }
4469
4470 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4471 if editor.focus_handle.is_focused(cx) {
4472 let multibuffer_point = action
4473 .deployed_from_indicator
4474 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4475 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4476 let (buffer, buffer_row) = snapshot
4477 .buffer_snapshot
4478 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4479 .and_then(|(buffer_snapshot, range)| {
4480 editor
4481 .buffer
4482 .read(cx)
4483 .buffer(buffer_snapshot.remote_id())
4484 .map(|buffer| (buffer, range.start.row))
4485 })?;
4486 let (_, code_actions) = editor
4487 .available_code_actions
4488 .clone()
4489 .and_then(|(location, code_actions)| {
4490 let snapshot = location.buffer.read(cx).snapshot();
4491 let point_range = location.range.to_point(&snapshot);
4492 let point_range = point_range.start.row..=point_range.end.row;
4493 if point_range.contains(&buffer_row) {
4494 Some((location, code_actions))
4495 } else {
4496 None
4497 }
4498 })
4499 .unzip();
4500 let buffer_id = buffer.read(cx).remote_id();
4501 let tasks = editor
4502 .tasks
4503 .get(&(buffer_id, buffer_row))
4504 .map(|t| Arc::new(t.to_owned()));
4505 if tasks.is_none() && code_actions.is_none() {
4506 return None;
4507 }
4508
4509 editor.completion_tasks.clear();
4510 editor.discard_inline_completion(false, cx);
4511 let task_context =
4512 tasks
4513 .as_ref()
4514 .zip(editor.project.clone())
4515 .map(|(tasks, project)| {
4516 let position = Point::new(buffer_row, tasks.column);
4517 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4518 let location = Location {
4519 buffer: buffer.clone(),
4520 range: range_start..range_start,
4521 };
4522 // Fill in the environmental variables from the tree-sitter captures
4523 let mut captured_task_variables = TaskVariables::default();
4524 for (capture_name, value) in tasks.extra_variables.clone() {
4525 captured_task_variables.insert(
4526 task::VariableName::Custom(capture_name.into()),
4527 value.clone(),
4528 );
4529 }
4530 project.update(cx, |project, cx| {
4531 project.task_context_for_location(
4532 captured_task_variables,
4533 location,
4534 cx,
4535 )
4536 })
4537 });
4538
4539 Some(cx.spawn(|editor, mut cx| async move {
4540 let task_context = match task_context {
4541 Some(task_context) => task_context.await,
4542 None => None,
4543 };
4544 let resolved_tasks =
4545 tasks.zip(task_context).map(|(tasks, task_context)| {
4546 Arc::new(ResolvedTasks {
4547 templates: tasks
4548 .templates
4549 .iter()
4550 .filter_map(|(kind, template)| {
4551 template
4552 .resolve_task(&kind.to_id_base(), &task_context)
4553 .map(|task| (kind.clone(), task))
4554 })
4555 .collect(),
4556 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4557 multibuffer_point.row,
4558 tasks.column,
4559 )),
4560 })
4561 });
4562 let spawn_straight_away = resolved_tasks
4563 .as_ref()
4564 .map_or(false, |tasks| tasks.templates.len() == 1)
4565 && code_actions
4566 .as_ref()
4567 .map_or(true, |actions| actions.is_empty());
4568 if let Some(task) = editor
4569 .update(&mut cx, |editor, cx| {
4570 *editor.context_menu.write() =
4571 Some(ContextMenu::CodeActions(CodeActionsMenu {
4572 buffer,
4573 actions: CodeActionContents {
4574 tasks: resolved_tasks,
4575 actions: code_actions,
4576 },
4577 selected_item: Default::default(),
4578 scroll_handle: UniformListScrollHandle::default(),
4579 deployed_from_indicator,
4580 }));
4581 if spawn_straight_away {
4582 if let Some(task) = editor.confirm_code_action(
4583 &ConfirmCodeAction { item_ix: Some(0) },
4584 cx,
4585 ) {
4586 cx.notify();
4587 return task;
4588 }
4589 }
4590 cx.notify();
4591 Task::ready(Ok(()))
4592 })
4593 .ok()
4594 {
4595 task.await
4596 } else {
4597 Ok(())
4598 }
4599 }))
4600 } else {
4601 Some(Task::ready(Ok(())))
4602 }
4603 })?;
4604 if let Some(task) = spawned_test_task {
4605 task.await?;
4606 }
4607
4608 Ok::<_, anyhow::Error>(())
4609 })
4610 .detach_and_log_err(cx);
4611 }
4612
4613 pub fn confirm_code_action(
4614 &mut self,
4615 action: &ConfirmCodeAction,
4616 cx: &mut ViewContext<Self>,
4617 ) -> Option<Task<Result<()>>> {
4618 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4619 menu
4620 } else {
4621 return None;
4622 };
4623 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4624 let action = actions_menu.actions.get(action_ix)?;
4625 let title = action.label();
4626 let buffer = actions_menu.buffer;
4627 let workspace = self.workspace()?;
4628
4629 match action {
4630 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4631 workspace.update(cx, |workspace, cx| {
4632 workspace::tasks::schedule_resolved_task(
4633 workspace,
4634 task_source_kind,
4635 resolved_task,
4636 false,
4637 cx,
4638 );
4639
4640 Some(Task::ready(Ok(())))
4641 })
4642 }
4643 CodeActionsItem::CodeAction(action) => {
4644 let apply_code_actions = workspace
4645 .read(cx)
4646 .project()
4647 .clone()
4648 .update(cx, |project, cx| {
4649 project.apply_code_action(buffer, action, true, cx)
4650 });
4651 let workspace = workspace.downgrade();
4652 Some(cx.spawn(|editor, cx| async move {
4653 let project_transaction = apply_code_actions.await?;
4654 Self::open_project_transaction(
4655 &editor,
4656 workspace,
4657 project_transaction,
4658 title,
4659 cx,
4660 )
4661 .await
4662 }))
4663 }
4664 }
4665 }
4666
4667 pub async fn open_project_transaction(
4668 this: &WeakView<Editor>,
4669 workspace: WeakView<Workspace>,
4670 transaction: ProjectTransaction,
4671 title: String,
4672 mut cx: AsyncWindowContext,
4673 ) -> Result<()> {
4674 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4675
4676 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4677 cx.update(|cx| {
4678 entries.sort_unstable_by_key(|(buffer, _)| {
4679 buffer.read(cx).file().map(|f| f.path().clone())
4680 });
4681 })?;
4682
4683 // If the project transaction's edits are all contained within this editor, then
4684 // avoid opening a new editor to display them.
4685
4686 if let Some((buffer, transaction)) = entries.first() {
4687 if entries.len() == 1 {
4688 let excerpt = this.update(&mut cx, |editor, cx| {
4689 editor
4690 .buffer()
4691 .read(cx)
4692 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4693 })?;
4694 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4695 if excerpted_buffer == *buffer {
4696 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4697 let excerpt_range = excerpt_range.to_offset(buffer);
4698 buffer
4699 .edited_ranges_for_transaction::<usize>(transaction)
4700 .all(|range| {
4701 excerpt_range.start <= range.start
4702 && excerpt_range.end >= range.end
4703 })
4704 })?;
4705
4706 if all_edits_within_excerpt {
4707 return Ok(());
4708 }
4709 }
4710 }
4711 }
4712 } else {
4713 return Ok(());
4714 }
4715
4716 let mut ranges_to_highlight = Vec::new();
4717 let excerpt_buffer = cx.new_model(|cx| {
4718 let mut multibuffer =
4719 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4720 for (buffer_handle, transaction) in &entries {
4721 let buffer = buffer_handle.read(cx);
4722 ranges_to_highlight.extend(
4723 multibuffer.push_excerpts_with_context_lines(
4724 buffer_handle.clone(),
4725 buffer
4726 .edited_ranges_for_transaction::<usize>(transaction)
4727 .collect(),
4728 DEFAULT_MULTIBUFFER_CONTEXT,
4729 cx,
4730 ),
4731 );
4732 }
4733 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4734 multibuffer
4735 })?;
4736
4737 workspace.update(&mut cx, |workspace, cx| {
4738 let project = workspace.project().clone();
4739 let editor =
4740 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4741 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4742 editor.update(cx, |editor, cx| {
4743 editor.highlight_background::<Self>(
4744 &ranges_to_highlight,
4745 |theme| theme.editor_highlighted_line_background,
4746 cx,
4747 );
4748 });
4749 })?;
4750
4751 Ok(())
4752 }
4753
4754 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4755 let project = self.project.clone()?;
4756 let buffer = self.buffer.read(cx);
4757 let newest_selection = self.selections.newest_anchor().clone();
4758 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4759 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4760 if start_buffer != end_buffer {
4761 return None;
4762 }
4763
4764 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4765 cx.background_executor()
4766 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4767 .await;
4768
4769 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4770 project.code_actions(&start_buffer, start..end, cx)
4771 }) {
4772 code_actions.await
4773 } else {
4774 Vec::new()
4775 };
4776
4777 this.update(&mut cx, |this, cx| {
4778 this.available_code_actions = if actions.is_empty() {
4779 None
4780 } else {
4781 Some((
4782 Location {
4783 buffer: start_buffer,
4784 range: start..end,
4785 },
4786 actions.into(),
4787 ))
4788 };
4789 cx.notify();
4790 })
4791 .log_err();
4792 }));
4793 None
4794 }
4795
4796 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4797 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4798 self.show_git_blame_inline = false;
4799
4800 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4801 cx.background_executor().timer(delay).await;
4802
4803 this.update(&mut cx, |this, cx| {
4804 this.show_git_blame_inline = true;
4805 cx.notify();
4806 })
4807 .log_err();
4808 }));
4809 }
4810 }
4811
4812 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4813 if self.pending_rename.is_some() {
4814 return None;
4815 }
4816
4817 let project = self.project.clone()?;
4818 let buffer = self.buffer.read(cx);
4819 let newest_selection = self.selections.newest_anchor().clone();
4820 let cursor_position = newest_selection.head();
4821 let (cursor_buffer, cursor_buffer_position) =
4822 buffer.text_anchor_for_position(cursor_position, cx)?;
4823 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4824 if cursor_buffer != tail_buffer {
4825 return None;
4826 }
4827
4828 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4829 cx.background_executor()
4830 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4831 .await;
4832
4833 let highlights = if let Some(highlights) = project
4834 .update(&mut cx, |project, cx| {
4835 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4836 })
4837 .log_err()
4838 {
4839 highlights.await.log_err()
4840 } else {
4841 None
4842 };
4843
4844 if let Some(highlights) = highlights {
4845 this.update(&mut cx, |this, cx| {
4846 if this.pending_rename.is_some() {
4847 return;
4848 }
4849
4850 let buffer_id = cursor_position.buffer_id;
4851 let buffer = this.buffer.read(cx);
4852 if !buffer
4853 .text_anchor_for_position(cursor_position, cx)
4854 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4855 {
4856 return;
4857 }
4858
4859 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4860 let mut write_ranges = Vec::new();
4861 let mut read_ranges = Vec::new();
4862 for highlight in highlights {
4863 for (excerpt_id, excerpt_range) in
4864 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4865 {
4866 let start = highlight
4867 .range
4868 .start
4869 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4870 let end = highlight
4871 .range
4872 .end
4873 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4874 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4875 continue;
4876 }
4877
4878 let range = Anchor {
4879 buffer_id,
4880 excerpt_id,
4881 text_anchor: start,
4882 }..Anchor {
4883 buffer_id,
4884 excerpt_id,
4885 text_anchor: end,
4886 };
4887 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4888 write_ranges.push(range);
4889 } else {
4890 read_ranges.push(range);
4891 }
4892 }
4893 }
4894
4895 this.highlight_background::<DocumentHighlightRead>(
4896 &read_ranges,
4897 |theme| theme.editor_document_highlight_read_background,
4898 cx,
4899 );
4900 this.highlight_background::<DocumentHighlightWrite>(
4901 &write_ranges,
4902 |theme| theme.editor_document_highlight_write_background,
4903 cx,
4904 );
4905 cx.notify();
4906 })
4907 .log_err();
4908 }
4909 }));
4910 None
4911 }
4912
4913 pub fn refresh_inline_completion(
4914 &mut self,
4915 debounce: bool,
4916 user_requested: bool,
4917 cx: &mut ViewContext<Self>,
4918 ) -> Option<()> {
4919 let provider = self.inline_completion_provider()?;
4920 let cursor = self.selections.newest_anchor().head();
4921 let (buffer, cursor_buffer_position) =
4922 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4923 if !user_requested
4924 && (!self.show_inline_completions
4925 || !provider.is_enabled(&buffer, cursor_buffer_position, cx))
4926 {
4927 self.discard_inline_completion(false, cx);
4928 return None;
4929 }
4930
4931 self.update_visible_inline_completion(cx);
4932 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4933 Some(())
4934 }
4935
4936 fn cycle_inline_completion(
4937 &mut self,
4938 direction: Direction,
4939 cx: &mut ViewContext<Self>,
4940 ) -> Option<()> {
4941 let provider = self.inline_completion_provider()?;
4942 let cursor = self.selections.newest_anchor().head();
4943 let (buffer, cursor_buffer_position) =
4944 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4945 if !self.show_inline_completions
4946 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4947 {
4948 return None;
4949 }
4950
4951 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4952 self.update_visible_inline_completion(cx);
4953
4954 Some(())
4955 }
4956
4957 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4958 if !self.has_active_inline_completion(cx) {
4959 self.refresh_inline_completion(false, true, cx);
4960 return;
4961 }
4962
4963 self.update_visible_inline_completion(cx);
4964 }
4965
4966 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4967 self.show_cursor_names(cx);
4968 }
4969
4970 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4971 self.show_cursor_names = true;
4972 cx.notify();
4973 cx.spawn(|this, mut cx| async move {
4974 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4975 this.update(&mut cx, |this, cx| {
4976 this.show_cursor_names = false;
4977 cx.notify()
4978 })
4979 .ok()
4980 })
4981 .detach();
4982 }
4983
4984 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4985 if self.has_active_inline_completion(cx) {
4986 self.cycle_inline_completion(Direction::Next, cx);
4987 } else {
4988 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4989 if is_copilot_disabled {
4990 cx.propagate();
4991 }
4992 }
4993 }
4994
4995 pub fn previous_inline_completion(
4996 &mut self,
4997 _: &PreviousInlineCompletion,
4998 cx: &mut ViewContext<Self>,
4999 ) {
5000 if self.has_active_inline_completion(cx) {
5001 self.cycle_inline_completion(Direction::Prev, cx);
5002 } else {
5003 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5004 if is_copilot_disabled {
5005 cx.propagate();
5006 }
5007 }
5008 }
5009
5010 pub fn accept_inline_completion(
5011 &mut self,
5012 _: &AcceptInlineCompletion,
5013 cx: &mut ViewContext<Self>,
5014 ) {
5015 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
5016 return;
5017 };
5018 if let Some(provider) = self.inline_completion_provider() {
5019 provider.accept(cx);
5020 }
5021
5022 cx.emit(EditorEvent::InputHandled {
5023 utf16_range_to_replace: None,
5024 text: completion.text.to_string().into(),
5025 });
5026
5027 if let Some(range) = delete_range {
5028 self.change_selections(None, cx, |s| s.select_ranges([range]))
5029 }
5030 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5031 self.refresh_inline_completion(true, true, cx);
5032 cx.notify();
5033 }
5034
5035 pub fn accept_partial_inline_completion(
5036 &mut self,
5037 _: &AcceptPartialInlineCompletion,
5038 cx: &mut ViewContext<Self>,
5039 ) {
5040 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5041 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5042 let mut partial_completion = completion
5043 .text
5044 .chars()
5045 .by_ref()
5046 .take_while(|c| c.is_alphabetic())
5047 .collect::<String>();
5048 if partial_completion.is_empty() {
5049 partial_completion = completion
5050 .text
5051 .chars()
5052 .by_ref()
5053 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5054 .collect::<String>();
5055 }
5056
5057 cx.emit(EditorEvent::InputHandled {
5058 utf16_range_to_replace: None,
5059 text: partial_completion.clone().into(),
5060 });
5061
5062 if let Some(range) = delete_range {
5063 self.change_selections(None, cx, |s| s.select_ranges([range]))
5064 }
5065 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5066
5067 self.refresh_inline_completion(true, true, cx);
5068 cx.notify();
5069 }
5070 }
5071 }
5072
5073 fn discard_inline_completion(
5074 &mut self,
5075 should_report_inline_completion_event: bool,
5076 cx: &mut ViewContext<Self>,
5077 ) -> bool {
5078 if let Some(provider) = self.inline_completion_provider() {
5079 provider.discard(should_report_inline_completion_event, cx);
5080 }
5081
5082 self.take_active_inline_completion(cx).is_some()
5083 }
5084
5085 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5086 if let Some(completion) = self.active_inline_completion.as_ref() {
5087 let buffer = self.buffer.read(cx).read(cx);
5088 completion.0.position.is_valid(&buffer)
5089 } else {
5090 false
5091 }
5092 }
5093
5094 fn take_active_inline_completion(
5095 &mut self,
5096 cx: &mut ViewContext<Self>,
5097 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5098 let completion = self.active_inline_completion.take()?;
5099 self.display_map.update(cx, |map, cx| {
5100 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5101 });
5102 let buffer = self.buffer.read(cx).read(cx);
5103
5104 if completion.0.position.is_valid(&buffer) {
5105 Some(completion)
5106 } else {
5107 None
5108 }
5109 }
5110
5111 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5112 let selection = self.selections.newest_anchor();
5113 let cursor = selection.head();
5114
5115 let excerpt_id = cursor.excerpt_id;
5116
5117 if self.context_menu.read().is_none()
5118 && self.completion_tasks.is_empty()
5119 && selection.start == selection.end
5120 {
5121 if let Some(provider) = self.inline_completion_provider() {
5122 if let Some((buffer, cursor_buffer_position)) =
5123 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5124 {
5125 if let Some((text, text_anchor_range)) =
5126 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5127 {
5128 let text = Rope::from(text);
5129 let mut to_remove = Vec::new();
5130 if let Some(completion) = self.active_inline_completion.take() {
5131 to_remove.push(completion.0.id);
5132 }
5133
5134 let completion_inlay =
5135 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5136
5137 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5138 let snapshot = self.buffer.read(cx).snapshot(cx);
5139 Some(
5140 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5141 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5142 )
5143 });
5144 self.active_inline_completion =
5145 Some((completion_inlay.clone(), multibuffer_anchor_range));
5146
5147 self.display_map.update(cx, move |map, cx| {
5148 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5149 });
5150 cx.notify();
5151 return;
5152 }
5153 }
5154 }
5155 }
5156
5157 self.discard_inline_completion(false, cx);
5158 }
5159
5160 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5161 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5162 }
5163
5164 fn render_code_actions_indicator(
5165 &self,
5166 _style: &EditorStyle,
5167 row: DisplayRow,
5168 is_active: bool,
5169 cx: &mut ViewContext<Self>,
5170 ) -> Option<IconButton> {
5171 if self.available_code_actions.is_some() {
5172 Some(
5173 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5174 .shape(ui::IconButtonShape::Square)
5175 .icon_size(IconSize::XSmall)
5176 .icon_color(Color::Muted)
5177 .selected(is_active)
5178 .on_click(cx.listener(move |editor, _e, cx| {
5179 editor.focus(cx);
5180 editor.toggle_code_actions(
5181 &ToggleCodeActions {
5182 deployed_from_indicator: Some(row),
5183 },
5184 cx,
5185 );
5186 })),
5187 )
5188 } else {
5189 None
5190 }
5191 }
5192
5193 fn clear_tasks(&mut self) {
5194 self.tasks.clear()
5195 }
5196
5197 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5198 if let Some(_) = self.tasks.insert(key, value) {
5199 // This case should hopefully be rare, but just in case...
5200 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5201 }
5202 }
5203
5204 fn render_run_indicator(
5205 &self,
5206 _style: &EditorStyle,
5207 is_active: bool,
5208 row: DisplayRow,
5209 cx: &mut ViewContext<Self>,
5210 ) -> IconButton {
5211 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5212 .shape(ui::IconButtonShape::Square)
5213 .icon_size(IconSize::XSmall)
5214 .icon_color(Color::Muted)
5215 .selected(is_active)
5216 .on_click(cx.listener(move |editor, _e, cx| {
5217 editor.focus(cx);
5218 editor.toggle_code_actions(
5219 &ToggleCodeActions {
5220 deployed_from_indicator: Some(row),
5221 },
5222 cx,
5223 );
5224 }))
5225 }
5226
5227 fn close_hunk_diff_button(
5228 &self,
5229 hunk: HoveredHunk,
5230 row: DisplayRow,
5231 cx: &mut ViewContext<Self>,
5232 ) -> IconButton {
5233 IconButton::new(
5234 ("close_hunk_diff_indicator", row.0 as usize),
5235 ui::IconName::Close,
5236 )
5237 .shape(ui::IconButtonShape::Square)
5238 .icon_size(IconSize::XSmall)
5239 .icon_color(Color::Muted)
5240 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5241 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5242 }
5243
5244 pub fn context_menu_visible(&self) -> bool {
5245 self.context_menu
5246 .read()
5247 .as_ref()
5248 .map_or(false, |menu| menu.visible())
5249 }
5250
5251 fn render_context_menu(
5252 &self,
5253 cursor_position: DisplayPoint,
5254 style: &EditorStyle,
5255 max_height: Pixels,
5256 cx: &mut ViewContext<Editor>,
5257 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5258 self.context_menu.read().as_ref().map(|menu| {
5259 menu.render(
5260 cursor_position,
5261 style,
5262 max_height,
5263 self.workspace.as_ref().map(|(w, _)| w.clone()),
5264 cx,
5265 )
5266 })
5267 }
5268
5269 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5270 cx.notify();
5271 self.completion_tasks.clear();
5272 let context_menu = self.context_menu.write().take();
5273 if context_menu.is_some() {
5274 self.update_visible_inline_completion(cx);
5275 }
5276 context_menu
5277 }
5278
5279 pub fn insert_snippet(
5280 &mut self,
5281 insertion_ranges: &[Range<usize>],
5282 snippet: Snippet,
5283 cx: &mut ViewContext<Self>,
5284 ) -> Result<()> {
5285 struct Tabstop<T> {
5286 is_end_tabstop: bool,
5287 ranges: Vec<Range<T>>,
5288 }
5289
5290 let tabstops = self.buffer.update(cx, |buffer, cx| {
5291 let snippet_text: Arc<str> = snippet.text.clone().into();
5292 buffer.edit(
5293 insertion_ranges
5294 .iter()
5295 .cloned()
5296 .map(|range| (range, snippet_text.clone())),
5297 Some(AutoindentMode::EachLine),
5298 cx,
5299 );
5300
5301 let snapshot = &*buffer.read(cx);
5302 let snippet = &snippet;
5303 snippet
5304 .tabstops
5305 .iter()
5306 .map(|tabstop| {
5307 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5308 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5309 });
5310 let mut tabstop_ranges = tabstop
5311 .iter()
5312 .flat_map(|tabstop_range| {
5313 let mut delta = 0_isize;
5314 insertion_ranges.iter().map(move |insertion_range| {
5315 let insertion_start = insertion_range.start as isize + delta;
5316 delta +=
5317 snippet.text.len() as isize - insertion_range.len() as isize;
5318
5319 let start = ((insertion_start + tabstop_range.start) as usize)
5320 .min(snapshot.len());
5321 let end = ((insertion_start + tabstop_range.end) as usize)
5322 .min(snapshot.len());
5323 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5324 })
5325 })
5326 .collect::<Vec<_>>();
5327 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5328
5329 Tabstop {
5330 is_end_tabstop,
5331 ranges: tabstop_ranges,
5332 }
5333 })
5334 .collect::<Vec<_>>()
5335 });
5336 if let Some(tabstop) = tabstops.first() {
5337 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5338 s.select_ranges(tabstop.ranges.iter().cloned());
5339 });
5340
5341 // If we're already at the last tabstop and it's at the end of the snippet,
5342 // we're done, we don't need to keep the state around.
5343 if !tabstop.is_end_tabstop {
5344 let ranges = tabstops
5345 .into_iter()
5346 .map(|tabstop| tabstop.ranges)
5347 .collect::<Vec<_>>();
5348 self.snippet_stack.push(SnippetState {
5349 active_index: 0,
5350 ranges,
5351 });
5352 }
5353
5354 // Check whether the just-entered snippet ends with an auto-closable bracket.
5355 if self.autoclose_regions.is_empty() {
5356 let snapshot = self.buffer.read(cx).snapshot(cx);
5357 for selection in &mut self.selections.all::<Point>(cx) {
5358 let selection_head = selection.head();
5359 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5360 continue;
5361 };
5362
5363 let mut bracket_pair = None;
5364 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5365 let prev_chars = snapshot
5366 .reversed_chars_at(selection_head)
5367 .collect::<String>();
5368 for (pair, enabled) in scope.brackets() {
5369 if enabled
5370 && pair.close
5371 && prev_chars.starts_with(pair.start.as_str())
5372 && next_chars.starts_with(pair.end.as_str())
5373 {
5374 bracket_pair = Some(pair.clone());
5375 break;
5376 }
5377 }
5378 if let Some(pair) = bracket_pair {
5379 let start = snapshot.anchor_after(selection_head);
5380 let end = snapshot.anchor_after(selection_head);
5381 self.autoclose_regions.push(AutocloseRegion {
5382 selection_id: selection.id,
5383 range: start..end,
5384 pair,
5385 });
5386 }
5387 }
5388 }
5389 }
5390 Ok(())
5391 }
5392
5393 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5394 self.move_to_snippet_tabstop(Bias::Right, cx)
5395 }
5396
5397 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5398 self.move_to_snippet_tabstop(Bias::Left, cx)
5399 }
5400
5401 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5402 if let Some(mut snippet) = self.snippet_stack.pop() {
5403 match bias {
5404 Bias::Left => {
5405 if snippet.active_index > 0 {
5406 snippet.active_index -= 1;
5407 } else {
5408 self.snippet_stack.push(snippet);
5409 return false;
5410 }
5411 }
5412 Bias::Right => {
5413 if snippet.active_index + 1 < snippet.ranges.len() {
5414 snippet.active_index += 1;
5415 } else {
5416 self.snippet_stack.push(snippet);
5417 return false;
5418 }
5419 }
5420 }
5421 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5422 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5423 s.select_anchor_ranges(current_ranges.iter().cloned())
5424 });
5425 // If snippet state is not at the last tabstop, push it back on the stack
5426 if snippet.active_index + 1 < snippet.ranges.len() {
5427 self.snippet_stack.push(snippet);
5428 }
5429 return true;
5430 }
5431 }
5432
5433 false
5434 }
5435
5436 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5437 self.transact(cx, |this, cx| {
5438 this.select_all(&SelectAll, cx);
5439 this.insert("", cx);
5440 });
5441 }
5442
5443 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5444 self.transact(cx, |this, cx| {
5445 this.select_autoclose_pair(cx);
5446 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5447 if !this.linked_edit_ranges.is_empty() {
5448 let selections = this.selections.all::<MultiBufferPoint>(cx);
5449 let snapshot = this.buffer.read(cx).snapshot(cx);
5450
5451 for selection in selections.iter() {
5452 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5453 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5454 if selection_start.buffer_id != selection_end.buffer_id {
5455 continue;
5456 }
5457 if let Some(ranges) =
5458 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5459 {
5460 for (buffer, entries) in ranges {
5461 linked_ranges.entry(buffer).or_default().extend(entries);
5462 }
5463 }
5464 }
5465 }
5466
5467 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5468 if !this.selections.line_mode {
5469 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5470 for selection in &mut selections {
5471 if selection.is_empty() {
5472 let old_head = selection.head();
5473 let mut new_head =
5474 movement::left(&display_map, old_head.to_display_point(&display_map))
5475 .to_point(&display_map);
5476 if let Some((buffer, line_buffer_range)) = display_map
5477 .buffer_snapshot
5478 .buffer_line_for_row(MultiBufferRow(old_head.row))
5479 {
5480 let indent_size =
5481 buffer.indent_size_for_line(line_buffer_range.start.row);
5482 let indent_len = match indent_size.kind {
5483 IndentKind::Space => {
5484 buffer.settings_at(line_buffer_range.start, cx).tab_size
5485 }
5486 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5487 };
5488 if old_head.column <= indent_size.len && old_head.column > 0 {
5489 let indent_len = indent_len.get();
5490 new_head = cmp::min(
5491 new_head,
5492 MultiBufferPoint::new(
5493 old_head.row,
5494 ((old_head.column - 1) / indent_len) * indent_len,
5495 ),
5496 );
5497 }
5498 }
5499
5500 selection.set_head(new_head, SelectionGoal::None);
5501 }
5502 }
5503 }
5504
5505 this.signature_help_state.set_backspace_pressed(true);
5506 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5507 this.insert("", cx);
5508 let empty_str: Arc<str> = Arc::from("");
5509 for (buffer, edits) in linked_ranges {
5510 let snapshot = buffer.read(cx).snapshot();
5511 use text::ToPoint as TP;
5512
5513 let edits = edits
5514 .into_iter()
5515 .map(|range| {
5516 let end_point = TP::to_point(&range.end, &snapshot);
5517 let mut start_point = TP::to_point(&range.start, &snapshot);
5518
5519 if end_point == start_point {
5520 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5521 .saturating_sub(1);
5522 start_point = TP::to_point(&offset, &snapshot);
5523 };
5524
5525 (start_point..end_point, empty_str.clone())
5526 })
5527 .sorted_by_key(|(range, _)| range.start)
5528 .collect::<Vec<_>>();
5529 buffer.update(cx, |this, cx| {
5530 this.edit(edits, None, cx);
5531 })
5532 }
5533 this.refresh_inline_completion(true, false, cx);
5534 linked_editing_ranges::refresh_linked_ranges(this, cx);
5535 });
5536 }
5537
5538 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5539 self.transact(cx, |this, cx| {
5540 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5541 let line_mode = s.line_mode;
5542 s.move_with(|map, selection| {
5543 if selection.is_empty() && !line_mode {
5544 let cursor = movement::right(map, selection.head());
5545 selection.end = cursor;
5546 selection.reversed = true;
5547 selection.goal = SelectionGoal::None;
5548 }
5549 })
5550 });
5551 this.insert("", cx);
5552 this.refresh_inline_completion(true, false, cx);
5553 });
5554 }
5555
5556 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5557 if self.move_to_prev_snippet_tabstop(cx) {
5558 return;
5559 }
5560
5561 self.outdent(&Outdent, cx);
5562 }
5563
5564 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5565 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5566 return;
5567 }
5568
5569 let mut selections = self.selections.all_adjusted(cx);
5570 let buffer = self.buffer.read(cx);
5571 let snapshot = buffer.snapshot(cx);
5572 let rows_iter = selections.iter().map(|s| s.head().row);
5573 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5574
5575 let mut edits = Vec::new();
5576 let mut prev_edited_row = 0;
5577 let mut row_delta = 0;
5578 for selection in &mut selections {
5579 if selection.start.row != prev_edited_row {
5580 row_delta = 0;
5581 }
5582 prev_edited_row = selection.end.row;
5583
5584 // If the selection is non-empty, then increase the indentation of the selected lines.
5585 if !selection.is_empty() {
5586 row_delta =
5587 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5588 continue;
5589 }
5590
5591 // If the selection is empty and the cursor is in the leading whitespace before the
5592 // suggested indentation, then auto-indent the line.
5593 let cursor = selection.head();
5594 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5595 if let Some(suggested_indent) =
5596 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5597 {
5598 if cursor.column < suggested_indent.len
5599 && cursor.column <= current_indent.len
5600 && current_indent.len <= suggested_indent.len
5601 {
5602 selection.start = Point::new(cursor.row, suggested_indent.len);
5603 selection.end = selection.start;
5604 if row_delta == 0 {
5605 edits.extend(Buffer::edit_for_indent_size_adjustment(
5606 cursor.row,
5607 current_indent,
5608 suggested_indent,
5609 ));
5610 row_delta = suggested_indent.len - current_indent.len;
5611 }
5612 continue;
5613 }
5614 }
5615
5616 // Otherwise, insert a hard or soft tab.
5617 let settings = buffer.settings_at(cursor, cx);
5618 let tab_size = if settings.hard_tabs {
5619 IndentSize::tab()
5620 } else {
5621 let tab_size = settings.tab_size.get();
5622 let char_column = snapshot
5623 .text_for_range(Point::new(cursor.row, 0)..cursor)
5624 .flat_map(str::chars)
5625 .count()
5626 + row_delta as usize;
5627 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5628 IndentSize::spaces(chars_to_next_tab_stop)
5629 };
5630 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5631 selection.end = selection.start;
5632 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5633 row_delta += tab_size.len;
5634 }
5635
5636 self.transact(cx, |this, cx| {
5637 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5638 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5639 this.refresh_inline_completion(true, false, cx);
5640 });
5641 }
5642
5643 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5644 if self.read_only(cx) {
5645 return;
5646 }
5647 let mut selections = self.selections.all::<Point>(cx);
5648 let mut prev_edited_row = 0;
5649 let mut row_delta = 0;
5650 let mut edits = Vec::new();
5651 let buffer = self.buffer.read(cx);
5652 let snapshot = buffer.snapshot(cx);
5653 for selection in &mut selections {
5654 if selection.start.row != prev_edited_row {
5655 row_delta = 0;
5656 }
5657 prev_edited_row = selection.end.row;
5658
5659 row_delta =
5660 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5661 }
5662
5663 self.transact(cx, |this, cx| {
5664 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5665 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5666 });
5667 }
5668
5669 fn indent_selection(
5670 buffer: &MultiBuffer,
5671 snapshot: &MultiBufferSnapshot,
5672 selection: &mut Selection<Point>,
5673 edits: &mut Vec<(Range<Point>, String)>,
5674 delta_for_start_row: u32,
5675 cx: &AppContext,
5676 ) -> u32 {
5677 let settings = buffer.settings_at(selection.start, cx);
5678 let tab_size = settings.tab_size.get();
5679 let indent_kind = if settings.hard_tabs {
5680 IndentKind::Tab
5681 } else {
5682 IndentKind::Space
5683 };
5684 let mut start_row = selection.start.row;
5685 let mut end_row = selection.end.row + 1;
5686
5687 // If a selection ends at the beginning of a line, don't indent
5688 // that last line.
5689 if selection.end.column == 0 && selection.end.row > selection.start.row {
5690 end_row -= 1;
5691 }
5692
5693 // Avoid re-indenting a row that has already been indented by a
5694 // previous selection, but still update this selection's column
5695 // to reflect that indentation.
5696 if delta_for_start_row > 0 {
5697 start_row += 1;
5698 selection.start.column += delta_for_start_row;
5699 if selection.end.row == selection.start.row {
5700 selection.end.column += delta_for_start_row;
5701 }
5702 }
5703
5704 let mut delta_for_end_row = 0;
5705 let has_multiple_rows = start_row + 1 != end_row;
5706 for row in start_row..end_row {
5707 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5708 let indent_delta = match (current_indent.kind, indent_kind) {
5709 (IndentKind::Space, IndentKind::Space) => {
5710 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5711 IndentSize::spaces(columns_to_next_tab_stop)
5712 }
5713 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5714 (_, IndentKind::Tab) => IndentSize::tab(),
5715 };
5716
5717 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5718 0
5719 } else {
5720 selection.start.column
5721 };
5722 let row_start = Point::new(row, start);
5723 edits.push((
5724 row_start..row_start,
5725 indent_delta.chars().collect::<String>(),
5726 ));
5727
5728 // Update this selection's endpoints to reflect the indentation.
5729 if row == selection.start.row {
5730 selection.start.column += indent_delta.len;
5731 }
5732 if row == selection.end.row {
5733 selection.end.column += indent_delta.len;
5734 delta_for_end_row = indent_delta.len;
5735 }
5736 }
5737
5738 if selection.start.row == selection.end.row {
5739 delta_for_start_row + delta_for_end_row
5740 } else {
5741 delta_for_end_row
5742 }
5743 }
5744
5745 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5746 if self.read_only(cx) {
5747 return;
5748 }
5749 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5750 let selections = self.selections.all::<Point>(cx);
5751 let mut deletion_ranges = Vec::new();
5752 let mut last_outdent = None;
5753 {
5754 let buffer = self.buffer.read(cx);
5755 let snapshot = buffer.snapshot(cx);
5756 for selection in &selections {
5757 let settings = buffer.settings_at(selection.start, cx);
5758 let tab_size = settings.tab_size.get();
5759 let mut rows = selection.spanned_rows(false, &display_map);
5760
5761 // Avoid re-outdenting a row that has already been outdented by a
5762 // previous selection.
5763 if let Some(last_row) = last_outdent {
5764 if last_row == rows.start {
5765 rows.start = rows.start.next_row();
5766 }
5767 }
5768 let has_multiple_rows = rows.len() > 1;
5769 for row in rows.iter_rows() {
5770 let indent_size = snapshot.indent_size_for_line(row);
5771 if indent_size.len > 0 {
5772 let deletion_len = match indent_size.kind {
5773 IndentKind::Space => {
5774 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5775 if columns_to_prev_tab_stop == 0 {
5776 tab_size
5777 } else {
5778 columns_to_prev_tab_stop
5779 }
5780 }
5781 IndentKind::Tab => 1,
5782 };
5783 let start = if has_multiple_rows
5784 || deletion_len > selection.start.column
5785 || indent_size.len < selection.start.column
5786 {
5787 0
5788 } else {
5789 selection.start.column - deletion_len
5790 };
5791 deletion_ranges.push(
5792 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5793 );
5794 last_outdent = Some(row);
5795 }
5796 }
5797 }
5798 }
5799
5800 self.transact(cx, |this, cx| {
5801 this.buffer.update(cx, |buffer, cx| {
5802 let empty_str: Arc<str> = Arc::default();
5803 buffer.edit(
5804 deletion_ranges
5805 .into_iter()
5806 .map(|range| (range, empty_str.clone())),
5807 None,
5808 cx,
5809 );
5810 });
5811 let selections = this.selections.all::<usize>(cx);
5812 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5813 });
5814 }
5815
5816 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5817 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5818 let selections = self.selections.all::<Point>(cx);
5819
5820 let mut new_cursors = Vec::new();
5821 let mut edit_ranges = Vec::new();
5822 let mut selections = selections.iter().peekable();
5823 while let Some(selection) = selections.next() {
5824 let mut rows = selection.spanned_rows(false, &display_map);
5825 let goal_display_column = selection.head().to_display_point(&display_map).column();
5826
5827 // Accumulate contiguous regions of rows that we want to delete.
5828 while let Some(next_selection) = selections.peek() {
5829 let next_rows = next_selection.spanned_rows(false, &display_map);
5830 if next_rows.start <= rows.end {
5831 rows.end = next_rows.end;
5832 selections.next().unwrap();
5833 } else {
5834 break;
5835 }
5836 }
5837
5838 let buffer = &display_map.buffer_snapshot;
5839 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5840 let edit_end;
5841 let cursor_buffer_row;
5842 if buffer.max_point().row >= rows.end.0 {
5843 // If there's a line after the range, delete the \n from the end of the row range
5844 // and position the cursor on the next line.
5845 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5846 cursor_buffer_row = rows.end;
5847 } else {
5848 // If there isn't a line after the range, delete the \n from the line before the
5849 // start of the row range and position the cursor there.
5850 edit_start = edit_start.saturating_sub(1);
5851 edit_end = buffer.len();
5852 cursor_buffer_row = rows.start.previous_row();
5853 }
5854
5855 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5856 *cursor.column_mut() =
5857 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5858
5859 new_cursors.push((
5860 selection.id,
5861 buffer.anchor_after(cursor.to_point(&display_map)),
5862 ));
5863 edit_ranges.push(edit_start..edit_end);
5864 }
5865
5866 self.transact(cx, |this, cx| {
5867 let buffer = this.buffer.update(cx, |buffer, cx| {
5868 let empty_str: Arc<str> = Arc::default();
5869 buffer.edit(
5870 edit_ranges
5871 .into_iter()
5872 .map(|range| (range, empty_str.clone())),
5873 None,
5874 cx,
5875 );
5876 buffer.snapshot(cx)
5877 });
5878 let new_selections = new_cursors
5879 .into_iter()
5880 .map(|(id, cursor)| {
5881 let cursor = cursor.to_point(&buffer);
5882 Selection {
5883 id,
5884 start: cursor,
5885 end: cursor,
5886 reversed: false,
5887 goal: SelectionGoal::None,
5888 }
5889 })
5890 .collect();
5891
5892 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5893 s.select(new_selections);
5894 });
5895 });
5896 }
5897
5898 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5899 if self.read_only(cx) {
5900 return;
5901 }
5902 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5903 for selection in self.selections.all::<Point>(cx) {
5904 let start = MultiBufferRow(selection.start.row);
5905 let end = if selection.start.row == selection.end.row {
5906 MultiBufferRow(selection.start.row + 1)
5907 } else {
5908 MultiBufferRow(selection.end.row)
5909 };
5910
5911 if let Some(last_row_range) = row_ranges.last_mut() {
5912 if start <= last_row_range.end {
5913 last_row_range.end = end;
5914 continue;
5915 }
5916 }
5917 row_ranges.push(start..end);
5918 }
5919
5920 let snapshot = self.buffer.read(cx).snapshot(cx);
5921 let mut cursor_positions = Vec::new();
5922 for row_range in &row_ranges {
5923 let anchor = snapshot.anchor_before(Point::new(
5924 row_range.end.previous_row().0,
5925 snapshot.line_len(row_range.end.previous_row()),
5926 ));
5927 cursor_positions.push(anchor..anchor);
5928 }
5929
5930 self.transact(cx, |this, cx| {
5931 for row_range in row_ranges.into_iter().rev() {
5932 for row in row_range.iter_rows().rev() {
5933 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5934 let next_line_row = row.next_row();
5935 let indent = snapshot.indent_size_for_line(next_line_row);
5936 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5937
5938 let replace = if snapshot.line_len(next_line_row) > indent.len {
5939 " "
5940 } else {
5941 ""
5942 };
5943
5944 this.buffer.update(cx, |buffer, cx| {
5945 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5946 });
5947 }
5948 }
5949
5950 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5951 s.select_anchor_ranges(cursor_positions)
5952 });
5953 });
5954 }
5955
5956 pub fn sort_lines_case_sensitive(
5957 &mut self,
5958 _: &SortLinesCaseSensitive,
5959 cx: &mut ViewContext<Self>,
5960 ) {
5961 self.manipulate_lines(cx, |lines| lines.sort())
5962 }
5963
5964 pub fn sort_lines_case_insensitive(
5965 &mut self,
5966 _: &SortLinesCaseInsensitive,
5967 cx: &mut ViewContext<Self>,
5968 ) {
5969 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5970 }
5971
5972 pub fn unique_lines_case_insensitive(
5973 &mut self,
5974 _: &UniqueLinesCaseInsensitive,
5975 cx: &mut ViewContext<Self>,
5976 ) {
5977 self.manipulate_lines(cx, |lines| {
5978 let mut seen = HashSet::default();
5979 lines.retain(|line| seen.insert(line.to_lowercase()));
5980 })
5981 }
5982
5983 pub fn unique_lines_case_sensitive(
5984 &mut self,
5985 _: &UniqueLinesCaseSensitive,
5986 cx: &mut ViewContext<Self>,
5987 ) {
5988 self.manipulate_lines(cx, |lines| {
5989 let mut seen = HashSet::default();
5990 lines.retain(|line| seen.insert(*line));
5991 })
5992 }
5993
5994 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5995 let mut revert_changes = HashMap::default();
5996 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5997 for hunk in hunks_for_rows(
5998 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
5999 &multi_buffer_snapshot,
6000 ) {
6001 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
6002 }
6003 if !revert_changes.is_empty() {
6004 self.transact(cx, |editor, cx| {
6005 editor.revert(revert_changes, cx);
6006 });
6007 }
6008 }
6009
6010 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6011 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6012 if !revert_changes.is_empty() {
6013 self.transact(cx, |editor, cx| {
6014 editor.revert(revert_changes, cx);
6015 });
6016 }
6017 }
6018
6019 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6020 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6021 let project_path = buffer.read(cx).project_path(cx)?;
6022 let project = self.project.as_ref()?.read(cx);
6023 let entry = project.entry_for_path(&project_path, cx)?;
6024 let abs_path = project.absolute_path(&project_path, cx)?;
6025 let parent = if entry.is_symlink {
6026 abs_path.canonicalize().ok()?
6027 } else {
6028 abs_path
6029 }
6030 .parent()?
6031 .to_path_buf();
6032 Some(parent)
6033 }) {
6034 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6035 }
6036 }
6037
6038 fn gather_revert_changes(
6039 &mut self,
6040 selections: &[Selection<Anchor>],
6041 cx: &mut ViewContext<'_, Editor>,
6042 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6043 let mut revert_changes = HashMap::default();
6044 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6045 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6046 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6047 }
6048 revert_changes
6049 }
6050
6051 pub fn prepare_revert_change(
6052 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6053 multi_buffer: &Model<MultiBuffer>,
6054 hunk: &DiffHunk<MultiBufferRow>,
6055 cx: &AppContext,
6056 ) -> Option<()> {
6057 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6058 let buffer = buffer.read(cx);
6059 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6060 let buffer_snapshot = buffer.snapshot();
6061 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6062 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6063 probe
6064 .0
6065 .start
6066 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6067 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6068 }) {
6069 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6070 Some(())
6071 } else {
6072 None
6073 }
6074 }
6075
6076 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6077 self.manipulate_lines(cx, |lines| lines.reverse())
6078 }
6079
6080 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6081 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6082 }
6083
6084 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6085 where
6086 Fn: FnMut(&mut Vec<&str>),
6087 {
6088 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6089 let buffer = self.buffer.read(cx).snapshot(cx);
6090
6091 let mut edits = Vec::new();
6092
6093 let selections = self.selections.all::<Point>(cx);
6094 let mut selections = selections.iter().peekable();
6095 let mut contiguous_row_selections = Vec::new();
6096 let mut new_selections = Vec::new();
6097 let mut added_lines = 0;
6098 let mut removed_lines = 0;
6099
6100 while let Some(selection) = selections.next() {
6101 let (start_row, end_row) = consume_contiguous_rows(
6102 &mut contiguous_row_selections,
6103 selection,
6104 &display_map,
6105 &mut selections,
6106 );
6107
6108 let start_point = Point::new(start_row.0, 0);
6109 let end_point = Point::new(
6110 end_row.previous_row().0,
6111 buffer.line_len(end_row.previous_row()),
6112 );
6113 let text = buffer
6114 .text_for_range(start_point..end_point)
6115 .collect::<String>();
6116
6117 let mut lines = text.split('\n').collect_vec();
6118
6119 let lines_before = lines.len();
6120 callback(&mut lines);
6121 let lines_after = lines.len();
6122
6123 edits.push((start_point..end_point, lines.join("\n")));
6124
6125 // Selections must change based on added and removed line count
6126 let start_row =
6127 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6128 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6129 new_selections.push(Selection {
6130 id: selection.id,
6131 start: start_row,
6132 end: end_row,
6133 goal: SelectionGoal::None,
6134 reversed: selection.reversed,
6135 });
6136
6137 if lines_after > lines_before {
6138 added_lines += lines_after - lines_before;
6139 } else if lines_before > lines_after {
6140 removed_lines += lines_before - lines_after;
6141 }
6142 }
6143
6144 self.transact(cx, |this, cx| {
6145 let buffer = this.buffer.update(cx, |buffer, cx| {
6146 buffer.edit(edits, None, cx);
6147 buffer.snapshot(cx)
6148 });
6149
6150 // Recalculate offsets on newly edited buffer
6151 let new_selections = new_selections
6152 .iter()
6153 .map(|s| {
6154 let start_point = Point::new(s.start.0, 0);
6155 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6156 Selection {
6157 id: s.id,
6158 start: buffer.point_to_offset(start_point),
6159 end: buffer.point_to_offset(end_point),
6160 goal: s.goal,
6161 reversed: s.reversed,
6162 }
6163 })
6164 .collect();
6165
6166 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6167 s.select(new_selections);
6168 });
6169
6170 this.request_autoscroll(Autoscroll::fit(), cx);
6171 });
6172 }
6173
6174 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6175 self.manipulate_text(cx, |text| text.to_uppercase())
6176 }
6177
6178 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6179 self.manipulate_text(cx, |text| text.to_lowercase())
6180 }
6181
6182 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6183 self.manipulate_text(cx, |text| {
6184 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6185 // https://github.com/rutrum/convert-case/issues/16
6186 text.split('\n')
6187 .map(|line| line.to_case(Case::Title))
6188 .join("\n")
6189 })
6190 }
6191
6192 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6193 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6194 }
6195
6196 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6197 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6198 }
6199
6200 pub fn convert_to_upper_camel_case(
6201 &mut self,
6202 _: &ConvertToUpperCamelCase,
6203 cx: &mut ViewContext<Self>,
6204 ) {
6205 self.manipulate_text(cx, |text| {
6206 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6207 // https://github.com/rutrum/convert-case/issues/16
6208 text.split('\n')
6209 .map(|line| line.to_case(Case::UpperCamel))
6210 .join("\n")
6211 })
6212 }
6213
6214 pub fn convert_to_lower_camel_case(
6215 &mut self,
6216 _: &ConvertToLowerCamelCase,
6217 cx: &mut ViewContext<Self>,
6218 ) {
6219 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6220 }
6221
6222 pub fn convert_to_opposite_case(
6223 &mut self,
6224 _: &ConvertToOppositeCase,
6225 cx: &mut ViewContext<Self>,
6226 ) {
6227 self.manipulate_text(cx, |text| {
6228 text.chars()
6229 .fold(String::with_capacity(text.len()), |mut t, c| {
6230 if c.is_uppercase() {
6231 t.extend(c.to_lowercase());
6232 } else {
6233 t.extend(c.to_uppercase());
6234 }
6235 t
6236 })
6237 })
6238 }
6239
6240 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6241 where
6242 Fn: FnMut(&str) -> String,
6243 {
6244 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6245 let buffer = self.buffer.read(cx).snapshot(cx);
6246
6247 let mut new_selections = Vec::new();
6248 let mut edits = Vec::new();
6249 let mut selection_adjustment = 0i32;
6250
6251 for selection in self.selections.all::<usize>(cx) {
6252 let selection_is_empty = selection.is_empty();
6253
6254 let (start, end) = if selection_is_empty {
6255 let word_range = movement::surrounding_word(
6256 &display_map,
6257 selection.start.to_display_point(&display_map),
6258 );
6259 let start = word_range.start.to_offset(&display_map, Bias::Left);
6260 let end = word_range.end.to_offset(&display_map, Bias::Left);
6261 (start, end)
6262 } else {
6263 (selection.start, selection.end)
6264 };
6265
6266 let text = buffer.text_for_range(start..end).collect::<String>();
6267 let old_length = text.len() as i32;
6268 let text = callback(&text);
6269
6270 new_selections.push(Selection {
6271 start: (start as i32 - selection_adjustment) as usize,
6272 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6273 goal: SelectionGoal::None,
6274 ..selection
6275 });
6276
6277 selection_adjustment += old_length - text.len() as i32;
6278
6279 edits.push((start..end, text));
6280 }
6281
6282 self.transact(cx, |this, cx| {
6283 this.buffer.update(cx, |buffer, cx| {
6284 buffer.edit(edits, None, cx);
6285 });
6286
6287 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6288 s.select(new_selections);
6289 });
6290
6291 this.request_autoscroll(Autoscroll::fit(), cx);
6292 });
6293 }
6294
6295 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6296 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6297 let buffer = &display_map.buffer_snapshot;
6298 let selections = self.selections.all::<Point>(cx);
6299
6300 let mut edits = Vec::new();
6301 let mut selections_iter = selections.iter().peekable();
6302 while let Some(selection) = selections_iter.next() {
6303 // Avoid duplicating the same lines twice.
6304 let mut rows = selection.spanned_rows(false, &display_map);
6305
6306 while let Some(next_selection) = selections_iter.peek() {
6307 let next_rows = next_selection.spanned_rows(false, &display_map);
6308 if next_rows.start < rows.end {
6309 rows.end = next_rows.end;
6310 selections_iter.next().unwrap();
6311 } else {
6312 break;
6313 }
6314 }
6315
6316 // Copy the text from the selected row region and splice it either at the start
6317 // or end of the region.
6318 let start = Point::new(rows.start.0, 0);
6319 let end = Point::new(
6320 rows.end.previous_row().0,
6321 buffer.line_len(rows.end.previous_row()),
6322 );
6323 let text = buffer
6324 .text_for_range(start..end)
6325 .chain(Some("\n"))
6326 .collect::<String>();
6327 let insert_location = if upwards {
6328 Point::new(rows.end.0, 0)
6329 } else {
6330 start
6331 };
6332 edits.push((insert_location..insert_location, text));
6333 }
6334
6335 self.transact(cx, |this, cx| {
6336 this.buffer.update(cx, |buffer, cx| {
6337 buffer.edit(edits, None, cx);
6338 });
6339
6340 this.request_autoscroll(Autoscroll::fit(), cx);
6341 });
6342 }
6343
6344 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6345 self.duplicate_line(true, cx);
6346 }
6347
6348 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6349 self.duplicate_line(false, cx);
6350 }
6351
6352 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6353 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6354 let buffer = self.buffer.read(cx).snapshot(cx);
6355
6356 let mut edits = Vec::new();
6357 let mut unfold_ranges = Vec::new();
6358 let mut refold_ranges = Vec::new();
6359
6360 let selections = self.selections.all::<Point>(cx);
6361 let mut selections = selections.iter().peekable();
6362 let mut contiguous_row_selections = Vec::new();
6363 let mut new_selections = Vec::new();
6364
6365 while let Some(selection) = selections.next() {
6366 // Find all the selections that span a contiguous row range
6367 let (start_row, end_row) = consume_contiguous_rows(
6368 &mut contiguous_row_selections,
6369 selection,
6370 &display_map,
6371 &mut selections,
6372 );
6373
6374 // Move the text spanned by the row range to be before the line preceding the row range
6375 if start_row.0 > 0 {
6376 let range_to_move = Point::new(
6377 start_row.previous_row().0,
6378 buffer.line_len(start_row.previous_row()),
6379 )
6380 ..Point::new(
6381 end_row.previous_row().0,
6382 buffer.line_len(end_row.previous_row()),
6383 );
6384 let insertion_point = display_map
6385 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6386 .0;
6387
6388 // Don't move lines across excerpts
6389 if buffer
6390 .excerpt_boundaries_in_range((
6391 Bound::Excluded(insertion_point),
6392 Bound::Included(range_to_move.end),
6393 ))
6394 .next()
6395 .is_none()
6396 {
6397 let text = buffer
6398 .text_for_range(range_to_move.clone())
6399 .flat_map(|s| s.chars())
6400 .skip(1)
6401 .chain(['\n'])
6402 .collect::<String>();
6403
6404 edits.push((
6405 buffer.anchor_after(range_to_move.start)
6406 ..buffer.anchor_before(range_to_move.end),
6407 String::new(),
6408 ));
6409 let insertion_anchor = buffer.anchor_after(insertion_point);
6410 edits.push((insertion_anchor..insertion_anchor, text));
6411
6412 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6413
6414 // Move selections up
6415 new_selections.extend(contiguous_row_selections.drain(..).map(
6416 |mut selection| {
6417 selection.start.row -= row_delta;
6418 selection.end.row -= row_delta;
6419 selection
6420 },
6421 ));
6422
6423 // Move folds up
6424 unfold_ranges.push(range_to_move.clone());
6425 for fold in display_map.folds_in_range(
6426 buffer.anchor_before(range_to_move.start)
6427 ..buffer.anchor_after(range_to_move.end),
6428 ) {
6429 let mut start = fold.range.start.to_point(&buffer);
6430 let mut end = fold.range.end.to_point(&buffer);
6431 start.row -= row_delta;
6432 end.row -= row_delta;
6433 refold_ranges.push((start..end, fold.placeholder.clone()));
6434 }
6435 }
6436 }
6437
6438 // If we didn't move line(s), preserve the existing selections
6439 new_selections.append(&mut contiguous_row_selections);
6440 }
6441
6442 self.transact(cx, |this, cx| {
6443 this.unfold_ranges(unfold_ranges, true, true, cx);
6444 this.buffer.update(cx, |buffer, cx| {
6445 for (range, text) in edits {
6446 buffer.edit([(range, text)], None, cx);
6447 }
6448 });
6449 this.fold_ranges(refold_ranges, true, cx);
6450 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6451 s.select(new_selections);
6452 })
6453 });
6454 }
6455
6456 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6457 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6458 let buffer = self.buffer.read(cx).snapshot(cx);
6459
6460 let mut edits = Vec::new();
6461 let mut unfold_ranges = Vec::new();
6462 let mut refold_ranges = Vec::new();
6463
6464 let selections = self.selections.all::<Point>(cx);
6465 let mut selections = selections.iter().peekable();
6466 let mut contiguous_row_selections = Vec::new();
6467 let mut new_selections = Vec::new();
6468
6469 while let Some(selection) = selections.next() {
6470 // Find all the selections that span a contiguous row range
6471 let (start_row, end_row) = consume_contiguous_rows(
6472 &mut contiguous_row_selections,
6473 selection,
6474 &display_map,
6475 &mut selections,
6476 );
6477
6478 // Move the text spanned by the row range to be after the last line of the row range
6479 if end_row.0 <= buffer.max_point().row {
6480 let range_to_move =
6481 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6482 let insertion_point = display_map
6483 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6484 .0;
6485
6486 // Don't move lines across excerpt boundaries
6487 if buffer
6488 .excerpt_boundaries_in_range((
6489 Bound::Excluded(range_to_move.start),
6490 Bound::Included(insertion_point),
6491 ))
6492 .next()
6493 .is_none()
6494 {
6495 let mut text = String::from("\n");
6496 text.extend(buffer.text_for_range(range_to_move.clone()));
6497 text.pop(); // Drop trailing newline
6498 edits.push((
6499 buffer.anchor_after(range_to_move.start)
6500 ..buffer.anchor_before(range_to_move.end),
6501 String::new(),
6502 ));
6503 let insertion_anchor = buffer.anchor_after(insertion_point);
6504 edits.push((insertion_anchor..insertion_anchor, text));
6505
6506 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6507
6508 // Move selections down
6509 new_selections.extend(contiguous_row_selections.drain(..).map(
6510 |mut selection| {
6511 selection.start.row += row_delta;
6512 selection.end.row += row_delta;
6513 selection
6514 },
6515 ));
6516
6517 // Move folds down
6518 unfold_ranges.push(range_to_move.clone());
6519 for fold in display_map.folds_in_range(
6520 buffer.anchor_before(range_to_move.start)
6521 ..buffer.anchor_after(range_to_move.end),
6522 ) {
6523 let mut start = fold.range.start.to_point(&buffer);
6524 let mut end = fold.range.end.to_point(&buffer);
6525 start.row += row_delta;
6526 end.row += row_delta;
6527 refold_ranges.push((start..end, fold.placeholder.clone()));
6528 }
6529 }
6530 }
6531
6532 // If we didn't move line(s), preserve the existing selections
6533 new_selections.append(&mut contiguous_row_selections);
6534 }
6535
6536 self.transact(cx, |this, cx| {
6537 this.unfold_ranges(unfold_ranges, true, true, cx);
6538 this.buffer.update(cx, |buffer, cx| {
6539 for (range, text) in edits {
6540 buffer.edit([(range, text)], None, cx);
6541 }
6542 });
6543 this.fold_ranges(refold_ranges, true, cx);
6544 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6545 });
6546 }
6547
6548 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6549 let text_layout_details = &self.text_layout_details(cx);
6550 self.transact(cx, |this, cx| {
6551 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6552 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6553 let line_mode = s.line_mode;
6554 s.move_with(|display_map, selection| {
6555 if !selection.is_empty() || line_mode {
6556 return;
6557 }
6558
6559 let mut head = selection.head();
6560 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6561 if head.column() == display_map.line_len(head.row()) {
6562 transpose_offset = display_map
6563 .buffer_snapshot
6564 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6565 }
6566
6567 if transpose_offset == 0 {
6568 return;
6569 }
6570
6571 *head.column_mut() += 1;
6572 head = display_map.clip_point(head, Bias::Right);
6573 let goal = SelectionGoal::HorizontalPosition(
6574 display_map
6575 .x_for_display_point(head, &text_layout_details)
6576 .into(),
6577 );
6578 selection.collapse_to(head, goal);
6579
6580 let transpose_start = display_map
6581 .buffer_snapshot
6582 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6583 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6584 let transpose_end = display_map
6585 .buffer_snapshot
6586 .clip_offset(transpose_offset + 1, Bias::Right);
6587 if let Some(ch) =
6588 display_map.buffer_snapshot.chars_at(transpose_start).next()
6589 {
6590 edits.push((transpose_start..transpose_offset, String::new()));
6591 edits.push((transpose_end..transpose_end, ch.to_string()));
6592 }
6593 }
6594 });
6595 edits
6596 });
6597 this.buffer
6598 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6599 let selections = this.selections.all::<usize>(cx);
6600 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6601 s.select(selections);
6602 });
6603 });
6604 }
6605
6606 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6607 let mut text = String::new();
6608 let buffer = self.buffer.read(cx).snapshot(cx);
6609 let mut selections = self.selections.all::<Point>(cx);
6610 let mut clipboard_selections = Vec::with_capacity(selections.len());
6611 {
6612 let max_point = buffer.max_point();
6613 let mut is_first = true;
6614 for selection in &mut selections {
6615 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6616 if is_entire_line {
6617 selection.start = Point::new(selection.start.row, 0);
6618 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6619 selection.goal = SelectionGoal::None;
6620 }
6621 if is_first {
6622 is_first = false;
6623 } else {
6624 text += "\n";
6625 }
6626 let mut len = 0;
6627 for chunk in buffer.text_for_range(selection.start..selection.end) {
6628 text.push_str(chunk);
6629 len += chunk.len();
6630 }
6631 clipboard_selections.push(ClipboardSelection {
6632 len,
6633 is_entire_line,
6634 first_line_indent: buffer
6635 .indent_size_for_line(MultiBufferRow(selection.start.row))
6636 .len,
6637 });
6638 }
6639 }
6640
6641 self.transact(cx, |this, cx| {
6642 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6643 s.select(selections);
6644 });
6645 this.insert("", cx);
6646 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6647 text,
6648 clipboard_selections,
6649 ));
6650 });
6651 }
6652
6653 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6654 let selections = self.selections.all::<Point>(cx);
6655 let buffer = self.buffer.read(cx).read(cx);
6656 let mut text = String::new();
6657
6658 let mut clipboard_selections = Vec::with_capacity(selections.len());
6659 {
6660 let max_point = buffer.max_point();
6661 let mut is_first = true;
6662 for selection in selections.iter() {
6663 let mut start = selection.start;
6664 let mut end = selection.end;
6665 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6666 if is_entire_line {
6667 start = Point::new(start.row, 0);
6668 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6669 }
6670 if is_first {
6671 is_first = false;
6672 } else {
6673 text += "\n";
6674 }
6675 let mut len = 0;
6676 for chunk in buffer.text_for_range(start..end) {
6677 text.push_str(chunk);
6678 len += chunk.len();
6679 }
6680 clipboard_selections.push(ClipboardSelection {
6681 len,
6682 is_entire_line,
6683 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6684 });
6685 }
6686 }
6687
6688 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6689 text,
6690 clipboard_selections,
6691 ));
6692 }
6693
6694 pub fn do_paste(
6695 &mut self,
6696 text: &String,
6697 clipboard_selections: Option<Vec<ClipboardSelection>>,
6698 handle_entire_lines: bool,
6699 cx: &mut ViewContext<Self>,
6700 ) {
6701 if self.read_only(cx) {
6702 return;
6703 }
6704
6705 let clipboard_text = Cow::Borrowed(text);
6706
6707 self.transact(cx, |this, cx| {
6708 if let Some(mut clipboard_selections) = clipboard_selections {
6709 let old_selections = this.selections.all::<usize>(cx);
6710 let all_selections_were_entire_line =
6711 clipboard_selections.iter().all(|s| s.is_entire_line);
6712 let first_selection_indent_column =
6713 clipboard_selections.first().map(|s| s.first_line_indent);
6714 if clipboard_selections.len() != old_selections.len() {
6715 clipboard_selections.drain(..);
6716 }
6717
6718 this.buffer.update(cx, |buffer, cx| {
6719 let snapshot = buffer.read(cx);
6720 let mut start_offset = 0;
6721 let mut edits = Vec::new();
6722 let mut original_indent_columns = Vec::new();
6723 for (ix, selection) in old_selections.iter().enumerate() {
6724 let to_insert;
6725 let entire_line;
6726 let original_indent_column;
6727 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6728 let end_offset = start_offset + clipboard_selection.len;
6729 to_insert = &clipboard_text[start_offset..end_offset];
6730 entire_line = clipboard_selection.is_entire_line;
6731 start_offset = end_offset + 1;
6732 original_indent_column = Some(clipboard_selection.first_line_indent);
6733 } else {
6734 to_insert = clipboard_text.as_str();
6735 entire_line = all_selections_were_entire_line;
6736 original_indent_column = first_selection_indent_column
6737 }
6738
6739 // If the corresponding selection was empty when this slice of the
6740 // clipboard text was written, then the entire line containing the
6741 // selection was copied. If this selection is also currently empty,
6742 // then paste the line before the current line of the buffer.
6743 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6744 let column = selection.start.to_point(&snapshot).column as usize;
6745 let line_start = selection.start - column;
6746 line_start..line_start
6747 } else {
6748 selection.range()
6749 };
6750
6751 edits.push((range, to_insert));
6752 original_indent_columns.extend(original_indent_column);
6753 }
6754 drop(snapshot);
6755
6756 buffer.edit(
6757 edits,
6758 Some(AutoindentMode::Block {
6759 original_indent_columns,
6760 }),
6761 cx,
6762 );
6763 });
6764
6765 let selections = this.selections.all::<usize>(cx);
6766 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6767 } else {
6768 this.insert(&clipboard_text, cx);
6769 }
6770 });
6771 }
6772
6773 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6774 if let Some(item) = cx.read_from_clipboard() {
6775 let entries = item.entries();
6776
6777 match entries.first() {
6778 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6779 // of all the pasted entries.
6780 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6781 .do_paste(
6782 clipboard_string.text(),
6783 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6784 true,
6785 cx,
6786 ),
6787 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6788 }
6789 }
6790 }
6791
6792 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6793 if self.read_only(cx) {
6794 return;
6795 }
6796
6797 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6798 if let Some((selections, _)) =
6799 self.selection_history.transaction(transaction_id).cloned()
6800 {
6801 self.change_selections(None, cx, |s| {
6802 s.select_anchors(selections.to_vec());
6803 });
6804 }
6805 self.request_autoscroll(Autoscroll::fit(), cx);
6806 self.unmark_text(cx);
6807 self.refresh_inline_completion(true, false, cx);
6808 cx.emit(EditorEvent::Edited { transaction_id });
6809 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6810 }
6811 }
6812
6813 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6814 if self.read_only(cx) {
6815 return;
6816 }
6817
6818 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6819 if let Some((_, Some(selections))) =
6820 self.selection_history.transaction(transaction_id).cloned()
6821 {
6822 self.change_selections(None, cx, |s| {
6823 s.select_anchors(selections.to_vec());
6824 });
6825 }
6826 self.request_autoscroll(Autoscroll::fit(), cx);
6827 self.unmark_text(cx);
6828 self.refresh_inline_completion(true, false, cx);
6829 cx.emit(EditorEvent::Edited { transaction_id });
6830 }
6831 }
6832
6833 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6834 self.buffer
6835 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6836 }
6837
6838 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6839 self.buffer
6840 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6841 }
6842
6843 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6844 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6845 let line_mode = s.line_mode;
6846 s.move_with(|map, selection| {
6847 let cursor = if selection.is_empty() && !line_mode {
6848 movement::left(map, selection.start)
6849 } else {
6850 selection.start
6851 };
6852 selection.collapse_to(cursor, SelectionGoal::None);
6853 });
6854 })
6855 }
6856
6857 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6858 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6859 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6860 })
6861 }
6862
6863 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6864 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6865 let line_mode = s.line_mode;
6866 s.move_with(|map, selection| {
6867 let cursor = if selection.is_empty() && !line_mode {
6868 movement::right(map, selection.end)
6869 } else {
6870 selection.end
6871 };
6872 selection.collapse_to(cursor, SelectionGoal::None)
6873 });
6874 })
6875 }
6876
6877 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6878 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6879 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6880 })
6881 }
6882
6883 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6884 if self.take_rename(true, cx).is_some() {
6885 return;
6886 }
6887
6888 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6889 cx.propagate();
6890 return;
6891 }
6892
6893 let text_layout_details = &self.text_layout_details(cx);
6894 let selection_count = self.selections.count();
6895 let first_selection = self.selections.first_anchor();
6896
6897 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6898 let line_mode = s.line_mode;
6899 s.move_with(|map, selection| {
6900 if !selection.is_empty() && !line_mode {
6901 selection.goal = SelectionGoal::None;
6902 }
6903 let (cursor, goal) = movement::up(
6904 map,
6905 selection.start,
6906 selection.goal,
6907 false,
6908 &text_layout_details,
6909 );
6910 selection.collapse_to(cursor, goal);
6911 });
6912 });
6913
6914 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6915 {
6916 cx.propagate();
6917 }
6918 }
6919
6920 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6921 if self.take_rename(true, cx).is_some() {
6922 return;
6923 }
6924
6925 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6926 cx.propagate();
6927 return;
6928 }
6929
6930 let text_layout_details = &self.text_layout_details(cx);
6931
6932 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6933 let line_mode = s.line_mode;
6934 s.move_with(|map, selection| {
6935 if !selection.is_empty() && !line_mode {
6936 selection.goal = SelectionGoal::None;
6937 }
6938 let (cursor, goal) = movement::up_by_rows(
6939 map,
6940 selection.start,
6941 action.lines,
6942 selection.goal,
6943 false,
6944 &text_layout_details,
6945 );
6946 selection.collapse_to(cursor, goal);
6947 });
6948 })
6949 }
6950
6951 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6952 if self.take_rename(true, cx).is_some() {
6953 return;
6954 }
6955
6956 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6957 cx.propagate();
6958 return;
6959 }
6960
6961 let text_layout_details = &self.text_layout_details(cx);
6962
6963 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6964 let line_mode = s.line_mode;
6965 s.move_with(|map, selection| {
6966 if !selection.is_empty() && !line_mode {
6967 selection.goal = SelectionGoal::None;
6968 }
6969 let (cursor, goal) = movement::down_by_rows(
6970 map,
6971 selection.start,
6972 action.lines,
6973 selection.goal,
6974 false,
6975 &text_layout_details,
6976 );
6977 selection.collapse_to(cursor, goal);
6978 });
6979 })
6980 }
6981
6982 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6983 let text_layout_details = &self.text_layout_details(cx);
6984 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6985 s.move_heads_with(|map, head, goal| {
6986 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6987 })
6988 })
6989 }
6990
6991 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6992 let text_layout_details = &self.text_layout_details(cx);
6993 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6994 s.move_heads_with(|map, head, goal| {
6995 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6996 })
6997 })
6998 }
6999
7000 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7001 let Some(row_count) = self.visible_row_count() else {
7002 return;
7003 };
7004
7005 let text_layout_details = &self.text_layout_details(cx);
7006
7007 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7008 s.move_heads_with(|map, head, goal| {
7009 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
7010 })
7011 })
7012 }
7013
7014 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7015 if self.take_rename(true, cx).is_some() {
7016 return;
7017 }
7018
7019 if self
7020 .context_menu
7021 .write()
7022 .as_mut()
7023 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7024 .unwrap_or(false)
7025 {
7026 return;
7027 }
7028
7029 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7030 cx.propagate();
7031 return;
7032 }
7033
7034 let Some(row_count) = self.visible_row_count() else {
7035 return;
7036 };
7037
7038 let autoscroll = if action.center_cursor {
7039 Autoscroll::center()
7040 } else {
7041 Autoscroll::fit()
7042 };
7043
7044 let text_layout_details = &self.text_layout_details(cx);
7045
7046 self.change_selections(Some(autoscroll), cx, |s| {
7047 let line_mode = s.line_mode;
7048 s.move_with(|map, selection| {
7049 if !selection.is_empty() && !line_mode {
7050 selection.goal = SelectionGoal::None;
7051 }
7052 let (cursor, goal) = movement::up_by_rows(
7053 map,
7054 selection.end,
7055 row_count,
7056 selection.goal,
7057 false,
7058 &text_layout_details,
7059 );
7060 selection.collapse_to(cursor, goal);
7061 });
7062 });
7063 }
7064
7065 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7066 let text_layout_details = &self.text_layout_details(cx);
7067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7068 s.move_heads_with(|map, head, goal| {
7069 movement::up(map, head, goal, false, &text_layout_details)
7070 })
7071 })
7072 }
7073
7074 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7075 self.take_rename(true, cx);
7076
7077 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7078 cx.propagate();
7079 return;
7080 }
7081
7082 let text_layout_details = &self.text_layout_details(cx);
7083 let selection_count = self.selections.count();
7084 let first_selection = self.selections.first_anchor();
7085
7086 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7087 let line_mode = s.line_mode;
7088 s.move_with(|map, selection| {
7089 if !selection.is_empty() && !line_mode {
7090 selection.goal = SelectionGoal::None;
7091 }
7092 let (cursor, goal) = movement::down(
7093 map,
7094 selection.end,
7095 selection.goal,
7096 false,
7097 &text_layout_details,
7098 );
7099 selection.collapse_to(cursor, goal);
7100 });
7101 });
7102
7103 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7104 {
7105 cx.propagate();
7106 }
7107 }
7108
7109 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7110 let Some(row_count) = self.visible_row_count() else {
7111 return;
7112 };
7113
7114 let text_layout_details = &self.text_layout_details(cx);
7115
7116 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7117 s.move_heads_with(|map, head, goal| {
7118 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7119 })
7120 })
7121 }
7122
7123 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7124 if self.take_rename(true, cx).is_some() {
7125 return;
7126 }
7127
7128 if self
7129 .context_menu
7130 .write()
7131 .as_mut()
7132 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7133 .unwrap_or(false)
7134 {
7135 return;
7136 }
7137
7138 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7139 cx.propagate();
7140 return;
7141 }
7142
7143 let Some(row_count) = self.visible_row_count() else {
7144 return;
7145 };
7146
7147 let autoscroll = if action.center_cursor {
7148 Autoscroll::center()
7149 } else {
7150 Autoscroll::fit()
7151 };
7152
7153 let text_layout_details = &self.text_layout_details(cx);
7154 self.change_selections(Some(autoscroll), cx, |s| {
7155 let line_mode = s.line_mode;
7156 s.move_with(|map, selection| {
7157 if !selection.is_empty() && !line_mode {
7158 selection.goal = SelectionGoal::None;
7159 }
7160 let (cursor, goal) = movement::down_by_rows(
7161 map,
7162 selection.end,
7163 row_count,
7164 selection.goal,
7165 false,
7166 &text_layout_details,
7167 );
7168 selection.collapse_to(cursor, goal);
7169 });
7170 });
7171 }
7172
7173 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7174 let text_layout_details = &self.text_layout_details(cx);
7175 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7176 s.move_heads_with(|map, head, goal| {
7177 movement::down(map, head, goal, false, &text_layout_details)
7178 })
7179 });
7180 }
7181
7182 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7183 if let Some(context_menu) = self.context_menu.write().as_mut() {
7184 context_menu.select_first(self.project.as_ref(), cx);
7185 }
7186 }
7187
7188 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7189 if let Some(context_menu) = self.context_menu.write().as_mut() {
7190 context_menu.select_prev(self.project.as_ref(), cx);
7191 }
7192 }
7193
7194 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7195 if let Some(context_menu) = self.context_menu.write().as_mut() {
7196 context_menu.select_next(self.project.as_ref(), cx);
7197 }
7198 }
7199
7200 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7201 if let Some(context_menu) = self.context_menu.write().as_mut() {
7202 context_menu.select_last(self.project.as_ref(), cx);
7203 }
7204 }
7205
7206 pub fn move_to_previous_word_start(
7207 &mut self,
7208 _: &MoveToPreviousWordStart,
7209 cx: &mut ViewContext<Self>,
7210 ) {
7211 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7212 s.move_cursors_with(|map, head, _| {
7213 (
7214 movement::previous_word_start(map, head),
7215 SelectionGoal::None,
7216 )
7217 });
7218 })
7219 }
7220
7221 pub fn move_to_previous_subword_start(
7222 &mut self,
7223 _: &MoveToPreviousSubwordStart,
7224 cx: &mut ViewContext<Self>,
7225 ) {
7226 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7227 s.move_cursors_with(|map, head, _| {
7228 (
7229 movement::previous_subword_start(map, head),
7230 SelectionGoal::None,
7231 )
7232 });
7233 })
7234 }
7235
7236 pub fn select_to_previous_word_start(
7237 &mut self,
7238 _: &SelectToPreviousWordStart,
7239 cx: &mut ViewContext<Self>,
7240 ) {
7241 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7242 s.move_heads_with(|map, head, _| {
7243 (
7244 movement::previous_word_start(map, head),
7245 SelectionGoal::None,
7246 )
7247 });
7248 })
7249 }
7250
7251 pub fn select_to_previous_subword_start(
7252 &mut self,
7253 _: &SelectToPreviousSubwordStart,
7254 cx: &mut ViewContext<Self>,
7255 ) {
7256 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7257 s.move_heads_with(|map, head, _| {
7258 (
7259 movement::previous_subword_start(map, head),
7260 SelectionGoal::None,
7261 )
7262 });
7263 })
7264 }
7265
7266 pub fn delete_to_previous_word_start(
7267 &mut self,
7268 _: &DeleteToPreviousWordStart,
7269 cx: &mut ViewContext<Self>,
7270 ) {
7271 self.transact(cx, |this, cx| {
7272 this.select_autoclose_pair(cx);
7273 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7274 let line_mode = s.line_mode;
7275 s.move_with(|map, selection| {
7276 if selection.is_empty() && !line_mode {
7277 let cursor = movement::previous_word_start(map, selection.head());
7278 selection.set_head(cursor, SelectionGoal::None);
7279 }
7280 });
7281 });
7282 this.insert("", cx);
7283 });
7284 }
7285
7286 pub fn delete_to_previous_subword_start(
7287 &mut self,
7288 _: &DeleteToPreviousSubwordStart,
7289 cx: &mut ViewContext<Self>,
7290 ) {
7291 self.transact(cx, |this, cx| {
7292 this.select_autoclose_pair(cx);
7293 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7294 let line_mode = s.line_mode;
7295 s.move_with(|map, selection| {
7296 if selection.is_empty() && !line_mode {
7297 let cursor = movement::previous_subword_start(map, selection.head());
7298 selection.set_head(cursor, SelectionGoal::None);
7299 }
7300 });
7301 });
7302 this.insert("", cx);
7303 });
7304 }
7305
7306 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7307 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7308 s.move_cursors_with(|map, head, _| {
7309 (movement::next_word_end(map, head), SelectionGoal::None)
7310 });
7311 })
7312 }
7313
7314 pub fn move_to_next_subword_end(
7315 &mut self,
7316 _: &MoveToNextSubwordEnd,
7317 cx: &mut ViewContext<Self>,
7318 ) {
7319 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7320 s.move_cursors_with(|map, head, _| {
7321 (movement::next_subword_end(map, head), SelectionGoal::None)
7322 });
7323 })
7324 }
7325
7326 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7327 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7328 s.move_heads_with(|map, head, _| {
7329 (movement::next_word_end(map, head), SelectionGoal::None)
7330 });
7331 })
7332 }
7333
7334 pub fn select_to_next_subword_end(
7335 &mut self,
7336 _: &SelectToNextSubwordEnd,
7337 cx: &mut ViewContext<Self>,
7338 ) {
7339 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7340 s.move_heads_with(|map, head, _| {
7341 (movement::next_subword_end(map, head), SelectionGoal::None)
7342 });
7343 })
7344 }
7345
7346 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7347 self.transact(cx, |this, cx| {
7348 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7349 let line_mode = s.line_mode;
7350 s.move_with(|map, selection| {
7351 if selection.is_empty() && !line_mode {
7352 let cursor = movement::next_word_end(map, selection.head());
7353 selection.set_head(cursor, SelectionGoal::None);
7354 }
7355 });
7356 });
7357 this.insert("", cx);
7358 });
7359 }
7360
7361 pub fn delete_to_next_subword_end(
7362 &mut self,
7363 _: &DeleteToNextSubwordEnd,
7364 cx: &mut ViewContext<Self>,
7365 ) {
7366 self.transact(cx, |this, cx| {
7367 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7368 s.move_with(|map, selection| {
7369 if selection.is_empty() {
7370 let cursor = movement::next_subword_end(map, selection.head());
7371 selection.set_head(cursor, SelectionGoal::None);
7372 }
7373 });
7374 });
7375 this.insert("", cx);
7376 });
7377 }
7378
7379 pub fn move_to_beginning_of_line(
7380 &mut self,
7381 action: &MoveToBeginningOfLine,
7382 cx: &mut ViewContext<Self>,
7383 ) {
7384 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7385 s.move_cursors_with(|map, head, _| {
7386 (
7387 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7388 SelectionGoal::None,
7389 )
7390 });
7391 })
7392 }
7393
7394 pub fn select_to_beginning_of_line(
7395 &mut self,
7396 action: &SelectToBeginningOfLine,
7397 cx: &mut ViewContext<Self>,
7398 ) {
7399 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7400 s.move_heads_with(|map, head, _| {
7401 (
7402 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7403 SelectionGoal::None,
7404 )
7405 });
7406 });
7407 }
7408
7409 pub fn delete_to_beginning_of_line(
7410 &mut self,
7411 _: &DeleteToBeginningOfLine,
7412 cx: &mut ViewContext<Self>,
7413 ) {
7414 self.transact(cx, |this, cx| {
7415 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7416 s.move_with(|_, selection| {
7417 selection.reversed = true;
7418 });
7419 });
7420
7421 this.select_to_beginning_of_line(
7422 &SelectToBeginningOfLine {
7423 stop_at_soft_wraps: false,
7424 },
7425 cx,
7426 );
7427 this.backspace(&Backspace, cx);
7428 });
7429 }
7430
7431 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7432 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7433 s.move_cursors_with(|map, head, _| {
7434 (
7435 movement::line_end(map, head, action.stop_at_soft_wraps),
7436 SelectionGoal::None,
7437 )
7438 });
7439 })
7440 }
7441
7442 pub fn select_to_end_of_line(
7443 &mut self,
7444 action: &SelectToEndOfLine,
7445 cx: &mut ViewContext<Self>,
7446 ) {
7447 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7448 s.move_heads_with(|map, head, _| {
7449 (
7450 movement::line_end(map, head, action.stop_at_soft_wraps),
7451 SelectionGoal::None,
7452 )
7453 });
7454 })
7455 }
7456
7457 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7458 self.transact(cx, |this, cx| {
7459 this.select_to_end_of_line(
7460 &SelectToEndOfLine {
7461 stop_at_soft_wraps: false,
7462 },
7463 cx,
7464 );
7465 this.delete(&Delete, cx);
7466 });
7467 }
7468
7469 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7470 self.transact(cx, |this, cx| {
7471 this.select_to_end_of_line(
7472 &SelectToEndOfLine {
7473 stop_at_soft_wraps: false,
7474 },
7475 cx,
7476 );
7477 this.cut(&Cut, cx);
7478 });
7479 }
7480
7481 pub fn move_to_start_of_paragraph(
7482 &mut self,
7483 _: &MoveToStartOfParagraph,
7484 cx: &mut ViewContext<Self>,
7485 ) {
7486 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7487 cx.propagate();
7488 return;
7489 }
7490
7491 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7492 s.move_with(|map, selection| {
7493 selection.collapse_to(
7494 movement::start_of_paragraph(map, selection.head(), 1),
7495 SelectionGoal::None,
7496 )
7497 });
7498 })
7499 }
7500
7501 pub fn move_to_end_of_paragraph(
7502 &mut self,
7503 _: &MoveToEndOfParagraph,
7504 cx: &mut ViewContext<Self>,
7505 ) {
7506 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7507 cx.propagate();
7508 return;
7509 }
7510
7511 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7512 s.move_with(|map, selection| {
7513 selection.collapse_to(
7514 movement::end_of_paragraph(map, selection.head(), 1),
7515 SelectionGoal::None,
7516 )
7517 });
7518 })
7519 }
7520
7521 pub fn select_to_start_of_paragraph(
7522 &mut self,
7523 _: &SelectToStartOfParagraph,
7524 cx: &mut ViewContext<Self>,
7525 ) {
7526 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7527 cx.propagate();
7528 return;
7529 }
7530
7531 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7532 s.move_heads_with(|map, head, _| {
7533 (
7534 movement::start_of_paragraph(map, head, 1),
7535 SelectionGoal::None,
7536 )
7537 });
7538 })
7539 }
7540
7541 pub fn select_to_end_of_paragraph(
7542 &mut self,
7543 _: &SelectToEndOfParagraph,
7544 cx: &mut ViewContext<Self>,
7545 ) {
7546 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7547 cx.propagate();
7548 return;
7549 }
7550
7551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7552 s.move_heads_with(|map, head, _| {
7553 (
7554 movement::end_of_paragraph(map, head, 1),
7555 SelectionGoal::None,
7556 )
7557 });
7558 })
7559 }
7560
7561 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7562 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7563 cx.propagate();
7564 return;
7565 }
7566
7567 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7568 s.select_ranges(vec![0..0]);
7569 });
7570 }
7571
7572 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7573 let mut selection = self.selections.last::<Point>(cx);
7574 selection.set_head(Point::zero(), SelectionGoal::None);
7575
7576 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7577 s.select(vec![selection]);
7578 });
7579 }
7580
7581 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7582 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7583 cx.propagate();
7584 return;
7585 }
7586
7587 let cursor = self.buffer.read(cx).read(cx).len();
7588 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7589 s.select_ranges(vec![cursor..cursor])
7590 });
7591 }
7592
7593 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7594 self.nav_history = nav_history;
7595 }
7596
7597 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7598 self.nav_history.as_ref()
7599 }
7600
7601 fn push_to_nav_history(
7602 &mut self,
7603 cursor_anchor: Anchor,
7604 new_position: Option<Point>,
7605 cx: &mut ViewContext<Self>,
7606 ) {
7607 if let Some(nav_history) = self.nav_history.as_mut() {
7608 let buffer = self.buffer.read(cx).read(cx);
7609 let cursor_position = cursor_anchor.to_point(&buffer);
7610 let scroll_state = self.scroll_manager.anchor();
7611 let scroll_top_row = scroll_state.top_row(&buffer);
7612 drop(buffer);
7613
7614 if let Some(new_position) = new_position {
7615 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7616 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7617 return;
7618 }
7619 }
7620
7621 nav_history.push(
7622 Some(NavigationData {
7623 cursor_anchor,
7624 cursor_position,
7625 scroll_anchor: scroll_state,
7626 scroll_top_row,
7627 }),
7628 cx,
7629 );
7630 }
7631 }
7632
7633 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7634 let buffer = self.buffer.read(cx).snapshot(cx);
7635 let mut selection = self.selections.first::<usize>(cx);
7636 selection.set_head(buffer.len(), SelectionGoal::None);
7637 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7638 s.select(vec![selection]);
7639 });
7640 }
7641
7642 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7643 let end = self.buffer.read(cx).read(cx).len();
7644 self.change_selections(None, cx, |s| {
7645 s.select_ranges(vec![0..end]);
7646 });
7647 }
7648
7649 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7650 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7651 let mut selections = self.selections.all::<Point>(cx);
7652 let max_point = display_map.buffer_snapshot.max_point();
7653 for selection in &mut selections {
7654 let rows = selection.spanned_rows(true, &display_map);
7655 selection.start = Point::new(rows.start.0, 0);
7656 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7657 selection.reversed = false;
7658 }
7659 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7660 s.select(selections);
7661 });
7662 }
7663
7664 pub fn split_selection_into_lines(
7665 &mut self,
7666 _: &SplitSelectionIntoLines,
7667 cx: &mut ViewContext<Self>,
7668 ) {
7669 let mut to_unfold = Vec::new();
7670 let mut new_selection_ranges = Vec::new();
7671 {
7672 let selections = self.selections.all::<Point>(cx);
7673 let buffer = self.buffer.read(cx).read(cx);
7674 for selection in selections {
7675 for row in selection.start.row..selection.end.row {
7676 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7677 new_selection_ranges.push(cursor..cursor);
7678 }
7679 new_selection_ranges.push(selection.end..selection.end);
7680 to_unfold.push(selection.start..selection.end);
7681 }
7682 }
7683 self.unfold_ranges(to_unfold, true, true, cx);
7684 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7685 s.select_ranges(new_selection_ranges);
7686 });
7687 }
7688
7689 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7690 self.add_selection(true, cx);
7691 }
7692
7693 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7694 self.add_selection(false, cx);
7695 }
7696
7697 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7698 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7699 let mut selections = self.selections.all::<Point>(cx);
7700 let text_layout_details = self.text_layout_details(cx);
7701 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7702 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7703 let range = oldest_selection.display_range(&display_map).sorted();
7704
7705 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7706 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7707 let positions = start_x.min(end_x)..start_x.max(end_x);
7708
7709 selections.clear();
7710 let mut stack = Vec::new();
7711 for row in range.start.row().0..=range.end.row().0 {
7712 if let Some(selection) = self.selections.build_columnar_selection(
7713 &display_map,
7714 DisplayRow(row),
7715 &positions,
7716 oldest_selection.reversed,
7717 &text_layout_details,
7718 ) {
7719 stack.push(selection.id);
7720 selections.push(selection);
7721 }
7722 }
7723
7724 if above {
7725 stack.reverse();
7726 }
7727
7728 AddSelectionsState { above, stack }
7729 });
7730
7731 let last_added_selection = *state.stack.last().unwrap();
7732 let mut new_selections = Vec::new();
7733 if above == state.above {
7734 let end_row = if above {
7735 DisplayRow(0)
7736 } else {
7737 display_map.max_point().row()
7738 };
7739
7740 'outer: for selection in selections {
7741 if selection.id == last_added_selection {
7742 let range = selection.display_range(&display_map).sorted();
7743 debug_assert_eq!(range.start.row(), range.end.row());
7744 let mut row = range.start.row();
7745 let positions =
7746 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7747 px(start)..px(end)
7748 } else {
7749 let start_x =
7750 display_map.x_for_display_point(range.start, &text_layout_details);
7751 let end_x =
7752 display_map.x_for_display_point(range.end, &text_layout_details);
7753 start_x.min(end_x)..start_x.max(end_x)
7754 };
7755
7756 while row != end_row {
7757 if above {
7758 row.0 -= 1;
7759 } else {
7760 row.0 += 1;
7761 }
7762
7763 if let Some(new_selection) = self.selections.build_columnar_selection(
7764 &display_map,
7765 row,
7766 &positions,
7767 selection.reversed,
7768 &text_layout_details,
7769 ) {
7770 state.stack.push(new_selection.id);
7771 if above {
7772 new_selections.push(new_selection);
7773 new_selections.push(selection);
7774 } else {
7775 new_selections.push(selection);
7776 new_selections.push(new_selection);
7777 }
7778
7779 continue 'outer;
7780 }
7781 }
7782 }
7783
7784 new_selections.push(selection);
7785 }
7786 } else {
7787 new_selections = selections;
7788 new_selections.retain(|s| s.id != last_added_selection);
7789 state.stack.pop();
7790 }
7791
7792 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7793 s.select(new_selections);
7794 });
7795 if state.stack.len() > 1 {
7796 self.add_selections_state = Some(state);
7797 }
7798 }
7799
7800 pub fn select_next_match_internal(
7801 &mut self,
7802 display_map: &DisplaySnapshot,
7803 replace_newest: bool,
7804 autoscroll: Option<Autoscroll>,
7805 cx: &mut ViewContext<Self>,
7806 ) -> Result<()> {
7807 fn select_next_match_ranges(
7808 this: &mut Editor,
7809 range: Range<usize>,
7810 replace_newest: bool,
7811 auto_scroll: Option<Autoscroll>,
7812 cx: &mut ViewContext<Editor>,
7813 ) {
7814 this.unfold_ranges([range.clone()], false, true, cx);
7815 this.change_selections(auto_scroll, cx, |s| {
7816 if replace_newest {
7817 s.delete(s.newest_anchor().id);
7818 }
7819 s.insert_range(range.clone());
7820 });
7821 }
7822
7823 let buffer = &display_map.buffer_snapshot;
7824 let mut selections = self.selections.all::<usize>(cx);
7825 if let Some(mut select_next_state) = self.select_next_state.take() {
7826 let query = &select_next_state.query;
7827 if !select_next_state.done {
7828 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7829 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7830 let mut next_selected_range = None;
7831
7832 let bytes_after_last_selection =
7833 buffer.bytes_in_range(last_selection.end..buffer.len());
7834 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7835 let query_matches = query
7836 .stream_find_iter(bytes_after_last_selection)
7837 .map(|result| (last_selection.end, result))
7838 .chain(
7839 query
7840 .stream_find_iter(bytes_before_first_selection)
7841 .map(|result| (0, result)),
7842 );
7843
7844 for (start_offset, query_match) in query_matches {
7845 let query_match = query_match.unwrap(); // can only fail due to I/O
7846 let offset_range =
7847 start_offset + query_match.start()..start_offset + query_match.end();
7848 let display_range = offset_range.start.to_display_point(&display_map)
7849 ..offset_range.end.to_display_point(&display_map);
7850
7851 if !select_next_state.wordwise
7852 || (!movement::is_inside_word(&display_map, display_range.start)
7853 && !movement::is_inside_word(&display_map, display_range.end))
7854 {
7855 // TODO: This is n^2, because we might check all the selections
7856 if !selections
7857 .iter()
7858 .any(|selection| selection.range().overlaps(&offset_range))
7859 {
7860 next_selected_range = Some(offset_range);
7861 break;
7862 }
7863 }
7864 }
7865
7866 if let Some(next_selected_range) = next_selected_range {
7867 select_next_match_ranges(
7868 self,
7869 next_selected_range,
7870 replace_newest,
7871 autoscroll,
7872 cx,
7873 );
7874 } else {
7875 select_next_state.done = true;
7876 }
7877 }
7878
7879 self.select_next_state = Some(select_next_state);
7880 } else {
7881 let mut only_carets = true;
7882 let mut same_text_selected = true;
7883 let mut selected_text = None;
7884
7885 let mut selections_iter = selections.iter().peekable();
7886 while let Some(selection) = selections_iter.next() {
7887 if selection.start != selection.end {
7888 only_carets = false;
7889 }
7890
7891 if same_text_selected {
7892 if selected_text.is_none() {
7893 selected_text =
7894 Some(buffer.text_for_range(selection.range()).collect::<String>());
7895 }
7896
7897 if let Some(next_selection) = selections_iter.peek() {
7898 if next_selection.range().len() == selection.range().len() {
7899 let next_selected_text = buffer
7900 .text_for_range(next_selection.range())
7901 .collect::<String>();
7902 if Some(next_selected_text) != selected_text {
7903 same_text_selected = false;
7904 selected_text = None;
7905 }
7906 } else {
7907 same_text_selected = false;
7908 selected_text = None;
7909 }
7910 }
7911 }
7912 }
7913
7914 if only_carets {
7915 for selection in &mut selections {
7916 let word_range = movement::surrounding_word(
7917 &display_map,
7918 selection.start.to_display_point(&display_map),
7919 );
7920 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7921 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7922 selection.goal = SelectionGoal::None;
7923 selection.reversed = false;
7924 select_next_match_ranges(
7925 self,
7926 selection.start..selection.end,
7927 replace_newest,
7928 autoscroll,
7929 cx,
7930 );
7931 }
7932
7933 if selections.len() == 1 {
7934 let selection = selections
7935 .last()
7936 .expect("ensured that there's only one selection");
7937 let query = buffer
7938 .text_for_range(selection.start..selection.end)
7939 .collect::<String>();
7940 let is_empty = query.is_empty();
7941 let select_state = SelectNextState {
7942 query: AhoCorasick::new(&[query])?,
7943 wordwise: true,
7944 done: is_empty,
7945 };
7946 self.select_next_state = Some(select_state);
7947 } else {
7948 self.select_next_state = None;
7949 }
7950 } else if let Some(selected_text) = selected_text {
7951 self.select_next_state = Some(SelectNextState {
7952 query: AhoCorasick::new(&[selected_text])?,
7953 wordwise: false,
7954 done: false,
7955 });
7956 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7957 }
7958 }
7959 Ok(())
7960 }
7961
7962 pub fn select_all_matches(
7963 &mut self,
7964 _action: &SelectAllMatches,
7965 cx: &mut ViewContext<Self>,
7966 ) -> Result<()> {
7967 self.push_to_selection_history();
7968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7969
7970 self.select_next_match_internal(&display_map, false, None, cx)?;
7971 let Some(select_next_state) = self.select_next_state.as_mut() else {
7972 return Ok(());
7973 };
7974 if select_next_state.done {
7975 return Ok(());
7976 }
7977
7978 let mut new_selections = self.selections.all::<usize>(cx);
7979
7980 let buffer = &display_map.buffer_snapshot;
7981 let query_matches = select_next_state
7982 .query
7983 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7984
7985 for query_match in query_matches {
7986 let query_match = query_match.unwrap(); // can only fail due to I/O
7987 let offset_range = query_match.start()..query_match.end();
7988 let display_range = offset_range.start.to_display_point(&display_map)
7989 ..offset_range.end.to_display_point(&display_map);
7990
7991 if !select_next_state.wordwise
7992 || (!movement::is_inside_word(&display_map, display_range.start)
7993 && !movement::is_inside_word(&display_map, display_range.end))
7994 {
7995 self.selections.change_with(cx, |selections| {
7996 new_selections.push(Selection {
7997 id: selections.new_selection_id(),
7998 start: offset_range.start,
7999 end: offset_range.end,
8000 reversed: false,
8001 goal: SelectionGoal::None,
8002 });
8003 });
8004 }
8005 }
8006
8007 new_selections.sort_by_key(|selection| selection.start);
8008 let mut ix = 0;
8009 while ix + 1 < new_selections.len() {
8010 let current_selection = &new_selections[ix];
8011 let next_selection = &new_selections[ix + 1];
8012 if current_selection.range().overlaps(&next_selection.range()) {
8013 if current_selection.id < next_selection.id {
8014 new_selections.remove(ix + 1);
8015 } else {
8016 new_selections.remove(ix);
8017 }
8018 } else {
8019 ix += 1;
8020 }
8021 }
8022
8023 select_next_state.done = true;
8024 self.unfold_ranges(
8025 new_selections.iter().map(|selection| selection.range()),
8026 false,
8027 false,
8028 cx,
8029 );
8030 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8031 selections.select(new_selections)
8032 });
8033
8034 Ok(())
8035 }
8036
8037 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8038 self.push_to_selection_history();
8039 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8040 self.select_next_match_internal(
8041 &display_map,
8042 action.replace_newest,
8043 Some(Autoscroll::newest()),
8044 cx,
8045 )?;
8046 Ok(())
8047 }
8048
8049 pub fn select_previous(
8050 &mut self,
8051 action: &SelectPrevious,
8052 cx: &mut ViewContext<Self>,
8053 ) -> Result<()> {
8054 self.push_to_selection_history();
8055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8056 let buffer = &display_map.buffer_snapshot;
8057 let mut selections = self.selections.all::<usize>(cx);
8058 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8059 let query = &select_prev_state.query;
8060 if !select_prev_state.done {
8061 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8062 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8063 let mut next_selected_range = None;
8064 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8065 let bytes_before_last_selection =
8066 buffer.reversed_bytes_in_range(0..last_selection.start);
8067 let bytes_after_first_selection =
8068 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8069 let query_matches = query
8070 .stream_find_iter(bytes_before_last_selection)
8071 .map(|result| (last_selection.start, result))
8072 .chain(
8073 query
8074 .stream_find_iter(bytes_after_first_selection)
8075 .map(|result| (buffer.len(), result)),
8076 );
8077 for (end_offset, query_match) in query_matches {
8078 let query_match = query_match.unwrap(); // can only fail due to I/O
8079 let offset_range =
8080 end_offset - query_match.end()..end_offset - query_match.start();
8081 let display_range = offset_range.start.to_display_point(&display_map)
8082 ..offset_range.end.to_display_point(&display_map);
8083
8084 if !select_prev_state.wordwise
8085 || (!movement::is_inside_word(&display_map, display_range.start)
8086 && !movement::is_inside_word(&display_map, display_range.end))
8087 {
8088 next_selected_range = Some(offset_range);
8089 break;
8090 }
8091 }
8092
8093 if let Some(next_selected_range) = next_selected_range {
8094 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8095 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8096 if action.replace_newest {
8097 s.delete(s.newest_anchor().id);
8098 }
8099 s.insert_range(next_selected_range);
8100 });
8101 } else {
8102 select_prev_state.done = true;
8103 }
8104 }
8105
8106 self.select_prev_state = Some(select_prev_state);
8107 } else {
8108 let mut only_carets = true;
8109 let mut same_text_selected = true;
8110 let mut selected_text = None;
8111
8112 let mut selections_iter = selections.iter().peekable();
8113 while let Some(selection) = selections_iter.next() {
8114 if selection.start != selection.end {
8115 only_carets = false;
8116 }
8117
8118 if same_text_selected {
8119 if selected_text.is_none() {
8120 selected_text =
8121 Some(buffer.text_for_range(selection.range()).collect::<String>());
8122 }
8123
8124 if let Some(next_selection) = selections_iter.peek() {
8125 if next_selection.range().len() == selection.range().len() {
8126 let next_selected_text = buffer
8127 .text_for_range(next_selection.range())
8128 .collect::<String>();
8129 if Some(next_selected_text) != selected_text {
8130 same_text_selected = false;
8131 selected_text = None;
8132 }
8133 } else {
8134 same_text_selected = false;
8135 selected_text = None;
8136 }
8137 }
8138 }
8139 }
8140
8141 if only_carets {
8142 for selection in &mut selections {
8143 let word_range = movement::surrounding_word(
8144 &display_map,
8145 selection.start.to_display_point(&display_map),
8146 );
8147 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8148 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8149 selection.goal = SelectionGoal::None;
8150 selection.reversed = false;
8151 }
8152 if selections.len() == 1 {
8153 let selection = selections
8154 .last()
8155 .expect("ensured that there's only one selection");
8156 let query = buffer
8157 .text_for_range(selection.start..selection.end)
8158 .collect::<String>();
8159 let is_empty = query.is_empty();
8160 let select_state = SelectNextState {
8161 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8162 wordwise: true,
8163 done: is_empty,
8164 };
8165 self.select_prev_state = Some(select_state);
8166 } else {
8167 self.select_prev_state = None;
8168 }
8169
8170 self.unfold_ranges(
8171 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8172 false,
8173 true,
8174 cx,
8175 );
8176 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8177 s.select(selections);
8178 });
8179 } else if let Some(selected_text) = selected_text {
8180 self.select_prev_state = Some(SelectNextState {
8181 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8182 wordwise: false,
8183 done: false,
8184 });
8185 self.select_previous(action, cx)?;
8186 }
8187 }
8188 Ok(())
8189 }
8190
8191 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8192 let text_layout_details = &self.text_layout_details(cx);
8193 self.transact(cx, |this, cx| {
8194 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8195 let mut edits = Vec::new();
8196 let mut selection_edit_ranges = Vec::new();
8197 let mut last_toggled_row = None;
8198 let snapshot = this.buffer.read(cx).read(cx);
8199 let empty_str: Arc<str> = Arc::default();
8200 let mut suffixes_inserted = Vec::new();
8201
8202 fn comment_prefix_range(
8203 snapshot: &MultiBufferSnapshot,
8204 row: MultiBufferRow,
8205 comment_prefix: &str,
8206 comment_prefix_whitespace: &str,
8207 ) -> Range<Point> {
8208 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8209
8210 let mut line_bytes = snapshot
8211 .bytes_in_range(start..snapshot.max_point())
8212 .flatten()
8213 .copied();
8214
8215 // If this line currently begins with the line comment prefix, then record
8216 // the range containing the prefix.
8217 if line_bytes
8218 .by_ref()
8219 .take(comment_prefix.len())
8220 .eq(comment_prefix.bytes())
8221 {
8222 // Include any whitespace that matches the comment prefix.
8223 let matching_whitespace_len = line_bytes
8224 .zip(comment_prefix_whitespace.bytes())
8225 .take_while(|(a, b)| a == b)
8226 .count() as u32;
8227 let end = Point::new(
8228 start.row,
8229 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8230 );
8231 start..end
8232 } else {
8233 start..start
8234 }
8235 }
8236
8237 fn comment_suffix_range(
8238 snapshot: &MultiBufferSnapshot,
8239 row: MultiBufferRow,
8240 comment_suffix: &str,
8241 comment_suffix_has_leading_space: bool,
8242 ) -> Range<Point> {
8243 let end = Point::new(row.0, snapshot.line_len(row));
8244 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8245
8246 let mut line_end_bytes = snapshot
8247 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8248 .flatten()
8249 .copied();
8250
8251 let leading_space_len = if suffix_start_column > 0
8252 && line_end_bytes.next() == Some(b' ')
8253 && comment_suffix_has_leading_space
8254 {
8255 1
8256 } else {
8257 0
8258 };
8259
8260 // If this line currently begins with the line comment prefix, then record
8261 // the range containing the prefix.
8262 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8263 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8264 start..end
8265 } else {
8266 end..end
8267 }
8268 }
8269
8270 // TODO: Handle selections that cross excerpts
8271 for selection in &mut selections {
8272 let start_column = snapshot
8273 .indent_size_for_line(MultiBufferRow(selection.start.row))
8274 .len;
8275 let language = if let Some(language) =
8276 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8277 {
8278 language
8279 } else {
8280 continue;
8281 };
8282
8283 selection_edit_ranges.clear();
8284
8285 // If multiple selections contain a given row, avoid processing that
8286 // row more than once.
8287 let mut start_row = MultiBufferRow(selection.start.row);
8288 if last_toggled_row == Some(start_row) {
8289 start_row = start_row.next_row();
8290 }
8291 let end_row =
8292 if selection.end.row > selection.start.row && selection.end.column == 0 {
8293 MultiBufferRow(selection.end.row - 1)
8294 } else {
8295 MultiBufferRow(selection.end.row)
8296 };
8297 last_toggled_row = Some(end_row);
8298
8299 if start_row > end_row {
8300 continue;
8301 }
8302
8303 // If the language has line comments, toggle those.
8304 let full_comment_prefixes = language.line_comment_prefixes();
8305 if !full_comment_prefixes.is_empty() {
8306 let first_prefix = full_comment_prefixes
8307 .first()
8308 .expect("prefixes is non-empty");
8309 let prefix_trimmed_lengths = full_comment_prefixes
8310 .iter()
8311 .map(|p| p.trim_end_matches(' ').len())
8312 .collect::<SmallVec<[usize; 4]>>();
8313
8314 let mut all_selection_lines_are_comments = true;
8315
8316 for row in start_row.0..=end_row.0 {
8317 let row = MultiBufferRow(row);
8318 if start_row < end_row && snapshot.is_line_blank(row) {
8319 continue;
8320 }
8321
8322 let prefix_range = full_comment_prefixes
8323 .iter()
8324 .zip(prefix_trimmed_lengths.iter().copied())
8325 .map(|(prefix, trimmed_prefix_len)| {
8326 comment_prefix_range(
8327 snapshot.deref(),
8328 row,
8329 &prefix[..trimmed_prefix_len],
8330 &prefix[trimmed_prefix_len..],
8331 )
8332 })
8333 .max_by_key(|range| range.end.column - range.start.column)
8334 .expect("prefixes is non-empty");
8335
8336 if prefix_range.is_empty() {
8337 all_selection_lines_are_comments = false;
8338 }
8339
8340 selection_edit_ranges.push(prefix_range);
8341 }
8342
8343 if all_selection_lines_are_comments {
8344 edits.extend(
8345 selection_edit_ranges
8346 .iter()
8347 .cloned()
8348 .map(|range| (range, empty_str.clone())),
8349 );
8350 } else {
8351 let min_column = selection_edit_ranges
8352 .iter()
8353 .map(|range| range.start.column)
8354 .min()
8355 .unwrap_or(0);
8356 edits.extend(selection_edit_ranges.iter().map(|range| {
8357 let position = Point::new(range.start.row, min_column);
8358 (position..position, first_prefix.clone())
8359 }));
8360 }
8361 } else if let Some((full_comment_prefix, comment_suffix)) =
8362 language.block_comment_delimiters()
8363 {
8364 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8365 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8366 let prefix_range = comment_prefix_range(
8367 snapshot.deref(),
8368 start_row,
8369 comment_prefix,
8370 comment_prefix_whitespace,
8371 );
8372 let suffix_range = comment_suffix_range(
8373 snapshot.deref(),
8374 end_row,
8375 comment_suffix.trim_start_matches(' '),
8376 comment_suffix.starts_with(' '),
8377 );
8378
8379 if prefix_range.is_empty() || suffix_range.is_empty() {
8380 edits.push((
8381 prefix_range.start..prefix_range.start,
8382 full_comment_prefix.clone(),
8383 ));
8384 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8385 suffixes_inserted.push((end_row, comment_suffix.len()));
8386 } else {
8387 edits.push((prefix_range, empty_str.clone()));
8388 edits.push((suffix_range, empty_str.clone()));
8389 }
8390 } else {
8391 continue;
8392 }
8393 }
8394
8395 drop(snapshot);
8396 this.buffer.update(cx, |buffer, cx| {
8397 buffer.edit(edits, None, cx);
8398 });
8399
8400 // Adjust selections so that they end before any comment suffixes that
8401 // were inserted.
8402 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8403 let mut selections = this.selections.all::<Point>(cx);
8404 let snapshot = this.buffer.read(cx).read(cx);
8405 for selection in &mut selections {
8406 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8407 match row.cmp(&MultiBufferRow(selection.end.row)) {
8408 Ordering::Less => {
8409 suffixes_inserted.next();
8410 continue;
8411 }
8412 Ordering::Greater => break,
8413 Ordering::Equal => {
8414 if selection.end.column == snapshot.line_len(row) {
8415 if selection.is_empty() {
8416 selection.start.column -= suffix_len as u32;
8417 }
8418 selection.end.column -= suffix_len as u32;
8419 }
8420 break;
8421 }
8422 }
8423 }
8424 }
8425
8426 drop(snapshot);
8427 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8428
8429 let selections = this.selections.all::<Point>(cx);
8430 let selections_on_single_row = selections.windows(2).all(|selections| {
8431 selections[0].start.row == selections[1].start.row
8432 && selections[0].end.row == selections[1].end.row
8433 && selections[0].start.row == selections[0].end.row
8434 });
8435 let selections_selecting = selections
8436 .iter()
8437 .any(|selection| selection.start != selection.end);
8438 let advance_downwards = action.advance_downwards
8439 && selections_on_single_row
8440 && !selections_selecting
8441 && !matches!(this.mode, EditorMode::SingleLine { .. });
8442
8443 if advance_downwards {
8444 let snapshot = this.buffer.read(cx).snapshot(cx);
8445
8446 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8447 s.move_cursors_with(|display_snapshot, display_point, _| {
8448 let mut point = display_point.to_point(display_snapshot);
8449 point.row += 1;
8450 point = snapshot.clip_point(point, Bias::Left);
8451 let display_point = point.to_display_point(display_snapshot);
8452 let goal = SelectionGoal::HorizontalPosition(
8453 display_snapshot
8454 .x_for_display_point(display_point, &text_layout_details)
8455 .into(),
8456 );
8457 (display_point, goal)
8458 })
8459 });
8460 }
8461 });
8462 }
8463
8464 pub fn select_enclosing_symbol(
8465 &mut self,
8466 _: &SelectEnclosingSymbol,
8467 cx: &mut ViewContext<Self>,
8468 ) {
8469 let buffer = self.buffer.read(cx).snapshot(cx);
8470 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8471
8472 fn update_selection(
8473 selection: &Selection<usize>,
8474 buffer_snap: &MultiBufferSnapshot,
8475 ) -> Option<Selection<usize>> {
8476 let cursor = selection.head();
8477 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8478 for symbol in symbols.iter().rev() {
8479 let start = symbol.range.start.to_offset(&buffer_snap);
8480 let end = symbol.range.end.to_offset(&buffer_snap);
8481 let new_range = start..end;
8482 if start < selection.start || end > selection.end {
8483 return Some(Selection {
8484 id: selection.id,
8485 start: new_range.start,
8486 end: new_range.end,
8487 goal: SelectionGoal::None,
8488 reversed: selection.reversed,
8489 });
8490 }
8491 }
8492 None
8493 }
8494
8495 let mut selected_larger_symbol = false;
8496 let new_selections = old_selections
8497 .iter()
8498 .map(|selection| match update_selection(selection, &buffer) {
8499 Some(new_selection) => {
8500 if new_selection.range() != selection.range() {
8501 selected_larger_symbol = true;
8502 }
8503 new_selection
8504 }
8505 None => selection.clone(),
8506 })
8507 .collect::<Vec<_>>();
8508
8509 if selected_larger_symbol {
8510 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8511 s.select(new_selections);
8512 });
8513 }
8514 }
8515
8516 pub fn select_larger_syntax_node(
8517 &mut self,
8518 _: &SelectLargerSyntaxNode,
8519 cx: &mut ViewContext<Self>,
8520 ) {
8521 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8522 let buffer = self.buffer.read(cx).snapshot(cx);
8523 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8524
8525 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8526 let mut selected_larger_node = false;
8527 let new_selections = old_selections
8528 .iter()
8529 .map(|selection| {
8530 let old_range = selection.start..selection.end;
8531 let mut new_range = old_range.clone();
8532 while let Some(containing_range) =
8533 buffer.range_for_syntax_ancestor(new_range.clone())
8534 {
8535 new_range = containing_range;
8536 if !display_map.intersects_fold(new_range.start)
8537 && !display_map.intersects_fold(new_range.end)
8538 {
8539 break;
8540 }
8541 }
8542
8543 selected_larger_node |= new_range != old_range;
8544 Selection {
8545 id: selection.id,
8546 start: new_range.start,
8547 end: new_range.end,
8548 goal: SelectionGoal::None,
8549 reversed: selection.reversed,
8550 }
8551 })
8552 .collect::<Vec<_>>();
8553
8554 if selected_larger_node {
8555 stack.push(old_selections);
8556 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8557 s.select(new_selections);
8558 });
8559 }
8560 self.select_larger_syntax_node_stack = stack;
8561 }
8562
8563 pub fn select_smaller_syntax_node(
8564 &mut self,
8565 _: &SelectSmallerSyntaxNode,
8566 cx: &mut ViewContext<Self>,
8567 ) {
8568 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8569 if let Some(selections) = stack.pop() {
8570 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8571 s.select(selections.to_vec());
8572 });
8573 }
8574 self.select_larger_syntax_node_stack = stack;
8575 }
8576
8577 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8578 if !EditorSettings::get_global(cx).gutter.runnables {
8579 self.clear_tasks();
8580 return Task::ready(());
8581 }
8582 let project = self.project.clone();
8583 cx.spawn(|this, mut cx| async move {
8584 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8585 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8586 }) else {
8587 return;
8588 };
8589
8590 let Some(project) = project else {
8591 return;
8592 };
8593
8594 let hide_runnables = project
8595 .update(&mut cx, |project, cx| {
8596 // Do not display any test indicators in non-dev server remote projects.
8597 project.is_remote() && project.ssh_connection_string(cx).is_none()
8598 })
8599 .unwrap_or(true);
8600 if hide_runnables {
8601 return;
8602 }
8603 let new_rows =
8604 cx.background_executor()
8605 .spawn({
8606 let snapshot = display_snapshot.clone();
8607 async move {
8608 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8609 }
8610 })
8611 .await;
8612 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8613
8614 this.update(&mut cx, |this, _| {
8615 this.clear_tasks();
8616 for (key, value) in rows {
8617 this.insert_tasks(key, value);
8618 }
8619 })
8620 .ok();
8621 })
8622 }
8623 fn fetch_runnable_ranges(
8624 snapshot: &DisplaySnapshot,
8625 range: Range<Anchor>,
8626 ) -> Vec<language::RunnableRange> {
8627 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8628 }
8629
8630 fn runnable_rows(
8631 project: Model<Project>,
8632 snapshot: DisplaySnapshot,
8633 runnable_ranges: Vec<RunnableRange>,
8634 mut cx: AsyncWindowContext,
8635 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8636 runnable_ranges
8637 .into_iter()
8638 .filter_map(|mut runnable| {
8639 let tasks = cx
8640 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8641 .ok()?;
8642 if tasks.is_empty() {
8643 return None;
8644 }
8645
8646 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8647
8648 let row = snapshot
8649 .buffer_snapshot
8650 .buffer_line_for_row(MultiBufferRow(point.row))?
8651 .1
8652 .start
8653 .row;
8654
8655 let context_range =
8656 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8657 Some((
8658 (runnable.buffer_id, row),
8659 RunnableTasks {
8660 templates: tasks,
8661 offset: MultiBufferOffset(runnable.run_range.start),
8662 context_range,
8663 column: point.column,
8664 extra_variables: runnable.extra_captures,
8665 },
8666 ))
8667 })
8668 .collect()
8669 }
8670
8671 fn templates_with_tags(
8672 project: &Model<Project>,
8673 runnable: &mut Runnable,
8674 cx: &WindowContext<'_>,
8675 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8676 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8677 let (worktree_id, file) = project
8678 .buffer_for_id(runnable.buffer, cx)
8679 .and_then(|buffer| buffer.read(cx).file())
8680 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8681 .unzip();
8682
8683 (project.task_inventory().clone(), worktree_id, file)
8684 });
8685
8686 let inventory = inventory.read(cx);
8687 let tags = mem::take(&mut runnable.tags);
8688 let mut tags: Vec<_> = tags
8689 .into_iter()
8690 .flat_map(|tag| {
8691 let tag = tag.0.clone();
8692 inventory
8693 .list_tasks(
8694 file.clone(),
8695 Some(runnable.language.clone()),
8696 worktree_id,
8697 cx,
8698 )
8699 .into_iter()
8700 .filter(move |(_, template)| {
8701 template.tags.iter().any(|source_tag| source_tag == &tag)
8702 })
8703 })
8704 .sorted_by_key(|(kind, _)| kind.to_owned())
8705 .collect();
8706 if let Some((leading_tag_source, _)) = tags.first() {
8707 // Strongest source wins; if we have worktree tag binding, prefer that to
8708 // global and language bindings;
8709 // if we have a global binding, prefer that to language binding.
8710 let first_mismatch = tags
8711 .iter()
8712 .position(|(tag_source, _)| tag_source != leading_tag_source);
8713 if let Some(index) = first_mismatch {
8714 tags.truncate(index);
8715 }
8716 }
8717
8718 tags
8719 }
8720
8721 pub fn move_to_enclosing_bracket(
8722 &mut self,
8723 _: &MoveToEnclosingBracket,
8724 cx: &mut ViewContext<Self>,
8725 ) {
8726 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8727 s.move_offsets_with(|snapshot, selection| {
8728 let Some(enclosing_bracket_ranges) =
8729 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8730 else {
8731 return;
8732 };
8733
8734 let mut best_length = usize::MAX;
8735 let mut best_inside = false;
8736 let mut best_in_bracket_range = false;
8737 let mut best_destination = None;
8738 for (open, close) in enclosing_bracket_ranges {
8739 let close = close.to_inclusive();
8740 let length = close.end() - open.start;
8741 let inside = selection.start >= open.end && selection.end <= *close.start();
8742 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8743 || close.contains(&selection.head());
8744
8745 // If best is next to a bracket and current isn't, skip
8746 if !in_bracket_range && best_in_bracket_range {
8747 continue;
8748 }
8749
8750 // Prefer smaller lengths unless best is inside and current isn't
8751 if length > best_length && (best_inside || !inside) {
8752 continue;
8753 }
8754
8755 best_length = length;
8756 best_inside = inside;
8757 best_in_bracket_range = in_bracket_range;
8758 best_destination = Some(
8759 if close.contains(&selection.start) && close.contains(&selection.end) {
8760 if inside {
8761 open.end
8762 } else {
8763 open.start
8764 }
8765 } else {
8766 if inside {
8767 *close.start()
8768 } else {
8769 *close.end()
8770 }
8771 },
8772 );
8773 }
8774
8775 if let Some(destination) = best_destination {
8776 selection.collapse_to(destination, SelectionGoal::None);
8777 }
8778 })
8779 });
8780 }
8781
8782 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8783 self.end_selection(cx);
8784 self.selection_history.mode = SelectionHistoryMode::Undoing;
8785 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8786 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8787 self.select_next_state = entry.select_next_state;
8788 self.select_prev_state = entry.select_prev_state;
8789 self.add_selections_state = entry.add_selections_state;
8790 self.request_autoscroll(Autoscroll::newest(), cx);
8791 }
8792 self.selection_history.mode = SelectionHistoryMode::Normal;
8793 }
8794
8795 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8796 self.end_selection(cx);
8797 self.selection_history.mode = SelectionHistoryMode::Redoing;
8798 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8799 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8800 self.select_next_state = entry.select_next_state;
8801 self.select_prev_state = entry.select_prev_state;
8802 self.add_selections_state = entry.add_selections_state;
8803 self.request_autoscroll(Autoscroll::newest(), cx);
8804 }
8805 self.selection_history.mode = SelectionHistoryMode::Normal;
8806 }
8807
8808 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8809 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8810 }
8811
8812 pub fn expand_excerpts_down(
8813 &mut self,
8814 action: &ExpandExcerptsDown,
8815 cx: &mut ViewContext<Self>,
8816 ) {
8817 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8818 }
8819
8820 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8821 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8822 }
8823
8824 pub fn expand_excerpts_for_direction(
8825 &mut self,
8826 lines: u32,
8827 direction: ExpandExcerptDirection,
8828 cx: &mut ViewContext<Self>,
8829 ) {
8830 let selections = self.selections.disjoint_anchors();
8831
8832 let lines = if lines == 0 {
8833 EditorSettings::get_global(cx).expand_excerpt_lines
8834 } else {
8835 lines
8836 };
8837
8838 self.buffer.update(cx, |buffer, cx| {
8839 buffer.expand_excerpts(
8840 selections
8841 .into_iter()
8842 .map(|selection| selection.head().excerpt_id)
8843 .dedup(),
8844 lines,
8845 direction,
8846 cx,
8847 )
8848 })
8849 }
8850
8851 pub fn expand_excerpt(
8852 &mut self,
8853 excerpt: ExcerptId,
8854 direction: ExpandExcerptDirection,
8855 cx: &mut ViewContext<Self>,
8856 ) {
8857 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8858 self.buffer.update(cx, |buffer, cx| {
8859 buffer.expand_excerpts([excerpt], lines, direction, cx)
8860 })
8861 }
8862
8863 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8864 self.go_to_diagnostic_impl(Direction::Next, cx)
8865 }
8866
8867 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8868 self.go_to_diagnostic_impl(Direction::Prev, cx)
8869 }
8870
8871 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8872 let buffer = self.buffer.read(cx).snapshot(cx);
8873 let selection = self.selections.newest::<usize>(cx);
8874
8875 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8876 if direction == Direction::Next {
8877 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8878 let (group_id, jump_to) = popover.activation_info();
8879 if self.activate_diagnostics(group_id, cx) {
8880 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8881 let mut new_selection = s.newest_anchor().clone();
8882 new_selection.collapse_to(jump_to, SelectionGoal::None);
8883 s.select_anchors(vec![new_selection.clone()]);
8884 });
8885 }
8886 return;
8887 }
8888 }
8889
8890 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8891 active_diagnostics
8892 .primary_range
8893 .to_offset(&buffer)
8894 .to_inclusive()
8895 });
8896 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8897 if active_primary_range.contains(&selection.head()) {
8898 *active_primary_range.start()
8899 } else {
8900 selection.head()
8901 }
8902 } else {
8903 selection.head()
8904 };
8905 let snapshot = self.snapshot(cx);
8906 loop {
8907 let diagnostics = if direction == Direction::Prev {
8908 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8909 } else {
8910 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8911 }
8912 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8913 let group = diagnostics
8914 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8915 // be sorted in a stable way
8916 // skip until we are at current active diagnostic, if it exists
8917 .skip_while(|entry| {
8918 (match direction {
8919 Direction::Prev => entry.range.start >= search_start,
8920 Direction::Next => entry.range.start <= search_start,
8921 }) && self
8922 .active_diagnostics
8923 .as_ref()
8924 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8925 })
8926 .find_map(|entry| {
8927 if entry.diagnostic.is_primary
8928 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8929 && !entry.range.is_empty()
8930 // if we match with the active diagnostic, skip it
8931 && Some(entry.diagnostic.group_id)
8932 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8933 {
8934 Some((entry.range, entry.diagnostic.group_id))
8935 } else {
8936 None
8937 }
8938 });
8939
8940 if let Some((primary_range, group_id)) = group {
8941 if self.activate_diagnostics(group_id, cx) {
8942 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8943 s.select(vec![Selection {
8944 id: selection.id,
8945 start: primary_range.start,
8946 end: primary_range.start,
8947 reversed: false,
8948 goal: SelectionGoal::None,
8949 }]);
8950 });
8951 }
8952 break;
8953 } else {
8954 // Cycle around to the start of the buffer, potentially moving back to the start of
8955 // the currently active diagnostic.
8956 active_primary_range.take();
8957 if direction == Direction::Prev {
8958 if search_start == buffer.len() {
8959 break;
8960 } else {
8961 search_start = buffer.len();
8962 }
8963 } else if search_start == 0 {
8964 break;
8965 } else {
8966 search_start = 0;
8967 }
8968 }
8969 }
8970 }
8971
8972 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8973 let snapshot = self
8974 .display_map
8975 .update(cx, |display_map, cx| display_map.snapshot(cx));
8976 let selection = self.selections.newest::<Point>(cx);
8977
8978 if !self.seek_in_direction(
8979 &snapshot,
8980 selection.head(),
8981 false,
8982 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8983 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8984 ),
8985 cx,
8986 ) {
8987 let wrapped_point = Point::zero();
8988 self.seek_in_direction(
8989 &snapshot,
8990 wrapped_point,
8991 true,
8992 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8993 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8994 ),
8995 cx,
8996 );
8997 }
8998 }
8999
9000 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9001 let snapshot = self
9002 .display_map
9003 .update(cx, |display_map, cx| display_map.snapshot(cx));
9004 let selection = self.selections.newest::<Point>(cx);
9005
9006 if !self.seek_in_direction(
9007 &snapshot,
9008 selection.head(),
9009 false,
9010 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9011 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9012 ),
9013 cx,
9014 ) {
9015 let wrapped_point = snapshot.buffer_snapshot.max_point();
9016 self.seek_in_direction(
9017 &snapshot,
9018 wrapped_point,
9019 true,
9020 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9021 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9022 ),
9023 cx,
9024 );
9025 }
9026 }
9027
9028 fn seek_in_direction(
9029 &mut self,
9030 snapshot: &DisplaySnapshot,
9031 initial_point: Point,
9032 is_wrapped: bool,
9033 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9034 cx: &mut ViewContext<Editor>,
9035 ) -> bool {
9036 let display_point = initial_point.to_display_point(snapshot);
9037 let mut hunks = hunks
9038 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9039 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9040 .dedup();
9041
9042 if let Some(hunk) = hunks.next() {
9043 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9044 let row = hunk.start_display_row();
9045 let point = DisplayPoint::new(row, 0);
9046 s.select_display_ranges([point..point]);
9047 });
9048
9049 true
9050 } else {
9051 false
9052 }
9053 }
9054
9055 pub fn go_to_definition(
9056 &mut self,
9057 _: &GoToDefinition,
9058 cx: &mut ViewContext<Self>,
9059 ) -> Task<Result<Navigated>> {
9060 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9061 let references = self.find_all_references(&FindAllReferences, cx);
9062 cx.background_executor().spawn(async move {
9063 if definition.await? == Navigated::Yes {
9064 return Ok(Navigated::Yes);
9065 }
9066 if let Some(references) = references {
9067 if references.await? == Navigated::Yes {
9068 return Ok(Navigated::Yes);
9069 }
9070 }
9071
9072 Ok(Navigated::No)
9073 })
9074 }
9075
9076 pub fn go_to_declaration(
9077 &mut self,
9078 _: &GoToDeclaration,
9079 cx: &mut ViewContext<Self>,
9080 ) -> Task<Result<Navigated>> {
9081 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9082 }
9083
9084 pub fn go_to_declaration_split(
9085 &mut self,
9086 _: &GoToDeclaration,
9087 cx: &mut ViewContext<Self>,
9088 ) -> Task<Result<Navigated>> {
9089 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9090 }
9091
9092 pub fn go_to_implementation(
9093 &mut self,
9094 _: &GoToImplementation,
9095 cx: &mut ViewContext<Self>,
9096 ) -> Task<Result<Navigated>> {
9097 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9098 }
9099
9100 pub fn go_to_implementation_split(
9101 &mut self,
9102 _: &GoToImplementationSplit,
9103 cx: &mut ViewContext<Self>,
9104 ) -> Task<Result<Navigated>> {
9105 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9106 }
9107
9108 pub fn go_to_type_definition(
9109 &mut self,
9110 _: &GoToTypeDefinition,
9111 cx: &mut ViewContext<Self>,
9112 ) -> Task<Result<Navigated>> {
9113 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9114 }
9115
9116 pub fn go_to_definition_split(
9117 &mut self,
9118 _: &GoToDefinitionSplit,
9119 cx: &mut ViewContext<Self>,
9120 ) -> Task<Result<Navigated>> {
9121 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9122 }
9123
9124 pub fn go_to_type_definition_split(
9125 &mut self,
9126 _: &GoToTypeDefinitionSplit,
9127 cx: &mut ViewContext<Self>,
9128 ) -> Task<Result<Navigated>> {
9129 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9130 }
9131
9132 fn go_to_definition_of_kind(
9133 &mut self,
9134 kind: GotoDefinitionKind,
9135 split: bool,
9136 cx: &mut ViewContext<Self>,
9137 ) -> Task<Result<Navigated>> {
9138 let Some(workspace) = self.workspace() else {
9139 return Task::ready(Ok(Navigated::No));
9140 };
9141 let buffer = self.buffer.read(cx);
9142 let head = self.selections.newest::<usize>(cx).head();
9143 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9144 text_anchor
9145 } else {
9146 return Task::ready(Ok(Navigated::No));
9147 };
9148
9149 let project = workspace.read(cx).project().clone();
9150 let definitions = project.update(cx, |project, cx| match kind {
9151 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9152 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9153 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9154 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9155 });
9156
9157 cx.spawn(|editor, mut cx| async move {
9158 let definitions = definitions.await?;
9159 let navigated = editor
9160 .update(&mut cx, |editor, cx| {
9161 editor.navigate_to_hover_links(
9162 Some(kind),
9163 definitions
9164 .into_iter()
9165 .filter(|location| {
9166 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9167 })
9168 .map(HoverLink::Text)
9169 .collect::<Vec<_>>(),
9170 split,
9171 cx,
9172 )
9173 })?
9174 .await?;
9175 anyhow::Ok(navigated)
9176 })
9177 }
9178
9179 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9180 let position = self.selections.newest_anchor().head();
9181 let Some((buffer, buffer_position)) =
9182 self.buffer.read(cx).text_anchor_for_position(position, cx)
9183 else {
9184 return;
9185 };
9186
9187 cx.spawn(|editor, mut cx| async move {
9188 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9189 editor.update(&mut cx, |_, cx| {
9190 cx.open_url(&url);
9191 })
9192 } else {
9193 Ok(())
9194 }
9195 })
9196 .detach();
9197 }
9198
9199 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9200 let Some(workspace) = self.workspace() else {
9201 return;
9202 };
9203
9204 let position = self.selections.newest_anchor().head();
9205
9206 let Some((buffer, buffer_position)) =
9207 self.buffer.read(cx).text_anchor_for_position(position, cx)
9208 else {
9209 return;
9210 };
9211
9212 let Some(project) = self.project.clone() else {
9213 return;
9214 };
9215
9216 cx.spawn(|_, mut cx| async move {
9217 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9218
9219 if let Some((_, path)) = result {
9220 workspace
9221 .update(&mut cx, |workspace, cx| {
9222 workspace.open_resolved_path(path, cx)
9223 })?
9224 .await?;
9225 }
9226 anyhow::Ok(())
9227 })
9228 .detach();
9229 }
9230
9231 pub(crate) fn navigate_to_hover_links(
9232 &mut self,
9233 kind: Option<GotoDefinitionKind>,
9234 mut definitions: Vec<HoverLink>,
9235 split: bool,
9236 cx: &mut ViewContext<Editor>,
9237 ) -> Task<Result<Navigated>> {
9238 // If there is one definition, just open it directly
9239 if definitions.len() == 1 {
9240 let definition = definitions.pop().unwrap();
9241
9242 enum TargetTaskResult {
9243 Location(Option<Location>),
9244 AlreadyNavigated,
9245 }
9246
9247 let target_task = match definition {
9248 HoverLink::Text(link) => {
9249 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9250 }
9251 HoverLink::InlayHint(lsp_location, server_id) => {
9252 let computation = self.compute_target_location(lsp_location, server_id, cx);
9253 cx.background_executor().spawn(async move {
9254 let location = computation.await?;
9255 Ok(TargetTaskResult::Location(location))
9256 })
9257 }
9258 HoverLink::Url(url) => {
9259 cx.open_url(&url);
9260 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9261 }
9262 HoverLink::File(path) => {
9263 if let Some(workspace) = self.workspace() {
9264 cx.spawn(|_, mut cx| async move {
9265 workspace
9266 .update(&mut cx, |workspace, cx| {
9267 workspace.open_resolved_path(path, cx)
9268 })?
9269 .await
9270 .map(|_| TargetTaskResult::AlreadyNavigated)
9271 })
9272 } else {
9273 Task::ready(Ok(TargetTaskResult::Location(None)))
9274 }
9275 }
9276 };
9277 cx.spawn(|editor, mut cx| async move {
9278 let target = match target_task.await.context("target resolution task")? {
9279 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9280 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9281 TargetTaskResult::Location(Some(target)) => target,
9282 };
9283
9284 editor.update(&mut cx, |editor, cx| {
9285 let Some(workspace) = editor.workspace() else {
9286 return Navigated::No;
9287 };
9288 let pane = workspace.read(cx).active_pane().clone();
9289
9290 let range = target.range.to_offset(target.buffer.read(cx));
9291 let range = editor.range_for_match(&range);
9292
9293 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9294 let buffer = target.buffer.read(cx);
9295 let range = check_multiline_range(buffer, range);
9296 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9297 s.select_ranges([range]);
9298 });
9299 } else {
9300 cx.window_context().defer(move |cx| {
9301 let target_editor: View<Self> =
9302 workspace.update(cx, |workspace, cx| {
9303 let pane = if split {
9304 workspace.adjacent_pane(cx)
9305 } else {
9306 workspace.active_pane().clone()
9307 };
9308
9309 workspace.open_project_item(
9310 pane,
9311 target.buffer.clone(),
9312 true,
9313 true,
9314 cx,
9315 )
9316 });
9317 target_editor.update(cx, |target_editor, cx| {
9318 // When selecting a definition in a different buffer, disable the nav history
9319 // to avoid creating a history entry at the previous cursor location.
9320 pane.update(cx, |pane, _| pane.disable_history());
9321 let buffer = target.buffer.read(cx);
9322 let range = check_multiline_range(buffer, range);
9323 target_editor.change_selections(
9324 Some(Autoscroll::focused()),
9325 cx,
9326 |s| {
9327 s.select_ranges([range]);
9328 },
9329 );
9330 pane.update(cx, |pane, _| pane.enable_history());
9331 });
9332 });
9333 }
9334 Navigated::Yes
9335 })
9336 })
9337 } else if !definitions.is_empty() {
9338 let replica_id = self.replica_id(cx);
9339 cx.spawn(|editor, mut cx| async move {
9340 let (title, location_tasks, workspace) = editor
9341 .update(&mut cx, |editor, cx| {
9342 let tab_kind = match kind {
9343 Some(GotoDefinitionKind::Implementation) => "Implementations",
9344 _ => "Definitions",
9345 };
9346 let title = definitions
9347 .iter()
9348 .find_map(|definition| match definition {
9349 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9350 let buffer = origin.buffer.read(cx);
9351 format!(
9352 "{} for {}",
9353 tab_kind,
9354 buffer
9355 .text_for_range(origin.range.clone())
9356 .collect::<String>()
9357 )
9358 }),
9359 HoverLink::InlayHint(_, _) => None,
9360 HoverLink::Url(_) => None,
9361 HoverLink::File(_) => None,
9362 })
9363 .unwrap_or(tab_kind.to_string());
9364 let location_tasks = definitions
9365 .into_iter()
9366 .map(|definition| match definition {
9367 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9368 HoverLink::InlayHint(lsp_location, server_id) => {
9369 editor.compute_target_location(lsp_location, server_id, cx)
9370 }
9371 HoverLink::Url(_) => Task::ready(Ok(None)),
9372 HoverLink::File(_) => Task::ready(Ok(None)),
9373 })
9374 .collect::<Vec<_>>();
9375 (title, location_tasks, editor.workspace().clone())
9376 })
9377 .context("location tasks preparation")?;
9378
9379 let locations = futures::future::join_all(location_tasks)
9380 .await
9381 .into_iter()
9382 .filter_map(|location| location.transpose())
9383 .collect::<Result<_>>()
9384 .context("location tasks")?;
9385
9386 let Some(workspace) = workspace else {
9387 return Ok(Navigated::No);
9388 };
9389 let opened = workspace
9390 .update(&mut cx, |workspace, cx| {
9391 Self::open_locations_in_multibuffer(
9392 workspace, locations, replica_id, title, split, cx,
9393 )
9394 })
9395 .ok();
9396
9397 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9398 })
9399 } else {
9400 Task::ready(Ok(Navigated::No))
9401 }
9402 }
9403
9404 fn compute_target_location(
9405 &self,
9406 lsp_location: lsp::Location,
9407 server_id: LanguageServerId,
9408 cx: &mut ViewContext<Editor>,
9409 ) -> Task<anyhow::Result<Option<Location>>> {
9410 let Some(project) = self.project.clone() else {
9411 return Task::Ready(Some(Ok(None)));
9412 };
9413
9414 cx.spawn(move |editor, mut cx| async move {
9415 let location_task = editor.update(&mut cx, |editor, cx| {
9416 project.update(cx, |project, cx| {
9417 let language_server_name =
9418 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9419 project
9420 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9421 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9422 });
9423 language_server_name.map(|language_server_name| {
9424 project.open_local_buffer_via_lsp(
9425 lsp_location.uri.clone(),
9426 server_id,
9427 language_server_name,
9428 cx,
9429 )
9430 })
9431 })
9432 })?;
9433 let location = match location_task {
9434 Some(task) => Some({
9435 let target_buffer_handle = task.await.context("open local buffer")?;
9436 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9437 let target_start = target_buffer
9438 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9439 let target_end = target_buffer
9440 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9441 target_buffer.anchor_after(target_start)
9442 ..target_buffer.anchor_before(target_end)
9443 })?;
9444 Location {
9445 buffer: target_buffer_handle,
9446 range,
9447 }
9448 }),
9449 None => None,
9450 };
9451 Ok(location)
9452 })
9453 }
9454
9455 pub fn find_all_references(
9456 &mut self,
9457 _: &FindAllReferences,
9458 cx: &mut ViewContext<Self>,
9459 ) -> Option<Task<Result<Navigated>>> {
9460 let multi_buffer = self.buffer.read(cx);
9461 let selection = self.selections.newest::<usize>(cx);
9462 let head = selection.head();
9463
9464 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9465 let head_anchor = multi_buffer_snapshot.anchor_at(
9466 head,
9467 if head < selection.tail() {
9468 Bias::Right
9469 } else {
9470 Bias::Left
9471 },
9472 );
9473
9474 match self
9475 .find_all_references_task_sources
9476 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9477 {
9478 Ok(_) => {
9479 log::info!(
9480 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9481 );
9482 return None;
9483 }
9484 Err(i) => {
9485 self.find_all_references_task_sources.insert(i, head_anchor);
9486 }
9487 }
9488
9489 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9490 let replica_id = self.replica_id(cx);
9491 let workspace = self.workspace()?;
9492 let project = workspace.read(cx).project().clone();
9493 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9494 Some(cx.spawn(|editor, mut cx| async move {
9495 let _cleanup = defer({
9496 let mut cx = cx.clone();
9497 move || {
9498 let _ = editor.update(&mut cx, |editor, _| {
9499 if let Ok(i) =
9500 editor
9501 .find_all_references_task_sources
9502 .binary_search_by(|anchor| {
9503 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9504 })
9505 {
9506 editor.find_all_references_task_sources.remove(i);
9507 }
9508 });
9509 }
9510 });
9511
9512 let locations = references.await?;
9513 if locations.is_empty() {
9514 return anyhow::Ok(Navigated::No);
9515 }
9516
9517 workspace.update(&mut cx, |workspace, cx| {
9518 let title = locations
9519 .first()
9520 .as_ref()
9521 .map(|location| {
9522 let buffer = location.buffer.read(cx);
9523 format!(
9524 "References to `{}`",
9525 buffer
9526 .text_for_range(location.range.clone())
9527 .collect::<String>()
9528 )
9529 })
9530 .unwrap();
9531 Self::open_locations_in_multibuffer(
9532 workspace, locations, replica_id, title, false, cx,
9533 );
9534 Navigated::Yes
9535 })
9536 }))
9537 }
9538
9539 /// Opens a multibuffer with the given project locations in it
9540 pub fn open_locations_in_multibuffer(
9541 workspace: &mut Workspace,
9542 mut locations: Vec<Location>,
9543 replica_id: ReplicaId,
9544 title: String,
9545 split: bool,
9546 cx: &mut ViewContext<Workspace>,
9547 ) {
9548 // If there are multiple definitions, open them in a multibuffer
9549 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9550 let mut locations = locations.into_iter().peekable();
9551 let mut ranges_to_highlight = Vec::new();
9552 let capability = workspace.project().read(cx).capability();
9553
9554 let excerpt_buffer = cx.new_model(|cx| {
9555 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9556 while let Some(location) = locations.next() {
9557 let buffer = location.buffer.read(cx);
9558 let mut ranges_for_buffer = Vec::new();
9559 let range = location.range.to_offset(buffer);
9560 ranges_for_buffer.push(range.clone());
9561
9562 while let Some(next_location) = locations.peek() {
9563 if next_location.buffer == location.buffer {
9564 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9565 locations.next();
9566 } else {
9567 break;
9568 }
9569 }
9570
9571 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9572 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9573 location.buffer.clone(),
9574 ranges_for_buffer,
9575 DEFAULT_MULTIBUFFER_CONTEXT,
9576 cx,
9577 ))
9578 }
9579
9580 multibuffer.with_title(title)
9581 });
9582
9583 let editor = cx.new_view(|cx| {
9584 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9585 });
9586 editor.update(cx, |editor, cx| {
9587 if let Some(first_range) = ranges_to_highlight.first() {
9588 editor.change_selections(None, cx, |selections| {
9589 selections.clear_disjoint();
9590 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9591 });
9592 }
9593 editor.highlight_background::<Self>(
9594 &ranges_to_highlight,
9595 |theme| theme.editor_highlighted_line_background,
9596 cx,
9597 );
9598 });
9599
9600 let item = Box::new(editor);
9601 let item_id = item.item_id();
9602
9603 if split {
9604 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9605 } else {
9606 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9607 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9608 pane.close_current_preview_item(cx)
9609 } else {
9610 None
9611 }
9612 });
9613 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9614 }
9615 workspace.active_pane().update(cx, |pane, cx| {
9616 pane.set_preview_item_id(Some(item_id), cx);
9617 });
9618 }
9619
9620 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9621 use language::ToOffset as _;
9622
9623 let project = self.project.clone()?;
9624 let selection = self.selections.newest_anchor().clone();
9625 let (cursor_buffer, cursor_buffer_position) = self
9626 .buffer
9627 .read(cx)
9628 .text_anchor_for_position(selection.head(), cx)?;
9629 let (tail_buffer, cursor_buffer_position_end) = self
9630 .buffer
9631 .read(cx)
9632 .text_anchor_for_position(selection.tail(), cx)?;
9633 if tail_buffer != cursor_buffer {
9634 return None;
9635 }
9636
9637 let snapshot = cursor_buffer.read(cx).snapshot();
9638 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9639 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9640 let prepare_rename = project.update(cx, |project, cx| {
9641 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9642 });
9643 drop(snapshot);
9644
9645 Some(cx.spawn(|this, mut cx| async move {
9646 let rename_range = if let Some(range) = prepare_rename.await? {
9647 Some(range)
9648 } else {
9649 this.update(&mut cx, |this, cx| {
9650 let buffer = this.buffer.read(cx).snapshot(cx);
9651 let mut buffer_highlights = this
9652 .document_highlights_for_position(selection.head(), &buffer)
9653 .filter(|highlight| {
9654 highlight.start.excerpt_id == selection.head().excerpt_id
9655 && highlight.end.excerpt_id == selection.head().excerpt_id
9656 });
9657 buffer_highlights
9658 .next()
9659 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9660 })?
9661 };
9662 if let Some(rename_range) = rename_range {
9663 this.update(&mut cx, |this, cx| {
9664 let snapshot = cursor_buffer.read(cx).snapshot();
9665 let rename_buffer_range = rename_range.to_offset(&snapshot);
9666 let cursor_offset_in_rename_range =
9667 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9668 let cursor_offset_in_rename_range_end =
9669 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9670
9671 this.take_rename(false, cx);
9672 let buffer = this.buffer.read(cx).read(cx);
9673 let cursor_offset = selection.head().to_offset(&buffer);
9674 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9675 let rename_end = rename_start + rename_buffer_range.len();
9676 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9677 let mut old_highlight_id = None;
9678 let old_name: Arc<str> = buffer
9679 .chunks(rename_start..rename_end, true)
9680 .map(|chunk| {
9681 if old_highlight_id.is_none() {
9682 old_highlight_id = chunk.syntax_highlight_id;
9683 }
9684 chunk.text
9685 })
9686 .collect::<String>()
9687 .into();
9688
9689 drop(buffer);
9690
9691 // Position the selection in the rename editor so that it matches the current selection.
9692 this.show_local_selections = false;
9693 let rename_editor = cx.new_view(|cx| {
9694 let mut editor = Editor::single_line(cx);
9695 editor.buffer.update(cx, |buffer, cx| {
9696 buffer.edit([(0..0, old_name.clone())], None, cx)
9697 });
9698 let rename_selection_range = match cursor_offset_in_rename_range
9699 .cmp(&cursor_offset_in_rename_range_end)
9700 {
9701 Ordering::Equal => {
9702 editor.select_all(&SelectAll, cx);
9703 return editor;
9704 }
9705 Ordering::Less => {
9706 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9707 }
9708 Ordering::Greater => {
9709 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9710 }
9711 };
9712 if rename_selection_range.end > old_name.len() {
9713 editor.select_all(&SelectAll, cx);
9714 } else {
9715 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9716 s.select_ranges([rename_selection_range]);
9717 });
9718 }
9719 editor
9720 });
9721 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9722 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9723 _ => {}
9724 })
9725 .detach();
9726
9727 let write_highlights =
9728 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9729 let read_highlights =
9730 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9731 let ranges = write_highlights
9732 .iter()
9733 .flat_map(|(_, ranges)| ranges.iter())
9734 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9735 .cloned()
9736 .collect();
9737
9738 this.highlight_text::<Rename>(
9739 ranges,
9740 HighlightStyle {
9741 fade_out: Some(0.6),
9742 ..Default::default()
9743 },
9744 cx,
9745 );
9746 let rename_focus_handle = rename_editor.focus_handle(cx);
9747 cx.focus(&rename_focus_handle);
9748 let block_id = this.insert_blocks(
9749 [BlockProperties {
9750 style: BlockStyle::Flex,
9751 position: range.start,
9752 height: 1,
9753 render: Box::new({
9754 let rename_editor = rename_editor.clone();
9755 move |cx: &mut BlockContext| {
9756 let mut text_style = cx.editor_style.text.clone();
9757 if let Some(highlight_style) = old_highlight_id
9758 .and_then(|h| h.style(&cx.editor_style.syntax))
9759 {
9760 text_style = text_style.highlight(highlight_style);
9761 }
9762 div()
9763 .pl(cx.anchor_x)
9764 .child(EditorElement::new(
9765 &rename_editor,
9766 EditorStyle {
9767 background: cx.theme().system().transparent,
9768 local_player: cx.editor_style.local_player,
9769 text: text_style,
9770 scrollbar_width: cx.editor_style.scrollbar_width,
9771 syntax: cx.editor_style.syntax.clone(),
9772 status: cx.editor_style.status.clone(),
9773 inlay_hints_style: HighlightStyle {
9774 color: Some(cx.theme().status().hint),
9775 font_weight: Some(FontWeight::BOLD),
9776 ..HighlightStyle::default()
9777 },
9778 suggestions_style: HighlightStyle {
9779 color: Some(cx.theme().status().predictive),
9780 ..HighlightStyle::default()
9781 },
9782 ..EditorStyle::default()
9783 },
9784 ))
9785 .into_any_element()
9786 }
9787 }),
9788 disposition: BlockDisposition::Below,
9789 priority: 0,
9790 }],
9791 Some(Autoscroll::fit()),
9792 cx,
9793 )[0];
9794 this.pending_rename = Some(RenameState {
9795 range,
9796 old_name,
9797 editor: rename_editor,
9798 block_id,
9799 });
9800 })?;
9801 }
9802
9803 Ok(())
9804 }))
9805 }
9806
9807 pub fn confirm_rename(
9808 &mut self,
9809 _: &ConfirmRename,
9810 cx: &mut ViewContext<Self>,
9811 ) -> Option<Task<Result<()>>> {
9812 let rename = self.take_rename(false, cx)?;
9813 let workspace = self.workspace()?;
9814 let (start_buffer, start) = self
9815 .buffer
9816 .read(cx)
9817 .text_anchor_for_position(rename.range.start, cx)?;
9818 let (end_buffer, end) = self
9819 .buffer
9820 .read(cx)
9821 .text_anchor_for_position(rename.range.end, cx)?;
9822 if start_buffer != end_buffer {
9823 return None;
9824 }
9825
9826 let buffer = start_buffer;
9827 let range = start..end;
9828 let old_name = rename.old_name;
9829 let new_name = rename.editor.read(cx).text(cx);
9830
9831 let rename = workspace
9832 .read(cx)
9833 .project()
9834 .clone()
9835 .update(cx, |project, cx| {
9836 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9837 });
9838 let workspace = workspace.downgrade();
9839
9840 Some(cx.spawn(|editor, mut cx| async move {
9841 let project_transaction = rename.await?;
9842 Self::open_project_transaction(
9843 &editor,
9844 workspace,
9845 project_transaction,
9846 format!("Rename: {} → {}", old_name, new_name),
9847 cx.clone(),
9848 )
9849 .await?;
9850
9851 editor.update(&mut cx, |editor, cx| {
9852 editor.refresh_document_highlights(cx);
9853 })?;
9854 Ok(())
9855 }))
9856 }
9857
9858 fn take_rename(
9859 &mut self,
9860 moving_cursor: bool,
9861 cx: &mut ViewContext<Self>,
9862 ) -> Option<RenameState> {
9863 let rename = self.pending_rename.take()?;
9864 if rename.editor.focus_handle(cx).is_focused(cx) {
9865 cx.focus(&self.focus_handle);
9866 }
9867
9868 self.remove_blocks(
9869 [rename.block_id].into_iter().collect(),
9870 Some(Autoscroll::fit()),
9871 cx,
9872 );
9873 self.clear_highlights::<Rename>(cx);
9874 self.show_local_selections = true;
9875
9876 if moving_cursor {
9877 let rename_editor = rename.editor.read(cx);
9878 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9879
9880 // Update the selection to match the position of the selection inside
9881 // the rename editor.
9882 let snapshot = self.buffer.read(cx).read(cx);
9883 let rename_range = rename.range.to_offset(&snapshot);
9884 let cursor_in_editor = snapshot
9885 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9886 .min(rename_range.end);
9887 drop(snapshot);
9888
9889 self.change_selections(None, cx, |s| {
9890 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9891 });
9892 } else {
9893 self.refresh_document_highlights(cx);
9894 }
9895
9896 Some(rename)
9897 }
9898
9899 pub fn pending_rename(&self) -> Option<&RenameState> {
9900 self.pending_rename.as_ref()
9901 }
9902
9903 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9904 let project = match &self.project {
9905 Some(project) => project.clone(),
9906 None => return None,
9907 };
9908
9909 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9910 }
9911
9912 fn perform_format(
9913 &mut self,
9914 project: Model<Project>,
9915 trigger: FormatTrigger,
9916 cx: &mut ViewContext<Self>,
9917 ) -> Task<Result<()>> {
9918 let buffer = self.buffer().clone();
9919 let mut buffers = buffer.read(cx).all_buffers();
9920 if trigger == FormatTrigger::Save {
9921 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9922 }
9923
9924 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9925 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9926
9927 cx.spawn(|_, mut cx| async move {
9928 let transaction = futures::select_biased! {
9929 () = timeout => {
9930 log::warn!("timed out waiting for formatting");
9931 None
9932 }
9933 transaction = format.log_err().fuse() => transaction,
9934 };
9935
9936 buffer
9937 .update(&mut cx, |buffer, cx| {
9938 if let Some(transaction) = transaction {
9939 if !buffer.is_singleton() {
9940 buffer.push_transaction(&transaction.0, cx);
9941 }
9942 }
9943
9944 cx.notify();
9945 })
9946 .ok();
9947
9948 Ok(())
9949 })
9950 }
9951
9952 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9953 if let Some(project) = self.project.clone() {
9954 self.buffer.update(cx, |multi_buffer, cx| {
9955 project.update(cx, |project, cx| {
9956 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9957 });
9958 })
9959 }
9960 }
9961
9962 fn cancel_language_server_work(
9963 &mut self,
9964 _: &CancelLanguageServerWork,
9965 cx: &mut ViewContext<Self>,
9966 ) {
9967 if let Some(project) = self.project.clone() {
9968 self.buffer.update(cx, |multi_buffer, cx| {
9969 project.update(cx, |project, cx| {
9970 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9971 });
9972 })
9973 }
9974 }
9975
9976 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9977 cx.show_character_palette();
9978 }
9979
9980 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9981 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9982 let buffer = self.buffer.read(cx).snapshot(cx);
9983 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9984 let is_valid = buffer
9985 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9986 .any(|entry| {
9987 entry.diagnostic.is_primary
9988 && !entry.range.is_empty()
9989 && entry.range.start == primary_range_start
9990 && entry.diagnostic.message == active_diagnostics.primary_message
9991 });
9992
9993 if is_valid != active_diagnostics.is_valid {
9994 active_diagnostics.is_valid = is_valid;
9995 let mut new_styles = HashMap::default();
9996 for (block_id, diagnostic) in &active_diagnostics.blocks {
9997 new_styles.insert(
9998 *block_id,
9999 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10000 );
10001 }
10002 self.display_map.update(cx, |display_map, _cx| {
10003 display_map.replace_blocks(new_styles)
10004 });
10005 }
10006 }
10007 }
10008
10009 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10010 self.dismiss_diagnostics(cx);
10011 let snapshot = self.snapshot(cx);
10012 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10013 let buffer = self.buffer.read(cx).snapshot(cx);
10014
10015 let mut primary_range = None;
10016 let mut primary_message = None;
10017 let mut group_end = Point::zero();
10018 let diagnostic_group = buffer
10019 .diagnostic_group::<MultiBufferPoint>(group_id)
10020 .filter_map(|entry| {
10021 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10022 && (entry.range.start.row == entry.range.end.row
10023 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10024 {
10025 return None;
10026 }
10027 if entry.range.end > group_end {
10028 group_end = entry.range.end;
10029 }
10030 if entry.diagnostic.is_primary {
10031 primary_range = Some(entry.range.clone());
10032 primary_message = Some(entry.diagnostic.message.clone());
10033 }
10034 Some(entry)
10035 })
10036 .collect::<Vec<_>>();
10037 let primary_range = primary_range?;
10038 let primary_message = primary_message?;
10039 let primary_range =
10040 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10041
10042 let blocks = display_map
10043 .insert_blocks(
10044 diagnostic_group.iter().map(|entry| {
10045 let diagnostic = entry.diagnostic.clone();
10046 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10047 BlockProperties {
10048 style: BlockStyle::Fixed,
10049 position: buffer.anchor_after(entry.range.start),
10050 height: message_height,
10051 render: diagnostic_block_renderer(diagnostic, None, true, true),
10052 disposition: BlockDisposition::Below,
10053 priority: 0,
10054 }
10055 }),
10056 cx,
10057 )
10058 .into_iter()
10059 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10060 .collect();
10061
10062 Some(ActiveDiagnosticGroup {
10063 primary_range,
10064 primary_message,
10065 group_id,
10066 blocks,
10067 is_valid: true,
10068 })
10069 });
10070 self.active_diagnostics.is_some()
10071 }
10072
10073 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10074 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10075 self.display_map.update(cx, |display_map, cx| {
10076 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10077 });
10078 cx.notify();
10079 }
10080 }
10081
10082 pub fn set_selections_from_remote(
10083 &mut self,
10084 selections: Vec<Selection<Anchor>>,
10085 pending_selection: Option<Selection<Anchor>>,
10086 cx: &mut ViewContext<Self>,
10087 ) {
10088 let old_cursor_position = self.selections.newest_anchor().head();
10089 self.selections.change_with(cx, |s| {
10090 s.select_anchors(selections);
10091 if let Some(pending_selection) = pending_selection {
10092 s.set_pending(pending_selection, SelectMode::Character);
10093 } else {
10094 s.clear_pending();
10095 }
10096 });
10097 self.selections_did_change(false, &old_cursor_position, true, cx);
10098 }
10099
10100 fn push_to_selection_history(&mut self) {
10101 self.selection_history.push(SelectionHistoryEntry {
10102 selections: self.selections.disjoint_anchors(),
10103 select_next_state: self.select_next_state.clone(),
10104 select_prev_state: self.select_prev_state.clone(),
10105 add_selections_state: self.add_selections_state.clone(),
10106 });
10107 }
10108
10109 pub fn transact(
10110 &mut self,
10111 cx: &mut ViewContext<Self>,
10112 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10113 ) -> Option<TransactionId> {
10114 self.start_transaction_at(Instant::now(), cx);
10115 update(self, cx);
10116 self.end_transaction_at(Instant::now(), cx)
10117 }
10118
10119 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10120 self.end_selection(cx);
10121 if let Some(tx_id) = self
10122 .buffer
10123 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10124 {
10125 self.selection_history
10126 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10127 cx.emit(EditorEvent::TransactionBegun {
10128 transaction_id: tx_id,
10129 })
10130 }
10131 }
10132
10133 fn end_transaction_at(
10134 &mut self,
10135 now: Instant,
10136 cx: &mut ViewContext<Self>,
10137 ) -> Option<TransactionId> {
10138 if let Some(transaction_id) = self
10139 .buffer
10140 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10141 {
10142 if let Some((_, end_selections)) =
10143 self.selection_history.transaction_mut(transaction_id)
10144 {
10145 *end_selections = Some(self.selections.disjoint_anchors());
10146 } else {
10147 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10148 }
10149
10150 cx.emit(EditorEvent::Edited { transaction_id });
10151 Some(transaction_id)
10152 } else {
10153 None
10154 }
10155 }
10156
10157 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10158 let mut fold_ranges = Vec::new();
10159
10160 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10161
10162 let selections = self.selections.all_adjusted(cx);
10163 for selection in selections {
10164 let range = selection.range().sorted();
10165 let buffer_start_row = range.start.row;
10166
10167 for row in (0..=range.end.row).rev() {
10168 if let Some((foldable_range, fold_text)) =
10169 display_map.foldable_range(MultiBufferRow(row))
10170 {
10171 if foldable_range.end.row >= buffer_start_row {
10172 fold_ranges.push((foldable_range, fold_text));
10173 if row <= range.start.row {
10174 break;
10175 }
10176 }
10177 }
10178 }
10179 }
10180
10181 self.fold_ranges(fold_ranges, true, cx);
10182 }
10183
10184 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10185 let buffer_row = fold_at.buffer_row;
10186 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10187
10188 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10189 let autoscroll = self
10190 .selections
10191 .all::<Point>(cx)
10192 .iter()
10193 .any(|selection| fold_range.overlaps(&selection.range()));
10194
10195 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10196 }
10197 }
10198
10199 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10200 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10201 let buffer = &display_map.buffer_snapshot;
10202 let selections = self.selections.all::<Point>(cx);
10203 let ranges = selections
10204 .iter()
10205 .map(|s| {
10206 let range = s.display_range(&display_map).sorted();
10207 let mut start = range.start.to_point(&display_map);
10208 let mut end = range.end.to_point(&display_map);
10209 start.column = 0;
10210 end.column = buffer.line_len(MultiBufferRow(end.row));
10211 start..end
10212 })
10213 .collect::<Vec<_>>();
10214
10215 self.unfold_ranges(ranges, true, true, cx);
10216 }
10217
10218 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10219 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10220
10221 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10222 ..Point::new(
10223 unfold_at.buffer_row.0,
10224 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10225 );
10226
10227 let autoscroll = self
10228 .selections
10229 .all::<Point>(cx)
10230 .iter()
10231 .any(|selection| selection.range().overlaps(&intersection_range));
10232
10233 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10234 }
10235
10236 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10237 let selections = self.selections.all::<Point>(cx);
10238 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10239 let line_mode = self.selections.line_mode;
10240 let ranges = selections.into_iter().map(|s| {
10241 if line_mode {
10242 let start = Point::new(s.start.row, 0);
10243 let end = Point::new(
10244 s.end.row,
10245 display_map
10246 .buffer_snapshot
10247 .line_len(MultiBufferRow(s.end.row)),
10248 );
10249 (start..end, display_map.fold_placeholder.clone())
10250 } else {
10251 (s.start..s.end, display_map.fold_placeholder.clone())
10252 }
10253 });
10254 self.fold_ranges(ranges, true, cx);
10255 }
10256
10257 pub fn fold_ranges<T: ToOffset + Clone>(
10258 &mut self,
10259 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10260 auto_scroll: bool,
10261 cx: &mut ViewContext<Self>,
10262 ) {
10263 let mut fold_ranges = Vec::new();
10264 let mut buffers_affected = HashMap::default();
10265 let multi_buffer = self.buffer().read(cx);
10266 for (fold_range, fold_text) in ranges {
10267 if let Some((_, buffer, _)) =
10268 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10269 {
10270 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10271 };
10272 fold_ranges.push((fold_range, fold_text));
10273 }
10274
10275 let mut ranges = fold_ranges.into_iter().peekable();
10276 if ranges.peek().is_some() {
10277 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10278
10279 if auto_scroll {
10280 self.request_autoscroll(Autoscroll::fit(), cx);
10281 }
10282
10283 for buffer in buffers_affected.into_values() {
10284 self.sync_expanded_diff_hunks(buffer, cx);
10285 }
10286
10287 cx.notify();
10288
10289 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10290 // Clear diagnostics block when folding a range that contains it.
10291 let snapshot = self.snapshot(cx);
10292 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10293 drop(snapshot);
10294 self.active_diagnostics = Some(active_diagnostics);
10295 self.dismiss_diagnostics(cx);
10296 } else {
10297 self.active_diagnostics = Some(active_diagnostics);
10298 }
10299 }
10300
10301 self.scrollbar_marker_state.dirty = true;
10302 }
10303 }
10304
10305 pub fn unfold_ranges<T: ToOffset + Clone>(
10306 &mut self,
10307 ranges: impl IntoIterator<Item = Range<T>>,
10308 inclusive: bool,
10309 auto_scroll: bool,
10310 cx: &mut ViewContext<Self>,
10311 ) {
10312 let mut unfold_ranges = Vec::new();
10313 let mut buffers_affected = HashMap::default();
10314 let multi_buffer = self.buffer().read(cx);
10315 for range in ranges {
10316 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10317 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10318 };
10319 unfold_ranges.push(range);
10320 }
10321
10322 let mut ranges = unfold_ranges.into_iter().peekable();
10323 if ranges.peek().is_some() {
10324 self.display_map
10325 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10326 if auto_scroll {
10327 self.request_autoscroll(Autoscroll::fit(), cx);
10328 }
10329
10330 for buffer in buffers_affected.into_values() {
10331 self.sync_expanded_diff_hunks(buffer, cx);
10332 }
10333
10334 cx.notify();
10335 self.scrollbar_marker_state.dirty = true;
10336 self.active_indent_guides_state.dirty = true;
10337 }
10338 }
10339
10340 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10341 if hovered != self.gutter_hovered {
10342 self.gutter_hovered = hovered;
10343 cx.notify();
10344 }
10345 }
10346
10347 pub fn insert_blocks(
10348 &mut self,
10349 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10350 autoscroll: Option<Autoscroll>,
10351 cx: &mut ViewContext<Self>,
10352 ) -> Vec<CustomBlockId> {
10353 let blocks = self
10354 .display_map
10355 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10356 if let Some(autoscroll) = autoscroll {
10357 self.request_autoscroll(autoscroll, cx);
10358 }
10359 cx.notify();
10360 blocks
10361 }
10362
10363 pub fn resize_blocks(
10364 &mut self,
10365 heights: HashMap<CustomBlockId, u32>,
10366 autoscroll: Option<Autoscroll>,
10367 cx: &mut ViewContext<Self>,
10368 ) {
10369 self.display_map
10370 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10371 if let Some(autoscroll) = autoscroll {
10372 self.request_autoscroll(autoscroll, cx);
10373 }
10374 cx.notify();
10375 }
10376
10377 pub fn replace_blocks(
10378 &mut self,
10379 renderers: HashMap<CustomBlockId, RenderBlock>,
10380 autoscroll: Option<Autoscroll>,
10381 cx: &mut ViewContext<Self>,
10382 ) {
10383 self.display_map
10384 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10385 if let Some(autoscroll) = autoscroll {
10386 self.request_autoscroll(autoscroll, cx);
10387 }
10388 cx.notify();
10389 }
10390
10391 pub fn remove_blocks(
10392 &mut self,
10393 block_ids: HashSet<CustomBlockId>,
10394 autoscroll: Option<Autoscroll>,
10395 cx: &mut ViewContext<Self>,
10396 ) {
10397 self.display_map.update(cx, |display_map, cx| {
10398 display_map.remove_blocks(block_ids, cx)
10399 });
10400 if let Some(autoscroll) = autoscroll {
10401 self.request_autoscroll(autoscroll, cx);
10402 }
10403 cx.notify();
10404 }
10405
10406 pub fn row_for_block(
10407 &self,
10408 block_id: CustomBlockId,
10409 cx: &mut ViewContext<Self>,
10410 ) -> Option<DisplayRow> {
10411 self.display_map
10412 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10413 }
10414
10415 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10416 self.focused_block = Some(focused_block);
10417 }
10418
10419 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10420 self.focused_block.take()
10421 }
10422
10423 pub fn insert_creases(
10424 &mut self,
10425 creases: impl IntoIterator<Item = Crease>,
10426 cx: &mut ViewContext<Self>,
10427 ) -> Vec<CreaseId> {
10428 self.display_map
10429 .update(cx, |map, cx| map.insert_creases(creases, cx))
10430 }
10431
10432 pub fn remove_creases(
10433 &mut self,
10434 ids: impl IntoIterator<Item = CreaseId>,
10435 cx: &mut ViewContext<Self>,
10436 ) {
10437 self.display_map
10438 .update(cx, |map, cx| map.remove_creases(ids, cx));
10439 }
10440
10441 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10442 self.display_map
10443 .update(cx, |map, cx| map.snapshot(cx))
10444 .longest_row()
10445 }
10446
10447 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10448 self.display_map
10449 .update(cx, |map, cx| map.snapshot(cx))
10450 .max_point()
10451 }
10452
10453 pub fn text(&self, cx: &AppContext) -> String {
10454 self.buffer.read(cx).read(cx).text()
10455 }
10456
10457 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10458 let text = self.text(cx);
10459 let text = text.trim();
10460
10461 if text.is_empty() {
10462 return None;
10463 }
10464
10465 Some(text.to_string())
10466 }
10467
10468 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10469 self.transact(cx, |this, cx| {
10470 this.buffer
10471 .read(cx)
10472 .as_singleton()
10473 .expect("you can only call set_text on editors for singleton buffers")
10474 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10475 });
10476 }
10477
10478 pub fn display_text(&self, cx: &mut AppContext) -> String {
10479 self.display_map
10480 .update(cx, |map, cx| map.snapshot(cx))
10481 .text()
10482 }
10483
10484 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10485 let mut wrap_guides = smallvec::smallvec![];
10486
10487 if self.show_wrap_guides == Some(false) {
10488 return wrap_guides;
10489 }
10490
10491 let settings = self.buffer.read(cx).settings_at(0, cx);
10492 if settings.show_wrap_guides {
10493 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10494 wrap_guides.push((soft_wrap as usize, true));
10495 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10496 wrap_guides.push((soft_wrap as usize, true));
10497 }
10498 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10499 }
10500
10501 wrap_guides
10502 }
10503
10504 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10505 let settings = self.buffer.read(cx).settings_at(0, cx);
10506 let mode = self
10507 .soft_wrap_mode_override
10508 .unwrap_or_else(|| settings.soft_wrap);
10509 match mode {
10510 language_settings::SoftWrap::None => SoftWrap::None,
10511 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10512 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10513 language_settings::SoftWrap::PreferredLineLength => {
10514 SoftWrap::Column(settings.preferred_line_length)
10515 }
10516 language_settings::SoftWrap::Bounded => {
10517 SoftWrap::Bounded(settings.preferred_line_length)
10518 }
10519 }
10520 }
10521
10522 pub fn set_soft_wrap_mode(
10523 &mut self,
10524 mode: language_settings::SoftWrap,
10525 cx: &mut ViewContext<Self>,
10526 ) {
10527 self.soft_wrap_mode_override = Some(mode);
10528 cx.notify();
10529 }
10530
10531 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10532 let rem_size = cx.rem_size();
10533 self.display_map.update(cx, |map, cx| {
10534 map.set_font(
10535 style.text.font(),
10536 style.text.font_size.to_pixels(rem_size),
10537 cx,
10538 )
10539 });
10540 self.style = Some(style);
10541 }
10542
10543 pub fn style(&self) -> Option<&EditorStyle> {
10544 self.style.as_ref()
10545 }
10546
10547 // Called by the element. This method is not designed to be called outside of the editor
10548 // element's layout code because it does not notify when rewrapping is computed synchronously.
10549 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10550 self.display_map
10551 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10552 }
10553
10554 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10555 if self.soft_wrap_mode_override.is_some() {
10556 self.soft_wrap_mode_override.take();
10557 } else {
10558 let soft_wrap = match self.soft_wrap_mode(cx) {
10559 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10560 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10561 language_settings::SoftWrap::PreferLine
10562 }
10563 };
10564 self.soft_wrap_mode_override = Some(soft_wrap);
10565 }
10566 cx.notify();
10567 }
10568
10569 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10570 let Some(workspace) = self.workspace() else {
10571 return;
10572 };
10573 let fs = workspace.read(cx).app_state().fs.clone();
10574 let current_show = TabBarSettings::get_global(cx).show;
10575 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10576 setting.show = Some(!current_show);
10577 });
10578 }
10579
10580 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10581 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10582 self.buffer
10583 .read(cx)
10584 .settings_at(0, cx)
10585 .indent_guides
10586 .enabled
10587 });
10588 self.show_indent_guides = Some(!currently_enabled);
10589 cx.notify();
10590 }
10591
10592 fn should_show_indent_guides(&self) -> Option<bool> {
10593 self.show_indent_guides
10594 }
10595
10596 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10597 let mut editor_settings = EditorSettings::get_global(cx).clone();
10598 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10599 EditorSettings::override_global(editor_settings, cx);
10600 }
10601
10602 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10603 self.show_gutter = show_gutter;
10604 cx.notify();
10605 }
10606
10607 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10608 self.show_line_numbers = Some(show_line_numbers);
10609 cx.notify();
10610 }
10611
10612 pub fn set_show_git_diff_gutter(
10613 &mut self,
10614 show_git_diff_gutter: bool,
10615 cx: &mut ViewContext<Self>,
10616 ) {
10617 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10618 cx.notify();
10619 }
10620
10621 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10622 self.show_code_actions = Some(show_code_actions);
10623 cx.notify();
10624 }
10625
10626 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10627 self.show_runnables = Some(show_runnables);
10628 cx.notify();
10629 }
10630
10631 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10632 if self.display_map.read(cx).masked != masked {
10633 self.display_map.update(cx, |map, _| map.masked = masked);
10634 }
10635 cx.notify()
10636 }
10637
10638 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10639 self.show_wrap_guides = Some(show_wrap_guides);
10640 cx.notify();
10641 }
10642
10643 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10644 self.show_indent_guides = Some(show_indent_guides);
10645 cx.notify();
10646 }
10647
10648 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10649 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10650 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10651 if let Some(dir) = file.abs_path(cx).parent() {
10652 return Some(dir.to_owned());
10653 }
10654 }
10655
10656 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10657 return Some(project_path.path.to_path_buf());
10658 }
10659 }
10660
10661 None
10662 }
10663
10664 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10665 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10666 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10667 cx.reveal_path(&file.abs_path(cx));
10668 }
10669 }
10670 }
10671
10672 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10673 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10674 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10675 if let Some(path) = file.abs_path(cx).to_str() {
10676 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10677 }
10678 }
10679 }
10680 }
10681
10682 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10683 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10684 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10685 if let Some(path) = file.path().to_str() {
10686 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10687 }
10688 }
10689 }
10690 }
10691
10692 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10693 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10694
10695 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10696 self.start_git_blame(true, cx);
10697 }
10698
10699 cx.notify();
10700 }
10701
10702 pub fn toggle_git_blame_inline(
10703 &mut self,
10704 _: &ToggleGitBlameInline,
10705 cx: &mut ViewContext<Self>,
10706 ) {
10707 self.toggle_git_blame_inline_internal(true, cx);
10708 cx.notify();
10709 }
10710
10711 pub fn git_blame_inline_enabled(&self) -> bool {
10712 self.git_blame_inline_enabled
10713 }
10714
10715 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10716 self.show_selection_menu = self
10717 .show_selection_menu
10718 .map(|show_selections_menu| !show_selections_menu)
10719 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10720
10721 cx.notify();
10722 }
10723
10724 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10725 self.show_selection_menu
10726 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10727 }
10728
10729 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10730 if let Some(project) = self.project.as_ref() {
10731 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10732 return;
10733 };
10734
10735 if buffer.read(cx).file().is_none() {
10736 return;
10737 }
10738
10739 let focused = self.focus_handle(cx).contains_focused(cx);
10740
10741 let project = project.clone();
10742 let blame =
10743 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10744 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10745 self.blame = Some(blame);
10746 }
10747 }
10748
10749 fn toggle_git_blame_inline_internal(
10750 &mut self,
10751 user_triggered: bool,
10752 cx: &mut ViewContext<Self>,
10753 ) {
10754 if self.git_blame_inline_enabled {
10755 self.git_blame_inline_enabled = false;
10756 self.show_git_blame_inline = false;
10757 self.show_git_blame_inline_delay_task.take();
10758 } else {
10759 self.git_blame_inline_enabled = true;
10760 self.start_git_blame_inline(user_triggered, cx);
10761 }
10762
10763 cx.notify();
10764 }
10765
10766 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10767 self.start_git_blame(user_triggered, cx);
10768
10769 if ProjectSettings::get_global(cx)
10770 .git
10771 .inline_blame_delay()
10772 .is_some()
10773 {
10774 self.start_inline_blame_timer(cx);
10775 } else {
10776 self.show_git_blame_inline = true
10777 }
10778 }
10779
10780 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10781 self.blame.as_ref()
10782 }
10783
10784 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10785 self.show_git_blame_gutter && self.has_blame_entries(cx)
10786 }
10787
10788 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10789 self.show_git_blame_inline
10790 && self.focus_handle.is_focused(cx)
10791 && !self.newest_selection_head_on_empty_line(cx)
10792 && self.has_blame_entries(cx)
10793 }
10794
10795 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10796 self.blame()
10797 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10798 }
10799
10800 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10801 let cursor_anchor = self.selections.newest_anchor().head();
10802
10803 let snapshot = self.buffer.read(cx).snapshot(cx);
10804 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10805
10806 snapshot.line_len(buffer_row) == 0
10807 }
10808
10809 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10810 let (path, selection, repo) = maybe!({
10811 let project_handle = self.project.as_ref()?.clone();
10812 let project = project_handle.read(cx);
10813
10814 let selection = self.selections.newest::<Point>(cx);
10815 let selection_range = selection.range();
10816
10817 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10818 (buffer, selection_range.start.row..selection_range.end.row)
10819 } else {
10820 let buffer_ranges = self
10821 .buffer()
10822 .read(cx)
10823 .range_to_buffer_ranges(selection_range, cx);
10824
10825 let (buffer, range, _) = if selection.reversed {
10826 buffer_ranges.first()
10827 } else {
10828 buffer_ranges.last()
10829 }?;
10830
10831 let snapshot = buffer.read(cx).snapshot();
10832 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10833 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10834 (buffer.clone(), selection)
10835 };
10836
10837 let path = buffer
10838 .read(cx)
10839 .file()?
10840 .as_local()?
10841 .path()
10842 .to_str()?
10843 .to_string();
10844 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10845 Some((path, selection, repo))
10846 })
10847 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10848
10849 const REMOTE_NAME: &str = "origin";
10850 let origin_url = repo
10851 .remote_url(REMOTE_NAME)
10852 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10853 let sha = repo
10854 .head_sha()
10855 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10856
10857 let (provider, remote) =
10858 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10859 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10860
10861 Ok(provider.build_permalink(
10862 remote,
10863 BuildPermalinkParams {
10864 sha: &sha,
10865 path: &path,
10866 selection: Some(selection),
10867 },
10868 ))
10869 }
10870
10871 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10872 let permalink = self.get_permalink_to_line(cx);
10873
10874 match permalink {
10875 Ok(permalink) => {
10876 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10877 }
10878 Err(err) => {
10879 let message = format!("Failed to copy permalink: {err}");
10880
10881 Err::<(), anyhow::Error>(err).log_err();
10882
10883 if let Some(workspace) = self.workspace() {
10884 workspace.update(cx, |workspace, cx| {
10885 struct CopyPermalinkToLine;
10886
10887 workspace.show_toast(
10888 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10889 cx,
10890 )
10891 })
10892 }
10893 }
10894 }
10895 }
10896
10897 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10898 let permalink = self.get_permalink_to_line(cx);
10899
10900 match permalink {
10901 Ok(permalink) => {
10902 cx.open_url(permalink.as_ref());
10903 }
10904 Err(err) => {
10905 let message = format!("Failed to open permalink: {err}");
10906
10907 Err::<(), anyhow::Error>(err).log_err();
10908
10909 if let Some(workspace) = self.workspace() {
10910 workspace.update(cx, |workspace, cx| {
10911 struct OpenPermalinkToLine;
10912
10913 workspace.show_toast(
10914 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10915 cx,
10916 )
10917 })
10918 }
10919 }
10920 }
10921 }
10922
10923 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10924 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10925 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10926 pub fn highlight_rows<T: 'static>(
10927 &mut self,
10928 rows: RangeInclusive<Anchor>,
10929 color: Option<Hsla>,
10930 should_autoscroll: bool,
10931 cx: &mut ViewContext<Self>,
10932 ) {
10933 let snapshot = self.buffer().read(cx).snapshot(cx);
10934 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10935 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10936 highlight
10937 .range
10938 .start()
10939 .cmp(&rows.start(), &snapshot)
10940 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10941 });
10942 match (color, existing_highlight_index) {
10943 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10944 ix,
10945 RowHighlight {
10946 index: post_inc(&mut self.highlight_order),
10947 range: rows,
10948 should_autoscroll,
10949 color,
10950 },
10951 ),
10952 (None, Ok(i)) => {
10953 row_highlights.remove(i);
10954 }
10955 }
10956 }
10957
10958 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10959 pub fn clear_row_highlights<T: 'static>(&mut self) {
10960 self.highlighted_rows.remove(&TypeId::of::<T>());
10961 }
10962
10963 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10964 pub fn highlighted_rows<T: 'static>(
10965 &self,
10966 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10967 Some(
10968 self.highlighted_rows
10969 .get(&TypeId::of::<T>())?
10970 .iter()
10971 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10972 )
10973 }
10974
10975 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10976 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10977 /// Allows to ignore certain kinds of highlights.
10978 pub fn highlighted_display_rows(
10979 &mut self,
10980 cx: &mut WindowContext,
10981 ) -> BTreeMap<DisplayRow, Hsla> {
10982 let snapshot = self.snapshot(cx);
10983 let mut used_highlight_orders = HashMap::default();
10984 self.highlighted_rows
10985 .iter()
10986 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10987 .fold(
10988 BTreeMap::<DisplayRow, Hsla>::new(),
10989 |mut unique_rows, highlight| {
10990 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10991 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10992 for row in start_row.0..=end_row.0 {
10993 let used_index =
10994 used_highlight_orders.entry(row).or_insert(highlight.index);
10995 if highlight.index >= *used_index {
10996 *used_index = highlight.index;
10997 match highlight.color {
10998 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10999 None => unique_rows.remove(&DisplayRow(row)),
11000 };
11001 }
11002 }
11003 unique_rows
11004 },
11005 )
11006 }
11007
11008 pub fn highlighted_display_row_for_autoscroll(
11009 &self,
11010 snapshot: &DisplaySnapshot,
11011 ) -> Option<DisplayRow> {
11012 self.highlighted_rows
11013 .values()
11014 .flat_map(|highlighted_rows| highlighted_rows.iter())
11015 .filter_map(|highlight| {
11016 if highlight.color.is_none() || !highlight.should_autoscroll {
11017 return None;
11018 }
11019 Some(highlight.range.start().to_display_point(&snapshot).row())
11020 })
11021 .min()
11022 }
11023
11024 pub fn set_search_within_ranges(
11025 &mut self,
11026 ranges: &[Range<Anchor>],
11027 cx: &mut ViewContext<Self>,
11028 ) {
11029 self.highlight_background::<SearchWithinRange>(
11030 ranges,
11031 |colors| colors.editor_document_highlight_read_background,
11032 cx,
11033 )
11034 }
11035
11036 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11037 self.breadcrumb_header = Some(new_header);
11038 }
11039
11040 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11041 self.clear_background_highlights::<SearchWithinRange>(cx);
11042 }
11043
11044 pub fn highlight_background<T: 'static>(
11045 &mut self,
11046 ranges: &[Range<Anchor>],
11047 color_fetcher: fn(&ThemeColors) -> Hsla,
11048 cx: &mut ViewContext<Self>,
11049 ) {
11050 self.background_highlights
11051 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11052 self.scrollbar_marker_state.dirty = true;
11053 cx.notify();
11054 }
11055
11056 pub fn clear_background_highlights<T: 'static>(
11057 &mut self,
11058 cx: &mut ViewContext<Self>,
11059 ) -> Option<BackgroundHighlight> {
11060 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11061 if !text_highlights.1.is_empty() {
11062 self.scrollbar_marker_state.dirty = true;
11063 cx.notify();
11064 }
11065 Some(text_highlights)
11066 }
11067
11068 pub fn highlight_gutter<T: 'static>(
11069 &mut self,
11070 ranges: &[Range<Anchor>],
11071 color_fetcher: fn(&AppContext) -> Hsla,
11072 cx: &mut ViewContext<Self>,
11073 ) {
11074 self.gutter_highlights
11075 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11076 cx.notify();
11077 }
11078
11079 pub fn clear_gutter_highlights<T: 'static>(
11080 &mut self,
11081 cx: &mut ViewContext<Self>,
11082 ) -> Option<GutterHighlight> {
11083 cx.notify();
11084 self.gutter_highlights.remove(&TypeId::of::<T>())
11085 }
11086
11087 #[cfg(feature = "test-support")]
11088 pub fn all_text_background_highlights(
11089 &mut self,
11090 cx: &mut ViewContext<Self>,
11091 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11092 let snapshot = self.snapshot(cx);
11093 let buffer = &snapshot.buffer_snapshot;
11094 let start = buffer.anchor_before(0);
11095 let end = buffer.anchor_after(buffer.len());
11096 let theme = cx.theme().colors();
11097 self.background_highlights_in_range(start..end, &snapshot, theme)
11098 }
11099
11100 #[cfg(feature = "test-support")]
11101 pub fn search_background_highlights(
11102 &mut self,
11103 cx: &mut ViewContext<Self>,
11104 ) -> Vec<Range<Point>> {
11105 let snapshot = self.buffer().read(cx).snapshot(cx);
11106
11107 let highlights = self
11108 .background_highlights
11109 .get(&TypeId::of::<items::BufferSearchHighlights>());
11110
11111 if let Some((_color, ranges)) = highlights {
11112 ranges
11113 .iter()
11114 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11115 .collect_vec()
11116 } else {
11117 vec![]
11118 }
11119 }
11120
11121 fn document_highlights_for_position<'a>(
11122 &'a self,
11123 position: Anchor,
11124 buffer: &'a MultiBufferSnapshot,
11125 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11126 let read_highlights = self
11127 .background_highlights
11128 .get(&TypeId::of::<DocumentHighlightRead>())
11129 .map(|h| &h.1);
11130 let write_highlights = self
11131 .background_highlights
11132 .get(&TypeId::of::<DocumentHighlightWrite>())
11133 .map(|h| &h.1);
11134 let left_position = position.bias_left(buffer);
11135 let right_position = position.bias_right(buffer);
11136 read_highlights
11137 .into_iter()
11138 .chain(write_highlights)
11139 .flat_map(move |ranges| {
11140 let start_ix = match ranges.binary_search_by(|probe| {
11141 let cmp = probe.end.cmp(&left_position, buffer);
11142 if cmp.is_ge() {
11143 Ordering::Greater
11144 } else {
11145 Ordering::Less
11146 }
11147 }) {
11148 Ok(i) | Err(i) => i,
11149 };
11150
11151 ranges[start_ix..]
11152 .iter()
11153 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11154 })
11155 }
11156
11157 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11158 self.background_highlights
11159 .get(&TypeId::of::<T>())
11160 .map_or(false, |(_, highlights)| !highlights.is_empty())
11161 }
11162
11163 pub fn background_highlights_in_range(
11164 &self,
11165 search_range: Range<Anchor>,
11166 display_snapshot: &DisplaySnapshot,
11167 theme: &ThemeColors,
11168 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11169 let mut results = Vec::new();
11170 for (color_fetcher, ranges) in self.background_highlights.values() {
11171 let color = color_fetcher(theme);
11172 let start_ix = match ranges.binary_search_by(|probe| {
11173 let cmp = probe
11174 .end
11175 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11176 if cmp.is_gt() {
11177 Ordering::Greater
11178 } else {
11179 Ordering::Less
11180 }
11181 }) {
11182 Ok(i) | Err(i) => i,
11183 };
11184 for range in &ranges[start_ix..] {
11185 if range
11186 .start
11187 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11188 .is_ge()
11189 {
11190 break;
11191 }
11192
11193 let start = range.start.to_display_point(&display_snapshot);
11194 let end = range.end.to_display_point(&display_snapshot);
11195 results.push((start..end, color))
11196 }
11197 }
11198 results
11199 }
11200
11201 pub fn background_highlight_row_ranges<T: 'static>(
11202 &self,
11203 search_range: Range<Anchor>,
11204 display_snapshot: &DisplaySnapshot,
11205 count: usize,
11206 ) -> Vec<RangeInclusive<DisplayPoint>> {
11207 let mut results = Vec::new();
11208 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11209 return vec![];
11210 };
11211
11212 let start_ix = match ranges.binary_search_by(|probe| {
11213 let cmp = probe
11214 .end
11215 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11216 if cmp.is_gt() {
11217 Ordering::Greater
11218 } else {
11219 Ordering::Less
11220 }
11221 }) {
11222 Ok(i) | Err(i) => i,
11223 };
11224 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11225 if let (Some(start_display), Some(end_display)) = (start, end) {
11226 results.push(
11227 start_display.to_display_point(display_snapshot)
11228 ..=end_display.to_display_point(display_snapshot),
11229 );
11230 }
11231 };
11232 let mut start_row: Option<Point> = None;
11233 let mut end_row: Option<Point> = None;
11234 if ranges.len() > count {
11235 return Vec::new();
11236 }
11237 for range in &ranges[start_ix..] {
11238 if range
11239 .start
11240 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11241 .is_ge()
11242 {
11243 break;
11244 }
11245 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11246 if let Some(current_row) = &end_row {
11247 if end.row == current_row.row {
11248 continue;
11249 }
11250 }
11251 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11252 if start_row.is_none() {
11253 assert_eq!(end_row, None);
11254 start_row = Some(start);
11255 end_row = Some(end);
11256 continue;
11257 }
11258 if let Some(current_end) = end_row.as_mut() {
11259 if start.row > current_end.row + 1 {
11260 push_region(start_row, end_row);
11261 start_row = Some(start);
11262 end_row = Some(end);
11263 } else {
11264 // Merge two hunks.
11265 *current_end = end;
11266 }
11267 } else {
11268 unreachable!();
11269 }
11270 }
11271 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11272 push_region(start_row, end_row);
11273 results
11274 }
11275
11276 pub fn gutter_highlights_in_range(
11277 &self,
11278 search_range: Range<Anchor>,
11279 display_snapshot: &DisplaySnapshot,
11280 cx: &AppContext,
11281 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11282 let mut results = Vec::new();
11283 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11284 let color = color_fetcher(cx);
11285 let start_ix = match ranges.binary_search_by(|probe| {
11286 let cmp = probe
11287 .end
11288 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11289 if cmp.is_gt() {
11290 Ordering::Greater
11291 } else {
11292 Ordering::Less
11293 }
11294 }) {
11295 Ok(i) | Err(i) => i,
11296 };
11297 for range in &ranges[start_ix..] {
11298 if range
11299 .start
11300 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11301 .is_ge()
11302 {
11303 break;
11304 }
11305
11306 let start = range.start.to_display_point(&display_snapshot);
11307 let end = range.end.to_display_point(&display_snapshot);
11308 results.push((start..end, color))
11309 }
11310 }
11311 results
11312 }
11313
11314 /// Get the text ranges corresponding to the redaction query
11315 pub fn redacted_ranges(
11316 &self,
11317 search_range: Range<Anchor>,
11318 display_snapshot: &DisplaySnapshot,
11319 cx: &WindowContext,
11320 ) -> Vec<Range<DisplayPoint>> {
11321 display_snapshot
11322 .buffer_snapshot
11323 .redacted_ranges(search_range, |file| {
11324 if let Some(file) = file {
11325 file.is_private()
11326 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11327 } else {
11328 false
11329 }
11330 })
11331 .map(|range| {
11332 range.start.to_display_point(display_snapshot)
11333 ..range.end.to_display_point(display_snapshot)
11334 })
11335 .collect()
11336 }
11337
11338 pub fn highlight_text<T: 'static>(
11339 &mut self,
11340 ranges: Vec<Range<Anchor>>,
11341 style: HighlightStyle,
11342 cx: &mut ViewContext<Self>,
11343 ) {
11344 self.display_map.update(cx, |map, _| {
11345 map.highlight_text(TypeId::of::<T>(), ranges, style)
11346 });
11347 cx.notify();
11348 }
11349
11350 pub(crate) fn highlight_inlays<T: 'static>(
11351 &mut self,
11352 highlights: Vec<InlayHighlight>,
11353 style: HighlightStyle,
11354 cx: &mut ViewContext<Self>,
11355 ) {
11356 self.display_map.update(cx, |map, _| {
11357 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11358 });
11359 cx.notify();
11360 }
11361
11362 pub fn text_highlights<'a, T: 'static>(
11363 &'a self,
11364 cx: &'a AppContext,
11365 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11366 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11367 }
11368
11369 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11370 let cleared = self
11371 .display_map
11372 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11373 if cleared {
11374 cx.notify();
11375 }
11376 }
11377
11378 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11379 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11380 && self.focus_handle.is_focused(cx)
11381 }
11382
11383 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11384 self.show_cursor_when_unfocused = is_enabled;
11385 cx.notify();
11386 }
11387
11388 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11389 cx.notify();
11390 }
11391
11392 fn on_buffer_event(
11393 &mut self,
11394 multibuffer: Model<MultiBuffer>,
11395 event: &multi_buffer::Event,
11396 cx: &mut ViewContext<Self>,
11397 ) {
11398 match event {
11399 multi_buffer::Event::Edited {
11400 singleton_buffer_edited,
11401 } => {
11402 self.scrollbar_marker_state.dirty = true;
11403 self.active_indent_guides_state.dirty = true;
11404 self.refresh_active_diagnostics(cx);
11405 self.refresh_code_actions(cx);
11406 if self.has_active_inline_completion(cx) {
11407 self.update_visible_inline_completion(cx);
11408 }
11409 cx.emit(EditorEvent::BufferEdited);
11410 cx.emit(SearchEvent::MatchesInvalidated);
11411 if *singleton_buffer_edited {
11412 if let Some(project) = &self.project {
11413 let project = project.read(cx);
11414 #[allow(clippy::mutable_key_type)]
11415 let languages_affected = multibuffer
11416 .read(cx)
11417 .all_buffers()
11418 .into_iter()
11419 .filter_map(|buffer| {
11420 let buffer = buffer.read(cx);
11421 let language = buffer.language()?;
11422 if project.is_local()
11423 && project.language_servers_for_buffer(buffer, cx).count() == 0
11424 {
11425 None
11426 } else {
11427 Some(language)
11428 }
11429 })
11430 .cloned()
11431 .collect::<HashSet<_>>();
11432 if !languages_affected.is_empty() {
11433 self.refresh_inlay_hints(
11434 InlayHintRefreshReason::BufferEdited(languages_affected),
11435 cx,
11436 );
11437 }
11438 }
11439 }
11440
11441 let Some(project) = &self.project else { return };
11442 let telemetry = project.read(cx).client().telemetry().clone();
11443 refresh_linked_ranges(self, cx);
11444 telemetry.log_edit_event("editor");
11445 }
11446 multi_buffer::Event::ExcerptsAdded {
11447 buffer,
11448 predecessor,
11449 excerpts,
11450 } => {
11451 self.tasks_update_task = Some(self.refresh_runnables(cx));
11452 cx.emit(EditorEvent::ExcerptsAdded {
11453 buffer: buffer.clone(),
11454 predecessor: *predecessor,
11455 excerpts: excerpts.clone(),
11456 });
11457 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11458 }
11459 multi_buffer::Event::ExcerptsRemoved { ids } => {
11460 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11461 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11462 }
11463 multi_buffer::Event::ExcerptsEdited { ids } => {
11464 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11465 }
11466 multi_buffer::Event::ExcerptsExpanded { ids } => {
11467 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11468 }
11469 multi_buffer::Event::Reparsed(buffer_id) => {
11470 self.tasks_update_task = Some(self.refresh_runnables(cx));
11471
11472 cx.emit(EditorEvent::Reparsed(*buffer_id));
11473 }
11474 multi_buffer::Event::LanguageChanged(buffer_id) => {
11475 linked_editing_ranges::refresh_linked_ranges(self, cx);
11476 cx.emit(EditorEvent::Reparsed(*buffer_id));
11477 cx.notify();
11478 }
11479 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11480 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11481 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11482 cx.emit(EditorEvent::TitleChanged)
11483 }
11484 multi_buffer::Event::DiffBaseChanged => {
11485 self.scrollbar_marker_state.dirty = true;
11486 cx.emit(EditorEvent::DiffBaseChanged);
11487 cx.notify();
11488 }
11489 multi_buffer::Event::DiffUpdated { buffer } => {
11490 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11491 cx.notify();
11492 }
11493 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11494 multi_buffer::Event::DiagnosticsUpdated => {
11495 self.refresh_active_diagnostics(cx);
11496 self.scrollbar_marker_state.dirty = true;
11497 cx.notify();
11498 }
11499 _ => {}
11500 };
11501 }
11502
11503 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11504 cx.notify();
11505 }
11506
11507 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11508 self.tasks_update_task = Some(self.refresh_runnables(cx));
11509 self.refresh_inline_completion(true, false, cx);
11510 self.refresh_inlay_hints(
11511 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11512 self.selections.newest_anchor().head(),
11513 &self.buffer.read(cx).snapshot(cx),
11514 cx,
11515 )),
11516 cx,
11517 );
11518 let editor_settings = EditorSettings::get_global(cx);
11519 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11520 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11521
11522 let project_settings = ProjectSettings::get_global(cx);
11523 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11524
11525 if self.mode == EditorMode::Full {
11526 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11527 if self.git_blame_inline_enabled != inline_blame_enabled {
11528 self.toggle_git_blame_inline_internal(false, cx);
11529 }
11530 }
11531
11532 cx.notify();
11533 }
11534
11535 pub fn set_searchable(&mut self, searchable: bool) {
11536 self.searchable = searchable;
11537 }
11538
11539 pub fn searchable(&self) -> bool {
11540 self.searchable
11541 }
11542
11543 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11544 self.open_excerpts_common(true, cx)
11545 }
11546
11547 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11548 self.open_excerpts_common(false, cx)
11549 }
11550
11551 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11552 let buffer = self.buffer.read(cx);
11553 if buffer.is_singleton() {
11554 cx.propagate();
11555 return;
11556 }
11557
11558 let Some(workspace) = self.workspace() else {
11559 cx.propagate();
11560 return;
11561 };
11562
11563 let mut new_selections_by_buffer = HashMap::default();
11564 for selection in self.selections.all::<usize>(cx) {
11565 for (buffer, mut range, _) in
11566 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11567 {
11568 if selection.reversed {
11569 mem::swap(&mut range.start, &mut range.end);
11570 }
11571 new_selections_by_buffer
11572 .entry(buffer)
11573 .or_insert(Vec::new())
11574 .push(range)
11575 }
11576 }
11577
11578 // We defer the pane interaction because we ourselves are a workspace item
11579 // and activating a new item causes the pane to call a method on us reentrantly,
11580 // which panics if we're on the stack.
11581 cx.window_context().defer(move |cx| {
11582 workspace.update(cx, |workspace, cx| {
11583 let pane = if split {
11584 workspace.adjacent_pane(cx)
11585 } else {
11586 workspace.active_pane().clone()
11587 };
11588
11589 for (buffer, ranges) in new_selections_by_buffer {
11590 let editor =
11591 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11592 editor.update(cx, |editor, cx| {
11593 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11594 s.select_ranges(ranges);
11595 });
11596 });
11597 }
11598 })
11599 });
11600 }
11601
11602 fn jump(
11603 &mut self,
11604 path: ProjectPath,
11605 position: Point,
11606 anchor: language::Anchor,
11607 offset_from_top: u32,
11608 cx: &mut ViewContext<Self>,
11609 ) {
11610 let workspace = self.workspace();
11611 cx.spawn(|_, mut cx| async move {
11612 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11613 let editor = workspace.update(&mut cx, |workspace, cx| {
11614 // Reset the preview item id before opening the new item
11615 workspace.active_pane().update(cx, |pane, cx| {
11616 pane.set_preview_item_id(None, cx);
11617 });
11618 workspace.open_path_preview(path, None, true, true, cx)
11619 })?;
11620 let editor = editor
11621 .await?
11622 .downcast::<Editor>()
11623 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11624 .downgrade();
11625 editor.update(&mut cx, |editor, cx| {
11626 let buffer = editor
11627 .buffer()
11628 .read(cx)
11629 .as_singleton()
11630 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11631 let buffer = buffer.read(cx);
11632 let cursor = if buffer.can_resolve(&anchor) {
11633 language::ToPoint::to_point(&anchor, buffer)
11634 } else {
11635 buffer.clip_point(position, Bias::Left)
11636 };
11637
11638 let nav_history = editor.nav_history.take();
11639 editor.change_selections(
11640 Some(Autoscroll::top_relative(offset_from_top as usize)),
11641 cx,
11642 |s| {
11643 s.select_ranges([cursor..cursor]);
11644 },
11645 );
11646 editor.nav_history = nav_history;
11647
11648 anyhow::Ok(())
11649 })??;
11650
11651 anyhow::Ok(())
11652 })
11653 .detach_and_log_err(cx);
11654 }
11655
11656 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11657 let snapshot = self.buffer.read(cx).read(cx);
11658 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11659 Some(
11660 ranges
11661 .iter()
11662 .map(move |range| {
11663 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11664 })
11665 .collect(),
11666 )
11667 }
11668
11669 fn selection_replacement_ranges(
11670 &self,
11671 range: Range<OffsetUtf16>,
11672 cx: &AppContext,
11673 ) -> Vec<Range<OffsetUtf16>> {
11674 let selections = self.selections.all::<OffsetUtf16>(cx);
11675 let newest_selection = selections
11676 .iter()
11677 .max_by_key(|selection| selection.id)
11678 .unwrap();
11679 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11680 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11681 let snapshot = self.buffer.read(cx).read(cx);
11682 selections
11683 .into_iter()
11684 .map(|mut selection| {
11685 selection.start.0 =
11686 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11687 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11688 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11689 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11690 })
11691 .collect()
11692 }
11693
11694 fn report_editor_event(
11695 &self,
11696 operation: &'static str,
11697 file_extension: Option<String>,
11698 cx: &AppContext,
11699 ) {
11700 if cfg!(any(test, feature = "test-support")) {
11701 return;
11702 }
11703
11704 let Some(project) = &self.project else { return };
11705
11706 // If None, we are in a file without an extension
11707 let file = self
11708 .buffer
11709 .read(cx)
11710 .as_singleton()
11711 .and_then(|b| b.read(cx).file());
11712 let file_extension = file_extension.or(file
11713 .as_ref()
11714 .and_then(|file| Path::new(file.file_name(cx)).extension())
11715 .and_then(|e| e.to_str())
11716 .map(|a| a.to_string()));
11717
11718 let vim_mode = cx
11719 .global::<SettingsStore>()
11720 .raw_user_settings()
11721 .get("vim_mode")
11722 == Some(&serde_json::Value::Bool(true));
11723
11724 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11725 == language::language_settings::InlineCompletionProvider::Copilot;
11726 let copilot_enabled_for_language = self
11727 .buffer
11728 .read(cx)
11729 .settings_at(0, cx)
11730 .show_inline_completions;
11731
11732 let telemetry = project.read(cx).client().telemetry().clone();
11733 telemetry.report_editor_event(
11734 file_extension,
11735 vim_mode,
11736 operation,
11737 copilot_enabled,
11738 copilot_enabled_for_language,
11739 )
11740 }
11741
11742 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11743 /// with each line being an array of {text, highlight} objects.
11744 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11745 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11746 return;
11747 };
11748
11749 #[derive(Serialize)]
11750 struct Chunk<'a> {
11751 text: String,
11752 highlight: Option<&'a str>,
11753 }
11754
11755 let snapshot = buffer.read(cx).snapshot();
11756 let range = self
11757 .selected_text_range(cx)
11758 .and_then(|selected_range| {
11759 if selected_range.is_empty() {
11760 None
11761 } else {
11762 Some(selected_range)
11763 }
11764 })
11765 .unwrap_or_else(|| 0..snapshot.len());
11766
11767 let chunks = snapshot.chunks(range, true);
11768 let mut lines = Vec::new();
11769 let mut line: VecDeque<Chunk> = VecDeque::new();
11770
11771 let Some(style) = self.style.as_ref() else {
11772 return;
11773 };
11774
11775 for chunk in chunks {
11776 let highlight = chunk
11777 .syntax_highlight_id
11778 .and_then(|id| id.name(&style.syntax));
11779 let mut chunk_lines = chunk.text.split('\n').peekable();
11780 while let Some(text) = chunk_lines.next() {
11781 let mut merged_with_last_token = false;
11782 if let Some(last_token) = line.back_mut() {
11783 if last_token.highlight == highlight {
11784 last_token.text.push_str(text);
11785 merged_with_last_token = true;
11786 }
11787 }
11788
11789 if !merged_with_last_token {
11790 line.push_back(Chunk {
11791 text: text.into(),
11792 highlight,
11793 });
11794 }
11795
11796 if chunk_lines.peek().is_some() {
11797 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11798 line.pop_front();
11799 }
11800 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11801 line.pop_back();
11802 }
11803
11804 lines.push(mem::take(&mut line));
11805 }
11806 }
11807 }
11808
11809 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11810 return;
11811 };
11812 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11813 }
11814
11815 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11816 &self.inlay_hint_cache
11817 }
11818
11819 pub fn replay_insert_event(
11820 &mut self,
11821 text: &str,
11822 relative_utf16_range: Option<Range<isize>>,
11823 cx: &mut ViewContext<Self>,
11824 ) {
11825 if !self.input_enabled {
11826 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11827 return;
11828 }
11829 if let Some(relative_utf16_range) = relative_utf16_range {
11830 let selections = self.selections.all::<OffsetUtf16>(cx);
11831 self.change_selections(None, cx, |s| {
11832 let new_ranges = selections.into_iter().map(|range| {
11833 let start = OffsetUtf16(
11834 range
11835 .head()
11836 .0
11837 .saturating_add_signed(relative_utf16_range.start),
11838 );
11839 let end = OffsetUtf16(
11840 range
11841 .head()
11842 .0
11843 .saturating_add_signed(relative_utf16_range.end),
11844 );
11845 start..end
11846 });
11847 s.select_ranges(new_ranges);
11848 });
11849 }
11850
11851 self.handle_input(text, cx);
11852 }
11853
11854 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11855 let Some(project) = self.project.as_ref() else {
11856 return false;
11857 };
11858 let project = project.read(cx);
11859
11860 let mut supports = false;
11861 self.buffer().read(cx).for_each_buffer(|buffer| {
11862 if !supports {
11863 supports = project
11864 .language_servers_for_buffer(buffer.read(cx), cx)
11865 .any(
11866 |(_, server)| match server.capabilities().inlay_hint_provider {
11867 Some(lsp::OneOf::Left(enabled)) => enabled,
11868 Some(lsp::OneOf::Right(_)) => true,
11869 None => false,
11870 },
11871 )
11872 }
11873 });
11874 supports
11875 }
11876
11877 pub fn focus(&self, cx: &mut WindowContext) {
11878 cx.focus(&self.focus_handle)
11879 }
11880
11881 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11882 self.focus_handle.is_focused(cx)
11883 }
11884
11885 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11886 cx.emit(EditorEvent::Focused);
11887
11888 if let Some(descendant) = self
11889 .last_focused_descendant
11890 .take()
11891 .and_then(|descendant| descendant.upgrade())
11892 {
11893 cx.focus(&descendant);
11894 } else {
11895 if let Some(blame) = self.blame.as_ref() {
11896 blame.update(cx, GitBlame::focus)
11897 }
11898
11899 self.blink_manager.update(cx, BlinkManager::enable);
11900 self.show_cursor_names(cx);
11901 self.buffer.update(cx, |buffer, cx| {
11902 buffer.finalize_last_transaction(cx);
11903 if self.leader_peer_id.is_none() {
11904 buffer.set_active_selections(
11905 &self.selections.disjoint_anchors(),
11906 self.selections.line_mode,
11907 self.cursor_shape,
11908 cx,
11909 );
11910 }
11911 });
11912 }
11913 }
11914
11915 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11916 cx.emit(EditorEvent::FocusedIn)
11917 }
11918
11919 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11920 if event.blurred != self.focus_handle {
11921 self.last_focused_descendant = Some(event.blurred);
11922 }
11923 }
11924
11925 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11926 self.blink_manager.update(cx, BlinkManager::disable);
11927 self.buffer
11928 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11929
11930 if let Some(blame) = self.blame.as_ref() {
11931 blame.update(cx, GitBlame::blur)
11932 }
11933 if !self.hover_state.focused(cx) {
11934 hide_hover(self, cx);
11935 }
11936
11937 self.hide_context_menu(cx);
11938 cx.emit(EditorEvent::Blurred);
11939 cx.notify();
11940 }
11941
11942 pub fn register_action<A: Action>(
11943 &mut self,
11944 listener: impl Fn(&A, &mut WindowContext) + 'static,
11945 ) -> Subscription {
11946 let id = self.next_editor_action_id.post_inc();
11947 let listener = Arc::new(listener);
11948 self.editor_actions.borrow_mut().insert(
11949 id,
11950 Box::new(move |cx| {
11951 let cx = cx.window_context();
11952 let listener = listener.clone();
11953 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11954 let action = action.downcast_ref().unwrap();
11955 if phase == DispatchPhase::Bubble {
11956 listener(action, cx)
11957 }
11958 })
11959 }),
11960 );
11961
11962 let editor_actions = self.editor_actions.clone();
11963 Subscription::new(move || {
11964 editor_actions.borrow_mut().remove(&id);
11965 })
11966 }
11967
11968 pub fn file_header_size(&self) -> u32 {
11969 self.file_header_size
11970 }
11971
11972 pub fn revert(
11973 &mut self,
11974 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11975 cx: &mut ViewContext<Self>,
11976 ) {
11977 self.buffer().update(cx, |multi_buffer, cx| {
11978 for (buffer_id, changes) in revert_changes {
11979 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11980 buffer.update(cx, |buffer, cx| {
11981 buffer.edit(
11982 changes.into_iter().map(|(range, text)| {
11983 (range, text.to_string().map(Arc::<str>::from))
11984 }),
11985 None,
11986 cx,
11987 );
11988 });
11989 }
11990 }
11991 });
11992 self.change_selections(None, cx, |selections| selections.refresh());
11993 }
11994
11995 pub fn to_pixel_point(
11996 &mut self,
11997 source: multi_buffer::Anchor,
11998 editor_snapshot: &EditorSnapshot,
11999 cx: &mut ViewContext<Self>,
12000 ) -> Option<gpui::Point<Pixels>> {
12001 let source_point = source.to_display_point(editor_snapshot);
12002 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12003 }
12004
12005 pub fn display_to_pixel_point(
12006 &mut self,
12007 source: DisplayPoint,
12008 editor_snapshot: &EditorSnapshot,
12009 cx: &mut ViewContext<Self>,
12010 ) -> Option<gpui::Point<Pixels>> {
12011 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12012 let text_layout_details = self.text_layout_details(cx);
12013 let scroll_top = text_layout_details
12014 .scroll_anchor
12015 .scroll_position(editor_snapshot)
12016 .y;
12017
12018 if source.row().as_f32() < scroll_top.floor() {
12019 return None;
12020 }
12021 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12022 let source_y = line_height * (source.row().as_f32() - scroll_top);
12023 Some(gpui::Point::new(source_x, source_y))
12024 }
12025
12026 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12027 let bounds = self.last_bounds?;
12028 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12029 }
12030
12031 pub fn has_active_completions_menu(&self) -> bool {
12032 self.context_menu.read().as_ref().map_or(false, |menu| {
12033 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12034 })
12035 }
12036
12037 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12038 self.addons
12039 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12040 }
12041
12042 pub fn unregister_addon<T: Addon>(&mut self) {
12043 self.addons.remove(&std::any::TypeId::of::<T>());
12044 }
12045
12046 pub fn addon<T: Addon>(&self) -> Option<&T> {
12047 let type_id = std::any::TypeId::of::<T>();
12048 self.addons
12049 .get(&type_id)
12050 .and_then(|item| item.to_any().downcast_ref::<T>())
12051 }
12052}
12053
12054fn hunks_for_selections(
12055 multi_buffer_snapshot: &MultiBufferSnapshot,
12056 selections: &[Selection<Anchor>],
12057) -> Vec<DiffHunk<MultiBufferRow>> {
12058 let buffer_rows_for_selections = selections.iter().map(|selection| {
12059 let head = selection.head();
12060 let tail = selection.tail();
12061 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12062 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12063 if start > end {
12064 end..start
12065 } else {
12066 start..end
12067 }
12068 });
12069
12070 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12071}
12072
12073pub fn hunks_for_rows(
12074 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12075 multi_buffer_snapshot: &MultiBufferSnapshot,
12076) -> Vec<DiffHunk<MultiBufferRow>> {
12077 let mut hunks = Vec::new();
12078 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12079 HashMap::default();
12080 for selected_multi_buffer_rows in rows {
12081 let query_rows =
12082 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12083 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12084 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12085 // when the caret is just above or just below the deleted hunk.
12086 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12087 let related_to_selection = if allow_adjacent {
12088 hunk.associated_range.overlaps(&query_rows)
12089 || hunk.associated_range.start == query_rows.end
12090 || hunk.associated_range.end == query_rows.start
12091 } else {
12092 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12093 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12094 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12095 || selected_multi_buffer_rows.end == hunk.associated_range.start
12096 };
12097 if related_to_selection {
12098 if !processed_buffer_rows
12099 .entry(hunk.buffer_id)
12100 .or_default()
12101 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12102 {
12103 continue;
12104 }
12105 hunks.push(hunk);
12106 }
12107 }
12108 }
12109
12110 hunks
12111}
12112
12113pub trait CollaborationHub {
12114 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12115 fn user_participant_indices<'a>(
12116 &self,
12117 cx: &'a AppContext,
12118 ) -> &'a HashMap<u64, ParticipantIndex>;
12119 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12120}
12121
12122impl CollaborationHub for Model<Project> {
12123 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12124 self.read(cx).collaborators()
12125 }
12126
12127 fn user_participant_indices<'a>(
12128 &self,
12129 cx: &'a AppContext,
12130 ) -> &'a HashMap<u64, ParticipantIndex> {
12131 self.read(cx).user_store().read(cx).participant_indices()
12132 }
12133
12134 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12135 let this = self.read(cx);
12136 let user_ids = this.collaborators().values().map(|c| c.user_id);
12137 this.user_store().read_with(cx, |user_store, cx| {
12138 user_store.participant_names(user_ids, cx)
12139 })
12140 }
12141}
12142
12143pub trait CompletionProvider {
12144 fn completions(
12145 &self,
12146 buffer: &Model<Buffer>,
12147 buffer_position: text::Anchor,
12148 trigger: CompletionContext,
12149 cx: &mut ViewContext<Editor>,
12150 ) -> Task<Result<Vec<Completion>>>;
12151
12152 fn resolve_completions(
12153 &self,
12154 buffer: Model<Buffer>,
12155 completion_indices: Vec<usize>,
12156 completions: Arc<RwLock<Box<[Completion]>>>,
12157 cx: &mut ViewContext<Editor>,
12158 ) -> Task<Result<bool>>;
12159
12160 fn apply_additional_edits_for_completion(
12161 &self,
12162 buffer: Model<Buffer>,
12163 completion: Completion,
12164 push_to_history: bool,
12165 cx: &mut ViewContext<Editor>,
12166 ) -> Task<Result<Option<language::Transaction>>>;
12167
12168 fn is_completion_trigger(
12169 &self,
12170 buffer: &Model<Buffer>,
12171 position: language::Anchor,
12172 text: &str,
12173 trigger_in_words: bool,
12174 cx: &mut ViewContext<Editor>,
12175 ) -> bool;
12176
12177 fn sort_completions(&self) -> bool {
12178 true
12179 }
12180}
12181
12182fn snippet_completions(
12183 project: &Project,
12184 buffer: &Model<Buffer>,
12185 buffer_position: text::Anchor,
12186 cx: &mut AppContext,
12187) -> Vec<Completion> {
12188 let language = buffer.read(cx).language_at(buffer_position);
12189 let language_name = language.as_ref().map(|language| language.lsp_id());
12190 let snippet_store = project.snippets().read(cx);
12191 let snippets = snippet_store.snippets_for(language_name, cx);
12192
12193 if snippets.is_empty() {
12194 return vec![];
12195 }
12196 let snapshot = buffer.read(cx).text_snapshot();
12197 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12198
12199 let mut lines = chunks.lines();
12200 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12201 return vec![];
12202 };
12203
12204 let scope = language.map(|language| language.default_scope());
12205 let mut last_word = line_at
12206 .chars()
12207 .rev()
12208 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12209 .collect::<String>();
12210 last_word = last_word.chars().rev().collect();
12211 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12212 let to_lsp = |point: &text::Anchor| {
12213 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12214 point_to_lsp(end)
12215 };
12216 let lsp_end = to_lsp(&buffer_position);
12217 snippets
12218 .into_iter()
12219 .filter_map(|snippet| {
12220 let matching_prefix = snippet
12221 .prefix
12222 .iter()
12223 .find(|prefix| prefix.starts_with(&last_word))?;
12224 let start = as_offset - last_word.len();
12225 let start = snapshot.anchor_before(start);
12226 let range = start..buffer_position;
12227 let lsp_start = to_lsp(&start);
12228 let lsp_range = lsp::Range {
12229 start: lsp_start,
12230 end: lsp_end,
12231 };
12232 Some(Completion {
12233 old_range: range,
12234 new_text: snippet.body.clone(),
12235 label: CodeLabel {
12236 text: matching_prefix.clone(),
12237 runs: vec![],
12238 filter_range: 0..matching_prefix.len(),
12239 },
12240 server_id: LanguageServerId(usize::MAX),
12241 documentation: snippet
12242 .description
12243 .clone()
12244 .map(|description| Documentation::SingleLine(description)),
12245 lsp_completion: lsp::CompletionItem {
12246 label: snippet.prefix.first().unwrap().clone(),
12247 kind: Some(CompletionItemKind::SNIPPET),
12248 label_details: snippet.description.as_ref().map(|description| {
12249 lsp::CompletionItemLabelDetails {
12250 detail: Some(description.clone()),
12251 description: None,
12252 }
12253 }),
12254 insert_text_format: Some(InsertTextFormat::SNIPPET),
12255 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12256 lsp::InsertReplaceEdit {
12257 new_text: snippet.body.clone(),
12258 insert: lsp_range,
12259 replace: lsp_range,
12260 },
12261 )),
12262 filter_text: Some(snippet.body.clone()),
12263 sort_text: Some(char::MAX.to_string()),
12264 ..Default::default()
12265 },
12266 confirm: None,
12267 })
12268 })
12269 .collect()
12270}
12271
12272impl CompletionProvider for Model<Project> {
12273 fn completions(
12274 &self,
12275 buffer: &Model<Buffer>,
12276 buffer_position: text::Anchor,
12277 options: CompletionContext,
12278 cx: &mut ViewContext<Editor>,
12279 ) -> Task<Result<Vec<Completion>>> {
12280 self.update(cx, |project, cx| {
12281 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12282 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12283 cx.background_executor().spawn(async move {
12284 let mut completions = project_completions.await?;
12285 //let snippets = snippets.into_iter().;
12286 completions.extend(snippets);
12287 Ok(completions)
12288 })
12289 })
12290 }
12291
12292 fn resolve_completions(
12293 &self,
12294 buffer: Model<Buffer>,
12295 completion_indices: Vec<usize>,
12296 completions: Arc<RwLock<Box<[Completion]>>>,
12297 cx: &mut ViewContext<Editor>,
12298 ) -> Task<Result<bool>> {
12299 self.update(cx, |project, cx| {
12300 project.resolve_completions(buffer, completion_indices, completions, cx)
12301 })
12302 }
12303
12304 fn apply_additional_edits_for_completion(
12305 &self,
12306 buffer: Model<Buffer>,
12307 completion: Completion,
12308 push_to_history: bool,
12309 cx: &mut ViewContext<Editor>,
12310 ) -> Task<Result<Option<language::Transaction>>> {
12311 self.update(cx, |project, cx| {
12312 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12313 })
12314 }
12315
12316 fn is_completion_trigger(
12317 &self,
12318 buffer: &Model<Buffer>,
12319 position: language::Anchor,
12320 text: &str,
12321 trigger_in_words: bool,
12322 cx: &mut ViewContext<Editor>,
12323 ) -> bool {
12324 if !EditorSettings::get_global(cx).show_completions_on_input {
12325 return false;
12326 }
12327
12328 let mut chars = text.chars();
12329 let char = if let Some(char) = chars.next() {
12330 char
12331 } else {
12332 return false;
12333 };
12334 if chars.next().is_some() {
12335 return false;
12336 }
12337
12338 let buffer = buffer.read(cx);
12339 let scope = buffer.snapshot().language_scope_at(position);
12340 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12341 return true;
12342 }
12343
12344 buffer
12345 .completion_triggers()
12346 .iter()
12347 .any(|string| string == text)
12348 }
12349}
12350
12351fn inlay_hint_settings(
12352 location: Anchor,
12353 snapshot: &MultiBufferSnapshot,
12354 cx: &mut ViewContext<'_, Editor>,
12355) -> InlayHintSettings {
12356 let file = snapshot.file_at(location);
12357 let language = snapshot.language_at(location);
12358 let settings = all_language_settings(file, cx);
12359 settings
12360 .language(language.map(|l| l.name()).as_deref())
12361 .inlay_hints
12362}
12363
12364fn consume_contiguous_rows(
12365 contiguous_row_selections: &mut Vec<Selection<Point>>,
12366 selection: &Selection<Point>,
12367 display_map: &DisplaySnapshot,
12368 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12369) -> (MultiBufferRow, MultiBufferRow) {
12370 contiguous_row_selections.push(selection.clone());
12371 let start_row = MultiBufferRow(selection.start.row);
12372 let mut end_row = ending_row(selection, display_map);
12373
12374 while let Some(next_selection) = selections.peek() {
12375 if next_selection.start.row <= end_row.0 {
12376 end_row = ending_row(next_selection, display_map);
12377 contiguous_row_selections.push(selections.next().unwrap().clone());
12378 } else {
12379 break;
12380 }
12381 }
12382 (start_row, end_row)
12383}
12384
12385fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12386 if next_selection.end.column > 0 || next_selection.is_empty() {
12387 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12388 } else {
12389 MultiBufferRow(next_selection.end.row)
12390 }
12391}
12392
12393impl EditorSnapshot {
12394 pub fn remote_selections_in_range<'a>(
12395 &'a self,
12396 range: &'a Range<Anchor>,
12397 collaboration_hub: &dyn CollaborationHub,
12398 cx: &'a AppContext,
12399 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12400 let participant_names = collaboration_hub.user_names(cx);
12401 let participant_indices = collaboration_hub.user_participant_indices(cx);
12402 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12403 let collaborators_by_replica_id = collaborators_by_peer_id
12404 .iter()
12405 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12406 .collect::<HashMap<_, _>>();
12407 self.buffer_snapshot
12408 .selections_in_range(range, false)
12409 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12410 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12411 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12412 let user_name = participant_names.get(&collaborator.user_id).cloned();
12413 Some(RemoteSelection {
12414 replica_id,
12415 selection,
12416 cursor_shape,
12417 line_mode,
12418 participant_index,
12419 peer_id: collaborator.peer_id,
12420 user_name,
12421 })
12422 })
12423 }
12424
12425 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12426 self.display_snapshot.buffer_snapshot.language_at(position)
12427 }
12428
12429 pub fn is_focused(&self) -> bool {
12430 self.is_focused
12431 }
12432
12433 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12434 self.placeholder_text.as_ref()
12435 }
12436
12437 pub fn scroll_position(&self) -> gpui::Point<f32> {
12438 self.scroll_anchor.scroll_position(&self.display_snapshot)
12439 }
12440
12441 fn gutter_dimensions(
12442 &self,
12443 font_id: FontId,
12444 font_size: Pixels,
12445 em_width: Pixels,
12446 max_line_number_width: Pixels,
12447 cx: &AppContext,
12448 ) -> GutterDimensions {
12449 if !self.show_gutter {
12450 return GutterDimensions::default();
12451 }
12452 let descent = cx.text_system().descent(font_id, font_size);
12453
12454 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12455 matches!(
12456 ProjectSettings::get_global(cx).git.git_gutter,
12457 Some(GitGutterSetting::TrackedFiles)
12458 )
12459 });
12460 let gutter_settings = EditorSettings::get_global(cx).gutter;
12461 let show_line_numbers = self
12462 .show_line_numbers
12463 .unwrap_or(gutter_settings.line_numbers);
12464 let line_gutter_width = if show_line_numbers {
12465 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12466 let min_width_for_number_on_gutter = em_width * 4.0;
12467 max_line_number_width.max(min_width_for_number_on_gutter)
12468 } else {
12469 0.0.into()
12470 };
12471
12472 let show_code_actions = self
12473 .show_code_actions
12474 .unwrap_or(gutter_settings.code_actions);
12475
12476 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12477
12478 let git_blame_entries_width = self
12479 .render_git_blame_gutter
12480 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12481
12482 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12483 left_padding += if show_code_actions || show_runnables {
12484 em_width * 3.0
12485 } else if show_git_gutter && show_line_numbers {
12486 em_width * 2.0
12487 } else if show_git_gutter || show_line_numbers {
12488 em_width
12489 } else {
12490 px(0.)
12491 };
12492
12493 let right_padding = if gutter_settings.folds && show_line_numbers {
12494 em_width * 4.0
12495 } else if gutter_settings.folds {
12496 em_width * 3.0
12497 } else if show_line_numbers {
12498 em_width
12499 } else {
12500 px(0.)
12501 };
12502
12503 GutterDimensions {
12504 left_padding,
12505 right_padding,
12506 width: line_gutter_width + left_padding + right_padding,
12507 margin: -descent,
12508 git_blame_entries_width,
12509 }
12510 }
12511
12512 pub fn render_fold_toggle(
12513 &self,
12514 buffer_row: MultiBufferRow,
12515 row_contains_cursor: bool,
12516 editor: View<Editor>,
12517 cx: &mut WindowContext,
12518 ) -> Option<AnyElement> {
12519 let folded = self.is_line_folded(buffer_row);
12520
12521 if let Some(crease) = self
12522 .crease_snapshot
12523 .query_row(buffer_row, &self.buffer_snapshot)
12524 {
12525 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12526 if folded {
12527 editor.update(cx, |editor, cx| {
12528 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12529 });
12530 } else {
12531 editor.update(cx, |editor, cx| {
12532 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12533 });
12534 }
12535 });
12536
12537 Some((crease.render_toggle)(
12538 buffer_row,
12539 folded,
12540 toggle_callback,
12541 cx,
12542 ))
12543 } else if folded
12544 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12545 {
12546 Some(
12547 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12548 .selected(folded)
12549 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12550 if folded {
12551 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12552 } else {
12553 this.fold_at(&FoldAt { buffer_row }, cx);
12554 }
12555 }))
12556 .into_any_element(),
12557 )
12558 } else {
12559 None
12560 }
12561 }
12562
12563 pub fn render_crease_trailer(
12564 &self,
12565 buffer_row: MultiBufferRow,
12566 cx: &mut WindowContext,
12567 ) -> Option<AnyElement> {
12568 let folded = self.is_line_folded(buffer_row);
12569 let crease = self
12570 .crease_snapshot
12571 .query_row(buffer_row, &self.buffer_snapshot)?;
12572 Some((crease.render_trailer)(buffer_row, folded, cx))
12573 }
12574}
12575
12576impl Deref for EditorSnapshot {
12577 type Target = DisplaySnapshot;
12578
12579 fn deref(&self) -> &Self::Target {
12580 &self.display_snapshot
12581 }
12582}
12583
12584#[derive(Clone, Debug, PartialEq, Eq)]
12585pub enum EditorEvent {
12586 InputIgnored {
12587 text: Arc<str>,
12588 },
12589 InputHandled {
12590 utf16_range_to_replace: Option<Range<isize>>,
12591 text: Arc<str>,
12592 },
12593 ExcerptsAdded {
12594 buffer: Model<Buffer>,
12595 predecessor: ExcerptId,
12596 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12597 },
12598 ExcerptsRemoved {
12599 ids: Vec<ExcerptId>,
12600 },
12601 ExcerptsEdited {
12602 ids: Vec<ExcerptId>,
12603 },
12604 ExcerptsExpanded {
12605 ids: Vec<ExcerptId>,
12606 },
12607 BufferEdited,
12608 Edited {
12609 transaction_id: clock::Lamport,
12610 },
12611 Reparsed(BufferId),
12612 Focused,
12613 FocusedIn,
12614 Blurred,
12615 DirtyChanged,
12616 Saved,
12617 TitleChanged,
12618 DiffBaseChanged,
12619 SelectionsChanged {
12620 local: bool,
12621 },
12622 ScrollPositionChanged {
12623 local: bool,
12624 autoscroll: bool,
12625 },
12626 Closed,
12627 TransactionUndone {
12628 transaction_id: clock::Lamport,
12629 },
12630 TransactionBegun {
12631 transaction_id: clock::Lamport,
12632 },
12633}
12634
12635impl EventEmitter<EditorEvent> for Editor {}
12636
12637impl FocusableView for Editor {
12638 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12639 self.focus_handle.clone()
12640 }
12641}
12642
12643impl Render for Editor {
12644 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12645 let settings = ThemeSettings::get_global(cx);
12646
12647 let text_style = match self.mode {
12648 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12649 color: cx.theme().colors().editor_foreground,
12650 font_family: settings.ui_font.family.clone(),
12651 font_features: settings.ui_font.features.clone(),
12652 font_fallbacks: settings.ui_font.fallbacks.clone(),
12653 font_size: rems(0.875).into(),
12654 font_weight: settings.ui_font.weight,
12655 line_height: relative(settings.buffer_line_height.value()),
12656 ..Default::default()
12657 },
12658 EditorMode::Full => TextStyle {
12659 color: cx.theme().colors().editor_foreground,
12660 font_family: settings.buffer_font.family.clone(),
12661 font_features: settings.buffer_font.features.clone(),
12662 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12663 font_size: settings.buffer_font_size(cx).into(),
12664 font_weight: settings.buffer_font.weight,
12665 line_height: relative(settings.buffer_line_height.value()),
12666 ..Default::default()
12667 },
12668 };
12669
12670 let background = match self.mode {
12671 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12672 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12673 EditorMode::Full => cx.theme().colors().editor_background,
12674 };
12675
12676 EditorElement::new(
12677 cx.view(),
12678 EditorStyle {
12679 background,
12680 local_player: cx.theme().players().local(),
12681 text: text_style,
12682 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12683 syntax: cx.theme().syntax().clone(),
12684 status: cx.theme().status().clone(),
12685 inlay_hints_style: HighlightStyle {
12686 color: Some(cx.theme().status().hint),
12687 ..HighlightStyle::default()
12688 },
12689 suggestions_style: HighlightStyle {
12690 color: Some(cx.theme().status().predictive),
12691 ..HighlightStyle::default()
12692 },
12693 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12694 },
12695 )
12696 }
12697}
12698
12699impl ViewInputHandler for Editor {
12700 fn text_for_range(
12701 &mut self,
12702 range_utf16: Range<usize>,
12703 cx: &mut ViewContext<Self>,
12704 ) -> Option<String> {
12705 Some(
12706 self.buffer
12707 .read(cx)
12708 .read(cx)
12709 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12710 .collect(),
12711 )
12712 }
12713
12714 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12715 // Prevent the IME menu from appearing when holding down an alphabetic key
12716 // while input is disabled.
12717 if !self.input_enabled {
12718 return None;
12719 }
12720
12721 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12722 Some(range.start.0..range.end.0)
12723 }
12724
12725 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12726 let snapshot = self.buffer.read(cx).read(cx);
12727 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12728 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12729 }
12730
12731 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12732 self.clear_highlights::<InputComposition>(cx);
12733 self.ime_transaction.take();
12734 }
12735
12736 fn replace_text_in_range(
12737 &mut self,
12738 range_utf16: Option<Range<usize>>,
12739 text: &str,
12740 cx: &mut ViewContext<Self>,
12741 ) {
12742 if !self.input_enabled {
12743 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12744 return;
12745 }
12746
12747 self.transact(cx, |this, cx| {
12748 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12749 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12750 Some(this.selection_replacement_ranges(range_utf16, cx))
12751 } else {
12752 this.marked_text_ranges(cx)
12753 };
12754
12755 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12756 let newest_selection_id = this.selections.newest_anchor().id;
12757 this.selections
12758 .all::<OffsetUtf16>(cx)
12759 .iter()
12760 .zip(ranges_to_replace.iter())
12761 .find_map(|(selection, range)| {
12762 if selection.id == newest_selection_id {
12763 Some(
12764 (range.start.0 as isize - selection.head().0 as isize)
12765 ..(range.end.0 as isize - selection.head().0 as isize),
12766 )
12767 } else {
12768 None
12769 }
12770 })
12771 });
12772
12773 cx.emit(EditorEvent::InputHandled {
12774 utf16_range_to_replace: range_to_replace,
12775 text: text.into(),
12776 });
12777
12778 if let Some(new_selected_ranges) = new_selected_ranges {
12779 this.change_selections(None, cx, |selections| {
12780 selections.select_ranges(new_selected_ranges)
12781 });
12782 this.backspace(&Default::default(), cx);
12783 }
12784
12785 this.handle_input(text, cx);
12786 });
12787
12788 if let Some(transaction) = self.ime_transaction {
12789 self.buffer.update(cx, |buffer, cx| {
12790 buffer.group_until_transaction(transaction, cx);
12791 });
12792 }
12793
12794 self.unmark_text(cx);
12795 }
12796
12797 fn replace_and_mark_text_in_range(
12798 &mut self,
12799 range_utf16: Option<Range<usize>>,
12800 text: &str,
12801 new_selected_range_utf16: Option<Range<usize>>,
12802 cx: &mut ViewContext<Self>,
12803 ) {
12804 if !self.input_enabled {
12805 return;
12806 }
12807
12808 let transaction = self.transact(cx, |this, cx| {
12809 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12810 let snapshot = this.buffer.read(cx).read(cx);
12811 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12812 for marked_range in &mut marked_ranges {
12813 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12814 marked_range.start.0 += relative_range_utf16.start;
12815 marked_range.start =
12816 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12817 marked_range.end =
12818 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12819 }
12820 }
12821 Some(marked_ranges)
12822 } else if let Some(range_utf16) = range_utf16 {
12823 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12824 Some(this.selection_replacement_ranges(range_utf16, cx))
12825 } else {
12826 None
12827 };
12828
12829 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12830 let newest_selection_id = this.selections.newest_anchor().id;
12831 this.selections
12832 .all::<OffsetUtf16>(cx)
12833 .iter()
12834 .zip(ranges_to_replace.iter())
12835 .find_map(|(selection, range)| {
12836 if selection.id == newest_selection_id {
12837 Some(
12838 (range.start.0 as isize - selection.head().0 as isize)
12839 ..(range.end.0 as isize - selection.head().0 as isize),
12840 )
12841 } else {
12842 None
12843 }
12844 })
12845 });
12846
12847 cx.emit(EditorEvent::InputHandled {
12848 utf16_range_to_replace: range_to_replace,
12849 text: text.into(),
12850 });
12851
12852 if let Some(ranges) = ranges_to_replace {
12853 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12854 }
12855
12856 let marked_ranges = {
12857 let snapshot = this.buffer.read(cx).read(cx);
12858 this.selections
12859 .disjoint_anchors()
12860 .iter()
12861 .map(|selection| {
12862 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12863 })
12864 .collect::<Vec<_>>()
12865 };
12866
12867 if text.is_empty() {
12868 this.unmark_text(cx);
12869 } else {
12870 this.highlight_text::<InputComposition>(
12871 marked_ranges.clone(),
12872 HighlightStyle {
12873 underline: Some(UnderlineStyle {
12874 thickness: px(1.),
12875 color: None,
12876 wavy: false,
12877 }),
12878 ..Default::default()
12879 },
12880 cx,
12881 );
12882 }
12883
12884 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12885 let use_autoclose = this.use_autoclose;
12886 let use_auto_surround = this.use_auto_surround;
12887 this.set_use_autoclose(false);
12888 this.set_use_auto_surround(false);
12889 this.handle_input(text, cx);
12890 this.set_use_autoclose(use_autoclose);
12891 this.set_use_auto_surround(use_auto_surround);
12892
12893 if let Some(new_selected_range) = new_selected_range_utf16 {
12894 let snapshot = this.buffer.read(cx).read(cx);
12895 let new_selected_ranges = marked_ranges
12896 .into_iter()
12897 .map(|marked_range| {
12898 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12899 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12900 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12901 snapshot.clip_offset_utf16(new_start, Bias::Left)
12902 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12903 })
12904 .collect::<Vec<_>>();
12905
12906 drop(snapshot);
12907 this.change_selections(None, cx, |selections| {
12908 selections.select_ranges(new_selected_ranges)
12909 });
12910 }
12911 });
12912
12913 self.ime_transaction = self.ime_transaction.or(transaction);
12914 if let Some(transaction) = self.ime_transaction {
12915 self.buffer.update(cx, |buffer, cx| {
12916 buffer.group_until_transaction(transaction, cx);
12917 });
12918 }
12919
12920 if self.text_highlights::<InputComposition>(cx).is_none() {
12921 self.ime_transaction.take();
12922 }
12923 }
12924
12925 fn bounds_for_range(
12926 &mut self,
12927 range_utf16: Range<usize>,
12928 element_bounds: gpui::Bounds<Pixels>,
12929 cx: &mut ViewContext<Self>,
12930 ) -> Option<gpui::Bounds<Pixels>> {
12931 let text_layout_details = self.text_layout_details(cx);
12932 let style = &text_layout_details.editor_style;
12933 let font_id = cx.text_system().resolve_font(&style.text.font());
12934 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12935 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12936
12937 let em_width = cx
12938 .text_system()
12939 .typographic_bounds(font_id, font_size, 'm')
12940 .unwrap()
12941 .size
12942 .width;
12943
12944 let snapshot = self.snapshot(cx);
12945 let scroll_position = snapshot.scroll_position();
12946 let scroll_left = scroll_position.x * em_width;
12947
12948 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12949 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12950 + self.gutter_dimensions.width;
12951 let y = line_height * (start.row().as_f32() - scroll_position.y);
12952
12953 Some(Bounds {
12954 origin: element_bounds.origin + point(x, y),
12955 size: size(em_width, line_height),
12956 })
12957 }
12958}
12959
12960trait SelectionExt {
12961 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12962 fn spanned_rows(
12963 &self,
12964 include_end_if_at_line_start: bool,
12965 map: &DisplaySnapshot,
12966 ) -> Range<MultiBufferRow>;
12967}
12968
12969impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12970 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12971 let start = self
12972 .start
12973 .to_point(&map.buffer_snapshot)
12974 .to_display_point(map);
12975 let end = self
12976 .end
12977 .to_point(&map.buffer_snapshot)
12978 .to_display_point(map);
12979 if self.reversed {
12980 end..start
12981 } else {
12982 start..end
12983 }
12984 }
12985
12986 fn spanned_rows(
12987 &self,
12988 include_end_if_at_line_start: bool,
12989 map: &DisplaySnapshot,
12990 ) -> Range<MultiBufferRow> {
12991 let start = self.start.to_point(&map.buffer_snapshot);
12992 let mut end = self.end.to_point(&map.buffer_snapshot);
12993 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12994 end.row -= 1;
12995 }
12996
12997 let buffer_start = map.prev_line_boundary(start).0;
12998 let buffer_end = map.next_line_boundary(end).0;
12999 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13000 }
13001}
13002
13003impl<T: InvalidationRegion> InvalidationStack<T> {
13004 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13005 where
13006 S: Clone + ToOffset,
13007 {
13008 while let Some(region) = self.last() {
13009 let all_selections_inside_invalidation_ranges =
13010 if selections.len() == region.ranges().len() {
13011 selections
13012 .iter()
13013 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13014 .all(|(selection, invalidation_range)| {
13015 let head = selection.head().to_offset(buffer);
13016 invalidation_range.start <= head && invalidation_range.end >= head
13017 })
13018 } else {
13019 false
13020 };
13021
13022 if all_selections_inside_invalidation_ranges {
13023 break;
13024 } else {
13025 self.pop();
13026 }
13027 }
13028 }
13029}
13030
13031impl<T> Default for InvalidationStack<T> {
13032 fn default() -> Self {
13033 Self(Default::default())
13034 }
13035}
13036
13037impl<T> Deref for InvalidationStack<T> {
13038 type Target = Vec<T>;
13039
13040 fn deref(&self) -> &Self::Target {
13041 &self.0
13042 }
13043}
13044
13045impl<T> DerefMut for InvalidationStack<T> {
13046 fn deref_mut(&mut self) -> &mut Self::Target {
13047 &mut self.0
13048 }
13049}
13050
13051impl InvalidationRegion for SnippetState {
13052 fn ranges(&self) -> &[Range<Anchor>] {
13053 &self.ranges[self.active_index]
13054 }
13055}
13056
13057pub fn diagnostic_block_renderer(
13058 diagnostic: Diagnostic,
13059 max_message_rows: Option<u8>,
13060 allow_closing: bool,
13061 _is_valid: bool,
13062) -> RenderBlock {
13063 let (text_without_backticks, code_ranges) =
13064 highlight_diagnostic_message(&diagnostic, max_message_rows);
13065
13066 Box::new(move |cx: &mut BlockContext| {
13067 let group_id: SharedString = cx.block_id.to_string().into();
13068
13069 let mut text_style = cx.text_style().clone();
13070 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13071 let theme_settings = ThemeSettings::get_global(cx);
13072 text_style.font_family = theme_settings.buffer_font.family.clone();
13073 text_style.font_style = theme_settings.buffer_font.style;
13074 text_style.font_features = theme_settings.buffer_font.features.clone();
13075 text_style.font_weight = theme_settings.buffer_font.weight;
13076
13077 let multi_line_diagnostic = diagnostic.message.contains('\n');
13078
13079 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13080 if multi_line_diagnostic {
13081 v_flex()
13082 } else {
13083 h_flex()
13084 }
13085 .when(allow_closing, |div| {
13086 div.children(diagnostic.is_primary.then(|| {
13087 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13088 .icon_color(Color::Muted)
13089 .size(ButtonSize::Compact)
13090 .style(ButtonStyle::Transparent)
13091 .visible_on_hover(group_id.clone())
13092 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13093 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13094 }))
13095 })
13096 .child(
13097 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13098 .icon_color(Color::Muted)
13099 .size(ButtonSize::Compact)
13100 .style(ButtonStyle::Transparent)
13101 .visible_on_hover(group_id.clone())
13102 .on_click({
13103 let message = diagnostic.message.clone();
13104 move |_click, cx| {
13105 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13106 }
13107 })
13108 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13109 )
13110 };
13111
13112 let icon_size = buttons(&diagnostic, cx.block_id)
13113 .into_any_element()
13114 .layout_as_root(AvailableSpace::min_size(), cx);
13115
13116 h_flex()
13117 .id(cx.block_id)
13118 .group(group_id.clone())
13119 .relative()
13120 .size_full()
13121 .pl(cx.gutter_dimensions.width)
13122 .w(cx.max_width + cx.gutter_dimensions.width)
13123 .child(
13124 div()
13125 .flex()
13126 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13127 .flex_shrink(),
13128 )
13129 .child(buttons(&diagnostic, cx.block_id))
13130 .child(div().flex().flex_shrink_0().child(
13131 StyledText::new(text_without_backticks.clone()).with_highlights(
13132 &text_style,
13133 code_ranges.iter().map(|range| {
13134 (
13135 range.clone(),
13136 HighlightStyle {
13137 font_weight: Some(FontWeight::BOLD),
13138 ..Default::default()
13139 },
13140 )
13141 }),
13142 ),
13143 ))
13144 .into_any_element()
13145 })
13146}
13147
13148pub fn highlight_diagnostic_message(
13149 diagnostic: &Diagnostic,
13150 mut max_message_rows: Option<u8>,
13151) -> (SharedString, Vec<Range<usize>>) {
13152 let mut text_without_backticks = String::new();
13153 let mut code_ranges = Vec::new();
13154
13155 if let Some(source) = &diagnostic.source {
13156 text_without_backticks.push_str(&source);
13157 code_ranges.push(0..source.len());
13158 text_without_backticks.push_str(": ");
13159 }
13160
13161 let mut prev_offset = 0;
13162 let mut in_code_block = false;
13163 let has_row_limit = max_message_rows.is_some();
13164 let mut newline_indices = diagnostic
13165 .message
13166 .match_indices('\n')
13167 .filter(|_| has_row_limit)
13168 .map(|(ix, _)| ix)
13169 .fuse()
13170 .peekable();
13171
13172 for (quote_ix, _) in diagnostic
13173 .message
13174 .match_indices('`')
13175 .chain([(diagnostic.message.len(), "")])
13176 {
13177 let mut first_newline_ix = None;
13178 let mut last_newline_ix = None;
13179 while let Some(newline_ix) = newline_indices.peek() {
13180 if *newline_ix < quote_ix {
13181 if first_newline_ix.is_none() {
13182 first_newline_ix = Some(*newline_ix);
13183 }
13184 last_newline_ix = Some(*newline_ix);
13185
13186 if let Some(rows_left) = &mut max_message_rows {
13187 if *rows_left == 0 {
13188 break;
13189 } else {
13190 *rows_left -= 1;
13191 }
13192 }
13193 let _ = newline_indices.next();
13194 } else {
13195 break;
13196 }
13197 }
13198 let prev_len = text_without_backticks.len();
13199 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13200 text_without_backticks.push_str(new_text);
13201 if in_code_block {
13202 code_ranges.push(prev_len..text_without_backticks.len());
13203 }
13204 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13205 in_code_block = !in_code_block;
13206 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13207 text_without_backticks.push_str("...");
13208 break;
13209 }
13210 }
13211
13212 (text_without_backticks.into(), code_ranges)
13213}
13214
13215fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13216 match severity {
13217 DiagnosticSeverity::ERROR => colors.error,
13218 DiagnosticSeverity::WARNING => colors.warning,
13219 DiagnosticSeverity::INFORMATION => colors.info,
13220 DiagnosticSeverity::HINT => colors.info,
13221 _ => colors.ignored,
13222 }
13223}
13224
13225pub fn styled_runs_for_code_label<'a>(
13226 label: &'a CodeLabel,
13227 syntax_theme: &'a theme::SyntaxTheme,
13228) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13229 let fade_out = HighlightStyle {
13230 fade_out: Some(0.35),
13231 ..Default::default()
13232 };
13233
13234 let mut prev_end = label.filter_range.end;
13235 label
13236 .runs
13237 .iter()
13238 .enumerate()
13239 .flat_map(move |(ix, (range, highlight_id))| {
13240 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13241 style
13242 } else {
13243 return Default::default();
13244 };
13245 let mut muted_style = style;
13246 muted_style.highlight(fade_out);
13247
13248 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13249 if range.start >= label.filter_range.end {
13250 if range.start > prev_end {
13251 runs.push((prev_end..range.start, fade_out));
13252 }
13253 runs.push((range.clone(), muted_style));
13254 } else if range.end <= label.filter_range.end {
13255 runs.push((range.clone(), style));
13256 } else {
13257 runs.push((range.start..label.filter_range.end, style));
13258 runs.push((label.filter_range.end..range.end, muted_style));
13259 }
13260 prev_end = cmp::max(prev_end, range.end);
13261
13262 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13263 runs.push((prev_end..label.text.len(), fade_out));
13264 }
13265
13266 runs
13267 })
13268}
13269
13270pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13271 let mut prev_index = 0;
13272 let mut prev_codepoint: Option<char> = None;
13273 text.char_indices()
13274 .chain([(text.len(), '\0')])
13275 .filter_map(move |(index, codepoint)| {
13276 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13277 let is_boundary = index == text.len()
13278 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13279 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13280 if is_boundary {
13281 let chunk = &text[prev_index..index];
13282 prev_index = index;
13283 Some(chunk)
13284 } else {
13285 None
13286 }
13287 })
13288}
13289
13290pub trait RangeToAnchorExt: Sized {
13291 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13292
13293 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13294 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13295 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13296 }
13297}
13298
13299impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13300 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13301 let start_offset = self.start.to_offset(snapshot);
13302 let end_offset = self.end.to_offset(snapshot);
13303 if start_offset == end_offset {
13304 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13305 } else {
13306 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13307 }
13308 }
13309}
13310
13311pub trait RowExt {
13312 fn as_f32(&self) -> f32;
13313
13314 fn next_row(&self) -> Self;
13315
13316 fn previous_row(&self) -> Self;
13317
13318 fn minus(&self, other: Self) -> u32;
13319}
13320
13321impl RowExt for DisplayRow {
13322 fn as_f32(&self) -> f32 {
13323 self.0 as f32
13324 }
13325
13326 fn next_row(&self) -> Self {
13327 Self(self.0 + 1)
13328 }
13329
13330 fn previous_row(&self) -> Self {
13331 Self(self.0.saturating_sub(1))
13332 }
13333
13334 fn minus(&self, other: Self) -> u32 {
13335 self.0 - other.0
13336 }
13337}
13338
13339impl RowExt for MultiBufferRow {
13340 fn as_f32(&self) -> f32 {
13341 self.0 as f32
13342 }
13343
13344 fn next_row(&self) -> Self {
13345 Self(self.0 + 1)
13346 }
13347
13348 fn previous_row(&self) -> Self {
13349 Self(self.0.saturating_sub(1))
13350 }
13351
13352 fn minus(&self, other: Self) -> u32 {
13353 self.0 - other.0
13354 }
13355}
13356
13357trait RowRangeExt {
13358 type Row;
13359
13360 fn len(&self) -> usize;
13361
13362 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13363}
13364
13365impl RowRangeExt for Range<MultiBufferRow> {
13366 type Row = MultiBufferRow;
13367
13368 fn len(&self) -> usize {
13369 (self.end.0 - self.start.0) as usize
13370 }
13371
13372 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13373 (self.start.0..self.end.0).map(MultiBufferRow)
13374 }
13375}
13376
13377impl RowRangeExt for Range<DisplayRow> {
13378 type Row = DisplayRow;
13379
13380 fn len(&self) -> usize {
13381 (self.end.0 - self.start.0) as usize
13382 }
13383
13384 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13385 (self.start.0..self.end.0).map(DisplayRow)
13386 }
13387}
13388
13389fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13390 if hunk.diff_base_byte_range.is_empty() {
13391 DiffHunkStatus::Added
13392 } else if hunk.associated_range.is_empty() {
13393 DiffHunkStatus::Removed
13394 } else {
13395 DiffHunkStatus::Modified
13396 }
13397}
13398
13399/// If select range has more than one line, we
13400/// just point the cursor to range.start.
13401fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13402 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13403 range
13404 } else {
13405 range.start..range.start
13406 }
13407}